define(["@jupyter-widgets/base"], (__WEBPACK_EXTERNAL_MODULE__2055__) => { return /******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

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

"use strict";
var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'chart-bar';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f080';
var svgPathData = 'M332.8 320h38.4c6.4 0 12.8-6.4 12.8-12.8V172.8c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h38.4c6.4 0 12.8-6.4 12.8-12.8V76.8c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-288 0h38.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h38.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zM496 384H64V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-32c0-8.84-7.16-16-16-16z';

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

exports.$F = 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;

/***/ }),

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

"use strict";
var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'check-square';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f14a';
var svgPathData = 'M400 480H48c-26.51 0-48-21.49-48-48V80c0-26.51 21.49-48 48-48h352c26.51 0 48 21.49 48 48v352c0 26.51-21.49 48-48 48zm-204.686-98.059l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.248-16.379-6.249-22.628 0L184 302.745l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.25 16.379 6.25 22.628.001z';

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

exports.rQ = 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;

/***/ }),

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

"use strict";
var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'eye';
var width = 576;
var height = 512;
var ligatures = [];
var unicode = 'f06e';
var svgPathData = 'M572.52 241.4C518.29 135.59 410.93 64 288 64S57.68 135.64 3.48 241.41a32.35 32.35 0 0 0 0 29.19C57.71 376.41 165.07 448 288 448s230.32-71.64 284.52-177.41a32.35 32.35 0 0 0 0-29.19zM288 400a144 144 0 1 1 144-144 143.93 143.93 0 0 1-144 144zm0-240a95.31 95.31 0 0 0-25.31 3.79 47.85 47.85 0 0 1-66.9 66.9A95.78 95.78 0 1 0 288 160z';

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

exports.pS = 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;

/***/ }),

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

"use strict";
var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'eye-slash';
var width = 640;
var height = 512;
var ligatures = [];
var unicode = 'f070';
var svgPathData = 'M320 400c-75.85 0-137.25-58.71-142.9-133.11L72.2 185.82c-13.79 17.3-26.48 35.59-36.72 55.59a32.35 32.35 0 0 0 0 29.19C89.71 376.41 197.07 448 320 448c26.91 0 52.87-4 77.89-10.46L346 397.39a144.13 144.13 0 0 1-26 2.61zm313.82 58.1l-110.55-85.44a331.25 331.25 0 0 0 81.25-102.07 32.35 32.35 0 0 0 0-29.19C550.29 135.59 442.93 64 320 64a308.15 308.15 0 0 0-147.32 37.7L45.46 3.37A16 16 0 0 0 23 6.18L3.37 31.45A16 16 0 0 0 6.18 53.9l588.36 454.73a16 16 0 0 0 22.46-2.81l19.64-25.27a16 16 0 0 0-2.82-22.45zm-183.72-142l-39.3-30.38A94.75 94.75 0 0 0 416 256a94.76 94.76 0 0 0-121.31-92.21A47.65 47.65 0 0 1 304 192a46.64 46.64 0 0 1-1.54 10l-73.61-56.89A142.31 142.31 0 0 1 320 112a143.92 143.92 0 0 1 144 144c0 21.63-5.29 41.79-13.9 60.11z';

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

exports.k6 = 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;

/***/ }),

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

"use strict";
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;

/***/ }),

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

"use strict";
var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'pause';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f04c';
var svgPathData = 'M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z';

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

exports.G1 = 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;

/***/ }),

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

"use strict";
var __webpack_unused_export__;

__webpack_unused_export__ = ({ value: true });
var prefix = 'fas';
var iconName = 'play';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f04b';
var svgPathData = 'M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z';

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

exports.ij = 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;

/***/ }),

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

"use strict";
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;

/***/ }),

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

"use strict";
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;

/***/ }),

/***/ 9704:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ActivityMonitor = void 0;
const signaling_1 = __webpack_require__(3992);
/**
 * A class that monitors activity on a signal.
 */
class ActivityMonitor {
    /**
     * Construct a new activity monitor.
     */
    constructor(options) {
        this._timer = -1;
        this._timeout = -1;
        this._isDisposed = false;
        this._activityStopped = new signaling_1.Signal(this);
        options.signal.connect(this._onSignalFired, this);
        this._timeout = options.timeout || 1000;
    }
    /**
     * A signal emitted when activity has ceased.
     */
    get activityStopped() {
        return this._activityStopped;
    }
    /**
     * The timeout associated with the monitor, in milliseconds.
     */
    get timeout() {
        return this._timeout;
    }
    set timeout(value) {
        this._timeout = value;
    }
    /**
     * Test whether the monitor has been disposed.
     *
     * #### Notes
     * This is a read-only property.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the activity monitor.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * A signal handler for the monitored signal.
     */
    _onSignalFired(sender, args) {
        clearTimeout(this._timer);
        this._sender = sender;
        this._args = args;
        this._timer = setTimeout(() => {
            this._activityStopped.emit({
                sender: this._sender,
                args: this._args
            });
        }, this._timeout);
    }
}
exports.ActivityMonitor = ActivityMonitor;
//# sourceMappingURL=activitymonitor.js.map

/***/ }),

/***/ 8925:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/**
 * @packageDocumentation
 * @module coreutils
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
__exportStar(__webpack_require__(9704), exports);
__exportStar(__webpack_require__(9269), exports);
__exportStar(__webpack_require__(1232), exports);
__exportStar(__webpack_require__(9547), exports);
__exportStar(__webpack_require__(5964), exports);
__exportStar(__webpack_require__(9830), exports);
__exportStar(__webpack_require__(7361), exports);
__exportStar(__webpack_require__(8126), exports);
__exportStar(__webpack_require__(1796), exports);
__exportStar(__webpack_require__(1692), exports);
//# sourceMappingURL=index.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=interfaces.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LruCache = void 0;
const DEFAULT_MAX_SIZE = 128;
/** A least-recently-used cache. */
class LruCache {
    constructor(options = {}) {
        this._map = new Map();
        this._maxSize = (options === null || options === void 0 ? void 0 : options.maxSize) || DEFAULT_MAX_SIZE;
    }
    /**
     * Return the current size of the cache.
     */
    get size() {
        return this._map.size;
    }
    /**
     * Clear the values in the cache.
     */
    clear() {
        this._map.clear();
    }
    /**
     * Get a value (or null) from the cache, pushing the item to the front of the cache.
     */
    get(key) {
        const item = this._map.get(key) || null;
        if (item != null) {
            this._map.delete(key);
            this._map.set(key, item);
        }
        return item;
    }
    /**
     * Set a value in the cache, potentially evicting an old item.
     */
    set(key, value) {
        if (this._map.size >= this._maxSize) {
            this._map.delete(this._map.keys().next().value);
        }
        this._map.set(key, value);
    }
}
exports.LruCache = LruCache;
//# sourceMappingURL=lru.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MarkdownCodeBlocks = void 0;
/**
 * The namespace for code block functions which help
 * in extract code from markdown text
 */
var MarkdownCodeBlocks;
(function (MarkdownCodeBlocks) {
    MarkdownCodeBlocks.CODE_BLOCK_MARKER = '```';
    const markdownExtensions = [
        '.markdown',
        '.mdown',
        '.mkdn',
        '.md',
        '.mkd',
        '.mdwn',
        '.mdtxt',
        '.mdtext',
        '.text',
        '.txt',
        '.Rmd'
    ];
    class MarkdownCodeBlock {
        constructor(startLine) {
            this.startLine = startLine;
            this.code = '';
            this.endLine = -1;
        }
    }
    MarkdownCodeBlocks.MarkdownCodeBlock = MarkdownCodeBlock;
    /**
     * Check whether the given file extension is a markdown extension
     * @param extension - A file extension
     *
     * @returns true/false depending on whether this is a supported markdown extension
     */
    function isMarkdown(extension) {
        return markdownExtensions.indexOf(extension) > -1;
    }
    MarkdownCodeBlocks.isMarkdown = isMarkdown;
    /**
     * Construct all code snippets from current text
     * (this could be potentially optimized if we can cache and detect differences)
     * @param text - A string to parse codeblocks from
     *
     * @returns An array of MarkdownCodeBlocks.
     */
    function findMarkdownCodeBlocks(text) {
        if (!text || text === '') {
            return [];
        }
        const lines = text.split('\n');
        const codeBlocks = [];
        let currentBlock = null;
        for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
            const line = lines[lineIndex];
            const lineContainsMarker = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER) === 0;
            const constructingBlock = currentBlock != null;
            // Skip this line if it is not part of any code block and doesn't contain a marker.
            if (!lineContainsMarker && !constructingBlock) {
                continue;
            }
            // Check if we are already constructing a code block.
            if (!constructingBlock) {
                // Start constructing a new code block.
                currentBlock = new MarkdownCodeBlock(lineIndex);
                // Check whether this is a single line code block of the form ```a = 10```.
                const firstIndex = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);
                const lastIndex = line.lastIndexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);
                const isSingleLine = firstIndex !== lastIndex;
                if (isSingleLine) {
                    currentBlock.code = line.substring(firstIndex + MarkdownCodeBlocks.CODE_BLOCK_MARKER.length, lastIndex);
                    currentBlock.endLine = lineIndex;
                    codeBlocks.push(currentBlock);
                    currentBlock = null;
                }
            }
            else if (currentBlock) {
                if (lineContainsMarker) {
                    // End of block, finish it up.
                    currentBlock.endLine = lineIndex - 1;
                    codeBlocks.push(currentBlock);
                    currentBlock = null;
                }
                else {
                    // Append the current line.
                    currentBlock.code += line + '\n';
                }
            }
        }
        return codeBlocks;
    }
    MarkdownCodeBlocks.findMarkdownCodeBlocks = findMarkdownCodeBlocks;
})(MarkdownCodeBlocks || (exports.MarkdownCodeBlocks = MarkdownCodeBlocks = {}));
//# sourceMappingURL=markdowncodeblocks.js.map

/***/ }),

/***/ 5964:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PageConfig = void 0;
const coreutils_1 = __webpack_require__(5764);
const minimist_1 = __importDefault(__webpack_require__(9600));
const url_1 = __webpack_require__(1692);
/**
 * The namespace for `PageConfig` functions.
 */
var PageConfig;
(function (PageConfig) {
    /**
     * Get global configuration data for the Jupyter application.
     *
     * @param name - The name of the configuration option.
     *
     * @returns The config value or an empty string if not found.
     *
     * #### Notes
     * All values are treated as strings.
     * For browser based applications, it is assumed that the page HTML
     * includes a script tag with the id `jupyter-config-data` containing the
     * configuration as valid JSON.  In order to support the classic Notebook,
     * we fall back on checking for `body` data of the given `name`.
     *
     * For node applications, it is assumed that the process was launched
     * with a `--jupyter-config-data` option pointing to a JSON settings
     * file.
     */
    function getOption(name) {
        if (configData) {
            return configData[name] || getBodyData(name);
        }
        configData = Object.create(null);
        let found = false;
        // Use script tag if available.
        if (typeof document !== 'undefined' && document) {
            const el = document.getElementById('jupyter-config-data');
            if (el) {
                configData = JSON.parse(el.textContent || '');
                found = true;
            }
        }
        // Otherwise use CLI if given.
        if (!found && typeof process !== 'undefined' && process.argv) {
            try {
                const cli = (0, minimist_1.default)(process.argv.slice(2));
                const path = __webpack_require__(9942);
                let fullPath = '';
                if ('jupyter-config-data' in cli) {
                    fullPath = path.resolve(cli['jupyter-config-data']);
                }
                else if ('JUPYTER_CONFIG_DATA' in process.env) {
                    fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);
                }
                if (fullPath) {
                    // Force Webpack to ignore this require.
                    // eslint-disable-next-line
                    configData = eval('require')(fullPath);
                }
            }
            catch (e) {
                console.error(e);
            }
        }
        if (!coreutils_1.JSONExt.isObject(configData)) {
            configData = Object.create(null);
        }
        else {
            for (const key in configData) {
                // PageConfig expects strings
                if (typeof configData[key] !== 'string') {
                    configData[key] = JSON.stringify(configData[key]);
                }
            }
        }
        return configData[name] || getBodyData(name);
    }
    PageConfig.getOption = getOption;
    /**
     * Set global configuration data for the Jupyter application.
     *
     * @param name - The name of the configuration option.
     * @param value - The value to set the option to.
     *
     * @returns The last config value or an empty string if it doesn't exist.
     */
    function setOption(name, value) {
        const last = getOption(name);
        configData[name] = value;
        return last;
    }
    PageConfig.setOption = setOption;
    /**
     * Get the base url for a Jupyter application, or the base url of the page.
     */
    function getBaseUrl() {
        return url_1.URLExt.normalize(getOption('baseUrl') || '/');
    }
    PageConfig.getBaseUrl = getBaseUrl;
    /**
     * Get the tree url for a JupyterLab application.
     */
    function getTreeUrl() {
        return url_1.URLExt.join(getBaseUrl(), getOption('treeUrl'));
    }
    PageConfig.getTreeUrl = getTreeUrl;
    /**
     * Get the base url for sharing links (usually baseUrl)
     */
    function getShareUrl() {
        return url_1.URLExt.normalize(getOption('shareUrl') || getBaseUrl());
    }
    PageConfig.getShareUrl = getShareUrl;
    /**
     * Get the tree url for shareable links.
     * Usually the same as treeUrl,
     * but overridable e.g. when sharing with JupyterHub.
     */
    function getTreeShareUrl() {
        return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(), getOption('treeUrl')));
    }
    PageConfig.getTreeShareUrl = getTreeShareUrl;
    /**
     * Create a new URL given an optional mode and tree path.
     *
     * This is used to create URLS when the mode or tree path change as the user
     * changes mode or the current document in the main area. If fields in
     * options are omitted, the value in PageConfig will be used.
     *
     * @param options - IGetUrlOptions for the new path.
     */
    function getUrl(options) {
        var _a, _b, _c, _d;
        let path = options.toShare ? getShareUrl() : getBaseUrl();
        const mode = (_a = options.mode) !== null && _a !== void 0 ? _a : getOption('mode');
        const workspace = (_b = options.workspace) !== null && _b !== void 0 ? _b : getOption('workspace');
        const labOrDoc = mode === 'single-document' ? 'doc' : 'lab';
        path = url_1.URLExt.join(path, labOrDoc);
        if (workspace !== PageConfig.defaultWorkspace) {
            path = url_1.URLExt.join(path, 'workspaces', encodeURIComponent((_c = getOption('workspace')) !== null && _c !== void 0 ? _c : PageConfig.defaultWorkspace));
        }
        const treePath = (_d = options.treePath) !== null && _d !== void 0 ? _d : getOption('treePath');
        if (treePath) {
            path = url_1.URLExt.join(path, 'tree', url_1.URLExt.encodeParts(treePath));
        }
        return path;
    }
    PageConfig.getUrl = getUrl;
    PageConfig.defaultWorkspace = 'default';
    /**
     * Get the base websocket url for a Jupyter application, or an empty string.
     */
    function getWsUrl(baseUrl) {
        let wsUrl = getOption('wsUrl');
        if (!wsUrl) {
            baseUrl = baseUrl ? url_1.URLExt.normalize(baseUrl) : getBaseUrl();
            if (baseUrl.indexOf('http') !== 0) {
                return '';
            }
            wsUrl = 'ws' + baseUrl.slice(4);
        }
        return url_1.URLExt.normalize(wsUrl);
    }
    PageConfig.getWsUrl = getWsUrl;
    /**
     * Returns the URL converting this notebook to a certain
     * format with nbconvert.
     */
    function getNBConvertURL({ path, format, download }) {
        const notebookPath = url_1.URLExt.encodeParts(path);
        const url = url_1.URLExt.join(getBaseUrl(), 'nbconvert', format, notebookPath);
        if (download) {
            return url + '?download=true';
        }
        return url;
    }
    PageConfig.getNBConvertURL = getNBConvertURL;
    /**
     * Get the authorization token for a Jupyter application.
     */
    function getToken() {
        return getOption('token') || getBodyData('jupyterApiToken');
    }
    PageConfig.getToken = getToken;
    /**
     * Get the Notebook version info [major, minor, patch].
     */
    function getNotebookVersion() {
        const notebookVersion = getOption('notebookVersion');
        if (notebookVersion === '') {
            return [0, 0, 0];
        }
        return JSON.parse(notebookVersion);
    }
    PageConfig.getNotebookVersion = getNotebookVersion;
    /**
     * Private page config data for the Jupyter application.
     */
    let configData = null;
    /**
     * Get a url-encoded item from `body.data` and decode it
     * We should never have any encoded URLs anywhere else in code
     * until we are building an actual request.
     */
    function getBodyData(key) {
        if (typeof document === 'undefined' || !document.body) {
            return '';
        }
        const val = document.body.dataset[key];
        if (typeof val === 'undefined') {
            return '';
        }
        return decodeURIComponent(val);
    }
    /**
     * The namespace for page config `Extension` functions.
     */
    let Extension;
    (function (Extension) {
        /**
         * Populate an array from page config.
         *
         * @param key - The page config key (e.g., `deferredExtensions`).
         *
         * #### Notes
         * This is intended for `deferredExtensions` and `disabledExtensions`.
         */
        function populate(key) {
            try {
                const raw = getOption(key);
                if (raw) {
                    return JSON.parse(raw);
                }
            }
            catch (error) {
                console.warn(`Unable to parse ${key}.`, error);
            }
            return [];
        }
        /**
         * The collection of deferred extensions in page config.
         */
        Extension.deferred = populate('deferredExtensions');
        /**
         * The collection of disabled extensions in page config.
         */
        Extension.disabled = populate('disabledExtensions');
        /**
         * Returns whether a plugin is deferred.
         *
         * @param id - The plugin ID.
         */
        function isDeferred(id) {
            // Check for either a full plugin id match or an extension
            // name match.
            const separatorIndex = id.indexOf(':');
            let extName = '';
            if (separatorIndex !== -1) {
                extName = id.slice(0, separatorIndex);
            }
            return Extension.deferred.some(val => val === id || (extName && val === extName));
        }
        Extension.isDeferred = isDeferred;
        /**
         * Returns whether a plugin is disabled.
         *
         * @param id - The plugin ID.
         */
        function isDisabled(id) {
            // Check for either a full plugin id match or an extension
            // name match.
            const separatorIndex = id.indexOf(':');
            let extName = '';
            if (separatorIndex !== -1) {
                extName = id.slice(0, separatorIndex);
            }
            return Extension.disabled.some(val => val === id || (extName && val === extName));
        }
        Extension.isDisabled = isDisabled;
    })(Extension = PageConfig.Extension || (PageConfig.Extension = {}));
})(PageConfig || (exports.PageConfig = PageConfig = {}));
//# sourceMappingURL=pageconfig.js.map

/***/ }),

/***/ 9830:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PathExt = void 0;
const path_1 = __webpack_require__(9942);
/**
 * The namespace for path-related functions.
 *
 * Note that Jupyter server paths do not start with a leading slash.
 */
var PathExt;
(function (PathExt) {
    /**
     * Join all arguments together and normalize the resulting path.
     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
     *
     * @param paths - The string paths to join.
     */
    function join(...paths) {
        const path = path_1.posix.join(...paths);
        return path === '.' ? '' : removeSlash(path);
    }
    PathExt.join = join;
    /**
     * Join all arguments together and normalize the resulting path and preserve the leading slash.
     *
     * @param paths - The string paths to join.
     */
    function joinWithLeadingSlash(...paths) {
        const path = path_1.posix.join(...paths);
        return path === '.' ? '' : path;
    }
    PathExt.joinWithLeadingSlash = joinWithLeadingSlash;
    /**
     * Return the last portion of a path. Similar to the Unix basename command.
     * Often used to extract the file name from a fully qualified path.
     *
     * @param path - The path to evaluate.
     *
     * @param ext - An extension to remove from the result.
     */
    function basename(path, ext) {
        return path_1.posix.basename(path, ext);
    }
    PathExt.basename = basename;
    /**
     * Get the directory name of a path, similar to the Unix dirname command.
     * When an empty path is given, returns the root path.
     *
     * @param path - The file path.
     */
    function dirname(path) {
        const dir = removeSlash(path_1.posix.dirname(path));
        return dir === '.' ? '' : dir;
    }
    PathExt.dirname = dirname;
    /**
     * Get the extension of the path.
     *
     * @param path - The file path.
     *
     * @returns the extension of the file.
     *
     * #### Notes
     * The extension is the string from the last occurrence of the `.`
     * character to end of string in the last portion of the path, inclusive.
     * If there is no `.` in the last portion of the path, or if the first
     * character of the basename of path [[basename]] is `.`, then an
     * empty string is returned.
     */
    function extname(path) {
        return path_1.posix.extname(path);
    }
    PathExt.extname = extname;
    /**
     * Normalize a string path, reducing '..' and '.' parts.
     * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
     * When an empty path is given, returns the root path.
     *
     * @param path - The string path to normalize.
     */
    function normalize(path) {
        if (path === '') {
            return '';
        }
        return removeSlash(path_1.posix.normalize(path));
    }
    PathExt.normalize = normalize;
    /**
     * Resolve a sequence of paths or path segments into an absolute path.
     * The root path in the application has no leading slash, so it is removed.
     *
     * @param parts - The paths to join.
     *
     * #### Notes
     * The right-most parameter is considered \{to\}.  Other parameters are considered an array of \{from\}.
     *
     * Starting from leftmost \{from\} parameter, resolves \{to\} to an absolute path.
     *
     * If \{to\} isn't already absolute, \{from\} arguments are prepended in right to left order, until an absolute path is found. If after using all \{from\} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.
     */
    function resolve(...parts) {
        return removeSlash(path_1.posix.resolve(...parts));
    }
    PathExt.resolve = resolve;
    /**
     * Solve the relative path from \{from\} to \{to\}.
     *
     * @param from - The source path.
     *
     * @param to - The target path.
     *
     * #### Notes
     * If from and to each resolve to the same path (after calling
     * path.resolve() on each), a zero-length string is returned.
     * If a zero-length string is passed as from or to, `/`
     * will be used instead of the zero-length strings.
     */
    function relative(from, to) {
        return removeSlash(path_1.posix.relative(from, to));
    }
    PathExt.relative = relative;
    /**
     * Normalize a file extension to be of the type `'.foo'`.
     *
     * @param extension - the file extension.
     *
     * #### Notes
     * Adds a leading dot if not present and converts to lower case.
     */
    function normalizeExtension(extension) {
        if (extension.length > 0 && extension.indexOf('.') !== 0) {
            extension = `.${extension}`;
        }
        return extension;
    }
    PathExt.normalizeExtension = normalizeExtension;
    /**
     * Remove the leading slash from a path.
     *
     * @param path the path from which to remove a leading slash.
     */
    function removeSlash(path) {
        if (path.indexOf('/') === 0) {
            path = path.slice(1);
        }
        return path;
    }
    PathExt.removeSlash = removeSlash;
})(PathExt || (exports.PathExt = PathExt = {}));
//# sourceMappingURL=path.js.map

/***/ }),

/***/ 7361:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 * Copyright (c) Jupyter Development Team.
 * Distributed under the terms of the Modified BSD License.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.signalToPromise = void 0;
const coreutils_1 = __webpack_require__(5764);
/**
 * Convert a signal into a promise for the first emitted value.
 *
 * @param signal - The signal we are listening to.
 * @param timeout - Timeout to wait for signal in ms (not timeout if not defined or 0)
 *
 * @returns a Promise that resolves with a `(sender, args)` pair.
 */
function signalToPromise(signal, timeout) {
    const waitForSignal = new coreutils_1.PromiseDelegate();
    function cleanup() {
        signal.disconnect(slot);
    }
    function slot(sender, args) {
        cleanup();
        waitForSignal.resolve([sender, args]);
    }
    signal.connect(slot);
    if ((timeout !== null && timeout !== void 0 ? timeout : 0) > 0) {
        setTimeout(() => {
            cleanup();
            waitForSignal.reject(`Signal not emitted within ${timeout} ms.`);
        }, timeout);
    }
    return waitForSignal.promise;
}
exports.signalToPromise = signalToPromise;
//# sourceMappingURL=signal.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Text = void 0;
/**
 * The namespace for text-related functions.
 */
var Text;
(function (Text) {
    // javascript stores text as utf16 and string indices use "code units",
    // which stores high-codepoint characters as "surrogate pairs",
    // which occupy two indices in the javascript string.
    // We need to translate cursor_pos in the Jupyter protocol (in characters)
    // to js offset (with surrogate pairs taking two spots).
    const HAS_SURROGATES = '𝐚'.length > 1;
    /**
     * Convert a javascript string index into a unicode character offset
     *
     * @param jsIdx - The javascript string index (counting surrogate pairs)
     *
     * @param text - The text in which the offset is calculated
     *
     * @returns The unicode character offset
     */
    function jsIndexToCharIndex(jsIdx, text) {
        if (HAS_SURROGATES) {
            // not using surrogates, nothing to do
            return jsIdx;
        }
        let charIdx = jsIdx;
        for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {
            const charCode = text.charCodeAt(i);
            // check for surrogate pair
            if (charCode >= 0xd800 && charCode <= 0xdbff) {
                const nextCharCode = text.charCodeAt(i + 1);
                if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {
                    charIdx--;
                    i++;
                }
            }
        }
        return charIdx;
    }
    Text.jsIndexToCharIndex = jsIndexToCharIndex;
    /**
     * Convert a unicode character offset to a javascript string index.
     *
     * @param charIdx - The index in unicode characters
     *
     * @param text - The text in which the offset is calculated
     *
     * @returns The js-native index
     */
    function charIndexToJsIndex(charIdx, text) {
        if (HAS_SURROGATES) {
            // not using surrogates, nothing to do
            return charIdx;
        }
        let jsIdx = charIdx;
        for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {
            const charCode = text.charCodeAt(i);
            // check for surrogate pair
            if (charCode >= 0xd800 && charCode <= 0xdbff) {
                const nextCharCode = text.charCodeAt(i + 1);
                if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {
                    jsIdx++;
                    i++;
                }
            }
        }
        return jsIdx;
    }
    Text.charIndexToJsIndex = charIndexToJsIndex;
    /**
     * Given a 'snake-case', 'snake_case', 'snake:case', or
     * 'snake case' string, will return the camel case version: 'snakeCase'.
     *
     * @param str the snake-case input string.
     *
     * @param upper default = false. If true, the first letter of the
     * returned string will be capitalized.
     *
     * @returns the camel case version of the input string.
     */
    function camelCase(str, upper = false) {
        return str.replace(/^(\w)|[\s-_:]+(\w)/g, function (match, p1, p2) {
            if (p2) {
                return p2.toUpperCase();
            }
            else {
                return upper ? p1.toUpperCase() : p1.toLowerCase();
            }
        });
    }
    Text.camelCase = camelCase;
    /**
     * Given a string, title case the words in the string.
     *
     * @param str the string to title case.
     *
     * @returns the same string, but with each word capitalized.
     */
    function titleCase(str) {
        return (str || '')
            .toLowerCase()
            .split(' ')
            .map(word => word.charAt(0).toUpperCase() + word.slice(1))
            .join(' ');
    }
    Text.titleCase = titleCase;
})(Text || (exports.Text = Text = {}));
//# sourceMappingURL=text.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Time = void 0;
/**
 * A list of time units with their associated value in milliseconds.
 */
const UNITS = [
    { name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },
    { name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },
    { name: 'days', milliseconds: 24 * 60 * 60 * 1000 },
    { name: 'hours', milliseconds: 60 * 60 * 1000 },
    { name: 'minutes', milliseconds: 60 * 1000 },
    { name: 'seconds', milliseconds: 1000 }
];
/**
 * The namespace for date functions.
 */
var Time;
(function (Time) {
    /**
     * Convert a timestring to a human readable string (e.g. 'two minutes ago').
     *
     * @param value - The date timestring or date object.
     *
     * @returns A formatted date.
     */
    function formatHuman(value, format = 'long') {
        const lang = document.documentElement.lang || 'en';
        const formatter = new Intl.RelativeTimeFormat(lang, {
            numeric: 'auto',
            style: format
        });
        const delta = new Date(value).getTime() - Date.now();
        for (let unit of UNITS) {
            const amount = Math.ceil(delta / unit.milliseconds);
            if (amount === 0) {
                continue;
            }
            return formatter.format(amount, unit.name);
        }
        return formatter.format(0, 'seconds');
    }
    Time.formatHuman = formatHuman;
    /**
     * Convenient helper to convert a timestring to a date format.
     *
     * @param value - The date timestring or date object.
     *
     * @returns A formatted date.
     */
    function format(value) {
        const lang = document.documentElement.lang || 'en';
        const formatter = new Intl.DateTimeFormat(lang, {
            dateStyle: 'short',
            timeStyle: 'short'
        });
        return formatter.format(new Date(value));
    }
    Time.format = format;
})(Time || (exports.Time = Time = {}));
//# sourceMappingURL=time.js.map

/***/ }),

/***/ 1692:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.URLExt = void 0;
const path_1 = __webpack_require__(9942);
const url_parse_1 = __importDefault(__webpack_require__(2225));
/**
 * The namespace for URL-related functions.
 */
var URLExt;
(function (URLExt) {
    /**
     * Parse a url into a URL object.
     *
     * @param url - The URL string to parse.
     *
     * @returns A URL object.
     */
    function parse(url) {
        if (typeof document !== 'undefined' && document) {
            const a = document.createElement('a');
            a.href = url;
            return a;
        }
        return (0, url_parse_1.default)(url);
    }
    URLExt.parse = parse;
    /**
     * Parse URL and retrieve hostname
     *
     * @param url - The URL string to parse
     *
     * @returns a hostname string value
     */
    function getHostName(url) {
        return (0, url_parse_1.default)(url).hostname;
    }
    URLExt.getHostName = getHostName;
    function normalize(url) {
        return url && parse(url).toString();
    }
    URLExt.normalize = normalize;
    /**
     * Join a sequence of url components and normalizes as in node `path.join`.
     *
     * @param parts - The url components.
     *
     * @returns the joined url.
     */
    function join(...parts) {
        let u = (0, url_parse_1.default)(parts[0], {});
        // Schema-less URL can be only parsed as relative to a base URL
        // see https://github.com/unshiftio/url-parse/issues/219#issuecomment-1002219326
        const isSchemaLess = u.protocol === '' && u.slashes;
        if (isSchemaLess) {
            u = (0, url_parse_1.default)(parts[0], 'https:' + parts[0]);
        }
        const prefix = `${isSchemaLess ? '' : u.protocol}${u.slashes ? '//' : ''}${u.auth}${u.auth ? '@' : ''}${u.host}`;
        // If there was a prefix, then the first path must start at the root.
        const path = path_1.posix.join(`${!!prefix && u.pathname[0] !== '/' ? '/' : ''}${u.pathname}`, ...parts.slice(1));
        return `${prefix}${path === '.' ? '' : path}`;
    }
    URLExt.join = join;
    /**
     * Encode the components of a multi-segment url.
     *
     * @param url - The url to encode.
     *
     * @returns the encoded url.
     *
     * #### Notes
     * Preserves the `'/'` separators.
     * Should not include the base url, since all parts are escaped.
     */
    function encodeParts(url) {
        return join(...url.split('/').map(encodeURIComponent));
    }
    URLExt.encodeParts = encodeParts;
    /**
     * Return a serialized object string suitable for a query.
     *
     * @param value The source object.
     *
     * @returns an encoded url query.
     *
     * #### Notes
     * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).
     */
    function objectToQueryString(value) {
        const keys = Object.keys(value).filter(key => key.length > 0);
        if (!keys.length) {
            return '';
        }
        return ('?' +
            keys
                .map(key => {
                const content = encodeURIComponent(String(value[key]));
                return key + (content ? '=' + content : '');
            })
                .join('&'));
    }
    URLExt.objectToQueryString = objectToQueryString;
    /**
     * Return a parsed object that represents the values in a query string.
     */
    function queryStringToObject(value) {
        return value
            .replace(/^\?/, '')
            .split('&')
            .reduce((acc, val) => {
            const [key, value] = val.split('=');
            if (key.length > 0) {
                acc[key] = decodeURIComponent(value || '');
            }
            return acc;
        }, {});
    }
    URLExt.queryStringToObject = queryStringToObject;
    /**
     * Test whether the url is a local url.
     *
     * @param allowRoot - Whether the paths starting at Unix-style filesystem root (`/`) are permitted.
     *
     * #### Notes
     * This function returns `false` for any fully qualified url, including
     * `data:`, `file:`, and `//` protocol URLs.
     */
    function isLocal(url, allowRoot = false) {
        const { protocol } = parse(url);
        return ((!protocol || url.toLowerCase().indexOf(protocol) !== 0) &&
            (allowRoot ? url.indexOf('//') !== 0 : url.indexOf('/') !== 0));
    }
    URLExt.isLocal = isLocal;
})(URLExt || (exports.URLExt = URLExt = {}));
//# sourceMappingURL=url.js.map

/***/ }),

/***/ 3867:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BaseManager = void 0;
const signaling_1 = __webpack_require__(3992);
const serverconnection_1 = __webpack_require__(2920);
class BaseManager {
    constructor(options) {
        var _a;
        this._isDisposed = false;
        this._disposed = new signaling_1.Signal(this);
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * A signal emitted when the delegate is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * Test whether the delegate has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Whether the manager is active.
     */
    get isActive() {
        return true;
    }
    /**
     * Dispose of the delegate and invoke the callback function.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._disposed.emit(undefined);
        signaling_1.Signal.clearData(this);
    }
}
exports.BaseManager = BaseManager;
//# sourceMappingURL=basemanager.js.map

/***/ }),

/***/ 4219:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BuildManager = void 0;
const coreutils_1 = __webpack_require__(8925);
const serverconnection_1 = __webpack_require__(2920);
/**
 * The url for the lab build service.
 */
const BUILD_SETTINGS_URL = 'api/build';
/**
 * The build API service manager.
 */
class BuildManager {
    /**
     * Create a new setting manager.
     */
    constructor(options = {}) {
        var _a;
        this._url = '';
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();
        const { baseUrl, appUrl } = this.serverSettings;
        this._url = coreutils_1.URLExt.join(baseUrl, appUrl, BUILD_SETTINGS_URL);
    }
    /**
     * Test whether the build service is available.
     */
    get isAvailable() {
        return coreutils_1.PageConfig.getOption('buildAvailable').toLowerCase() === 'true';
    }
    /**
     * Test whether to check build status automatically.
     */
    get shouldCheck() {
        return coreutils_1.PageConfig.getOption('buildCheck').toLowerCase() === 'true';
    }
    /**
     * Get whether the application should be built.
     */
    getStatus() {
        const { _url, serverSettings } = this;
        const promise = serverconnection_1.ServerConnection.makeRequest(_url, {}, serverSettings);
        return promise
            .then(response => {
            if (response.status !== 200) {
                throw new serverconnection_1.ServerConnection.ResponseError(response);
            }
            return response.json();
        })
            .then(data => {
            if (typeof data.status !== 'string') {
                throw new Error('Invalid data');
            }
            if (typeof data.message !== 'string') {
                throw new Error('Invalid data');
            }
            return data;
        });
    }
    /**
     * Build the application.
     */
    build() {
        const { _url, serverSettings } = this;
        const init = { method: 'POST' };
        const promise = serverconnection_1.ServerConnection.makeRequest(_url, init, serverSettings);
        return promise.then(response => {
            if (response.status === 400) {
                throw new serverconnection_1.ServerConnection.ResponseError(response, 'Build aborted');
            }
            if (response.status !== 200) {
                const message = `Build failed with ${response.status}.

        If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').

        If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;
                throw new serverconnection_1.ServerConnection.ResponseError(response, message);
            }
        });
    }
    /**
     * Cancel an active build.
     */
    cancel() {
        const { _url, serverSettings } = this;
        const init = { method: 'DELETE' };
        const promise = serverconnection_1.ServerConnection.makeRequest(_url, init, serverSettings);
        return promise.then(response => {
            if (response.status !== 204) {
                throw new serverconnection_1.ServerConnection.ResponseError(response);
            }
        });
    }
}
exports.BuildManager = BuildManager;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 2170:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ConfigWithDefaults = exports.ConfigSection = void 0;
const coreutils_1 = __webpack_require__(8925);
const __1 = __webpack_require__(7883);
/**
 * The url for the config service.
 */
const SERVICE_CONFIG_URL = 'api/config';
/**
 * The namespace for ConfigSection statics.
 */
var ConfigSection;
(function (ConfigSection) {
    /**
     * Create a config section.
     *
     * @returns A Promise that is fulfilled with the config section is loaded.
     */
    function create(options) {
        const section = new DefaultConfigSection(options);
        return section.load().then(() => {
            return section;
        });
    }
    ConfigSection.create = create;
})(ConfigSection || (exports.ConfigSection = ConfigSection = {}));
/**
 * Implementation of the Configurable data section.
 */
class DefaultConfigSection {
    /**
     * Construct a new config section.
     */
    constructor(options) {
        var _a;
        this._url = 'unknown';
        const settings = (this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings());
        this._url = coreutils_1.URLExt.join(settings.baseUrl, SERVICE_CONFIG_URL, encodeURIComponent(options.name));
    }
    /**
     * Get the data for this section.
     */
    get data() {
        return this._data;
    }
    /**
     * Load the initial data for this section.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    async load() {
        const response = await __1.ServerConnection.makeRequest(this._url, {}, this.serverSettings);
        if (response.status !== 200) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        this._data = await response.json();
    }
    /**
     * Modify the stored config values.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * Updates the local data immediately, sends the change to the server,
     * and updates the local data with the response, and fulfils the promise
     * with that data.
     */
    async update(newdata) {
        this._data = { ...this._data, ...newdata };
        const init = {
            method: 'PATCH',
            body: JSON.stringify(newdata)
        };
        const response = await __1.ServerConnection.makeRequest(this._url, init, this.serverSettings);
        if (response.status !== 200) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        this._data = await response.json();
        return this._data;
    }
}
/**
 * Configurable object with defaults.
 */
class ConfigWithDefaults {
    /**
     * Create a new config with defaults.
     */
    constructor(options) {
        var _a, _b;
        this._className = '';
        this._section = options.section;
        this._defaults = (_a = options.defaults) !== null && _a !== void 0 ? _a : {};
        this._className = (_b = options.className) !== null && _b !== void 0 ? _b : '';
    }
    /**
     * Get data from the config section or fall back to defaults.
     */
    get(key) {
        const data = this._classData();
        return key in data ? data[key] : this._defaults[key];
    }
    /**
     * Set a config value.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * Sends the update to the server, and changes our local copy of the data
     * immediately.
     */
    set(key, value) {
        const d = {};
        d[key] = value;
        if (this._className) {
            const d2 = {};
            d2[this._className] = d;
            return this._section.update(d2);
        }
        else {
            return this._section.update(d);
        }
    }
    /**
     * Get data from the Section with our classname, if available.
     *
     * #### Notes
     * If we have no classname, get all of the data in the Section
     */
    _classData() {
        const data = this._section.data;
        if (this._className && this._className in data) {
            return data[this._className];
        }
        return data;
    }
}
exports.ConfigWithDefaults = ConfigWithDefaults;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 8790:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Drive = exports.ContentsManager = exports.Contents = void 0;
const coreutils_1 = __webpack_require__(8925);
const signaling_1 = __webpack_require__(3992);
const __1 = __webpack_require__(7883);
const validate = __importStar(__webpack_require__(2706));
/**
 * The url for the default drive service.
 */
const SERVICE_DRIVE_URL = 'api/contents';
/**
 * The url for the file access.
 */
const FILES_URL = 'files';
/**
 * A namespace for contents interfaces.
 */
var Contents;
(function (Contents) {
    /**
     * Validates an IModel, throwing an error if it does not pass.
     */
    function validateContentsModel(contents) {
        validate.validateContentsModel(contents);
    }
    Contents.validateContentsModel = validateContentsModel;
    /**
     * Validates an ICheckpointModel, throwing an error if it does not pass.
     */
    function validateCheckpointModel(checkpoint) {
        validate.validateCheckpointModel(checkpoint);
    }
    Contents.validateCheckpointModel = validateCheckpointModel;
})(Contents || (exports.Contents = Contents = {}));
/**
 * A contents manager that passes file operations to the server.
 * Multiple servers implementing the `IDrive` interface can be
 * attached to the contents manager, so that the same session can
 * perform file operations on multiple backends.
 *
 * This includes checkpointing with the normal file operations.
 */
class ContentsManager {
    /**
     * Construct a new contents manager object.
     *
     * @param options - The options used to initialize the object.
     */
    constructor(options = {}) {
        var _a, _b;
        this._isDisposed = false;
        this._additionalDrives = new Map();
        this._fileChanged = new signaling_1.Signal(this);
        const serverSettings = (this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings());
        this._defaultDrive = (_b = options.defaultDrive) !== null && _b !== void 0 ? _b : new Drive({ serverSettings });
        this._defaultDrive.fileChanged.connect(this._onFileChanged, this);
    }
    /**
     * A signal emitted when a file operation takes place.
     */
    get fileChanged() {
        return this._fileChanged;
    }
    /**
     * Test whether the manager has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Add an `IDrive` to the manager.
     */
    addDrive(drive) {
        this._additionalDrives.set(drive.name, drive);
        drive.fileChanged.connect(this._onFileChanged, this);
    }
    /**
     * Given a path, get a shared model factory from the
     * relevant backend. Returns `null` if the backend
     * does not provide one.
     */
    getSharedModelFactory(path) {
        var _a;
        const [drive] = this._driveForPath(path);
        return (_a = drive === null || drive === void 0 ? void 0 : drive.sharedModelFactory) !== null && _a !== void 0 ? _a : null;
    }
    /**
     * Given a path of the form `drive:local/portion/of/it.txt`
     * get the local part of it.
     *
     * @param path the path.
     *
     * @returns The local part of the path.
     */
    localPath(path) {
        const parts = path.split('/');
        const firstParts = parts[0].split(':');
        if (firstParts.length === 1 || !this._additionalDrives.has(firstParts[0])) {
            return coreutils_1.PathExt.removeSlash(path);
        }
        return coreutils_1.PathExt.join(firstParts.slice(1).join(':'), ...parts.slice(1));
    }
    /**
     * Normalize a global path. Reduces '..' and '.' parts, and removes
     * leading slashes from the local part of the path, while retaining
     * the drive name if it exists.
     *
     * @param path the path.
     *
     * @returns The normalized path.
     */
    normalize(path) {
        const parts = path.split(':');
        if (parts.length === 1) {
            return coreutils_1.PathExt.normalize(path);
        }
        return `${parts[0]}:${coreutils_1.PathExt.normalize(parts.slice(1).join(':'))}`;
    }
    /**
     * Resolve a global path, starting from the root path. Behaves like
     * posix-path.resolve, with 3 differences:
     *  - will never prepend cwd
     *  - if root has a drive name, the result is prefixed with "<drive>:"
     *  - before adding drive name, leading slashes are removed
     *
     * @param path the path.
     *
     * @returns The normalized path.
     */
    resolvePath(root, path) {
        const driveName = this.driveName(root);
        const localPath = this.localPath(root);
        const resolved = coreutils_1.PathExt.resolve('/', localPath, path);
        return driveName ? `${driveName}:${resolved}` : resolved;
    }
    /**
     * Given a path of the form `drive:local/portion/of/it.txt`
     * get the name of the drive. If the path is missing
     * a drive portion, returns an empty string.
     *
     * @param path the path.
     *
     * @returns The drive name for the path, or the empty string.
     */
    driveName(path) {
        const parts = path.split('/');
        const firstParts = parts[0].split(':');
        if (firstParts.length === 1) {
            return '';
        }
        if (this._additionalDrives.has(firstParts[0])) {
            return firstParts[0];
        }
        return '';
    }
    /**
     * Get a file or directory.
     *
     * @param path The path to the file.
     *
     * @param options The options used to fetch the file.
     *
     * @returns A promise which resolves with the file content.
     */
    get(path, options) {
        const [drive, localPath] = this._driveForPath(path);
        return drive.get(localPath, options).then(contentsModel => {
            const listing = [];
            if (contentsModel.type === 'directory' && contentsModel.content) {
                for (const item of contentsModel.content) {
                    listing.push({ ...item, path: this._toGlobalPath(drive, item.path) });
                }
                return {
                    ...contentsModel,
                    path: this._toGlobalPath(drive, localPath),
                    content: listing,
                    serverPath: contentsModel.path
                };
            }
            else {
                return {
                    ...contentsModel,
                    path: this._toGlobalPath(drive, localPath),
                    serverPath: contentsModel.path
                };
            }
        });
    }
    /**
     * Get an encoded download url given a file path.
     *
     * @param path - An absolute POSIX file path on the server.
     *
     * #### Notes
     * It is expected that the path contains no relative paths.
     *
     * The returned URL may include a query parameter.
     */
    getDownloadUrl(path) {
        const [drive, localPath] = this._driveForPath(path);
        return drive.getDownloadUrl(localPath);
    }
    /**
     * Create a new untitled file or directory in the specified directory path.
     *
     * @param options The options used to create the file.
     *
     * @returns A promise which resolves with the created file content when the
     *    file is created.
     */
    newUntitled(options = {}) {
        if (options.path) {
            const globalPath = this.normalize(options.path);
            const [drive, localPath] = this._driveForPath(globalPath);
            return drive
                .newUntitled({ ...options, path: localPath })
                .then(contentsModel => {
                return {
                    ...contentsModel,
                    path: coreutils_1.PathExt.join(globalPath, contentsModel.name),
                    serverPath: contentsModel.path
                };
            });
        }
        else {
            return this._defaultDrive.newUntitled(options);
        }
    }
    /**
     * Delete a file.
     *
     * @param path - The path to the file.
     *
     * @returns A promise which resolves when the file is deleted.
     */
    delete(path) {
        const [drive, localPath] = this._driveForPath(path);
        return drive.delete(localPath);
    }
    /**
     * Rename a file or directory.
     *
     * @param path - The original file path.
     *
     * @param newPath - The new file path.
     *
     * @returns A promise which resolves with the new file contents model when
     *   the file is renamed.
     */
    rename(path, newPath) {
        const [drive1, path1] = this._driveForPath(path);
        const [drive2, path2] = this._driveForPath(newPath);
        if (drive1 !== drive2) {
            throw Error('ContentsManager: renaming files must occur within a Drive');
        }
        return drive1.rename(path1, path2).then(contentsModel => {
            return {
                ...contentsModel,
                path: this._toGlobalPath(drive1, path2),
                serverPath: contentsModel.path
            };
        });
    }
    /**
     * Save a file.
     *
     * @param path - The desired file path.
     *
     * @param options - Optional overrides to the model.
     *
     * @returns A promise which resolves with the file content model when the
     *   file is saved.
     *
     * #### Notes
     * Ensure that `model.content` is populated for the file.
     */
    save(path, options = {}) {
        const globalPath = this.normalize(path);
        const [drive, localPath] = this._driveForPath(path);
        return drive
            .save(localPath, { ...options, path: localPath })
            .then(contentsModel => {
            return {
                ...contentsModel,
                path: globalPath,
                serverPath: contentsModel.path
            };
        });
    }
    /**
     * Copy a file into a given directory.
     *
     * @param path - The original file path.
     *
     * @param toDir - The destination directory path.
     *
     * @returns A promise which resolves with the new contents model when the
     *  file is copied.
     *
     * #### Notes
     * The server will select the name of the copied file.
     */
    copy(fromFile, toDir) {
        const [drive1, path1] = this._driveForPath(fromFile);
        const [drive2, path2] = this._driveForPath(toDir);
        if (drive1 === drive2) {
            return drive1.copy(path1, path2).then(contentsModel => {
                return {
                    ...contentsModel,
                    path: this._toGlobalPath(drive1, contentsModel.path),
                    serverPath: contentsModel.path
                };
            });
        }
        else {
            throw Error('Copying files between drives is not currently implemented');
        }
    }
    /**
     * Create a checkpoint for a file.
     *
     * @param path - The path of the file.
     *
     * @returns A promise which resolves with the new checkpoint model when the
     *   checkpoint is created.
     */
    createCheckpoint(path) {
        const [drive, localPath] = this._driveForPath(path);
        return drive.createCheckpoint(localPath);
    }
    /**
     * List available checkpoints for a file.
     *
     * @param path - The path of the file.
     *
     * @returns A promise which resolves with a list of checkpoint models for
     *    the file.
     */
    listCheckpoints(path) {
        const [drive, localPath] = this._driveForPath(path);
        return drive.listCheckpoints(localPath);
    }
    /**
     * Restore a file to a known checkpoint state.
     *
     * @param path - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to restore.
     *
     * @returns A promise which resolves when the checkpoint is restored.
     */
    restoreCheckpoint(path, checkpointID) {
        const [drive, localPath] = this._driveForPath(path);
        return drive.restoreCheckpoint(localPath, checkpointID);
    }
    /**
     * Delete a checkpoint for a file.
     *
     * @param path - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to delete.
     *
     * @returns A promise which resolves when the checkpoint is deleted.
     */
    deleteCheckpoint(path, checkpointID) {
        const [drive, localPath] = this._driveForPath(path);
        return drive.deleteCheckpoint(localPath, checkpointID);
    }
    /**
     * Given a drive and a local path, construct a fully qualified
     * path. The inverse of `_driveForPath`.
     *
     * @param drive an `IDrive`.
     *
     * @param localPath the local path on the drive.
     *
     * @returns the fully qualified path.
     */
    _toGlobalPath(drive, localPath) {
        if (drive === this._defaultDrive) {
            return coreutils_1.PathExt.removeSlash(localPath);
        }
        else {
            return `${drive.name}:${coreutils_1.PathExt.removeSlash(localPath)}`;
        }
    }
    /**
     * Given a path, get the `IDrive to which it refers,
     * where the path satisfies the pattern
     * `'driveName:path/to/file'`. If there is no `driveName`
     * prepended to the path, it returns the default drive.
     *
     * @param path a path to a file.
     *
     * @returns A tuple containing an `IDrive` object for the path,
     * and a local path for that drive.
     */
    _driveForPath(path) {
        const driveName = this.driveName(path);
        const localPath = this.localPath(path);
        if (driveName) {
            return [this._additionalDrives.get(driveName), localPath];
        }
        else {
            return [this._defaultDrive, localPath];
        }
    }
    /**
     * Respond to fileChanged signals from the drives attached to
     * the manager. This prepends the drive name to the path if necessary,
     * and then forwards the signal.
     */
    _onFileChanged(sender, args) {
        var _a, _b;
        if (sender === this._defaultDrive) {
            this._fileChanged.emit(args);
        }
        else {
            let newValue = null;
            let oldValue = null;
            if ((_a = args.newValue) === null || _a === void 0 ? void 0 : _a.path) {
                newValue = {
                    ...args.newValue,
                    path: this._toGlobalPath(sender, args.newValue.path)
                };
            }
            if ((_b = args.oldValue) === null || _b === void 0 ? void 0 : _b.path) {
                oldValue = {
                    ...args.oldValue,
                    path: this._toGlobalPath(sender, args.oldValue.path)
                };
            }
            this._fileChanged.emit({
                type: args.type,
                newValue,
                oldValue
            });
        }
    }
}
exports.ContentsManager = ContentsManager;
/**
 * A default implementation for an `IDrive`, talking to the
 * server using the Jupyter REST API.
 */
class Drive {
    /**
     * Construct a new contents manager object.
     *
     * @param options - The options used to initialize the object.
     */
    constructor(options = {}) {
        var _a, _b, _c;
        this._isDisposed = false;
        this._fileChanged = new signaling_1.Signal(this);
        this.name = (_a = options.name) !== null && _a !== void 0 ? _a : 'Default';
        this._apiEndpoint = (_b = options.apiEndpoint) !== null && _b !== void 0 ? _b : SERVICE_DRIVE_URL;
        this.serverSettings =
            (_c = options.serverSettings) !== null && _c !== void 0 ? _c : __1.ServerConnection.makeSettings();
    }
    /**
     * A signal emitted when a file operation takes place.
     */
    get fileChanged() {
        return this._fileChanged;
    }
    /**
     * Test whether the manager has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
    }
    /**
     * Get a file or directory.
     *
     * @param localPath The path to the file.
     *
     * @param options The options used to fetch the file.
     *
     * @returns A promise which resolves with the file content.
     *
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.
     */
    async get(localPath, options) {
        let url = this._getUrl(localPath);
        if (options) {
            // The notebook type cannot take an format option.
            if (options.type === 'notebook') {
                delete options['format'];
            }
            const content = options.content ? '1' : '0';
            const hash = options.hash ? '1' : '0';
            const params = { ...options, content, hash };
            url += coreutils_1.URLExt.objectToQueryString(params);
        }
        const settings = this.serverSettings;
        const response = await __1.ServerConnection.makeRequest(url, {}, settings);
        if (response.status !== 200) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        validate.validateContentsModel(data);
        return data;
    }
    /**
     * Get an encoded download url given a file path.
     *
     * @param localPath - An absolute POSIX file path on the server.
     *
     * #### Notes
     * It is expected that the path contains no relative paths.
     *
     * The returned URL may include a query parameter.
     */
    getDownloadUrl(localPath) {
        const baseUrl = this.serverSettings.baseUrl;
        let url = coreutils_1.URLExt.join(baseUrl, FILES_URL, coreutils_1.URLExt.encodeParts(localPath));
        let cookie = '';
        try {
            cookie = document.cookie;
        }
        catch (e) {
            // e.g. SecurityError in case of CSP Sandbox
        }
        const xsrfTokenMatch = cookie.match('\\b_xsrf=([^;]*)\\b');
        if (xsrfTokenMatch) {
            const fullUrl = new URL(url);
            fullUrl.searchParams.append('_xsrf', xsrfTokenMatch[1]);
            url = fullUrl.toString();
        }
        return Promise.resolve(url);
    }
    /**
     * Create a new untitled file or directory in the specified directory path.
     *
     * @param options The options used to create the file.
     *
     * @returns A promise which resolves with the created file content when the
     *    file is created.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.
     */
    async newUntitled(options = {}) {
        var _a;
        let body = '{}';
        if (options) {
            if (options.ext) {
                options.ext = Private.normalizeExtension(options.ext);
            }
            body = JSON.stringify(options);
        }
        const settings = this.serverSettings;
        const url = this._getUrl((_a = options.path) !== null && _a !== void 0 ? _a : '');
        const init = {
            method: 'POST',
            body
        };
        const response = await __1.ServerConnection.makeRequest(url, init, settings);
        if (response.status !== 201) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        validate.validateContentsModel(data);
        this._fileChanged.emit({
            type: 'new',
            oldValue: null,
            newValue: data
        });
        return data;
    }
    /**
     * Delete a file.
     *
     * @param localPath - The path to the file.
     *
     * @returns A promise which resolves when the file is deleted.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).
     */
    async delete(localPath) {
        const url = this._getUrl(localPath);
        const settings = this.serverSettings;
        const init = { method: 'DELETE' };
        const response = await __1.ServerConnection.makeRequest(url, init, settings);
        // TODO: update IPEP27 to specify errors more precisely, so
        // that error types can be detected here with certainty.
        if (response.status !== 204) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        this._fileChanged.emit({
            type: 'delete',
            oldValue: { path: localPath },
            newValue: null
        });
    }
    /**
     * Rename a file or directory.
     *
     * @param oldLocalPath - The original file path.
     *
     * @param newLocalPath - The new file path.
     *
     * @returns A promise which resolves with the new file contents model when
     *   the file is renamed.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.
     */
    async rename(oldLocalPath, newLocalPath) {
        const settings = this.serverSettings;
        const url = this._getUrl(oldLocalPath);
        const init = {
            method: 'PATCH',
            body: JSON.stringify({ path: newLocalPath })
        };
        const response = await __1.ServerConnection.makeRequest(url, init, settings);
        if (response.status !== 200) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        validate.validateContentsModel(data);
        this._fileChanged.emit({
            type: 'rename',
            oldValue: { path: oldLocalPath },
            newValue: data
        });
        return data;
    }
    /**
     * Save a file.
     *
     * @param localPath - The desired file path.
     *
     * @param options - Optional overrides to the model.
     *
     * @returns A promise which resolves with the file content model when the
     *   file is saved.
     *
     * #### Notes
     * Ensure that `model.content` is populated for the file.
     *
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.
     */
    async save(localPath, options = {}) {
        const settings = this.serverSettings;
        const url = this._getUrl(localPath);
        const init = {
            method: 'PUT',
            body: JSON.stringify(options)
        };
        const response = await __1.ServerConnection.makeRequest(url, init, settings);
        // will return 200 for an existing file and 201 for a new file
        if (response.status !== 200 && response.status !== 201) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        validate.validateContentsModel(data);
        this._fileChanged.emit({
            type: 'save',
            oldValue: null,
            newValue: data
        });
        return data;
    }
    /**
     * Copy a file into a given directory.
     *
     * @param localPath - The original file path.
     *
     * @param toDir - The destination directory path.
     *
     * @returns A promise which resolves with the new contents model when the
     *  file is copied.
     *
     * #### Notes
     * The server will select the name of the copied file.
     *
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.
     */
    async copy(fromFile, toDir) {
        const settings = this.serverSettings;
        const url = this._getUrl(toDir);
        const init = {
            method: 'POST',
            body: JSON.stringify({ copy_from: fromFile })
        };
        const response = await __1.ServerConnection.makeRequest(url, init, settings);
        if (response.status !== 201) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        validate.validateContentsModel(data);
        this._fileChanged.emit({
            type: 'new',
            oldValue: null,
            newValue: data
        });
        return data;
    }
    /**
     * Create a checkpoint for a file.
     *
     * @param localPath - The path of the file.
     *
     * @returns A promise which resolves with the new checkpoint model when the
     *   checkpoint is created.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.
     */
    async createCheckpoint(localPath) {
        const url = this._getUrl(localPath, 'checkpoints');
        const init = { method: 'POST' };
        const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);
        if (response.status !== 201) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        validate.validateCheckpointModel(data);
        return data;
    }
    /**
     * List available checkpoints for a file.
     *
     * @param localPath - The path of the file.
     *
     * @returns A promise which resolves with a list of checkpoint models for
     *    the file.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.
     */
    async listCheckpoints(localPath) {
        const url = this._getUrl(localPath, 'checkpoints');
        const response = await __1.ServerConnection.makeRequest(url, {}, this.serverSettings);
        if (response.status !== 200) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        if (!Array.isArray(data)) {
            throw new Error('Invalid Checkpoint list');
        }
        for (let i = 0; i < data.length; i++) {
            validate.validateCheckpointModel(data[i]);
        }
        return data;
    }
    /**
     * Restore a file to a known checkpoint state.
     *
     * @param localPath - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to restore.
     *
     * @returns A promise which resolves when the checkpoint is restored.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).
     */
    async restoreCheckpoint(localPath, checkpointID) {
        const url = this._getUrl(localPath, 'checkpoints', checkpointID);
        const init = { method: 'POST' };
        const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);
        if (response.status !== 204) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
    }
    /**
     * Delete a checkpoint for a file.
     *
     * @param localPath - The path of the file.
     *
     * @param checkpointID - The id of the checkpoint to delete.
     *
     * @returns A promise which resolves when the checkpoint is deleted.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).
     */
    async deleteCheckpoint(localPath, checkpointID) {
        const url = this._getUrl(localPath, 'checkpoints', checkpointID);
        const init = { method: 'DELETE' };
        const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);
        if (response.status !== 204) {
            const err = await __1.ServerConnection.ResponseError.create(response);
            throw err;
        }
    }
    /**
     * Get a REST url for a file given a path.
     */
    _getUrl(...args) {
        const parts = args.map(path => coreutils_1.URLExt.encodeParts(path));
        const baseUrl = this.serverSettings.baseUrl;
        return coreutils_1.URLExt.join(baseUrl, this._apiEndpoint, ...parts);
    }
}
exports.Drive = Drive;
/**
 * A namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Normalize a file extension to be of the type `'.foo'`.
     *
     * Adds a leading dot if not present and converts to lower case.
     */
    function normalizeExtension(extension) {
        if (extension.length > 0 && extension.indexOf('.') !== 0) {
            extension = `.${extension}`;
        }
        return extension;
    }
    Private.normalizeExtension = normalizeExtension;
})(Private || (Private = {}));
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 2706:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateCheckpointModel = exports.validateContentsModel = void 0;
const validate_1 = __webpack_require__(7441);
/**
 * Validate an `Contents.IModel` object.
 */
function validateContentsModel(model) {
    (0, validate_1.validateProperty)(model, 'name', 'string');
    (0, validate_1.validateProperty)(model, 'path', 'string');
    (0, validate_1.validateProperty)(model, 'type', 'string');
    (0, validate_1.validateProperty)(model, 'created', 'string');
    (0, validate_1.validateProperty)(model, 'last_modified', 'string');
    (0, validate_1.validateProperty)(model, 'mimetype', 'object');
    (0, validate_1.validateProperty)(model, 'content', 'object');
    (0, validate_1.validateProperty)(model, 'format', 'object');
}
exports.validateContentsModel = validateContentsModel;
/**
 * Validate an `Contents.ICheckpointModel` object.
 */
function validateCheckpointModel(model) {
    (0, validate_1.validateProperty)(model, 'id', 'string');
    (0, validate_1.validateProperty)(model, 'last_modified', 'string');
}
exports.validateCheckpointModel = validateCheckpointModel;
//# sourceMappingURL=validate.js.map

/***/ }),

/***/ 9480:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.EventManager = void 0;
const coreutils_1 = __webpack_require__(8925);
const polling_1 = __webpack_require__(6049);
const signaling_1 = __webpack_require__(3992);
const serverconnection_1 = __webpack_require__(2920);
/**
 * The url for the jupyter-server events service.
 */
const SERVICE_EVENTS_URL = 'api/events';
/**
 * The events API service manager.
 */
class EventManager {
    /**
     * Create a new event manager.
     */
    constructor(options = {}) {
        var _a;
        this._socket = null;
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();
        // If subscription fails, the poll attempts to reconnect and backs off.
        this._poll = new polling_1.Poll({ factory: () => this._subscribe() });
        this._stream = new signaling_1.Stream(this);
        // Subscribe to the events socket.
        void this._poll.start();
    }
    /**
     * Whether the event manager is disposed.
     */
    get isDisposed() {
        return this._poll.isDisposed;
    }
    /**
     * An event stream that emits and yields each new event.
     */
    get stream() {
        return this._stream;
    }
    /**
     * Dispose the event manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        // Clean up poll.
        this._poll.dispose();
        // Clean up socket.
        const socket = this._socket;
        if (socket) {
            this._socket = null;
            socket.onopen = () => undefined;
            socket.onerror = () => undefined;
            socket.onmessage = () => undefined;
            socket.onclose = () => undefined;
            socket.close();
        }
        // Clean up stream.
        signaling_1.Signal.clearData(this);
        this._stream.stop();
    }
    /**
     * Post an event request to be emitted by the event bus.
     */
    async emit(event) {
        const { serverSettings } = this;
        const { baseUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const url = coreutils_1.URLExt.join(baseUrl, SERVICE_EVENTS_URL);
        const init = { body: JSON.stringify(event), method: 'POST' };
        const response = await makeRequest(url, init, serverSettings);
        if (response.status !== 204) {
            throw new ResponseError(response);
        }
    }
    /**
     * Subscribe to event bus emissions.
     */
    _subscribe() {
        return new Promise((_, reject) => {
            if (this.isDisposed) {
                return;
            }
            const { appendToken, token, WebSocket, wsUrl } = this.serverSettings;
            let url = coreutils_1.URLExt.join(wsUrl, SERVICE_EVENTS_URL, 'subscribe');
            if (appendToken && token !== '') {
                url += `?token=${encodeURIComponent(token)}`;
            }
            const socket = (this._socket = new WebSocket(url));
            const stream = this._stream;
            socket.onclose = () => reject(new Error('EventManager socket closed'));
            socket.onmessage = msg => msg.data && stream.emit(JSON.parse(msg.data));
        });
    }
}
exports.EventManager = EventManager;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 7883:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/**
 * @packageDocumentation
 * @module services
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
__exportStar(__webpack_require__(3867), exports);
__exportStar(__webpack_require__(2170), exports);
__exportStar(__webpack_require__(8790), exports);
__exportStar(__webpack_require__(9480), exports);
__exportStar(__webpack_require__(973), exports);
__exportStar(__webpack_require__(2946), exports);
__exportStar(__webpack_require__(9740), exports);
__exportStar(__webpack_require__(2920), exports);
__exportStar(__webpack_require__(7668), exports);
__exportStar(__webpack_require__(7780), exports);
__exportStar(__webpack_require__(9040), exports);
__exportStar(__webpack_require__(9191), exports);
__exportStar(__webpack_require__(8053), exports);
__exportStar(__webpack_require__(8683), exports);
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 7489:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CommHandler = void 0;
const disposable_1 = __webpack_require__(7556);
const KernelMessage = __importStar(__webpack_require__(9909));
/**
 * Comm channel handler.
 */
class CommHandler extends disposable_1.DisposableDelegate {
    /**
     * Construct a new comm channel.
     */
    constructor(target, id, kernel, disposeCb) {
        super(disposeCb);
        this._target = '';
        this._id = '';
        this._id = id;
        this._target = target;
        this._kernel = kernel;
    }
    /**
     * The unique id for the comm channel.
     */
    get commId() {
        return this._id;
    }
    /**
     * The target name for the comm channel.
     */
    get targetName() {
        return this._target;
    }
    /**
     * Get the callback for a comm close event.
     *
     * #### Notes
     * This is called when the comm is closed from either the server or client.
     *
     * **See also:** [[ICommClose]], [[close]]
     */
    get onClose() {
        return this._onClose;
    }
    /**
     * Set the callback for a comm close event.
     *
     * #### Notes
     * This is called when the comm is closed from either the server or client. If
     * the function returns a promise, and the kernel was closed from the server,
     * kernel message processing will pause until the returned promise is
     * fulfilled.
     *
     * **See also:** [[close]]
     */
    set onClose(cb) {
        this._onClose = cb;
    }
    /**
     * Get the callback for a comm message received event.
     */
    get onMsg() {
        return this._onMsg;
    }
    /**
     * Set the callback for a comm message received event.
     *
     * #### Notes
     * This is called when a comm message is received. If the function returns a
     * promise, kernel message processing will pause until it is fulfilled.
     */
    set onMsg(cb) {
        this._onMsg = cb;
    }
    /**
     * Open a comm with optional data and metadata.
     *
     * #### Notes
     * This sends a `comm_open` message to the server.
     *
     * **See also:** [[ICommOpen]]
     */
    open(data, metadata, buffers = []) {
        if (this.isDisposed || this._kernel.isDisposed) {
            throw new Error('Cannot open');
        }
        const msg = KernelMessage.createMessage({
            msgType: 'comm_open',
            channel: 'shell',
            username: this._kernel.username,
            session: this._kernel.clientId,
            content: {
                comm_id: this._id,
                target_name: this._target,
                data: data !== null && data !== void 0 ? data : {}
            },
            metadata,
            buffers
        });
        return this._kernel.sendShellMessage(msg, false, true);
    }
    /**
     * Send a `comm_msg` message to the kernel.
     *
     * #### Notes
     * This is a no-op if the comm has been closed.
     *
     * **See also:** [[ICommMsg]]
     */
    send(data, metadata, buffers = [], disposeOnDone = true) {
        if (this.isDisposed || this._kernel.isDisposed) {
            throw new Error('Cannot send');
        }
        const msg = KernelMessage.createMessage({
            msgType: 'comm_msg',
            channel: 'shell',
            username: this._kernel.username,
            session: this._kernel.clientId,
            content: {
                comm_id: this._id,
                data: data
            },
            metadata,
            buffers
        });
        return this._kernel.sendShellMessage(msg, false, disposeOnDone);
    }
    /**
     * Close the comm.
     *
     * #### Notes
     * This will send a `comm_close` message to the kernel, and call the
     * `onClose` callback if set.
     *
     * This is a no-op if the comm is already closed.
     *
     * **See also:** [[ICommClose]], [[onClose]]
     */
    close(data, metadata, buffers = []) {
        if (this.isDisposed || this._kernel.isDisposed) {
            throw new Error('Cannot close');
        }
        const msg = KernelMessage.createMessage({
            msgType: 'comm_close',
            channel: 'shell',
            username: this._kernel.username,
            session: this._kernel.clientId,
            content: {
                comm_id: this._id,
                data: data !== null && data !== void 0 ? data : {}
            },
            metadata,
            buffers
        });
        const future = this._kernel.sendShellMessage(msg, false, true);
        const onClose = this._onClose;
        if (onClose) {
            const ioMsg = KernelMessage.createMessage({
                msgType: 'comm_close',
                channel: 'iopub',
                username: this._kernel.username,
                session: this._kernel.clientId,
                content: {
                    comm_id: this._id,
                    data: data !== null && data !== void 0 ? data : {}
                },
                metadata,
                buffers
            });
            // In the future, we may want to communicate back to the user the possible
            // promise returned from onClose.
            void onClose(ioMsg);
        }
        this.dispose();
        return future;
    }
}
exports.CommHandler = CommHandler;
//# sourceMappingURL=comm.js.map

/***/ }),

/***/ 2456:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.KernelConnection = void 0;
const coreutils_1 = __webpack_require__(8925);
const coreutils_2 = __webpack_require__(5764);
const signaling_1 = __webpack_require__(3992);
const __1 = __webpack_require__(7883);
const comm_1 = __webpack_require__(7489);
const KernelMessage = __importStar(__webpack_require__(9909));
const future_1 = __webpack_require__(134);
const validate = __importStar(__webpack_require__(5855));
const kernelspec_1 = __webpack_require__(2946);
const restapi = __importStar(__webpack_require__(8235));
const KERNEL_INFO_TIMEOUT = 3000;
const RESTARTING_KERNEL_SESSION = '_RESTARTING_';
const STARTING_KERNEL_SESSION = '';
/**
 * Implementation of the Kernel object.
 *
 * #### Notes
 * Messages from the server are handled in the order they were received and
 * asynchronously. Any message handler can return a promise, and message
 * handling will pause until the promise is fulfilled.
 */
class KernelConnection {
    /**
     * Construct a kernel object.
     */
    constructor(options) {
        var _a, _b, _c, _d;
        /**
         * Create the kernel websocket connection and add socket status handlers.
         */
        this._createSocket = (useProtocols = true) => {
            this._errorIfDisposed();
            // Make sure the socket is clear
            this._clearSocket();
            // Update the connection status to reflect opening a new connection.
            this._updateConnectionStatus('connecting');
            const settings = this.serverSettings;
            const partialUrl = coreutils_1.URLExt.join(settings.wsUrl, restapi.KERNEL_SERVICE_URL, encodeURIComponent(this._id));
            // Strip any authentication from the display string.
            const display = partialUrl.replace(/^((?:\w+:)?\/\/)(?:[^@\/]+@)/, '$1');
            console.debug(`Starting WebSocket: ${display}`);
            let url = coreutils_1.URLExt.join(partialUrl, 'channels?session_id=' + encodeURIComponent(this._clientId));
            // If token authentication is in use.
            const token = settings.token;
            if (settings.appendToken && token !== '') {
                url = url + `&token=${encodeURIComponent(token)}`;
            }
            // Try opening the websocket with our list of subprotocols.
            // If the server doesn't handle subprotocols,
            // the accepted protocol will be ''.
            // But we cannot send '' as a subprotocol, so if connection fails,
            // reconnect without subprotocols.
            const supportedProtocols = useProtocols ? this._supportedProtocols : [];
            this._ws = new settings.WebSocket(url, supportedProtocols);
            // Ensure incoming binary messages are not Blobs
            this._ws.binaryType = 'arraybuffer';
            let alreadyCalledOnclose = false;
            const getKernelModel = async (evt) => {
                var _a, _b;
                if (this._isDisposed) {
                    return;
                }
                this._reason = '';
                this._model = undefined;
                try {
                    const model = await restapi.getKernelModel(this._id, settings);
                    this._model = model;
                    if ((model === null || model === void 0 ? void 0 : model.execution_state) === 'dead') {
                        this._updateStatus('dead');
                    }
                    else {
                        this._onWSClose(evt);
                    }
                }
                catch (err) {
                    // Try again, if there is a network failure
                    // Handle network errors, as well as cases where we are on a
                    // JupyterHub and the server is not running. JupyterHub returns a
                    // 503 (<2.0) or 424 (>2.0) in that case.
                    if (err instanceof __1.ServerConnection.NetworkError ||
                        ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||
                        ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {
                        const timeout = Private.getRandomIntInclusive(10, 30) * 1e3;
                        setTimeout(getKernelModel, timeout, evt);
                    }
                    else {
                        this._reason = 'Kernel died unexpectedly';
                        this._updateStatus('dead');
                    }
                }
                return;
            };
            const earlyClose = async (evt) => {
                // If the websocket was closed early, that could mean
                // that the kernel is actually dead. Try getting
                // information about the kernel from the API call,
                // if that fails, then assume the kernel is dead,
                // otherwise just follow the typical websocket closed
                // protocol.
                if (alreadyCalledOnclose) {
                    return;
                }
                alreadyCalledOnclose = true;
                await getKernelModel(evt);
                return;
            };
            this._ws.onmessage = this._onWSMessage;
            this._ws.onopen = this._onWSOpen;
            this._ws.onclose = earlyClose;
            this._ws.onerror = earlyClose;
        };
        // Make websocket callbacks arrow functions so they bind `this`.
        /**
         * Handle a websocket open event.
         */
        this._onWSOpen = (evt) => {
            if (this._ws.protocol !== '' &&
                !this._supportedProtocols.includes(this._ws.protocol)) {
                console.log('Server selected unknown kernel wire protocol:', this._ws.protocol);
                this._updateStatus('dead');
                throw new Error(`Unknown kernel wire protocol:  ${this._ws.protocol}`);
            }
            // Remember the kernel wire protocol selected by the server.
            this._selectedProtocol = this._ws.protocol;
            this._ws.onclose = this._onWSClose;
            this._ws.onerror = this._onWSClose;
            this._updateConnectionStatus('connected');
        };
        /**
         * Handle a websocket message, validating and routing appropriately.
         */
        this._onWSMessage = (evt) => {
            // Notify immediately if there is an error with the message.
            let msg;
            try {
                msg = this.serverSettings.serializer.deserialize(evt.data, this._ws.protocol);
                validate.validateMessage(msg);
            }
            catch (error) {
                error.message = `Kernel message validation error: ${error.message}`;
                // We throw the error so that it bubbles up to the top, and displays the right stack.
                throw error;
            }
            // Update the current kernel session id
            this._kernelSession = msg.header.session;
            // Handle the message asynchronously, in the order received.
            this._msgChain = this._msgChain
                .then(() => {
                // Return so that any promises from handling a message are fulfilled
                // before proceeding to the next message.
                return this._handleMessage(msg);
            })
                .catch(error => {
                // Log any errors in handling the message, thus resetting the _msgChain
                // promise so we can process more messages.
                // Ignore the "Canceled" errors that are thrown during kernel dispose.
                if (error.message.startsWith('Canceled future for ')) {
                    console.error(error);
                }
            });
            // Emit the message receive signal
            this._anyMessage.emit({ msg, direction: 'recv' });
        };
        /**
         * Handle a websocket close event.
         */
        this._onWSClose = (evt) => {
            if (!this.isDisposed) {
                this._reconnect();
            }
        };
        this._id = '';
        this._name = '';
        this._status = 'unknown';
        this._connectionStatus = 'connecting';
        this._kernelSession = '';
        this._isDisposed = false;
        /**
         * Websocket to communicate with kernel.
         */
        this._ws = null;
        this._username = '';
        this._reconnectLimit = 7;
        this._reconnectAttempt = 0;
        this._reconnectTimeout = null;
        this._supportedProtocols = Object.values(KernelMessage.supportedKernelWebSocketProtocols);
        this._selectedProtocol = '';
        this._futures = new Map();
        this._comms = new Map();
        this._targetRegistry = Object.create(null);
        this._info = new coreutils_2.PromiseDelegate();
        this._pendingMessages = [];
        this._statusChanged = new signaling_1.Signal(this);
        this._connectionStatusChanged = new signaling_1.Signal(this);
        this._disposed = new signaling_1.Signal(this);
        this._iopubMessage = new signaling_1.Signal(this);
        this._anyMessage = new signaling_1.Signal(this);
        this._pendingInput = new signaling_1.Signal(this);
        this._unhandledMessage = new signaling_1.Signal(this);
        this._displayIdToParentIds = new Map();
        this._msgIdToDisplayIds = new Map();
        this._msgChain = Promise.resolve();
        this._hasPendingInput = false;
        this._reason = '';
        this._noOp = () => {
            /* no-op */
        };
        this._name = options.model.name;
        this._id = options.model.id;
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings();
        this._clientId = (_b = options.clientId) !== null && _b !== void 0 ? _b : coreutils_2.UUID.uuid4();
        this._username = (_c = options.username) !== null && _c !== void 0 ? _c : '';
        this.handleComms = (_d = options.handleComms) !== null && _d !== void 0 ? _d : true;
        this._createSocket();
    }
    get disposed() {
        return this._disposed;
    }
    /**
     * A signal emitted when the kernel status changes.
     */
    get statusChanged() {
        return this._statusChanged;
    }
    /**
     * A signal emitted when the kernel status changes.
     */
    get connectionStatusChanged() {
        return this._connectionStatusChanged;
    }
    /**
     * A signal emitted for iopub kernel messages.
     *
     * #### Notes
     * This signal is emitted after the iopub message is handled asynchronously.
     */
    get iopubMessage() {
        return this._iopubMessage;
    }
    /**
     * A signal emitted for unhandled kernel message.
     *
     * #### Notes
     * This signal is emitted for a message that was not handled. It is emitted
     * during the asynchronous message handling code.
     */
    get unhandledMessage() {
        return this._unhandledMessage;
    }
    /**
     * The kernel model
     */
    get model() {
        return (this._model || {
            id: this.id,
            name: this.name,
            reason: this._reason
        });
    }
    /**
     * A signal emitted for any kernel message.
     *
     * #### Notes
     * This signal is emitted when a message is received, before it is handled
     * asynchronously.
     *
     * This message is emitted when a message is queued for sending (either in
     * the websocket buffer, or our own pending message buffer). The message may
     * actually be sent across the wire at a later time.
     *
     * The message emitted in this signal should not be modified in any way.
     */
    get anyMessage() {
        return this._anyMessage;
    }
    /**
     * A signal emitted when a kernel has pending inputs from the user.
     */
    get pendingInput() {
        return this._pendingInput;
    }
    /**
     * The id of the server-side kernel.
     */
    get id() {
        return this._id;
    }
    /**
     * The name of the server-side kernel.
     */
    get name() {
        return this._name;
    }
    /**
     * The client username.
     */
    get username() {
        return this._username;
    }
    /**
     * The client unique id.
     */
    get clientId() {
        return this._clientId;
    }
    /**
     * The current status of the kernel.
     */
    get status() {
        return this._status;
    }
    /**
     * The current connection status of the kernel connection.
     */
    get connectionStatus() {
        return this._connectionStatus;
    }
    /**
     * Test whether the kernel has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * The cached kernel info.
     *
     * @returns A promise that resolves to the kernel info.
     */
    get info() {
        return this._info.promise;
    }
    /**
     * The kernel spec.
     *
     * @returns A promise that resolves to the kernel spec.
     */
    get spec() {
        if (this._specPromise) {
            return this._specPromise;
        }
        this._specPromise = kernelspec_1.KernelSpecAPI.getSpecs(this.serverSettings).then(specs => {
            return specs.kernelspecs[this._name];
        });
        return this._specPromise;
    }
    /**
     * Clone the current kernel with a new clientId.
     */
    clone(options = {}) {
        return new KernelConnection({
            model: this.model,
            username: this.username,
            serverSettings: this.serverSettings,
            // handleComms defaults to false since that is safer
            handleComms: false,
            ...options
        });
    }
    /**
     * Dispose of the resources held by the kernel.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._disposed.emit();
        this._updateConnectionStatus('disconnected');
        this._clearKernelState();
        this._pendingMessages = [];
        this._clearSocket();
        // Clear Lumino signals
        signaling_1.Signal.clearData(this);
    }
    /**
     * Send a shell message to the kernel.
     *
     * #### Notes
     * Send a message to the kernel's shell channel, yielding a future object
     * for accepting replies.
     *
     * If `expectReply` is given and `true`, the future is disposed when both a
     * shell reply and an idle status message are received. If `expectReply`
     * is not given or is `false`, the future is resolved when an idle status
     * message is received.
     * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
     * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
     *
     * All replies are validated as valid kernel messages.
     *
     * If the kernel status is `dead`, this will throw an error.
     */
    sendShellMessage(msg, expectReply = false, disposeOnDone = true) {
        return this._sendKernelShellControl(future_1.KernelShellFutureHandler, msg, expectReply, disposeOnDone);
    }
    /**
     * Send a control message to the kernel.
     *
     * #### Notes
     * Send a message to the kernel's control channel, yielding a future object
     * for accepting replies.
     *
     * If `expectReply` is given and `true`, the future is disposed when both a
     * control reply and an idle status message are received. If `expectReply`
     * is not given or is `false`, the future is resolved when an idle status
     * message is received.
     * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
     * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
     *
     * All replies are validated as valid kernel messages.
     *
     * If the kernel status is `dead`, this will throw an error.
     */
    sendControlMessage(msg, expectReply = false, disposeOnDone = true) {
        return this._sendKernelShellControl(future_1.KernelControlFutureHandler, msg, expectReply, disposeOnDone);
    }
    _sendKernelShellControl(ctor, msg, expectReply = false, disposeOnDone = true) {
        this._sendMessage(msg);
        this._anyMessage.emit({ msg, direction: 'send' });
        const future = new ctor(() => {
            const msgId = msg.header.msg_id;
            this._futures.delete(msgId);
            // Remove stored display id information.
            const displayIds = this._msgIdToDisplayIds.get(msgId);
            if (!displayIds) {
                return;
            }
            displayIds.forEach(displayId => {
                const msgIds = this._displayIdToParentIds.get(displayId);
                if (msgIds) {
                    const idx = msgIds.indexOf(msgId);
                    if (idx === -1) {
                        return;
                    }
                    if (msgIds.length === 1) {
                        this._displayIdToParentIds.delete(displayId);
                    }
                    else {
                        msgIds.splice(idx, 1);
                        this._displayIdToParentIds.set(displayId, msgIds);
                    }
                }
            });
            this._msgIdToDisplayIds.delete(msgId);
        }, msg, expectReply, disposeOnDone, this);
        this._futures.set(msg.header.msg_id, future);
        return future;
    }
    /**
     * Send a message on the websocket.
     *
     * If queue is true, queue the message for later sending if we cannot send
     * now. Otherwise throw an error.
     *
     * #### Notes
     * As an exception to the queueing, if we are sending a kernel_info_request
     * message while we think the kernel is restarting, we send the message
     * immediately without queueing. This is so that we can trigger a message
     * back, which will then clear the kernel restarting state.
     */
    _sendMessage(msg, queue = true) {
        if (this.status === 'dead') {
            throw new Error('Kernel is dead');
        }
        // If we have a kernel_info_request and we are starting or restarting, send the
        // kernel_info_request immediately if we can, and if not throw an error so
        // we can retry later. On restarting we do this because we must get at least one message
        // from the kernel to reset the kernel session (thus clearing the restart
        // status sentinel).
        if ((this._kernelSession === STARTING_KERNEL_SESSION ||
            this._kernelSession === RESTARTING_KERNEL_SESSION) &&
            KernelMessage.isInfoRequestMsg(msg)) {
            if (this.connectionStatus === 'connected') {
                this._ws.send(this.serverSettings.serializer.serialize(msg, this._ws.protocol));
                return;
            }
            else {
                throw new Error('Could not send message: status is not connected');
            }
        }
        // If there are pending messages, add to the queue so we keep messages in order
        if (queue && this._pendingMessages.length > 0) {
            this._pendingMessages.push(msg);
            return;
        }
        // Send if the ws allows it, otherwise queue the message.
        if (this.connectionStatus === 'connected' &&
            this._kernelSession !== RESTARTING_KERNEL_SESSION) {
            this._ws.send(this.serverSettings.serializer.serialize(msg, this._ws.protocol));
        }
        else if (queue) {
            this._pendingMessages.push(msg);
        }
        else {
            throw new Error('Could not send message');
        }
    }
    /**
     * Interrupt a kernel.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * It is assumed that the API call does not mutate the kernel id or name.
     *
     * The promise will be rejected if the kernel status is `Dead` or if the
     * request fails or the response is invalid.
     */
    async interrupt() {
        this.hasPendingInput = false;
        if (this.status === 'dead') {
            throw new Error('Kernel is dead');
        }
        return restapi.interruptKernel(this.id, this.serverSettings);
    }
    /**
     * Request a kernel restart.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels)
     * and validates the response model.
     *
     * Any existing Future or Comm objects are cleared once the kernel has
     * actually be restarted.
     *
     * The promise is fulfilled on a valid server response (after the kernel restarts)
     * and rejected otherwise.
     *
     * It is assumed that the API call does not mutate the kernel id or name.
     *
     * The promise will be rejected if the request fails or the response is
     * invalid.
     */
    async restart() {
        if (this.status === 'dead') {
            throw new Error('Kernel is dead');
        }
        this._updateStatus('restarting');
        this._clearKernelState();
        this._kernelSession = RESTARTING_KERNEL_SESSION;
        await restapi.restartKernel(this.id, this.serverSettings);
        // Reconnect to the kernel to address cases where kernel ports
        // have changed during the restart.
        await this.reconnect();
        this.hasPendingInput = false;
    }
    /**
     * Reconnect to a kernel.
     *
     * #### Notes
     * This may try multiple times to reconnect to a kernel, and will sever any
     * existing connection.
     */
    reconnect() {
        this._errorIfDisposed();
        const result = new coreutils_2.PromiseDelegate();
        // Set up a listener for the connection status changing, which accepts or
        // rejects after the retries are done.
        const fulfill = (sender, status) => {
            if (status === 'connected') {
                result.resolve();
                this.connectionStatusChanged.disconnect(fulfill, this);
            }
            else if (status === 'disconnected') {
                result.reject(new Error('Kernel connection disconnected'));
                this.connectionStatusChanged.disconnect(fulfill, this);
            }
        };
        this.connectionStatusChanged.connect(fulfill, this);
        // Reset the reconnect limit so we start the connection attempts fresh
        this._reconnectAttempt = 0;
        // Start the reconnection process, which will also clear any existing
        // connection.
        this._reconnect();
        // Return the promise that should resolve on connection or reject if the
        // retries don't work.
        return result.promise;
    }
    /**
     * Shutdown a kernel.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).
     *
     * The promise is fulfilled on a valid response and rejected otherwise.
     *
     * On a valid response, disposes this kernel connection.
     *
     * If the kernel is already `dead`, disposes this kernel connection without
     * a server request.
     */
    async shutdown() {
        if (this.status !== 'dead') {
            await restapi.shutdownKernel(this.id, this.serverSettings);
        }
        this.handleShutdown();
    }
    /**
     * Handles a kernel shutdown.
     *
     * #### Notes
     * This method should be called if we know from outside information that a
     * kernel is dead (for example, we cannot find the kernel model on the
     * server).
     */
    handleShutdown() {
        this._updateStatus('dead');
        this.dispose();
    }
    /**
     * Send a `kernel_info_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).
     *
     * Fulfills with the `kernel_info_response` content when the shell reply is
     * received and validated.
     */
    async requestKernelInfo() {
        const msg = KernelMessage.createMessage({
            msgType: 'kernel_info_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId,
            content: {}
        });
        let reply;
        try {
            reply = (await Private.handleShellMessage(this, msg));
        }
        catch (e) {
            // If we rejected because the future was disposed, ignore and return.
            if (this.isDisposed) {
                return;
            }
            else {
                throw e;
            }
        }
        this._errorIfDisposed();
        if (!reply) {
            return;
        }
        // Kernels sometimes do not include a status field on kernel_info_reply
        // messages, so set a default for now.
        // See https://github.com/jupyterlab/jupyterlab/issues/6760
        if (reply.content.status === undefined) {
            reply.content.status = 'ok';
        }
        if (reply.content.status !== 'ok') {
            this._info.reject('Kernel info reply errored');
            return reply;
        }
        this._info.resolve(reply.content);
        this._kernelSession = reply.header.session;
        return reply;
    }
    /**
     * Send a `complete_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).
     *
     * Fulfills with the `complete_reply` content when the shell reply is
     * received and validated.
     */
    requestComplete(content) {
        const msg = KernelMessage.createMessage({
            msgType: 'complete_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId,
            content
        });
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send an `inspect_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).
     *
     * Fulfills with the `inspect_reply` content when the shell reply is
     * received and validated.
     */
    requestInspect(content) {
        const msg = KernelMessage.createMessage({
            msgType: 'inspect_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId,
            content: content
        });
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send a `history_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).
     *
     * Fulfills with the `history_reply` content when the shell reply is
     * received and validated.
     */
    requestHistory(content) {
        const msg = KernelMessage.createMessage({
            msgType: 'history_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId,
            content
        });
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send an `execute_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).
     *
     * Future `onReply` is called with the `execute_reply` content when the
     * shell reply is received and validated. The future will resolve when
     * this message is received and the `idle` iopub status is received.
     * The future will also be disposed at this point unless `disposeOnDone`
     * is specified and `false`, in which case it is up to the caller to dispose
     * of the future.
     *
     * **See also:** [[IExecuteReply]]
     */
    requestExecute(content, disposeOnDone = true, metadata) {
        const defaults = {
            silent: false,
            store_history: true,
            user_expressions: {},
            allow_stdin: true,
            stop_on_error: false
        };
        const msg = KernelMessage.createMessage({
            msgType: 'execute_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId,
            content: { ...defaults, ...content },
            metadata
        });
        return this.sendShellMessage(msg, true, disposeOnDone);
    }
    /**
     * Send an experimental `debug_request` message.
     *
     * @hidden
     *
     * #### Notes
     * Debug messages are experimental messages that are not in the official
     * kernel message specification. As such, this function is *NOT* considered
     * part of the public API, and may change without notice.
     */
    requestDebug(content, disposeOnDone = true) {
        const msg = KernelMessage.createMessage({
            msgType: 'debug_request',
            channel: 'control',
            username: this._username,
            session: this._clientId,
            content
        });
        return this.sendControlMessage(msg, true, disposeOnDone);
    }
    /**
     * Send an `is_complete_request` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).
     *
     * Fulfills with the `is_complete_response` content when the shell reply is
     * received and validated.
     */
    requestIsComplete(content) {
        const msg = KernelMessage.createMessage({
            msgType: 'is_complete_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId,
            content
        });
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send a `comm_info_request` message.
     *
     * #### Notes
     * Fulfills with the `comm_info_reply` content when the shell reply is
     * received and validated.
     */
    requestCommInfo(content) {
        const msg = KernelMessage.createMessage({
            msgType: 'comm_info_request',
            channel: 'shell',
            username: this._username,
            session: this._clientId,
            content
        });
        return Private.handleShellMessage(this, msg);
    }
    /**
     * Send an `input_reply` message.
     *
     * #### Notes
     * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).
     */
    sendInputReply(content, parent_header) {
        const msg = KernelMessage.createMessage({
            msgType: 'input_reply',
            channel: 'stdin',
            username: this._username,
            session: this._clientId,
            content
        });
        msg.parent_header = parent_header;
        this._sendMessage(msg);
        this._anyMessage.emit({ msg, direction: 'send' });
        this.hasPendingInput = false;
    }
    /**
     * Create a new comm.
     *
     * #### Notes
     * If a client-side comm already exists with the given commId, an error is thrown.
     * If the kernel does not handle comms, an error is thrown.
     */
    createComm(targetName, commId = coreutils_2.UUID.uuid4()) {
        if (!this.handleComms) {
            throw new Error('Comms are disabled on this kernel connection');
        }
        if (this._comms.has(commId)) {
            throw new Error('Comm is already created');
        }
        const comm = new comm_1.CommHandler(targetName, commId, this, () => {
            this._unregisterComm(commId);
        });
        this._comms.set(commId, comm);
        return comm;
    }
    /**
     * Check if a comm exists.
     */
    hasComm(commId) {
        return this._comms.has(commId);
    }
    /**
     * Register a comm target handler.
     *
     * @param targetName - The name of the comm target.
     *
     * @param callback - The callback invoked for a comm open message.
     *
     * @returns A disposable used to unregister the comm target.
     *
     * #### Notes
     * Only one comm target can be registered to a target name at a time, an
     * existing callback for the same target name will be overridden.  A registered
     * comm target handler will take precedence over a comm which specifies a
     * `target_module`.
     *
     * If the callback returns a promise, kernel message processing will pause
     * until the returned promise is fulfilled.
     */
    registerCommTarget(targetName, callback) {
        if (!this.handleComms) {
            return;
        }
        this._targetRegistry[targetName] = callback;
    }
    /**
     * Remove a comm target handler.
     *
     * @param targetName - The name of the comm target to remove.
     *
     * @param callback - The callback to remove.
     *
     * #### Notes
     * The comm target is only removed if the callback argument matches.
     */
    removeCommTarget(targetName, callback) {
        if (!this.handleComms) {
            return;
        }
        if (!this.isDisposed && this._targetRegistry[targetName] === callback) {
            delete this._targetRegistry[targetName];
        }
    }
    /**
     * Register an IOPub message hook.
     *
     * @param msg_id - The parent_header message id the hook will intercept.
     *
     * @param hook - The callback invoked for the message.
     *
     * #### Notes
     * The IOPub hook system allows you to preempt the handlers for IOPub
     * messages that are responses to a given message id.
     *
     * The most recently registered hook is run first. A hook can return a
     * boolean or a promise to a boolean, in which case all kernel message
     * processing pauses until the promise is fulfilled. If a hook return value
     * resolves to false, any later hooks will not run and the function will
     * return a promise resolving to false. If a hook throws an error, the error
     * is logged to the console and the next hook is run. If a hook is
     * registered during the hook processing, it will not run until the next
     * message. If a hook is removed during the hook processing, it will be
     * deactivated immediately.
     *
     * See also [[IFuture.registerMessageHook]].
     */
    registerMessageHook(msgId, hook) {
        var _a;
        const future = (_a = this._futures) === null || _a === void 0 ? void 0 : _a.get(msgId);
        if (future) {
            future.registerMessageHook(hook);
        }
    }
    /**
     * Remove an IOPub message hook.
     *
     * @param msg_id - The parent_header message id the hook intercepted.
     *
     * @param hook - The callback invoked for the message.
     *
     */
    removeMessageHook(msgId, hook) {
        var _a;
        const future = (_a = this._futures) === null || _a === void 0 ? void 0 : _a.get(msgId);
        if (future) {
            future.removeMessageHook(hook);
        }
    }
    /**
     * Remove the input guard, if any.
     */
    removeInputGuard() {
        this.hasPendingInput = false;
    }
    /**
     * Handle a message with a display id.
     *
     * @returns Whether the message was handled.
     */
    async _handleDisplayId(displayId, msg) {
        var _a, _b;
        const msgId = msg.parent_header.msg_id;
        let parentIds = this._displayIdToParentIds.get(displayId);
        if (parentIds) {
            // We've seen it before, update existing outputs with same display_id
            // by handling display_data as update_display_data.
            const updateMsg = {
                header: coreutils_2.JSONExt.deepCopy(msg.header),
                parent_header: coreutils_2.JSONExt.deepCopy(msg.parent_header),
                metadata: coreutils_2.JSONExt.deepCopy(msg.metadata),
                content: coreutils_2.JSONExt.deepCopy(msg.content),
                channel: msg.channel,
                buffers: msg.buffers ? msg.buffers.slice() : []
            };
            updateMsg.header.msg_type = 'update_display_data';
            await Promise.all(parentIds.map(async (parentId) => {
                const future = this._futures && this._futures.get(parentId);
                if (future) {
                    await future.handleMsg(updateMsg);
                }
            }));
        }
        // We're done here if it's update_display.
        if (msg.header.msg_type === 'update_display_data') {
            // It's an update, don't proceed to the normal display.
            return true;
        }
        // Regular display_data with id, record it for future updating
        // in _displayIdToParentIds for future lookup.
        parentIds = (_a = this._displayIdToParentIds.get(displayId)) !== null && _a !== void 0 ? _a : [];
        if (parentIds.indexOf(msgId) === -1) {
            parentIds.push(msgId);
        }
        this._displayIdToParentIds.set(displayId, parentIds);
        // Add to our map of display ids for this message.
        const displayIds = (_b = this._msgIdToDisplayIds.get(msgId)) !== null && _b !== void 0 ? _b : [];
        if (displayIds.indexOf(msgId) === -1) {
            displayIds.push(msgId);
        }
        this._msgIdToDisplayIds.set(msgId, displayIds);
        // Let the message propagate to the intended recipient.
        return false;
    }
    /**
     * Forcefully clear the socket state.
     *
     * #### Notes
     * This will clear all socket state without calling any handlers and will
     * not update the connection status. If you call this method, you are
     * responsible for updating the connection status as needed and recreating
     * the socket if you plan to reconnect.
     */
    _clearSocket() {
        if (this._ws !== null) {
            // Clear the websocket event handlers and the socket itself.
            this._ws.onopen = this._noOp;
            this._ws.onclose = this._noOp;
            this._ws.onerror = this._noOp;
            this._ws.onmessage = this._noOp;
            this._ws.close();
            this._ws = null;
        }
    }
    /**
     * Handle status iopub messages from the kernel.
     */
    _updateStatus(status) {
        if (this._status === status || this._status === 'dead') {
            return;
        }
        this._status = status;
        Private.logKernelStatus(this);
        this._statusChanged.emit(status);
        if (status === 'dead') {
            this.dispose();
        }
    }
    /**
     * Send pending messages to the kernel.
     */
    _sendPending() {
        // We check to make sure we are still connected each time. For
        // example, if a websocket buffer overflows, it may close, so we should
        // stop sending messages.
        while (this.connectionStatus === 'connected' &&
            this._kernelSession !== RESTARTING_KERNEL_SESSION &&
            this._pendingMessages.length > 0) {
            this._sendMessage(this._pendingMessages[0], false);
            // We shift the message off the queue after the message is sent so that
            // if there is an exception, the message is still pending.
            this._pendingMessages.shift();
        }
    }
    /**
     * Clear the internal state.
     */
    _clearKernelState() {
        this._kernelSession = '';
        this._pendingMessages = [];
        this._futures.forEach(future => {
            future.dispose();
        });
        this._comms.forEach(comm => {
            comm.dispose();
        });
        this._msgChain = Promise.resolve();
        this._futures = new Map();
        this._comms = new Map();
        this._displayIdToParentIds.clear();
        this._msgIdToDisplayIds.clear();
    }
    /**
     * Check to make sure it is okay to proceed to handle a message.
     *
     * #### Notes
     * Because we handle messages asynchronously, before a message is handled the
     * kernel might be disposed or restarted (and have a different session id).
     * This function throws an error in each of these cases. This is meant to be
     * called at the start of an asynchronous message handler to cancel message
     * processing if the message no longer is valid.
     */
    _assertCurrentMessage(msg) {
        this._errorIfDisposed();
        if (msg.header.session !== this._kernelSession) {
            throw new Error(`Canceling handling of old message: ${msg.header.msg_type}`);
        }
    }
    /**
     * Handle a `comm_open` kernel message.
     */
    async _handleCommOpen(msg) {
        this._assertCurrentMessage(msg);
        const content = msg.content;
        const comm = new comm_1.CommHandler(content.target_name, content.comm_id, this, () => {
            this._unregisterComm(content.comm_id);
        });
        this._comms.set(content.comm_id, comm);
        try {
            const target = await Private.loadObject(content.target_name, content.target_module, this._targetRegistry);
            await target(comm, msg);
        }
        catch (e) {
            // Close the comm asynchronously. We cannot block message processing on
            // kernel messages to wait for another kernel message.
            comm.close();
            console.error('Exception opening new comm');
            throw e;
        }
    }
    /**
     * Handle 'comm_close' kernel message.
     */
    async _handleCommClose(msg) {
        this._assertCurrentMessage(msg);
        const content = msg.content;
        const comm = this._comms.get(content.comm_id);
        if (!comm) {
            console.error('Comm not found for comm id ' + content.comm_id);
            return;
        }
        this._unregisterComm(comm.commId);
        const onClose = comm.onClose;
        if (onClose) {
            // tslint:disable-next-line:await-promise
            await onClose(msg);
        }
        comm.dispose();
    }
    /**
     * Handle a 'comm_msg' kernel message.
     */
    async _handleCommMsg(msg) {
        this._assertCurrentMessage(msg);
        const content = msg.content;
        const comm = this._comms.get(content.comm_id);
        if (!comm) {
            return;
        }
        const onMsg = comm.onMsg;
        if (onMsg) {
            // tslint:disable-next-line:await-promise
            await onMsg(msg);
        }
    }
    /**
     * Unregister a comm instance.
     */
    _unregisterComm(commId) {
        this._comms.delete(commId);
    }
    /**
     * Handle connection status changes.
     */
    _updateConnectionStatus(connectionStatus) {
        if (this._connectionStatus === connectionStatus) {
            return;
        }
        this._connectionStatus = connectionStatus;
        // If we are not 'connecting', reset any reconnection attempts.
        if (connectionStatus !== 'connecting') {
            this._reconnectAttempt = 0;
            clearTimeout(this._reconnectTimeout);
        }
        if (this.status !== 'dead') {
            if (connectionStatus === 'connected') {
                let restarting = this._kernelSession === RESTARTING_KERNEL_SESSION;
                // Send a kernel info request to make sure we send at least one
                // message to get kernel status back. Always request kernel info
                // first, to get kernel status back and ensure iopub is fully
                // established. If we are restarting, this message will skip the queue
                // and be sent immediately.
                let p = this.requestKernelInfo();
                // Send any pending messages after the kernelInfo resolves, or after a
                // timeout as a failsafe.
                let sendPendingCalled = false;
                let sendPendingOnce = () => {
                    if (sendPendingCalled) {
                        return;
                    }
                    sendPendingCalled = true;
                    if (restarting && this._kernelSession === RESTARTING_KERNEL_SESSION) {
                        // We were restarting and a message didn't arrive to set the
                        // session, but we just assume the restart succeeded and send any
                        // pending messages.
                        // FIXME: it would be better to retry the kernel_info_request here
                        this._kernelSession = '';
                    }
                    clearTimeout(timeoutHandle);
                    if (this._pendingMessages.length > 0) {
                        this._sendPending();
                    }
                };
                void p.then(sendPendingOnce);
                // FIXME: if sent while zmq subscriptions are not established,
                // kernelInfo may not resolve, so use a timeout to ensure we don't hang forever.
                // It may be preferable to retry kernelInfo rather than give up after one timeout.
                let timeoutHandle = setTimeout(sendPendingOnce, KERNEL_INFO_TIMEOUT);
            }
            else {
                // If the connection is down, then we do not know what is happening
                // with the kernel, so set the status to unknown.
                this._updateStatus('unknown');
            }
        }
        // Notify others that the connection status changed.
        this._connectionStatusChanged.emit(connectionStatus);
    }
    async _handleMessage(msg) {
        var _a, _b;
        let handled = false;
        // Check to see if we have a display_id we need to reroute.
        if (msg.parent_header &&
            msg.channel === 'iopub' &&
            (KernelMessage.isDisplayDataMsg(msg) ||
                KernelMessage.isUpdateDisplayDataMsg(msg) ||
                KernelMessage.isExecuteResultMsg(msg))) {
            // display_data messages may re-route based on their display_id.
            const transient = ((_a = msg.content.transient) !== null && _a !== void 0 ? _a : {});
            const displayId = transient['display_id'];
            if (displayId) {
                handled = await this._handleDisplayId(displayId, msg);
                // The await above may make this message out of date, so check again.
                this._assertCurrentMessage(msg);
            }
        }
        if (!handled && msg.parent_header) {
            const parentHeader = msg.parent_header;
            const future = (_b = this._futures) === null || _b === void 0 ? void 0 : _b.get(parentHeader.msg_id);
            if (future) {
                await future.handleMsg(msg);
                this._assertCurrentMessage(msg);
            }
            else {
                // If the message was sent by us and was not iopub, it is orphaned.
                const owned = parentHeader.session === this.clientId;
                if (msg.channel !== 'iopub' && owned) {
                    this._unhandledMessage.emit(msg);
                }
            }
        }
        if (msg.channel === 'iopub') {
            switch (msg.header.msg_type) {
                case 'status': {
                    // Updating the status is synchronous, and we call no async user code
                    const executionState = msg.content
                        .execution_state;
                    if (executionState === 'restarting') {
                        // The kernel has been auto-restarted by the server. After
                        // processing for this message is completely done, we want to
                        // handle this restart, so we don't await, but instead schedule
                        // the work as a microtask (i.e., in a promise resolution). We
                        // schedule this here so that it comes before any microtasks that
                        // might be scheduled in the status signal emission below.
                        void Promise.resolve().then(async () => {
                            this._updateStatus('autorestarting');
                            this._clearKernelState();
                            // We must reconnect since the kernel connection information may have
                            // changed, and the server only refreshes its zmq connection when a new
                            // websocket is opened.
                            await this.reconnect();
                        });
                    }
                    this._updateStatus(executionState);
                    break;
                }
                case 'comm_open':
                    if (this.handleComms) {
                        await this._handleCommOpen(msg);
                    }
                    break;
                case 'comm_msg':
                    if (this.handleComms) {
                        await this._handleCommMsg(msg);
                    }
                    break;
                case 'comm_close':
                    if (this.handleComms) {
                        await this._handleCommClose(msg);
                    }
                    break;
                default:
                    break;
            }
            // If the message was a status dead message, we might have disposed ourselves.
            if (!this.isDisposed) {
                this._assertCurrentMessage(msg);
                // the message wouldn't be emitted if we were disposed anyway.
                this._iopubMessage.emit(msg);
            }
        }
    }
    /**
     * Attempt a connection if we have not exhausted connection attempts.
     */
    _reconnect() {
        this._errorIfDisposed();
        // Clear any existing reconnection attempt
        clearTimeout(this._reconnectTimeout);
        // Update the connection status and schedule a possible reconnection.
        if (this._reconnectAttempt < this._reconnectLimit) {
            this._updateConnectionStatus('connecting');
            // The first reconnect attempt should happen immediately, and subsequent
            // attempts should pick a random number in a growing range so that we
            // don't overload the server with synchronized reconnection attempts
            // across multiple kernels.
            const timeout = Private.getRandomIntInclusive(0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1));
            console.warn(`Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`);
            // Try reconnection with subprotocols if the server had supported them.
            // Otherwise, try reconnection without subprotocols.
            const useProtocols = this._selectedProtocol !== '' ? true : false;
            this._reconnectTimeout = setTimeout(this._createSocket, timeout, useProtocols);
            this._reconnectAttempt += 1;
        }
        else {
            this._updateConnectionStatus('disconnected');
        }
        // Clear the websocket event handlers and the socket itself.
        this._clearSocket();
    }
    /**
     * Utility function to throw an error if this instance is disposed.
     */
    _errorIfDisposed() {
        if (this.isDisposed) {
            throw new Error('Kernel connection is disposed');
        }
    }
    get hasPendingInput() {
        return this._hasPendingInput;
    }
    set hasPendingInput(value) {
        this._hasPendingInput = value;
        this._pendingInput.emit(value);
    }
}
exports.KernelConnection = KernelConnection;
/**
 * A private namespace for the Kernel.
 */
var Private;
(function (Private) {
    /**
     * Log the current kernel status.
     */
    function logKernelStatus(kernel) {
        switch (kernel.status) {
            case 'idle':
            case 'busy':
            case 'unknown':
                return;
            default:
                console.debug(`Kernel: ${kernel.status} (${kernel.id})`);
                break;
        }
    }
    Private.logKernelStatus = logKernelStatus;
    /**
     * Send a kernel message to the kernel and resolve the reply message.
     */
    async function handleShellMessage(kernel, msg) {
        const future = kernel.sendShellMessage(msg, true);
        return future.done;
    }
    Private.handleShellMessage = handleShellMessage;
    /**
     * Try to load an object from a module or a registry.
     *
     * Try to load an object from a module asynchronously if a module
     * is specified, otherwise tries to load an object from the global
     * registry, if the global registry is provided.
     *
     * #### Notes
     * Loading a module uses requirejs.
     */
    function loadObject(name, moduleName, registry) {
        return new Promise((resolve, reject) => {
            // Try loading the module using require.js
            if (moduleName) {
                if (typeof requirejs === 'undefined') {
                    throw new Error('requirejs not found');
                }
                requirejs([moduleName], (mod) => {
                    if (mod[name] === void 0) {
                        const msg = `Object '${name}' not found in module '${moduleName}'`;
                        reject(new Error(msg));
                    }
                    else {
                        resolve(mod[name]);
                    }
                }, reject);
            }
            else {
                if (registry === null || registry === void 0 ? void 0 : registry[name]) {
                    resolve(registry[name]);
                }
                else {
                    reject(new Error(`Object '${name}' not found in registry`));
                }
            }
        });
    }
    Private.loadObject = loadObject;
    /**
     * Get a random integer between min and max, inclusive of both.
     *
     * #### Notes
     * From
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive
     *
     * From the MDN page: It might be tempting to use Math.round() to accomplish
     * that, but doing so would cause your random numbers to follow a non-uniform
     * distribution, which may not be acceptable for your needs.
     */
    function getRandomIntInclusive(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    Private.getRandomIntInclusive = getRandomIntInclusive;
})(Private || (Private = {}));
//# sourceMappingURL=default.js.map

/***/ }),

/***/ 134:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.KernelShellFutureHandler = exports.KernelControlFutureHandler = exports.KernelFutureHandler = void 0;
const coreutils_1 = __webpack_require__(5764);
const disposable_1 = __webpack_require__(7556);
const KernelMessage = __importStar(__webpack_require__(9909));
/**
 * Implementation of a kernel future.
 *
 * If a reply is expected, the Future is considered done when both a `reply`
 * message and an `idle` iopub status message have been received.  Otherwise, it
 * is considered done when the `idle` status is received.
 *
 */
class KernelFutureHandler extends disposable_1.DisposableDelegate {
    /**
     * Construct a new KernelFutureHandler.
     */
    constructor(cb, msg, expectReply, disposeOnDone, kernel) {
        super(cb);
        this._status = 0;
        this._stdin = Private.noOp;
        this._iopub = Private.noOp;
        this._reply = Private.noOp;
        this._done = new coreutils_1.PromiseDelegate();
        this._hooks = new Private.HookList();
        this._disposeOnDone = true;
        this._msg = msg;
        if (!expectReply) {
            this._setFlag(Private.KernelFutureFlag.GotReply);
        }
        this._disposeOnDone = disposeOnDone;
        this._kernel = kernel;
    }
    /**
     * Get the original outgoing message.
     */
    get msg() {
        return this._msg;
    }
    /**
     * A promise that resolves when the future is done.
     */
    get done() {
        return this._done.promise;
    }
    /**
     * Get the reply handler.
     */
    get onReply() {
        return this._reply;
    }
    /**
     * Set the reply handler.
     */
    set onReply(cb) {
        this._reply = cb;
    }
    /**
     * Get the iopub handler.
     */
    get onIOPub() {
        return this._iopub;
    }
    /**
     * Set the iopub handler.
     */
    set onIOPub(cb) {
        this._iopub = cb;
    }
    /**
     * Get the stdin handler.
     */
    get onStdin() {
        return this._stdin;
    }
    /**
     * Set the stdin handler.
     */
    set onStdin(cb) {
        this._stdin = cb;
    }
    /**
     * Register hook for IOPub messages.
     *
     * @param hook - The callback invoked for an IOPub message.
     *
     * #### Notes
     * The IOPub hook system allows you to preempt the handlers for IOPub
     * messages handled by the future.
     *
     * The most recently registered hook is run first. A hook can return a
     * boolean or a promise to a boolean, in which case all kernel message
     * processing pauses until the promise is fulfilled. If a hook return value
     * resolves to false, any later hooks will not run and the function will
     * return a promise resolving to false. If a hook throws an error, the error
     * is logged to the console and the next hook is run. If a hook is
     * registered during the hook processing, it will not run until the next
     * message. If a hook is removed during the hook processing, it will be
     * deactivated immediately.
     */
    registerMessageHook(hook) {
        if (this.isDisposed) {
            throw new Error('Kernel future is disposed');
        }
        this._hooks.add(hook);
    }
    /**
     * Remove a hook for IOPub messages.
     *
     * @param hook - The hook to remove.
     *
     * #### Notes
     * If a hook is removed during the hook processing, it will be deactivated immediately.
     */
    removeMessageHook(hook) {
        if (this.isDisposed) {
            return;
        }
        this._hooks.remove(hook);
    }
    /**
     * Send an `input_reply` message.
     */
    sendInputReply(content, parent_header) {
        this._kernel.sendInputReply(content, parent_header);
    }
    /**
     * Dispose and unregister the future.
     */
    dispose() {
        this._stdin = Private.noOp;
        this._iopub = Private.noOp;
        this._reply = Private.noOp;
        this._hooks = null;
        if (!this._testFlag(Private.KernelFutureFlag.IsDone)) {
            // TODO: Uncomment the following logging code, and check for any tests that trigger it.
            // let status = [];
            // if (!this._testFlag(Private.KernelFutureFlag.GotIdle)) {
            //   status.push('idle');
            // }
            // if (!this._testFlag(Private.KernelFutureFlag.GotReply)) {
            //   status.push('reply');
            // }
            // console.warn(
            //   `*************** DISPOSED BEFORE DONE: K${this._kernel.id.slice(
            //     0,
            //     6
            //   )} M${this._msg.header.msg_id.slice(0, 6)} missing ${status.join(' ')}`
            // );
            // Reject the `done` promise, but catch its error here in case no one else
            // is waiting for the promise to resolve. This prevents the error from
            // being displayed in the console, but does not prevent it from being
            // caught by a client who is waiting for it.
            // Note: any `.then` and `.finally` attached to the `done` promise
            // will cause the error to be thrown as uncaught anyways.
            this._done.promise.catch(() => {
                /* no-op */
            });
            this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`));
        }
        super.dispose();
    }
    /**
     * Handle an incoming kernel message.
     */
    async handleMsg(msg) {
        switch (msg.channel) {
            case 'control':
            case 'shell':
                if (msg.channel === this.msg.channel &&
                    msg.parent_header.msg_id === this.msg.header.msg_id) {
                    await this._handleReply(msg);
                }
                break;
            case 'stdin':
                await this._handleStdin(msg);
                break;
            case 'iopub':
                await this._handleIOPub(msg);
                break;
            default:
                break;
        }
    }
    async _handleReply(msg) {
        const reply = this._reply;
        if (reply) {
            // tslint:disable-next-line:await-promise
            await reply(msg);
        }
        this._replyMsg = msg;
        this._setFlag(Private.KernelFutureFlag.GotReply);
        if (this._testFlag(Private.KernelFutureFlag.GotIdle)) {
            this._handleDone();
        }
    }
    async _handleStdin(msg) {
        this._kernel.hasPendingInput = true;
        const stdin = this._stdin;
        if (stdin) {
            // tslint:disable-next-line:await-promise
            await stdin(msg);
        }
    }
    async _handleIOPub(msg) {
        const process = await this._hooks.process(msg);
        const iopub = this._iopub;
        if (process && iopub) {
            // tslint:disable-next-line:await-promise
            await iopub(msg);
        }
        if (KernelMessage.isStatusMsg(msg) &&
            msg.content.execution_state === 'idle') {
            this._setFlag(Private.KernelFutureFlag.GotIdle);
            if (this._testFlag(Private.KernelFutureFlag.GotReply)) {
                this._handleDone();
            }
        }
    }
    _handleDone() {
        if (this._testFlag(Private.KernelFutureFlag.IsDone)) {
            return;
        }
        this._setFlag(Private.KernelFutureFlag.IsDone);
        this._done.resolve(this._replyMsg);
        if (this._disposeOnDone) {
            this.dispose();
        }
    }
    /**
     * Test whether the given future flag is set.
     */
    _testFlag(flag) {
        // tslint:disable-next-line
        return (this._status & flag) !== 0;
    }
    /**
     * Set the given future flag.
     */
    _setFlag(flag) {
        // tslint:disable-next-line
        this._status |= flag;
    }
}
exports.KernelFutureHandler = KernelFutureHandler;
class KernelControlFutureHandler extends KernelFutureHandler {
}
exports.KernelControlFutureHandler = KernelControlFutureHandler;
class KernelShellFutureHandler extends KernelFutureHandler {
}
exports.KernelShellFutureHandler = KernelShellFutureHandler;
var Private;
(function (Private) {
    /**
     * A no-op function.
     */
    Private.noOp = () => {
        /* no-op */
    };
    /**
     * Defer a computation.
     *
     * #### NOTES
     * We can't just use requestAnimationFrame since it is not available in node.
     * This implementation is from Phosphor:
     * https://github.com/phosphorjs/phosphor/blob/e88e4321289bb1198f3098e7bda40736501f2ed8/tests/test-messaging/src/index.spec.ts#L63
     */
    const defer = (() => {
        const ok = typeof requestAnimationFrame === 'function';
        return ok ? requestAnimationFrame : setImmediate;
    })();
    class HookList {
        constructor() {
            this._hooks = [];
        }
        /**
         * Register a hook.
         *
         * @param hook - The callback to register.
         */
        add(hook) {
            this.remove(hook);
            this._hooks.push(hook);
        }
        /**
         * Remove a hook, if it exists in the hook list.
         *
         * @param hook - The callback to remove.
         */
        remove(hook) {
            const index = this._hooks.indexOf(hook);
            if (index >= 0) {
                this._hooks[index] = null;
                this._scheduleCompact();
            }
        }
        /**
         * Process a message through the hooks.
         *
         * @returns a promise resolving to false if any hook resolved as false,
         * otherwise true
         *
         * #### Notes
         * The most recently registered hook is run first. A hook can return a
         * boolean or a promise to a boolean, in which case processing pauses until
         * the promise is fulfilled. If a hook return value resolves to false, any
         * later hooks will not run and the function will return a promise resolving
         * to false. If a hook throws an error, the error is logged to the console
         * and the next hook is run. If a hook is registered during the hook
         * processing, it will not run until the next message. If a hook is removed
         * during the hook processing, it will be deactivated immediately.
         */
        async process(msg) {
            // Wait until we can start a new process run.
            await this._processing;
            // Start the next process run.
            const processing = new coreutils_1.PromiseDelegate();
            this._processing = processing.promise;
            let continueHandling;
            // Call the end hook (most recently-added) first. Starting at the end also
            // guarantees that hooks added during the processing will not be run in
            // this process run.
            for (let i = this._hooks.length - 1; i >= 0; i--) {
                const hook = this._hooks[i];
                // If the hook has been removed, continue to the next one.
                if (hook === null) {
                    continue;
                }
                // Execute the hook and log any errors.
                try {
                    // tslint:disable-next-line:await-promise
                    continueHandling = await hook(msg);
                }
                catch (err) {
                    continueHandling = true;
                    console.error(err);
                }
                // If the hook resolved to false, stop processing and return.
                if (continueHandling === false) {
                    processing.resolve(undefined);
                    return false;
                }
            }
            // All hooks returned true (or errored out), so return true.
            processing.resolve(undefined);
            return true;
        }
        /**
         * Schedule a cleanup of the list, removing any hooks that have been nulled out.
         */
        _scheduleCompact() {
            if (!this._compactScheduled) {
                this._compactScheduled = true;
                // Schedule a compaction in between processing runs. We do the
                // scheduling in an animation frame to rate-limit our compactions. If we
                // need to compact more frequently, we can change this to directly
                // schedule the compaction.
                defer(() => {
                    this._processing = this._processing.then(() => {
                        this._compactScheduled = false;
                        this._compact();
                    });
                });
            }
        }
        /**
         * Compact the list, removing any nulls.
         */
        _compact() {
            let numNulls = 0;
            for (let i = 0, len = this._hooks.length; i < len; i++) {
                const hook = this._hooks[i];
                if (this._hooks[i] === null) {
                    numNulls++;
                }
                else {
                    this._hooks[i - numNulls] = hook;
                }
            }
            this._hooks.length -= numNulls;
        }
    }
    Private.HookList = HookList;
    /**
     * Bit flags for the kernel future state.
     */
    let KernelFutureFlag;
    (function (KernelFutureFlag) {
        KernelFutureFlag[KernelFutureFlag["GotReply"] = 1] = "GotReply";
        KernelFutureFlag[KernelFutureFlag["GotIdle"] = 2] = "GotIdle";
        KernelFutureFlag[KernelFutureFlag["IsDone"] = 4] = "IsDone";
        KernelFutureFlag[KernelFutureFlag["DisposeOnDone"] = 8] = "DisposeOnDone";
    })(KernelFutureFlag = Private.KernelFutureFlag || (Private.KernelFutureFlag = {}));
})(Private || (Private = {}));
//# sourceMappingURL=future.js.map

/***/ }),

/***/ 973:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.KernelConnection = exports.KernelAPI = exports.KernelMessage = exports.Kernel = void 0;
// Namespace some of our modules for convenience and backwards compatibility.
const Kernel = __importStar(__webpack_require__(2956));
exports.Kernel = Kernel;
const KernelMessage = __importStar(__webpack_require__(9909));
exports.KernelMessage = KernelMessage;
const KernelAPI = __importStar(__webpack_require__(8235));
exports.KernelAPI = KernelAPI;
const default_1 = __webpack_require__(2456);
Object.defineProperty(exports, "KernelConnection", ({ enumerable: true, get: function () { return default_1.KernelConnection; } }));
__exportStar(__webpack_require__(5198), exports);
//# sourceMappingURL=index.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=kernel.js.map

/***/ }),

/***/ 5198:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.KernelManager = void 0;
const polling_1 = __webpack_require__(6049);
const signaling_1 = __webpack_require__(3992);
const __1 = __webpack_require__(7883);
const basemanager_1 = __webpack_require__(3867);
const restapi_1 = __webpack_require__(8235);
const default_1 = __webpack_require__(2456);
/**
 * An implementation of a kernel manager.
 */
class KernelManager extends basemanager_1.BaseManager {
    /**
     * Construct a new kernel manager.
     *
     * @param options - The default options for kernel.
     */
    constructor(options = {}) {
        var _a;
        super(options);
        this._isReady = false;
        this._kernelConnections = new Set();
        this._models = new Map();
        this._runningChanged = new signaling_1.Signal(this);
        this._connectionFailure = new signaling_1.Signal(this);
        // Start model and specs polling with exponential backoff.
        this._pollModels = new polling_1.Poll({
            auto: false,
            factory: () => this.requestRunning(),
            frequency: {
                interval: 10 * 1000,
                backoff: true,
                max: 300 * 1000
            },
            name: `@jupyterlab/services:KernelManager#models`,
            standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'
        });
        // Initialize internal data.
        this._ready = (async () => {
            await this._pollModels.start();
            await this._pollModels.tick;
            this._isReady = true;
        })();
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._ready;
    }
    /**
     * A signal emitted when the running kernels change.
     */
    get runningChanged() {
        return this._runningChanged;
    }
    /**
     * A signal emitted when there is a connection failure.
     */
    get connectionFailure() {
        return this._connectionFailure;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._models.clear();
        this._kernelConnections.forEach(x => x.dispose());
        this._pollModels.dispose();
        super.dispose();
    }
    /**
     * Connect to an existing kernel.
     *
     * @returns The new kernel connection.
     *
     * #### Notes
     * This will use the manager's server settings and ignore any server
     * settings passed in the options.
     */
    connectTo(options) {
        var _a;
        const { id } = options.model;
        let handleComms = (_a = options.handleComms) !== null && _a !== void 0 ? _a : true;
        // By default, handle comms only if no other kernel connection is.
        if (options.handleComms === undefined) {
            for (const kc of this._kernelConnections) {
                if (kc.id === id && kc.handleComms) {
                    handleComms = false;
                    break;
                }
            }
        }
        const kernelConnection = new default_1.KernelConnection({
            handleComms,
            ...options,
            serverSettings: this.serverSettings
        });
        this._onStarted(kernelConnection);
        if (!this._models.has(id)) {
            // We trust the user to connect to an existing kernel, but we verify
            // asynchronously.
            void this.refreshRunning().catch(() => {
                /* no-op */
            });
        }
        return kernelConnection;
    }
    /**
     * Create an iterator over the most recent running kernels.
     *
     * @returns A new iterator over the running kernels.
     */
    running() {
        return this._models.values();
    }
    /**
     * The number of running kernels.
     */
    get runningCount() {
        return this._models.size;
    }
    /**
     * Force a refresh of the running kernels.
     *
     * @returns A promise that resolves when the running list has been refreshed.
     *
     * #### Notes
     * This is not typically meant to be called by the user, since the
     * manager maintains its own internal state.
     */
    async refreshRunning() {
        await this._pollModels.refresh();
        await this._pollModels.tick;
    }
    /**
     * Start a new kernel.
     *
     * @param createOptions - The kernel creation options
     *
     * @param connectOptions - The kernel connection options
     *
     * @returns A promise that resolves with the kernel connection.
     *
     * #### Notes
     * The manager `serverSettings` will be always be used.
     */
    async startNew(createOptions = {}, connectOptions = {}) {
        const model = await (0, restapi_1.startNew)(createOptions, this.serverSettings);
        return this.connectTo({
            ...connectOptions,
            model
        });
    }
    /**
     * Shut down a kernel by id.
     *
     * @param id - The id of the target kernel.
     *
     * @returns A promise that resolves when the operation is complete.
     */
    async shutdown(id) {
        await (0, restapi_1.shutdownKernel)(id, this.serverSettings);
        await this.refreshRunning();
    }
    /**
     * Shut down all kernels.
     *
     * @returns A promise that resolves when all of the kernels are shut down.
     */
    async shutdownAll() {
        // Update the list of models to make sure our list is current.
        await this.refreshRunning();
        // Shut down all models.
        await Promise.all([...this._models.keys()].map(id => (0, restapi_1.shutdownKernel)(id, this.serverSettings)));
        // Update the list of models to clear out our state.
        await this.refreshRunning();
    }
    /**
     * Find a kernel by id.
     *
     * @param id - The id of the target kernel.
     *
     * @returns A promise that resolves with the kernel's model.
     */
    async findById(id) {
        if (this._models.has(id)) {
            return this._models.get(id);
        }
        await this.refreshRunning();
        return this._models.get(id);
    }
    /**
     * Execute a request to the server to poll running kernels and update state.
     */
    async requestRunning() {
        var _a, _b;
        let models;
        try {
            models = await (0, restapi_1.listRunning)(this.serverSettings);
        }
        catch (err) {
            // Handle network errors, as well as cases where we are on a
            // JupyterHub and the server is not running. JupyterHub returns a
            // 503 (<2.0) or 424 (>2.0) in that case.
            if (err instanceof __1.ServerConnection.NetworkError ||
                ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||
                ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {
                this._connectionFailure.emit(err);
            }
            throw err;
        }
        if (this.isDisposed) {
            return;
        }
        if (this._models.size === models.length &&
            models.every(model => {
                const existing = this._models.get(model.id);
                if (!existing) {
                    return false;
                }
                return (existing.connections === model.connections &&
                    existing.execution_state === model.execution_state &&
                    existing.last_activity === model.last_activity &&
                    existing.name === model.name &&
                    existing.reason === model.reason &&
                    existing.traceback === model.traceback);
            })) {
            // Identical models list (presuming models does not contain duplicate
            // ids), so just return
            return;
        }
        this._models = new Map(models.map(x => [x.id, x]));
        // For any kernel connection to a kernel that doesn't exist, notify it of
        // the shutdown.
        this._kernelConnections.forEach(kc => {
            if (!this._models.has(kc.id)) {
                kc.handleShutdown();
            }
        });
        this._runningChanged.emit(models);
    }
    /**
     * Handle a kernel starting.
     */
    _onStarted(kernelConnection) {
        this._kernelConnections.add(kernelConnection);
        kernelConnection.statusChanged.connect(this._onStatusChanged, this);
        kernelConnection.disposed.connect(this._onDisposed, this);
    }
    _onDisposed(kernelConnection) {
        this._kernelConnections.delete(kernelConnection);
        // A dispose emission could mean the server session is deleted, or that
        // the kernel JS object is disposed and the kernel still exists on the
        // server, so we refresh from the server to make sure we reflect the
        // server state.
        void this.refreshRunning().catch(() => {
            /* no-op */
        });
    }
    _onStatusChanged(kernelConnection, status) {
        if (status === 'dead') {
            // We asynchronously update our list of kernels, which asynchronously
            // will dispose them. We do not want to immediately dispose them because
            // there may be other signal handlers that want to be called.
            void this.refreshRunning().catch(() => {
                /* no-op */
            });
        }
    }
}
exports.KernelManager = KernelManager;
/**
 * The namespace for `KernelManager` class statics.
 */
(function (KernelManager) {
    /**
     * A no-op kernel manager to be used when starting kernels.
     */
    class NoopManager extends KernelManager {
        constructor() {
            super(...arguments);
            this._readyPromise = new Promise(() => {
                /* no-op */
            });
        }
        /**
         * Whether the manager is active.
         */
        get isActive() {
            return false;
        }
        /**
         * Used for testing.
         */
        get parentReady() {
            return super.ready;
        }
        /**
         * Start a new kernel - throws an error since it is not supported.
         */
        async startNew(createOptions = {}, connectOptions = {}) {
            return Promise.reject(new Error('Not implemented in no-op Kernel Manager'));
        }
        /**
         * Connect to an existing kernel - throws an error since it is not supported.
         */
        connectTo(options) {
            throw new Error('Not implemented in no-op Kernel Manager');
        }
        /**
         * Shut down a kernel by id - throws an error since it is not supported.
         */
        async shutdown(id) {
            return Promise.reject(new Error('Not implemented in no-op Kernel Manager'));
        }
        /**
         * A promise that fulfills when the manager is ready (never).
         */
        get ready() {
            return this.parentReady.then(() => this._readyPromise);
        }
        /**
         * Execute a request to the server to poll running kernels and update state.
         */
        async requestRunning() {
            return Promise.resolve();
        }
    }
    KernelManager.NoopManager = NoopManager;
})(KernelManager || (exports.KernelManager = KernelManager = {}));
//# sourceMappingURL=manager.js.map

/***/ }),

/***/ 9909:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.supportedKernelWebSocketProtocols = exports.isInputReplyMsg = exports.isInputRequestMsg = exports.isDebugReplyMsg = exports.isDebugRequestMsg = exports.isExecuteReplyMsg = exports.isInfoRequestMsg = exports.isCommMsgMsg = exports.isCommCloseMsg = exports.isCommOpenMsg = exports.isDebugEventMsg = exports.isClearOutputMsg = exports.isStatusMsg = exports.isErrorMsg = exports.isExecuteResultMsg = exports.isExecuteInputMsg = exports.isUpdateDisplayDataMsg = exports.isDisplayDataMsg = exports.isStreamMsg = exports.createMessage = void 0;
const coreutils_1 = __webpack_require__(5764);
function createMessage(options) {
    var _a, _b, _c, _d, _e;
    return {
        buffers: (_a = options.buffers) !== null && _a !== void 0 ? _a : [],
        channel: options.channel,
        content: options.content,
        header: {
            date: new Date().toISOString(),
            msg_id: (_b = options.msgId) !== null && _b !== void 0 ? _b : coreutils_1.UUID.uuid4(),
            msg_type: options.msgType,
            session: options.session,
            username: (_c = options.username) !== null && _c !== void 0 ? _c : '',
            version: '5.2'
        },
        metadata: (_d = options.metadata) !== null && _d !== void 0 ? _d : {},
        parent_header: (_e = options.parentHeader) !== null && _e !== void 0 ? _e : {}
    };
}
exports.createMessage = createMessage;
/**
 * Test whether a kernel message is a `'stream'` message.
 */
function isStreamMsg(msg) {
    return msg.header.msg_type === 'stream';
}
exports.isStreamMsg = isStreamMsg;
/**
 * Test whether a kernel message is an `'display_data'` message.
 */
function isDisplayDataMsg(msg) {
    return msg.header.msg_type === 'display_data';
}
exports.isDisplayDataMsg = isDisplayDataMsg;
/**
 * Test whether a kernel message is an `'update_display_data'` message.
 */
function isUpdateDisplayDataMsg(msg) {
    return msg.header.msg_type === 'update_display_data';
}
exports.isUpdateDisplayDataMsg = isUpdateDisplayDataMsg;
/**
 * Test whether a kernel message is an `'execute_input'` message.
 */
function isExecuteInputMsg(msg) {
    return msg.header.msg_type === 'execute_input';
}
exports.isExecuteInputMsg = isExecuteInputMsg;
/**
 * Test whether a kernel message is an `'execute_result'` message.
 */
function isExecuteResultMsg(msg) {
    return msg.header.msg_type === 'execute_result';
}
exports.isExecuteResultMsg = isExecuteResultMsg;
/**
 * Test whether a kernel message is an `'error'` message.
 */
function isErrorMsg(msg) {
    return msg.header.msg_type === 'error';
}
exports.isErrorMsg = isErrorMsg;
/**
 * Test whether a kernel message is a `'status'` message.
 */
function isStatusMsg(msg) {
    return msg.header.msg_type === 'status';
}
exports.isStatusMsg = isStatusMsg;
/**
 * Test whether a kernel message is a `'clear_output'` message.
 */
function isClearOutputMsg(msg) {
    return msg.header.msg_type === 'clear_output';
}
exports.isClearOutputMsg = isClearOutputMsg;
/**
 * Test whether a kernel message is an experimental `'debug_event'` message.
 *
 * @hidden
 *
 * #### Notes
 * Debug messages are experimental messages that are not in the official
 * kernel message specification. As such, this is *NOT* considered
 * part of the public API, and may change without notice.
 */
function isDebugEventMsg(msg) {
    return msg.header.msg_type === 'debug_event';
}
exports.isDebugEventMsg = isDebugEventMsg;
/**
 * Test whether a kernel message is a `'comm_open'` message.
 */
function isCommOpenMsg(msg) {
    return msg.header.msg_type === 'comm_open';
}
exports.isCommOpenMsg = isCommOpenMsg;
/**
 * Test whether a kernel message is a `'comm_close'` message.
 */
function isCommCloseMsg(msg) {
    return msg.header.msg_type === 'comm_close';
}
exports.isCommCloseMsg = isCommCloseMsg;
/**
 * Test whether a kernel message is a `'comm_msg'` message.
 */
function isCommMsgMsg(msg) {
    return msg.header.msg_type === 'comm_msg';
}
exports.isCommMsgMsg = isCommMsgMsg;
/**
 * Test whether a kernel message is a `'kernel_info_request'` message.
 */
function isInfoRequestMsg(msg) {
    return msg.header.msg_type === 'kernel_info_request';
}
exports.isInfoRequestMsg = isInfoRequestMsg;
/**
 * Test whether a kernel message is an `'execute_reply'` message.
 */
function isExecuteReplyMsg(msg) {
    return msg.header.msg_type === 'execute_reply';
}
exports.isExecuteReplyMsg = isExecuteReplyMsg;
/**
 * Test whether a kernel message is an experimental `'debug_request'` message.
 *
 * @hidden
 *
 * #### Notes
 * Debug messages are experimental messages that are not in the official
 * kernel message specification. As such, this is *NOT* considered
 * part of the public API, and may change without notice.
 */
function isDebugRequestMsg(msg) {
    return msg.header.msg_type === 'debug_request';
}
exports.isDebugRequestMsg = isDebugRequestMsg;
/**
 * Test whether a kernel message is an experimental `'debug_reply'` message.
 *
 * @hidden
 *
 * #### Notes
 * Debug messages are experimental messages that are not in the official
 * kernel message specification. As such, this is *NOT* considered
 * part of the public API, and may change without notice.
 */
function isDebugReplyMsg(msg) {
    return msg.header.msg_type === 'debug_reply';
}
exports.isDebugReplyMsg = isDebugReplyMsg;
/**
 * Test whether a kernel message is an `'input_request'` message.
 */
function isInputRequestMsg(msg) {
    return msg.header.msg_type === 'input_request';
}
exports.isInputRequestMsg = isInputRequestMsg;
/**
 * Test whether a kernel message is an `'input_reply'` message.
 */
function isInputReplyMsg(msg) {
    return msg.header.msg_type === 'input_reply';
}
exports.isInputReplyMsg = isInputReplyMsg;
// ///////////////////////////////////////////////
// Message (de)serialization
// ///////////////////////////////////////////////
/**
 * The list of supported kernel wire protocols over websocket.
 */
var supportedKernelWebSocketProtocols;
(function (supportedKernelWebSocketProtocols) {
    supportedKernelWebSocketProtocols["v1KernelWebsocketJupyterOrg"] = "v1.kernel.websocket.jupyter.org";
})(supportedKernelWebSocketProtocols || (exports.supportedKernelWebSocketProtocols = supportedKernelWebSocketProtocols = {}));
//# sourceMappingURL=messages.js.map

/***/ }),

/***/ 8235:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getKernelModel = exports.shutdownKernel = exports.interruptKernel = exports.restartKernel = exports.startNew = exports.listRunning = exports.KERNEL_SERVICE_URL = void 0;
const serverconnection_1 = __webpack_require__(2920);
const coreutils_1 = __webpack_require__(8925);
const validate_1 = __webpack_require__(5855);
/**
 * The url for the kernel service.
 */
exports.KERNEL_SERVICE_URL = 'api/kernels';
/**
 * Fetch the running kernels.
 *
 * @param settings - The optional server settings.
 *
 * @returns A promise that resolves with the list of running kernels.
 *
 * #### Notes
 * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.
 *
 * The promise is fulfilled on a valid response and rejected otherwise.
 */
async function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL);
    const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    (0, validate_1.validateModels)(data);
    return data;
}
exports.listRunning = listRunning;
/**
 * Start a new kernel.
 *
 * @param options - The options used to create the kernel.
 *
 * @returns A promise that resolves with a kernel connection object.
 *
 * #### Notes
 * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.
 *
 * The promise is fulfilled on a valid response and rejected otherwise.
 */
async function startNew(options = {}, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL);
    const init = {
        method: 'POST',
        body: JSON.stringify(options)
    };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status !== 201) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    (0, validate_1.validateModel)(data);
    return data;
}
exports.startNew = startNew;
/**
 * Restart a kernel.
 *
 * #### Notes
 * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.
 *
 * The promise is fulfilled on a valid response (and thus after a restart) and rejected otherwise.
 */
async function restartKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id), 'restart');
    const init = { method: 'POST' };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    (0, validate_1.validateModel)(data);
}
exports.restartKernel = restartKernel;
/**
 * Interrupt a kernel.
 *
 * #### Notes
 * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.
 *
 * The promise is fulfilled on a valid response and rejected otherwise.
 */
async function interruptKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id), 'interrupt');
    const init = { method: 'POST' };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status !== 204) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
}
exports.interruptKernel = interruptKernel;
/**
 * Shut down a kernel.
 *
 * @param id - The id of the running kernel.
 *
 * @param settings - The server settings for the request.
 *
 * @returns A promise that resolves when the kernel is shut down.
 *
 *
 * #### Notes
 * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.
 *
 * The promise is fulfilled on a valid response and rejected otherwise.
 */
async function shutdownKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id));
    const init = { method: 'DELETE' };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status === 404) {
        const msg = `The kernel "${id}" does not exist on the server`;
        console.warn(msg);
    }
    else if (response.status !== 204) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
}
exports.shutdownKernel = shutdownKernel;
/**
 * Get a full kernel model from the server by kernel id string.
 *
 * #### Notes
 * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.
 *
 * The promise is fulfilled on a valid response and rejected otherwise.
 */
async function getKernelModel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id));
    const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);
    if (response.status === 404) {
        return undefined;
    }
    else if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    (0, validate_1.validateModel)(data);
    return data;
}
exports.getKernelModel = getKernelModel;
//# sourceMappingURL=restapi.js.map

/***/ }),

/***/ 7179:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.deserialize = exports.serialize = void 0;
const KernelMessage = __importStar(__webpack_require__(9909));
/**
 * Serialize a kernel message for transport.
 */
function serialize(msg, protocol = '') {
    switch (protocol) {
        case KernelMessage.supportedKernelWebSocketProtocols
            .v1KernelWebsocketJupyterOrg:
            return Private.serializeV1KernelWebsocketJupyterOrg(msg);
        default:
            return Private.serializeDefault(msg);
    }
}
exports.serialize = serialize;
/**
 * Deserialize and return the unpacked message.
 */
function deserialize(data, protocol = '') {
    switch (protocol) {
        case KernelMessage.supportedKernelWebSocketProtocols
            .v1KernelWebsocketJupyterOrg:
            return Private.deserializeV1KernelWebsocketJupyterOrg(data);
        default:
            return Private.deserializeDefault(data);
    }
}
exports.deserialize = deserialize;
var Private;
(function (Private) {
    /**
     * Deserialize and return the unpacked message.
     * Protocol `v1.kernel.websocket.jupyter.org`
     */
    function deserializeV1KernelWebsocketJupyterOrg(binMsg) {
        let msg;
        const data = new DataView(binMsg);
        const offsetNumber = Number(data.getBigUint64(0, true /* littleEndian */));
        let offsets = [];
        for (let i = 0; i < offsetNumber; i++) {
            // WARNING: we cast our 64-bit unsigned int to a number!
            // so offsets cannot index up to 2**64 bytes
            offsets.push(Number(data.getBigUint64(8 * (i + 1), true /* littleEndian */)));
        }
        const decoder = new TextDecoder('utf8');
        const channel = decoder.decode(binMsg.slice(offsets[0], offsets[1]));
        const header = JSON.parse(decoder.decode(binMsg.slice(offsets[1], offsets[2])));
        const parent_header = JSON.parse(decoder.decode(binMsg.slice(offsets[2], offsets[3])));
        const metadata = JSON.parse(decoder.decode(binMsg.slice(offsets[3], offsets[4])));
        const content = JSON.parse(decoder.decode(binMsg.slice(offsets[4], offsets[5])));
        let buffers = [];
        for (let i = 5; i < offsets.length - 1; i++) {
            buffers.push(new DataView(binMsg.slice(offsets[i], offsets[i + 1])));
        }
        msg = {
            channel,
            header,
            parent_header,
            metadata,
            content,
            buffers
        };
        return msg;
    }
    Private.deserializeV1KernelWebsocketJupyterOrg = deserializeV1KernelWebsocketJupyterOrg;
    /**
     * Serialize a kernel message for transport.
     * Protocol `v1.kernel.websocket.jupyter.org`
     */
    function serializeV1KernelWebsocketJupyterOrg(msg) {
        const header = JSON.stringify(msg.header);
        const parentHeader = msg.parent_header == null ? '{}' : JSON.stringify(msg.parent_header);
        const metadata = JSON.stringify(msg.metadata);
        const content = JSON.stringify(msg.content);
        const buffers = msg.buffers !== undefined ? msg.buffers : [];
        const offsetNumber = 1 + 4 + buffers.length + 1;
        let offsets = [];
        offsets.push(8 * (1 + offsetNumber));
        offsets.push(msg.channel.length + offsets[offsets.length - 1]);
        const encoder = new TextEncoder();
        const channelEncoded = encoder.encode(msg.channel);
        const headerEncoded = encoder.encode(header);
        const parentHeaderEncoded = encoder.encode(parentHeader);
        const metadataEncoded = encoder.encode(metadata);
        const contentEncoded = encoder.encode(content);
        const binMsgNoBuff = new Uint8Array(channelEncoded.length +
            headerEncoded.length +
            parentHeaderEncoded.length +
            metadataEncoded.length +
            contentEncoded.length);
        binMsgNoBuff.set(channelEncoded);
        binMsgNoBuff.set(headerEncoded, channelEncoded.length);
        binMsgNoBuff.set(parentHeaderEncoded, channelEncoded.length + headerEncoded.length);
        binMsgNoBuff.set(metadataEncoded, channelEncoded.length + headerEncoded.length + parentHeaderEncoded.length);
        binMsgNoBuff.set(contentEncoded, channelEncoded.length +
            headerEncoded.length +
            parentHeaderEncoded.length +
            metadataEncoded.length);
        for (let length of [
            headerEncoded.length,
            parentHeaderEncoded.length,
            metadataEncoded.length,
            contentEncoded.length
        ]) {
            offsets.push(length + offsets[offsets.length - 1]);
        }
        let buffersByteLength = 0;
        for (let buffer of buffers) {
            let length = buffer.byteLength;
            offsets.push(length + offsets[offsets.length - 1]);
            buffersByteLength += length;
        }
        const binMsg = new Uint8Array(8 * (1 + offsetNumber) + binMsgNoBuff.byteLength + buffersByteLength);
        const word = new ArrayBuffer(8);
        const data = new DataView(word);
        data.setBigUint64(0, BigInt(offsetNumber), true /* littleEndian */);
        binMsg.set(new Uint8Array(word), 0);
        for (let i = 0; i < offsets.length; i++) {
            data.setBigUint64(0, BigInt(offsets[i]), true /* littleEndian */);
            binMsg.set(new Uint8Array(word), 8 * (i + 1));
        }
        binMsg.set(binMsgNoBuff, offsets[0]);
        for (let i = 0; i < buffers.length; i++) {
            const buffer = buffers[i];
            binMsg.set(new Uint8Array(ArrayBuffer.isView(buffer) ? buffer.buffer : buffer), offsets[5 + i]);
        }
        return binMsg.buffer;
    }
    Private.serializeV1KernelWebsocketJupyterOrg = serializeV1KernelWebsocketJupyterOrg;
    /**
     * Deserialize and return the unpacked message.
     * Default protocol
     *
     * #### Notes
     * Handles JSON blob strings and binary messages.
     */
    function deserializeDefault(data) {
        let value;
        if (typeof data === 'string') {
            value = JSON.parse(data);
        }
        else {
            value = deserializeBinary(data);
        }
        return value;
    }
    Private.deserializeDefault = deserializeDefault;
    /**
     * Serialize a kernel message for transport.
     * Default protocol
     *
     * #### Notes
     * If there is binary content, an `ArrayBuffer` is returned,
     * otherwise the message is converted to a JSON string.
     */
    function serializeDefault(msg) {
        var _a;
        let value;
        if ((_a = msg.buffers) === null || _a === void 0 ? void 0 : _a.length) {
            value = serializeBinary(msg);
        }
        else {
            value = JSON.stringify(msg);
        }
        return value;
    }
    Private.serializeDefault = serializeDefault;
    /**
     * Deserialize a binary message to a Kernel Message.
     */
    function deserializeBinary(buf) {
        const data = new DataView(buf);
        // read the header: 1 + nbufs 32b integers
        const nbufs = data.getUint32(0);
        const offsets = [];
        if (nbufs < 2) {
            throw new Error('Invalid incoming Kernel Message');
        }
        for (let i = 1; i <= nbufs; i++) {
            offsets.push(data.getUint32(i * 4));
        }
        const jsonBytes = new Uint8Array(buf.slice(offsets[0], offsets[1]));
        const msg = JSON.parse(new TextDecoder('utf8').decode(jsonBytes));
        // the remaining chunks are stored as DataViews in msg.buffers
        msg.buffers = [];
        for (let i = 1; i < nbufs; i++) {
            const start = offsets[i];
            const stop = offsets[i + 1] || buf.byteLength;
            msg.buffers.push(new DataView(buf.slice(start, stop)));
        }
        return msg;
    }
    /**
     * Implement the binary serialization protocol.
     *
     * Serialize Kernel message to ArrayBuffer.
     */
    function serializeBinary(msg) {
        const offsets = [];
        const buffers = [];
        const encoder = new TextEncoder();
        let origBuffers = [];
        if (msg.buffers !== undefined) {
            origBuffers = msg.buffers;
            delete msg['buffers'];
        }
        const jsonUtf8 = encoder.encode(JSON.stringify(msg));
        buffers.push(jsonUtf8.buffer);
        for (let i = 0; i < origBuffers.length; i++) {
            // msg.buffers elements could be either views or ArrayBuffers
            // buffers elements are ArrayBuffers
            const b = origBuffers[i];
            buffers.push(ArrayBuffer.isView(b) ? b.buffer : b);
        }
        const nbufs = buffers.length;
        offsets.push(4 * (nbufs + 1));
        for (let i = 0; i + 1 < buffers.length; i++) {
            offsets.push(offsets[offsets.length - 1] + buffers[i].byteLength);
        }
        const msgBuf = new Uint8Array(offsets[offsets.length - 1] + buffers[buffers.length - 1].byteLength);
        // use DataView.setUint32 for network byte-order
        const view = new DataView(msgBuf.buffer);
        // write nbufs to first 4 bytes
        view.setUint32(0, nbufs);
        // write offsets to next 4 * nbufs bytes
        for (let i = 0; i < offsets.length; i++) {
            view.setUint32(4 * (i + 1), offsets[i]);
        }
        // write all the buffers at their respective offsets
        for (let i = 0; i < buffers.length; i++) {
            msgBuf.set(new Uint8Array(buffers[i]), offsets[i]);
        }
        return msgBuf.buffer;
    }
})(Private || (Private = {}));
//# sourceMappingURL=serialize.js.map

/***/ }),

/***/ 5855:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateModels = exports.validateModel = exports.validateMessage = void 0;
const validate_1 = __webpack_require__(7441);
/**
 * Required fields for `IKernelHeader`.
 */
const HEADER_FIELDS = ['username', 'version', 'session', 'msg_id', 'msg_type'];
/**
 * Required fields and types for contents of various types of `kernel.IMessage`
 * messages on the iopub channel.
 */
const IOPUB_CONTENT_FIELDS = {
    stream: { name: 'string', text: 'string' },
    display_data: { data: 'object', metadata: 'object' },
    execute_input: { code: 'string', execution_count: 'number' },
    execute_result: {
        execution_count: 'number',
        data: 'object',
        metadata: 'object'
    },
    error: { ename: 'string', evalue: 'string', traceback: 'object' },
    status: {
        execution_state: [
            'string',
            ['starting', 'idle', 'busy', 'restarting', 'dead']
        ]
    },
    clear_output: { wait: 'boolean' },
    comm_open: { comm_id: 'string', target_name: 'string', data: 'object' },
    comm_msg: { comm_id: 'string', data: 'object' },
    comm_close: { comm_id: 'string' },
    shutdown_reply: { restart: 'boolean' } // Emitted by the IPython kernel.
};
/**
 * Validate the header of a kernel message.
 */
function validateHeader(header) {
    for (let i = 0; i < HEADER_FIELDS.length; i++) {
        (0, validate_1.validateProperty)(header, HEADER_FIELDS[i], 'string');
    }
}
/**
 * Validate a kernel message object.
 */
function validateMessage(msg) {
    (0, validate_1.validateProperty)(msg, 'metadata', 'object');
    (0, validate_1.validateProperty)(msg, 'content', 'object');
    (0, validate_1.validateProperty)(msg, 'channel', 'string');
    validateHeader(msg.header);
    if (msg.channel === 'iopub') {
        validateIOPubContent(msg);
    }
}
exports.validateMessage = validateMessage;
/**
 * Validate content an kernel message on the iopub channel.
 */
function validateIOPubContent(msg) {
    if (msg.channel === 'iopub') {
        const fields = IOPUB_CONTENT_FIELDS[msg.header.msg_type];
        // Check for unknown message type.
        if (fields === undefined) {
            return;
        }
        const names = Object.keys(fields);
        const content = msg.content;
        for (let i = 0; i < names.length; i++) {
            let args = fields[names[i]];
            if (!Array.isArray(args)) {
                args = [args];
            }
            (0, validate_1.validateProperty)(content, names[i], ...args);
        }
    }
}
/**
 * Validate a `Kernel.IModel` object.
 */
function validateModel(model) {
    (0, validate_1.validateProperty)(model, 'name', 'string');
    (0, validate_1.validateProperty)(model, 'id', 'string');
}
exports.validateModel = validateModel;
/**
 * Validate an array of `IModel` objects.
 */
function validateModels(models) {
    if (!Array.isArray(models)) {
        throw new Error('Invalid kernel list');
    }
    models.forEach(d => validateModel(d));
}
exports.validateModels = validateModels;
//# sourceMappingURL=validate.js.map

/***/ }),

/***/ 2946:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.KernelSpecAPI = exports.KernelSpec = void 0;
const KernelSpec = __importStar(__webpack_require__(4806));
exports.KernelSpec = KernelSpec;
const KernelSpecAPI = __importStar(__webpack_require__(6492));
exports.KernelSpecAPI = KernelSpecAPI;
__exportStar(__webpack_require__(733), exports);
//# sourceMappingURL=index.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=kernelspec.js.map

/***/ }),

/***/ 733:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.KernelSpecManager = void 0;
const coreutils_1 = __webpack_require__(5764);
const polling_1 = __webpack_require__(6049);
const signaling_1 = __webpack_require__(3992);
const restapi = __importStar(__webpack_require__(6492));
const basemanager_1 = __webpack_require__(3867);
/**
 * An implementation of a kernel spec manager.
 */
class KernelSpecManager extends basemanager_1.BaseManager {
    /**
     * Construct a new kernel spec manager.
     *
     * @param options - The default options for kernel.
     */
    constructor(options = {}) {
        var _a;
        super(options);
        this._isReady = false;
        this._connectionFailure = new signaling_1.Signal(this);
        this._specs = null;
        this._specsChanged = new signaling_1.Signal(this);
        // Initialize internal data.
        this._ready = Promise.all([this.requestSpecs()])
            .then(_ => undefined)
            .catch(_ => undefined)
            .then(() => {
            if (this.isDisposed) {
                return;
            }
            this._isReady = true;
        });
        this._pollSpecs = new polling_1.Poll({
            auto: false,
            factory: () => this.requestSpecs(),
            frequency: {
                interval: 61 * 1000,
                backoff: true,
                max: 300 * 1000
            },
            name: `@jupyterlab/services:KernelSpecManager#specs`,
            standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'
        });
        void this.ready.then(() => {
            void this._pollSpecs.start();
        });
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._ready;
    }
    /**
     * Get the most recently fetched kernel specs.
     */
    get specs() {
        return this._specs;
    }
    /**
     * A signal emitted when the specs change.
     */
    get specsChanged() {
        return this._specsChanged;
    }
    /**
     * A signal emitted when there is a connection failure.
     */
    get connectionFailure() {
        return this._connectionFailure;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        this._pollSpecs.dispose();
        super.dispose();
    }
    /**
     * Force a refresh of the specs from the server.
     *
     * @returns A promise that resolves when the specs are fetched.
     *
     * #### Notes
     * This is intended to be called only in response to a user action,
     * since the manager maintains its internal state.
     */
    async refreshSpecs() {
        await this._pollSpecs.refresh();
        await this._pollSpecs.tick;
    }
    /**
     * Execute a request to the server to poll specs and update state.
     */
    async requestSpecs() {
        const specs = await restapi.getSpecs(this.serverSettings);
        if (this.isDisposed) {
            return;
        }
        if (!coreutils_1.JSONExt.deepEqual(specs, this._specs)) {
            this._specs = specs;
            this._specsChanged.emit(specs);
        }
    }
}
exports.KernelSpecManager = KernelSpecManager;
//# sourceMappingURL=manager.js.map

/***/ }),

/***/ 6492:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSpecs = void 0;
const serverconnection_1 = __webpack_require__(2920);
const validate_1 = __webpack_require__(2598);
const coreutils_1 = __webpack_require__(8925);
/**
 * The url for the kernelspec service.
 */
const KERNELSPEC_SERVICE_URL = 'api/kernelspecs';
/**
 * Fetch all of the kernel specs.
 *
 * @param settings - The optional server settings.
 * @param useCache - Whether to use the cache. If false, always request.
 *
 * @returns A promise that resolves with the kernel specs.
 *
 * #### Notes
 * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernelspecs).
 */
async function getSpecs(settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, KERNELSPEC_SERVICE_URL);
    const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    return (0, validate_1.validateSpecModels)(data);
}
exports.getSpecs = getSpecs;
//# sourceMappingURL=restapi.js.map

/***/ }),

/***/ 2598:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateSpecModels = exports.validateSpecModel = void 0;
const validate_1 = __webpack_require__(7441);
/**
 * Validate a server kernelspec model to a client side model.
 */
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function validateSpecModel(data) {
    const spec = data.spec;
    if (!spec) {
        throw new Error('Invalid kernel spec');
    }
    (0, validate_1.validateProperty)(data, 'name', 'string');
    (0, validate_1.validateProperty)(data, 'resources', 'object');
    (0, validate_1.validateProperty)(spec, 'language', 'string');
    (0, validate_1.validateProperty)(spec, 'display_name', 'string');
    (0, validate_1.validateProperty)(spec, 'argv', 'array');
    let metadata = null;
    if (spec.hasOwnProperty('metadata')) {
        (0, validate_1.validateProperty)(spec, 'metadata', 'object');
        metadata = spec.metadata;
    }
    let env = null;
    if (spec.hasOwnProperty('env')) {
        (0, validate_1.validateProperty)(spec, 'env', 'object');
        env = spec.env;
    }
    return {
        name: data.name,
        resources: data.resources,
        language: spec.language,
        display_name: spec.display_name,
        argv: spec.argv,
        metadata,
        env
    };
}
exports.validateSpecModel = validateSpecModel;
/**
 * Validate a `Kernel.ISpecModels` object.
 */
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function validateSpecModels(data) {
    if (!data.hasOwnProperty('kernelspecs')) {
        throw new Error('No kernelspecs found');
    }
    let keys = Object.keys(data.kernelspecs);
    const kernelspecs = Object.create(null);
    let defaultSpec = data.default;
    for (let i = 0; i < keys.length; i++) {
        const ks = data.kernelspecs[keys[i]];
        try {
            kernelspecs[keys[i]] = validateSpecModel(ks);
        }
        catch (err) {
            // Remove the errant kernel spec.
            console.warn(`Removing errant kernel spec: ${keys[i]}`);
        }
    }
    keys = Object.keys(kernelspecs);
    if (!keys.length) {
        throw new Error('No valid kernelspecs found');
    }
    if (!defaultSpec ||
        typeof defaultSpec !== 'string' ||
        !(defaultSpec in kernelspecs)) {
        defaultSpec = keys[0];
        console.warn(`Default kernel not found, using '${keys[0]}'`);
    }
    return {
        default: defaultSpec,
        kernelspecs
    };
}
exports.validateSpecModels = validateSpecModels;
//# sourceMappingURL=validate.js.map

/***/ }),

/***/ 9740:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ServiceManager = void 0;
const signaling_1 = __webpack_require__(3992);
const builder_1 = __webpack_require__(4219);
const contents_1 = __webpack_require__(8790);
const event_1 = __webpack_require__(9480);
const kernel_1 = __webpack_require__(973);
const kernelspec_1 = __webpack_require__(2946);
const nbconvert_1 = __webpack_require__(8683);
const serverconnection_1 = __webpack_require__(2920);
const session_1 = __webpack_require__(7668);
const setting_1 = __webpack_require__(7780);
const terminal_1 = __webpack_require__(9040);
const user_1 = __webpack_require__(9191);
const workspace_1 = __webpack_require__(8053);
/**
 * A Jupyter services manager.
 */
class ServiceManager {
    /**
     * Construct a new services provider.
     */
    constructor(options = {}) {
        var _a, _b;
        this._isDisposed = false;
        this._connectionFailure = new signaling_1.Signal(this);
        this._isReady = false;
        const defaultDrive = options.defaultDrive;
        const serverSettings = (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();
        const standby = (_b = options.standby) !== null && _b !== void 0 ? _b : 'when-hidden';
        const normalized = { defaultDrive, serverSettings, standby };
        this.serverSettings = serverSettings;
        this.contents = options.contents || new contents_1.ContentsManager(normalized);
        this.events = options.events || new event_1.EventManager(normalized);
        this.kernels = options.kernels || new kernel_1.KernelManager(normalized);
        this.sessions =
            options.sessions ||
                new session_1.SessionManager({
                    ...normalized,
                    kernelManager: this.kernels
                });
        this.settings = options.settings || new setting_1.SettingManager(normalized);
        this.terminals = options.terminals || new terminal_1.TerminalManager(normalized);
        this.builder = options.builder || new builder_1.BuildManager(normalized);
        this.workspaces = options.workspaces || new workspace_1.WorkspaceManager(normalized);
        this.nbconvert = options.nbconvert || new nbconvert_1.NbConvertManager(normalized);
        this.kernelspecs = options.kernelspecs || new kernelspec_1.KernelSpecManager(normalized);
        this.user = options.user || new user_1.UserManager(normalized);
        // Proxy all connection failures from the individual service managers.
        this.kernelspecs.connectionFailure.connect(this._onConnectionFailure, this);
        this.sessions.connectionFailure.connect(this._onConnectionFailure, this);
        this.terminals.connectionFailure.connect(this._onConnectionFailure, this);
        // Define promises that need to be resolved before service manager is ready.
        const readyList = [this.sessions.ready, this.kernelspecs.ready];
        if (this.terminals.isAvailable()) {
            readyList.push(this.terminals.ready);
        }
        this._readyPromise = Promise.all(readyList).then(() => {
            this._isReady = true;
        });
    }
    /**
     * A signal emitted when there is a connection failure with the kernel.
     */
    get connectionFailure() {
        return this._connectionFailure;
    }
    /**
     * Test whether the service manager is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        signaling_1.Signal.clearData(this);
        this.contents.dispose();
        this.events.dispose();
        this.sessions.dispose();
        this.terminals.dispose();
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._readyPromise;
    }
    _onConnectionFailure(sender, err) {
        this._connectionFailure.emit(err);
    }
}
exports.ServiceManager = ServiceManager;
//# sourceMappingURL=manager.js.map

/***/ }),

/***/ 8683:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NbConvertManager = void 0;
const coreutils_1 = __webpack_require__(8925);
const serverconnection_1 = __webpack_require__(2920);
const coreutils_2 = __webpack_require__(5764);
/**
 * The url for the lab nbconvert service.
 */
const NBCONVERT_SETTINGS_URL = 'api/nbconvert';
/**
 * The nbconvert API service manager.
 */
class NbConvertManager {
    /**
     * Create a new nbconvert manager.
     */
    constructor(options = {}) {
        var _a;
        this._exportFormats = null;
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * Fetch and cache the export formats from the expensive nbconvert handler.
     */
    async fetchExportFormats() {
        this._requestingFormats = new coreutils_2.PromiseDelegate();
        this._exportFormats = null;
        const base = this.serverSettings.baseUrl;
        const url = coreutils_1.URLExt.join(base, NBCONVERT_SETTINGS_URL);
        const { serverSettings } = this;
        const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, serverSettings);
        if (response.status !== 200) {
            const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
            throw err;
        }
        const data = await response.json();
        const exportList = {};
        const keys = Object.keys(data);
        keys.forEach(function (key) {
            const mimeType = data[key].output_mimetype;
            exportList[key] = { output_mimetype: mimeType };
        });
        this._exportFormats = exportList;
        this._requestingFormats.resolve(exportList);
        return exportList;
    }
    /**
     * Get the list of export formats, preferring pre-cached ones.
     */
    async getExportFormats(force = true) {
        if (this._requestingFormats) {
            return this._requestingFormats.promise;
        }
        if (force || !this._exportFormats) {
            return await this.fetchExportFormats();
        }
        return this._exportFormats;
    }
}
exports.NbConvertManager = NbConvertManager;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 2920:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ServerConnection = void 0;
const coreutils_1 = __webpack_require__(8925);
const serialize_1 = __webpack_require__(7179);
let WEBSOCKET;
if (typeof window === 'undefined') {
    // Mangle the require statements so it does not get picked up in the
    // browser assets.
    WEBSOCKET = __webpack_require__(7251);
}
else {
    WEBSOCKET = WebSocket;
}
/**
 * The namespace for ServerConnection functions.
 *
 * #### Notes
 * This is only intended to manage communication with the Jupyter server.
 *
 * The default values can be used in a JupyterLab or Jupyter Notebook context.
 *
 * We use `token` authentication if available, falling back on an XSRF
 * cookie if one has been provided on the `document`.
 *
 * A content type of `'application/json'` is added when using authentication
 * and there is no body data to allow the server to prevent malicious forms.
 */
var ServerConnection;
(function (ServerConnection) {
    /**
     * Create a settings object given a subset of options.
     *
     * @param options - An optional partial set of options.
     *
     * @returns The full settings object.
     */
    function makeSettings(options) {
        return Private.makeSettings(options);
    }
    ServerConnection.makeSettings = makeSettings;
    /**
     * Make an request to the notebook server.
     *
     * @param url - The url for the request.
     *
     * @param init - The initialization options for the request.
     *
     * @param settings - The server settings to apply to the request.
     *
     * @returns a Promise that resolves with the response.
     *
     * @throws If the url of the request is not a notebook server url.
     *
     * #### Notes
     * The `url` must start with `settings.baseUrl`.  The `init` settings are
     * merged with `settings.init`, with `init` taking precedence.
     * The headers in the two objects are not merged.
     * If there is no body data, we set the content type to `application/json`
     * because it is required by the Notebook server.
     */
    function makeRequest(url, init, settings) {
        return Private.handleRequest(url, init, settings);
    }
    ServerConnection.makeRequest = makeRequest;
    /**
     * A wrapped error for a fetch response.
     */
    class ResponseError extends Error {
        /**
         * Create a ResponseError from a response, handling the traceback and message
         * as appropriate.
         *
         * @param response The response object.
         *
         * @returns A promise that resolves with a `ResponseError` object.
         */
        static async create(response) {
            try {
                const data = await response.json();
                const { message, traceback } = data;
                if (traceback) {
                    console.error(traceback);
                }
                return new ResponseError(response, message !== null && message !== void 0 ? message : ResponseError._defaultMessage(response), traceback !== null && traceback !== void 0 ? traceback : '');
            }
            catch (e) {
                console.debug(e);
                return new ResponseError(response);
            }
        }
        /**
         * Create a new response error.
         */
        constructor(response, message = ResponseError._defaultMessage(response), traceback = '') {
            super(message);
            this.response = response;
            this.traceback = traceback;
        }
        static _defaultMessage(response) {
            return `Invalid response: ${response.status} ${response.statusText}`;
        }
    }
    ServerConnection.ResponseError = ResponseError;
    /**
     * A wrapped error for a network error.
     */
    class NetworkError extends TypeError {
        /**
         * Create a new network error.
         */
        constructor(original) {
            super(original.message);
            this.stack = original.stack;
        }
    }
    ServerConnection.NetworkError = NetworkError;
})(ServerConnection || (exports.ServerConnection = ServerConnection = {}));
/**
 * The namespace for module private data.
 */
var Private;
(function (Private) {
    /**
     * Handle the server connection settings, returning a new value.
     */
    function makeSettings(options = {}) {
        var _a;
        const pageBaseUrl = coreutils_1.PageConfig.getBaseUrl();
        const pageWsUrl = coreutils_1.PageConfig.getWsUrl();
        const baseUrl = coreutils_1.URLExt.normalize(options.baseUrl) || pageBaseUrl;
        let wsUrl = options.wsUrl;
        // Prefer the default wsUrl if we are using the default baseUrl.
        if (!wsUrl && baseUrl === pageBaseUrl) {
            wsUrl = pageWsUrl;
        }
        // Otherwise convert the baseUrl to a wsUrl if possible.
        if (!wsUrl && baseUrl.indexOf('http') === 0) {
            wsUrl = 'ws' + baseUrl.slice(4);
        }
        // Otherwise fall back on the default wsUrl.
        wsUrl = wsUrl !== null && wsUrl !== void 0 ? wsUrl : pageWsUrl;
        const appendTokenConfig = coreutils_1.PageConfig.getOption('appendToken').toLowerCase();
        let appendToken;
        if (appendTokenConfig === '') {
            appendToken =
                typeof window === 'undefined' ||
                    (typeof process !== 'undefined' &&
                        ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.JEST_WORKER_ID) !== undefined) ||
                    coreutils_1.URLExt.getHostName(pageBaseUrl) !== coreutils_1.URLExt.getHostName(wsUrl);
        }
        else {
            appendToken = appendTokenConfig === 'true';
        }
        return {
            init: { cache: 'no-store', credentials: 'same-origin' },
            fetch,
            Headers,
            Request,
            WebSocket: WEBSOCKET,
            token: coreutils_1.PageConfig.getToken(),
            appUrl: coreutils_1.PageConfig.getOption('appUrl'),
            appendToken,
            serializer: { serialize: serialize_1.serialize, deserialize: serialize_1.deserialize },
            ...options,
            baseUrl,
            wsUrl
        };
    }
    Private.makeSettings = makeSettings;
    /**
     * Handle a request.
     *
     * @param url - The url for the request.
     *
     * @param init - The overrides for the request init.
     *
     * @param settings - The settings object for the request.
     *
     * #### Notes
     * The `url` must start with `settings.baseUrl`.  The `init` settings
     * take precedence over `settings.init`.
     */
    function handleRequest(url, init, settings) {
        var _a;
        // Handle notebook server requests.
        if (url.indexOf(settings.baseUrl) !== 0) {
            throw new Error('Can only be used for notebook server requests');
        }
        // Use explicit cache buster when `no-store` is set since
        // not all browsers use it properly.
        const cache = (_a = init.cache) !== null && _a !== void 0 ? _a : settings.init.cache;
        if (cache === 'no-store') {
            // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
            url += (/\?/.test(url) ? '&' : '?') + new Date().getTime();
        }
        const request = new settings.Request(url, { ...settings.init, ...init });
        // Handle authentication. Authentication can be overdetermined by
        // settings token and XSRF token.
        let authenticated = false;
        if (settings.token) {
            authenticated = true;
            request.headers.append('Authorization', `token ${settings.token}`);
        }
        if (typeof document !== 'undefined') {
            const xsrfToken = getCookie('_xsrf');
            if (xsrfToken !== undefined) {
                authenticated = true;
                request.headers.append('X-XSRFToken', xsrfToken);
            }
        }
        // Set the content type if there is no given data and we are
        // using an authenticated connection.
        if (!request.headers.has('Content-Type') && authenticated) {
            request.headers.set('Content-Type', 'application/json');
        }
        // Use `call` to avoid a `TypeError` in the browser.
        return settings.fetch.call(null, request).catch((e) => {
            // Convert the TypeError into a more specific error.
            throw new ServerConnection.NetworkError(e);
        });
        // TODO: *this* is probably where we need a system-wide connectionFailure
        // signal we can hook into.
    }
    Private.handleRequest = handleRequest;
    /**
     * Get a cookie from the document.
     */
    function getCookie(name) {
        // From http://www.tornadoweb.org/en/stable/guide/security.html
        let cookie = '';
        try {
            cookie = document.cookie;
        }
        catch (e) {
            // e.g. SecurityError in case of CSP Sandbox
            return;
        }
        const matches = cookie.match('\\b' + name + '=([^;]*)\\b');
        return matches === null || matches === void 0 ? void 0 : matches[1];
    }
})(Private || (Private = {}));
//# sourceMappingURL=serverconnection.js.map

/***/ }),

/***/ 5341:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SessionConnection = void 0;
const signaling_1 = __webpack_require__(3992);
const __1 = __webpack_require__(7883);
const restapi_1 = __webpack_require__(7570);
const coreutils_1 = __webpack_require__(5764);
/**
 * Session object for accessing the session REST api. The session
 * should be used to start kernels and then shut them down -- for
 * all other kernel operations, the kernel object should be used.
 */
class SessionConnection {
    /**
     * Construct a new session.
     */
    constructor(options) {
        var _a, _b, _c, _d;
        this._id = '';
        this._path = '';
        this._name = '';
        this._type = '';
        this._kernel = null;
        this._isDisposed = false;
        this._disposed = new signaling_1.Signal(this);
        this._kernelChanged = new signaling_1.Signal(this);
        this._statusChanged = new signaling_1.Signal(this);
        this._connectionStatusChanged = new signaling_1.Signal(this);
        this._pendingInput = new signaling_1.Signal(this);
        this._iopubMessage = new signaling_1.Signal(this);
        this._unhandledMessage = new signaling_1.Signal(this);
        this._anyMessage = new signaling_1.Signal(this);
        this._propertyChanged = new signaling_1.Signal(this);
        this._id = options.model.id;
        this._name = options.model.name;
        this._path = options.model.path;
        this._type = options.model.type;
        this._username = (_a = options.username) !== null && _a !== void 0 ? _a : '';
        this._clientId = (_b = options.clientId) !== null && _b !== void 0 ? _b : coreutils_1.UUID.uuid4();
        this._connectToKernel = options.connectToKernel;
        this._kernelConnectionOptions = (_c = options.kernelConnectionOptions) !== null && _c !== void 0 ? _c : {};
        this.serverSettings =
            (_d = options.serverSettings) !== null && _d !== void 0 ? _d : __1.ServerConnection.makeSettings();
        this.setupKernel(options.model.kernel);
    }
    /**
     * A signal emitted when the session is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * A signal emitted when the kernel changes.
     */
    get kernelChanged() {
        return this._kernelChanged;
    }
    /**
     * A signal proxied from the connection about the kernel status.
     */
    get statusChanged() {
        return this._statusChanged;
    }
    /**
     * A signal proxied from the kernel about the connection status.
     */
    get connectionStatusChanged() {
        return this._connectionStatusChanged;
    }
    /**
     * A signal proxied from the kernel pending input.
     */
    get pendingInput() {
        return this._pendingInput;
    }
    /**
     * A signal proxied from the kernel about iopub kernel messages.
     */
    get iopubMessage() {
        return this._iopubMessage;
    }
    /**
     * A signal proxied from the kernel for an unhandled kernel message.
     */
    get unhandledMessage() {
        return this._unhandledMessage;
    }
    /**
     * A signal proxied from the kernel emitted for any kernel message.
     *
     * #### Notes
     * The behavior is undefined if the message is modified during message
     * handling. As such, it should be treated as read-only.
     */
    get anyMessage() {
        return this._anyMessage;
    }
    /**
     * A signal emitted when a session property changes.
     */
    get propertyChanged() {
        return this._propertyChanged;
    }
    /**
     * Get the session id.
     */
    get id() {
        return this._id;
    }
    /**
     * Get the session kernel connection object.
     *
     * #### Notes
     * This is a read-only property, and can be altered by [changeKernel].
     */
    get kernel() {
        return this._kernel;
    }
    /**
     * Get the session path.
     */
    get path() {
        return this._path;
    }
    /**
     * Get the session type.
     */
    get type() {
        return this._type;
    }
    /**
     * Get the session name.
     */
    get name() {
        return this._name;
    }
    /**
     * Get the model associated with the session.
     */
    get model() {
        return {
            id: this.id,
            kernel: this.kernel && { id: this.kernel.id, name: this.kernel.name },
            path: this._path,
            type: this._type,
            name: this._name
        };
    }
    /**
     * Test whether the session has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Update the session based on a session model from the server.
     *
     * #### Notes
     * This only updates this session connection instance. Use `setPath`,
     * `setName`, `setType`, and `changeKernel` to change the session values on
     * the server.
     */
    update(model) {
        const oldModel = this.model;
        this._path = model.path;
        this._name = model.name;
        this._type = model.type;
        if ((this._kernel === null && model.kernel !== null) ||
            (this._kernel !== null && model.kernel === null) ||
            (this._kernel !== null &&
                model.kernel !== null &&
                this._kernel.id !== model.kernel.id)) {
            if (this._kernel !== null) {
                this._kernel.dispose();
            }
            const oldValue = this._kernel || null;
            this.setupKernel(model.kernel);
            const newValue = this._kernel || null;
            this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });
        }
        this._handleModelChange(oldModel);
    }
    /**
     * Dispose of the resources held by the session.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._disposed.emit();
        if (this._kernel) {
            this._kernel.dispose();
            const oldValue = this._kernel;
            this._kernel = null;
            const newValue = this._kernel;
            this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });
        }
        signaling_1.Signal.clearData(this);
    }
    /**
     * Change the session path.
     *
     * @param path - The new session path.
     *
     * @returns A promise that resolves when the session has renamed.
     *
     * #### Notes
     * This uses the Jupyter REST API, and the response is validated.
     * The promise is fulfilled on a valid response and rejected otherwise.
     */
    async setPath(path) {
        if (this.isDisposed) {
            throw new Error('Session is disposed');
        }
        await this._patch({ path });
    }
    /**
     * Change the session name.
     */
    async setName(name) {
        if (this.isDisposed) {
            throw new Error('Session is disposed');
        }
        await this._patch({ name });
    }
    /**
     * Change the session type.
     */
    async setType(type) {
        if (this.isDisposed) {
            throw new Error('Session is disposed');
        }
        await this._patch({ type });
    }
    /**
     * Change the kernel.
     *
     * @param options - The name or id of the new kernel.
     *
     * #### Notes
     * This shuts down the existing kernel and creates a new kernel,
     * keeping the existing session ID and session path.
     */
    async changeKernel(options) {
        if (this.isDisposed) {
            throw new Error('Session is disposed');
        }
        await this._patch({ kernel: options });
        return this.kernel;
    }
    /**
     * Kill the kernel and shutdown the session.
     *
     * @returns - The promise fulfilled on a valid response from the server.
     *
     * #### Notes
     * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions), and validates the response.
     * Disposes of the session and emits a [sessionDied] signal on success.
     */
    async shutdown() {
        if (this.isDisposed) {
            throw new Error('Session is disposed');
        }
        await (0, restapi_1.shutdownSession)(this.id, this.serverSettings);
        this.dispose();
    }
    /**
     * Create a new kernel connection and connect to its signals.
     *
     * #### Notes
     * This method is not meant to be subclassed.
     */
    setupKernel(model) {
        if (model === null) {
            this._kernel = null;
            return;
        }
        const kc = this._connectToKernel({
            ...this._kernelConnectionOptions,
            model,
            username: this._username,
            clientId: this._clientId,
            serverSettings: this.serverSettings
        });
        this._kernel = kc;
        kc.statusChanged.connect(this.onKernelStatus, this);
        kc.connectionStatusChanged.connect(this.onKernelConnectionStatus, this);
        kc.pendingInput.connect(this.onPendingInput, this);
        kc.unhandledMessage.connect(this.onUnhandledMessage, this);
        kc.iopubMessage.connect(this.onIOPubMessage, this);
        kc.anyMessage.connect(this.onAnyMessage, this);
    }
    /**
     * Handle to changes in the Kernel status.
     */
    onKernelStatus(sender, state) {
        this._statusChanged.emit(state);
    }
    /**
     * Handle to changes in the Kernel status.
     */
    onKernelConnectionStatus(sender, state) {
        this._connectionStatusChanged.emit(state);
    }
    /**
     * Handle a change in the pendingInput.
     */
    onPendingInput(sender, state) {
        this._pendingInput.emit(state);
    }
    /**
     * Handle iopub kernel messages.
     */
    onIOPubMessage(sender, msg) {
        this._iopubMessage.emit(msg);
    }
    /**
     * Handle unhandled kernel messages.
     */
    onUnhandledMessage(sender, msg) {
        this._unhandledMessage.emit(msg);
    }
    /**
     * Handle any kernel messages.
     */
    onAnyMessage(sender, args) {
        this._anyMessage.emit(args);
    }
    /**
     * Send a PATCH to the server, updating the session path or the kernel.
     */
    async _patch(body) {
        const model = await (0, restapi_1.updateSession)({ ...body, id: this._id }, this.serverSettings);
        this.update(model);
        return model;
    }
    /**
     * Handle a change to the model.
     */
    _handleModelChange(oldModel) {
        if (oldModel.name !== this._name) {
            this._propertyChanged.emit('name');
        }
        if (oldModel.type !== this._type) {
            this._propertyChanged.emit('type');
        }
        if (oldModel.path !== this._path) {
            this._propertyChanged.emit('path');
        }
    }
}
exports.SessionConnection = SessionConnection;
//# sourceMappingURL=default.js.map

/***/ }),

/***/ 7668:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SessionAPI = exports.Session = void 0;
const Session = __importStar(__webpack_require__(7240));
exports.Session = Session;
const SessionAPI = __importStar(__webpack_require__(7570));
exports.SessionAPI = SessionAPI;
__exportStar(__webpack_require__(6919), exports);
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 6919:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SessionManager = void 0;
const polling_1 = __webpack_require__(6049);
const signaling_1 = __webpack_require__(3992);
const serverconnection_1 = __webpack_require__(2920);
const basemanager_1 = __webpack_require__(3867);
const default_1 = __webpack_require__(5341);
const restapi_1 = __webpack_require__(7570);
/**
 * An implementation of a session manager.
 */
class SessionManager extends basemanager_1.BaseManager {
    /**
     * Construct a new session manager.
     *
     * @param options - The default options for each session.
     */
    constructor(options) {
        var _a;
        super(options);
        this._isReady = false;
        this._sessionConnections = new Set();
        this._models = new Map();
        this._runningChanged = new signaling_1.Signal(this);
        this._connectionFailure = new signaling_1.Signal(this);
        // We define these here so they bind `this` correctly
        this._connectToKernel = (options) => {
            return this._kernelManager.connectTo(options);
        };
        this._kernelManager = options.kernelManager;
        // Start model polling with exponential backoff.
        this._pollModels = new polling_1.Poll({
            auto: false,
            factory: () => this.requestRunning(),
            frequency: {
                interval: 10 * 1000,
                backoff: true,
                max: 300 * 1000
            },
            name: `@jupyterlab/services:SessionManager#models`,
            standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'
        });
        // Initialize internal data.
        this._ready = (async () => {
            await this._pollModels.start();
            await this._pollModels.tick;
            if (this._kernelManager.isActive) {
                await this._kernelManager.ready;
            }
            this._isReady = true;
        })();
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._ready;
    }
    /**
     * A signal emitted when the running sessions change.
     */
    get runningChanged() {
        return this._runningChanged;
    }
    /**
     * A signal emitted when there is a connection failure.
     */
    get connectionFailure() {
        return this._connectionFailure;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._models.clear();
        this._sessionConnections.forEach(x => x.dispose());
        this._pollModels.dispose();
        super.dispose();
    }
    /*
     * Connect to a running session.  See also [[connectToSession]].
     */
    connectTo(options) {
        const sessionConnection = new default_1.SessionConnection({
            ...options,
            connectToKernel: this._connectToKernel,
            serverSettings: this.serverSettings
        });
        this._onStarted(sessionConnection);
        if (!this._models.has(options.model.id)) {
            // We trust the user to connect to an existing session, but we verify
            // asynchronously.
            void this.refreshRunning().catch(() => {
                /* no-op */
            });
        }
        return sessionConnection;
    }
    /**
     * Create an iterator over the most recent running sessions.
     *
     * @returns A new iterator over the running sessions.
     */
    running() {
        return this._models.values();
    }
    /**
     * Force a refresh of the running sessions.
     *
     * @returns A promise that with the list of running sessions.
     *
     * #### Notes
     * This is not typically meant to be called by the user, since the
     * manager maintains its own internal state.
     */
    async refreshRunning() {
        await this._pollModels.refresh();
        await this._pollModels.tick;
    }
    /**
     * Start a new session.  See also [[startNewSession]].
     *
     * @param createOptions - Options for creating the session
     *
     * @param connectOptions - Options for connecting to the session
     */
    async startNew(createOptions, connectOptions = {}) {
        const model = await (0, restapi_1.startSession)(createOptions, this.serverSettings);
        await this.refreshRunning();
        return this.connectTo({ ...connectOptions, model });
    }
    /**
     * Shut down a session by id.
     */
    async shutdown(id) {
        await (0, restapi_1.shutdownSession)(id, this.serverSettings);
        await this.refreshRunning();
    }
    /**
     * Shut down all sessions.
     *
     * @returns A promise that resolves when all of the kernels are shut down.
     */
    async shutdownAll() {
        // Update the list of models to make sure our list is current.
        await this.refreshRunning();
        // Shut down all models.
        await Promise.all([...this._models.keys()].map(id => (0, restapi_1.shutdownSession)(id, this.serverSettings)));
        // Update the list of models to clear out our state.
        await this.refreshRunning();
    }
    /**
     * Find a session associated with a path and stop it if it is the only session
     * using that kernel.
     *
     * @param path - The path in question.
     *
     * @returns A promise that resolves when the relevant sessions are stopped.
     */
    async stopIfNeeded(path) {
        try {
            const sessions = await (0, restapi_1.listRunning)(this.serverSettings);
            const matches = sessions.filter(value => value.path === path);
            if (matches.length === 1) {
                const id = matches[0].id;
                await this.shutdown(id);
            }
        }
        catch (error) {
            /* Always succeed. */
        }
    }
    /**
     * Find a session by id.
     */
    async findById(id) {
        if (this._models.has(id)) {
            return this._models.get(id);
        }
        await this.refreshRunning();
        return this._models.get(id);
    }
    /**
     * Find a session by path.
     */
    async findByPath(path) {
        for (const m of this._models.values()) {
            if (m.path === path) {
                return m;
            }
        }
        await this.refreshRunning();
        for (const m of this._models.values()) {
            if (m.path === path) {
                return m;
            }
        }
        return undefined;
    }
    /**
     * Execute a request to the server to poll running kernels and update state.
     */
    async requestRunning() {
        var _a, _b;
        let models;
        try {
            models = await (0, restapi_1.listRunning)(this.serverSettings);
        }
        catch (err) {
            // Handle network errors, as well as cases where we are on a
            // JupyterHub and the server is not running. JupyterHub returns a
            // 503 (<2.0) or 424 (>2.0) in that case.
            if (err instanceof serverconnection_1.ServerConnection.NetworkError ||
                ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||
                ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {
                this._connectionFailure.emit(err);
            }
            throw err;
        }
        if (this.isDisposed) {
            return;
        }
        if (this._models.size === models.length &&
            models.every(model => {
                var _a, _b, _c, _d;
                const existing = this._models.get(model.id);
                if (!existing) {
                    return false;
                }
                return (((_a = existing.kernel) === null || _a === void 0 ? void 0 : _a.id) === ((_b = model.kernel) === null || _b === void 0 ? void 0 : _b.id) &&
                    ((_c = existing.kernel) === null || _c === void 0 ? void 0 : _c.name) === ((_d = model.kernel) === null || _d === void 0 ? void 0 : _d.name) &&
                    existing.name === model.name &&
                    existing.path === model.path &&
                    existing.type === model.type);
            })) {
            // Identical models list (presuming models does not contain duplicate
            // ids), so just return
            return;
        }
        this._models = new Map(models.map(x => [x.id, x]));
        this._sessionConnections.forEach(sc => {
            if (this._models.has(sc.id)) {
                sc.update(this._models.get(sc.id));
            }
            else {
                sc.dispose();
            }
        });
        this._runningChanged.emit(models);
    }
    /**
     * Handle a session starting.
     */
    _onStarted(sessionConnection) {
        this._sessionConnections.add(sessionConnection);
        sessionConnection.disposed.connect(this._onDisposed, this);
        sessionConnection.propertyChanged.connect(this._onChanged, this);
        sessionConnection.kernelChanged.connect(this._onChanged, this);
    }
    _onDisposed(sessionConnection) {
        this._sessionConnections.delete(sessionConnection);
        // A session termination emission could mean the server session is deleted,
        // or that the session JS object is disposed and the session still exists on
        // the server, so we refresh from the server to make sure we reflect the
        // server state.
        void this.refreshRunning().catch(() => {
            /* no-op */
        });
    }
    _onChanged() {
        void this.refreshRunning().catch(() => {
            /* no-op */
        });
    }
}
exports.SessionManager = SessionManager;
/**
 * The namespace for `SessionManager` class statics.
 */
(function (SessionManager) {
    /**
     * A no-op session manager to be used when starting sessions is not supported.
     */
    class NoopManager extends SessionManager {
        constructor() {
            super(...arguments);
            this._readyPromise = new Promise(() => {
                /* no-op */
            });
        }
        /**
         * Whether the manager is active.
         */
        get isActive() {
            return false;
        }
        /**
         * Used for testing.
         */
        get parentReady() {
            return super.ready;
        }
        /**
         * Start a new session - throw an error since it is not supported.
         */
        async startNew(createOptions, connectOptions = {}) {
            return Promise.reject(new Error('Not implemented in no-op Session Manager'));
        }
        /*
         * Connect to a running session - throw an error since it is not supported.
         */
        connectTo(options) {
            throw Error('Not implemented in no-op Session Manager');
        }
        /**
         * A promise that fulfills when the manager is ready (never).
         */
        get ready() {
            return this.parentReady.then(() => this._readyPromise);
        }
        /**
         * Shut down a session by id - throw an error since it is not supported.
         */
        async shutdown(id) {
            return Promise.reject(new Error('Not implemented in no-op Session Manager'));
        }
        /**
         * Execute a request to the server to poll running sessions and update state.
         */
        async requestRunning() {
            return Promise.resolve();
        }
    }
    SessionManager.NoopManager = NoopManager;
})(SessionManager || (exports.SessionManager = SessionManager = {}));
//# sourceMappingURL=manager.js.map

/***/ }),

/***/ 7570:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.updateSession = exports.startSession = exports.getSessionModel = exports.shutdownSession = exports.getSessionUrl = exports.listRunning = exports.SESSION_SERVICE_URL = void 0;
const serverconnection_1 = __webpack_require__(2920);
const coreutils_1 = __webpack_require__(8925);
const validate_1 = __webpack_require__(5684);
/**
 * The url for the session service.
 */
exports.SESSION_SERVICE_URL = 'api/sessions';
/**
 * List the running sessions.
 */
async function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.SESSION_SERVICE_URL);
    const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    if (!Array.isArray(data)) {
        throw new Error('Invalid Session list');
    }
    data.forEach(m => {
        (0, validate_1.updateLegacySessionModel)(m);
        (0, validate_1.validateModel)(m);
    });
    return data;
}
exports.listRunning = listRunning;
/**
 * Get a session url.
 */
function getSessionUrl(baseUrl, id) {
    const servicesBase = coreutils_1.URLExt.join(baseUrl, exports.SESSION_SERVICE_URL);
    const result = coreutils_1.URLExt.join(servicesBase, id);
    if (!result.startsWith(servicesBase)) {
        throw new Error('Can only be used for services requests');
    }
    return result;
}
exports.getSessionUrl = getSessionUrl;
/**
 * Shut down a session by id.
 */
async function shutdownSession(id, settings = serverconnection_1.ServerConnection.makeSettings()) {
    var _a;
    const url = getSessionUrl(settings.baseUrl, id);
    const init = { method: 'DELETE' };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status === 404) {
        const data = await response.json();
        const msg = (_a = data.message) !== null && _a !== void 0 ? _a : `The session "${id}"" does not exist on the server`;
        console.warn(msg);
    }
    else if (response.status === 410) {
        throw new serverconnection_1.ServerConnection.ResponseError(response, 'The kernel was deleted but the session was not');
    }
    else if (response.status !== 204) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
}
exports.shutdownSession = shutdownSession;
/**
 * Get a full session model from the server by session id string.
 */
async function getSessionModel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = getSessionUrl(settings.baseUrl, id);
    const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    (0, validate_1.updateLegacySessionModel)(data);
    (0, validate_1.validateModel)(data);
    return data;
}
exports.getSessionModel = getSessionModel;
/**
 * Create a new session, or return an existing session if the session path
 * already exists.
 */
async function startSession(options, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.SESSION_SERVICE_URL);
    const init = {
        method: 'POST',
        body: JSON.stringify(options)
    };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status !== 201) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    (0, validate_1.updateLegacySessionModel)(data);
    (0, validate_1.validateModel)(data);
    return data;
}
exports.startSession = startSession;
/**
 * Send a PATCH to the server, updating the session path or the kernel.
 */
async function updateSession(model, settings = serverconnection_1.ServerConnection.makeSettings()) {
    const url = getSessionUrl(settings.baseUrl, model.id);
    const init = {
        method: 'PATCH',
        body: JSON.stringify(model)
    };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    (0, validate_1.updateLegacySessionModel)(data);
    (0, validate_1.validateModel)(data);
    return data;
}
exports.updateSession = updateSession;
//# sourceMappingURL=restapi.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=session.js.map

/***/ }),

/***/ 5684:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateModels = exports.updateLegacySessionModel = exports.validateModel = void 0;
const validate_1 = __webpack_require__(5855);
const validate_2 = __webpack_require__(7441);
/**
 * Validate an `Session.IModel` object.
 */
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function validateModel(data) {
    (0, validate_2.validateProperty)(data, 'id', 'string');
    (0, validate_2.validateProperty)(data, 'type', 'string');
    (0, validate_2.validateProperty)(data, 'name', 'string');
    (0, validate_2.validateProperty)(data, 'path', 'string');
    (0, validate_2.validateProperty)(data, 'kernel', 'object');
    (0, validate_1.validateModel)(data.kernel);
}
exports.validateModel = validateModel;
/**
 * Update model from legacy session data.
 */
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function updateLegacySessionModel(data) {
    if (data.path === undefined && data.notebook !== undefined) {
        data.path = data.notebook.path;
        data.type = 'notebook';
        data.name = '';
    }
}
exports.updateLegacySessionModel = updateLegacySessionModel;
/**
 * Validate an array of `Session.IModel` objects.
 */
function validateModels(models) {
    if (!Array.isArray(models)) {
        throw new Error('Invalid session list');
    }
    models.forEach(d => validateModel(d));
}
exports.validateModels = validateModels;
//# sourceMappingURL=validate.js.map

/***/ }),

/***/ 7780:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SettingManager = void 0;
const coreutils_1 = __webpack_require__(8925);
const statedb_1 = __webpack_require__(1670);
const serverconnection_1 = __webpack_require__(2920);
/**
 * The url for the lab settings service.
 */
const SERVICE_SETTINGS_URL = 'api/settings';
/**
 * The settings API service manager.
 */
class SettingManager extends statedb_1.DataConnector {
    /**
     * Create a new setting manager.
     */
    constructor(options = {}) {
        var _a;
        super();
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * Fetch a plugin's settings.
     *
     * @param id - The plugin's ID.
     *
     * @returns A promise that resolves if successful.
     */
    async fetch(id) {
        if (!id) {
            throw new Error('Plugin `id` parameter is required for settings fetch.');
        }
        const { serverSettings } = this;
        const { baseUrl, appUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const base = baseUrl + appUrl;
        const url = Private.url(base, id);
        const response = await makeRequest(url, {}, serverSettings);
        if (response.status !== 200) {
            const err = await ResponseError.create(response);
            throw err;
        }
        // Assert what type the server response is returning.
        return response.json();
    }
    /**
     * Fetch the list of all plugin setting bundles.
     *
     * @returns A promise that resolves if successful.
     */
    async list(query) {
        var _a, _b, _c, _d;
        const { serverSettings } = this;
        const { baseUrl, appUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const base = baseUrl + appUrl;
        const url = Private.url(base, '', query === 'ids');
        const response = await makeRequest(url, {}, serverSettings);
        if (response.status !== 200) {
            throw new ResponseError(response);
        }
        const json = await response.json();
        const ids = (_b = (_a = json === null || json === void 0 ? void 0 : json['settings']) === null || _a === void 0 ? void 0 : _a.map((plugin) => plugin.id)) !== null && _b !== void 0 ? _b : [];
        let values = [];
        if (!query) {
            values =
                (_d = (_c = json === null || json === void 0 ? void 0 : json['settings']) === null || _c === void 0 ? void 0 : _c.map((plugin) => {
                    plugin.data = { composite: {}, user: {} };
                    return plugin;
                })) !== null && _d !== void 0 ? _d : [];
        }
        return { ids, values };
    }
    /**
     * Save a plugin's settings.
     *
     * @param id - The plugin's ID.
     *
     * @param raw - The user setting values as a raw string of JSON with comments.
     *
     * @returns A promise that resolves if successful.
     */
    async save(id, raw) {
        const { serverSettings } = this;
        const { baseUrl, appUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const base = baseUrl + appUrl;
        const url = Private.url(base, id);
        // NOTE: 'raw' is JSON5 (not valid JSON), so we encode it as a string in a valid JSON body
        const init = { body: JSON.stringify({ raw }), method: 'PUT' };
        const response = await makeRequest(url, init, serverSettings);
        if (response.status !== 204) {
            throw new ResponseError(response);
        }
    }
}
exports.SettingManager = SettingManager;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Get the url for a plugin's settings.
     */
    function url(base, id, idsOnly) {
        const idsOnlyParam = idsOnly
            ? coreutils_1.URLExt.objectToQueryString({ ids_only: true })
            : '';
        const settingsBase = coreutils_1.URLExt.join(base, SERVICE_SETTINGS_URL);
        const result = coreutils_1.URLExt.join(settingsBase, id);
        if (!result.startsWith(settingsBase)) {
            throw new Error('Can only be used for workspaces requests');
        }
        return `${result}${idsOnlyParam}`;
    }
    Private.url = url;
})(Private || (Private = {}));
//# sourceMappingURL=index.js.map

/***/ }),

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

"use strict";

/*
 * Copyright (c) Jupyter Development Team.
 * Distributed under the terms of the Modified BSD License.
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports["default"] = WebSocket;
//# sourceMappingURL=ws.js.map

/***/ }),

/***/ 9822:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TerminalConnection = void 0;
const coreutils_1 = __webpack_require__(8925);
const coreutils_2 = __webpack_require__(5764);
const signaling_1 = __webpack_require__(3992);
const __1 = __webpack_require__(7883);
const restapi_1 = __webpack_require__(6134);
/**
 * An implementation of a terminal interface.
 */
class TerminalConnection {
    /**
     * Construct a new terminal session.
     */
    constructor(options) {
        var _a;
        /**
         * Create the terminal websocket connection and add socket status handlers.
         *
         * #### Notes
         * You are responsible for updating the connection status as appropriate.
         */
        this._createSocket = () => {
            this._errorIfDisposed();
            // Make sure the socket is clear
            this._clearSocket();
            // Update the connection status to reflect opening a new connection.
            this._updateConnectionStatus('connecting');
            const name = this._name;
            const settings = this.serverSettings;
            let url = coreutils_1.URLExt.join(settings.wsUrl, 'terminals', 'websocket', encodeURIComponent(name));
            // If token authentication is in use.
            const token = settings.token;
            if (settings.appendToken && token !== '') {
                url = url + `?token=${encodeURIComponent(token)}`;
            }
            this._ws = new settings.WebSocket(url);
            this._ws.onmessage = this._onWSMessage;
            this._ws.onclose = this._onWSClose;
            this._ws.onerror = this._onWSClose;
        };
        // Websocket messages events are defined as variables to bind `this`
        this._onWSMessage = (event) => {
            if (this._isDisposed) {
                return;
            }
            const data = JSON.parse(event.data);
            // Handle a disconnect message.
            if (data[0] === 'disconnect') {
                this.dispose();
            }
            if (this._connectionStatus === 'connecting') {
                // After reconnection, ignore all messages until a 'setup' message
                // before we are truly connected. Setting the connection status to
                // connected only then means that if we do not get a setup message
                // before our retry timeout, we will delete the websocket and try again.
                if (data[0] === 'setup') {
                    this._updateConnectionStatus('connected');
                }
                return;
            }
            this._messageReceived.emit({
                type: data[0],
                content: data.slice(1)
            });
        };
        this._onWSClose = (event) => {
            console.warn(`Terminal websocket closed: ${event.code}`);
            if (!this.isDisposed) {
                this._reconnect();
            }
        };
        this._connectionStatus = 'connecting';
        this._connectionStatusChanged = new signaling_1.Signal(this);
        this._isDisposed = false;
        this._disposed = new signaling_1.Signal(this);
        this._messageReceived = new signaling_1.Signal(this);
        this._reconnectTimeout = null;
        this._ws = null;
        this._noOp = () => {
            /* no-op */
        };
        this._reconnectLimit = 7;
        this._reconnectAttempt = 0;
        this._pendingMessages = [];
        this._name = options.model.name;
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings();
        this._createSocket();
    }
    /**
     * A signal emitted when the session is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * A signal emitted when a message is received from the server.
     */
    get messageReceived() {
        return this._messageReceived;
    }
    /**
     * Get the name of the terminal session.
     */
    get name() {
        return this._name;
    }
    /**
     * Get the model for the terminal session.
     */
    get model() {
        return { name: this._name };
    }
    /**
     * Test whether the session is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the session.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._disposed.emit();
        this._updateConnectionStatus('disconnected');
        this._clearSocket();
        signaling_1.Signal.clearData(this);
    }
    /**
     * Send a message to the terminal session.
     *
     * #### Notes
     * If the connection is down, the message will be queued for sending when
     * the connection comes back up.
     */
    send(message) {
        this._sendMessage(message);
    }
    /**
     * Send a message on the websocket, or possibly queue for later sending.
     *
     * @param queue - whether to queue the message if it cannot be sent
     */
    _sendMessage(message, queue = true) {
        if (this._isDisposed || !message.content) {
            return;
        }
        if (this.connectionStatus === 'connected' && this._ws) {
            const msg = [message.type, ...message.content];
            this._ws.send(JSON.stringify(msg));
        }
        else if (queue) {
            this._pendingMessages.push(message);
        }
        else {
            throw new Error(`Could not send message: ${JSON.stringify(message)}`);
        }
    }
    /**
     * Send pending messages to the kernel.
     */
    _sendPending() {
        // We check to make sure we are still connected each time. For
        // example, if a websocket buffer overflows, it may close, so we should
        // stop sending messages.
        while (this.connectionStatus === 'connected' &&
            this._pendingMessages.length > 0) {
            this._sendMessage(this._pendingMessages[0], false);
            // We shift the message off the queue after the message is sent so that
            // if there is an exception, the message is still pending.
            this._pendingMessages.shift();
        }
    }
    /**
     * Reconnect to a terminal.
     *
     * #### Notes
     * This may try multiple times to reconnect to a terminal, and will sever
     * any existing connection.
     */
    reconnect() {
        this._errorIfDisposed();
        const result = new coreutils_2.PromiseDelegate();
        // Set up a listener for the connection status changing, which accepts or
        // rejects after the retries are done.
        const fulfill = (sender, status) => {
            if (status === 'connected') {
                result.resolve();
                this.connectionStatusChanged.disconnect(fulfill, this);
            }
            else if (status === 'disconnected') {
                result.reject(new Error('Terminal connection disconnected'));
                this.connectionStatusChanged.disconnect(fulfill, this);
            }
        };
        this.connectionStatusChanged.connect(fulfill, this);
        // Reset the reconnect limit so we start the connection attempts fresh
        this._reconnectAttempt = 0;
        // Start the reconnection process, which will also clear any existing
        // connection.
        this._reconnect();
        // Return the promise that should resolve on connection or reject if the
        // retries don't work.
        return result.promise;
    }
    /**
     * Attempt a connection if we have not exhausted connection attempts.
     */
    _reconnect() {
        this._errorIfDisposed();
        // Clear any existing reconnection attempt
        clearTimeout(this._reconnectTimeout);
        // Update the connection status and schedule a possible reconnection.
        if (this._reconnectAttempt < this._reconnectLimit) {
            this._updateConnectionStatus('connecting');
            // The first reconnect attempt should happen immediately, and subsequent
            // attempts should pick a random number in a growing range so that we
            // don't overload the server with synchronized reconnection attempts
            // across multiple kernels.
            const timeout = Private.getRandomIntInclusive(0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1));
            console.error(`Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`);
            this._reconnectTimeout = setTimeout(this._createSocket, timeout);
            this._reconnectAttempt += 1;
        }
        else {
            this._updateConnectionStatus('disconnected');
        }
        // Clear the websocket event handlers and the socket itself.
        this._clearSocket();
    }
    /**
     * Forcefully clear the socket state.
     *
     * #### Notes
     * This will clear all socket state without calling any handlers and will
     * not update the connection status. If you call this method, you are
     * responsible for updating the connection status as needed and recreating
     * the socket if you plan to reconnect.
     */
    _clearSocket() {
        if (this._ws !== null) {
            // Clear the websocket event handlers and the socket itself.
            this._ws.onopen = this._noOp;
            this._ws.onclose = this._noOp;
            this._ws.onerror = this._noOp;
            this._ws.onmessage = this._noOp;
            this._ws.close();
            this._ws = null;
        }
    }
    /**
     * Shut down the terminal session.
     */
    async shutdown() {
        await (0, restapi_1.shutdownTerminal)(this.name, this.serverSettings);
        this.dispose();
    }
    /**
     * Clone the current terminal connection.
     */
    clone() {
        return new TerminalConnection(this);
    }
    /**
     * Handle connection status changes.
     */
    _updateConnectionStatus(connectionStatus) {
        if (this._connectionStatus === connectionStatus) {
            return;
        }
        this._connectionStatus = connectionStatus;
        // If we are not 'connecting', stop any reconnection attempts.
        if (connectionStatus !== 'connecting') {
            this._reconnectAttempt = 0;
            clearTimeout(this._reconnectTimeout);
        }
        // Send the pending messages if we just connected.
        if (connectionStatus === 'connected') {
            this._sendPending();
        }
        // Notify others that the connection status changed.
        this._connectionStatusChanged.emit(connectionStatus);
    }
    /**
     * Utility function to throw an error if this instance is disposed.
     */
    _errorIfDisposed() {
        if (this.isDisposed) {
            throw new Error('Terminal connection is disposed');
        }
    }
    /**
     * A signal emitted when the terminal connection status changes.
     */
    get connectionStatusChanged() {
        return this._connectionStatusChanged;
    }
    /**
     * The current connection status of the terminal connection.
     */
    get connectionStatus() {
        return this._connectionStatus;
    }
}
exports.TerminalConnection = TerminalConnection;
var Private;
(function (Private) {
    /**
     * Get the url for a terminal.
     */
    function getTermUrl(baseUrl, name) {
        return coreutils_1.URLExt.join(baseUrl, restapi_1.TERMINAL_SERVICE_URL, encodeURIComponent(name));
    }
    Private.getTermUrl = getTermUrl;
    /**
     * Get a random integer between min and max, inclusive of both.
     *
     * #### Notes
     * From
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive
     *
     * From the MDN page: It might be tempting to use Math.round() to accomplish
     * that, but doing so would cause your random numbers to follow a non-uniform
     * distribution, which may not be acceptable for your needs.
     */
    function getRandomIntInclusive(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    Private.getRandomIntInclusive = getRandomIntInclusive;
})(Private || (Private = {}));
//# sourceMappingURL=default.js.map

/***/ }),

/***/ 9040:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TerminalAPI = exports.Terminal = void 0;
const Terminal = __importStar(__webpack_require__(6994));
exports.Terminal = Terminal;
const TerminalAPI = __importStar(__webpack_require__(6134));
exports.TerminalAPI = TerminalAPI;
__exportStar(__webpack_require__(9883), exports);
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 9883:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TerminalManager = void 0;
const polling_1 = __webpack_require__(6049);
const signaling_1 = __webpack_require__(3992);
const __1 = __webpack_require__(7883);
const basemanager_1 = __webpack_require__(3867);
const restapi_1 = __webpack_require__(6134);
const default_1 = __webpack_require__(9822);
/**
 * A terminal session manager.
 */
class TerminalManager extends basemanager_1.BaseManager {
    /**
     * Construct a new terminal manager.
     */
    constructor(options = {}) {
        var _a;
        super(options);
        this._isReady = false;
        // As an optimization, we unwrap the models to just store the names.
        this._names = [];
        this._terminalConnections = new Set();
        this._runningChanged = new signaling_1.Signal(this);
        this._connectionFailure = new signaling_1.Signal(this);
        // Check if terminals are available
        if (!this.isAvailable()) {
            this._ready = Promise.reject('Terminals unavailable');
            this._ready.catch(_ => undefined);
            return;
        }
        // Start polling with exponential backoff.
        this._pollModels = new polling_1.Poll({
            auto: false,
            factory: () => this.requestRunning(),
            frequency: {
                interval: 10 * 1000,
                backoff: true,
                max: 300 * 1000
            },
            name: `@jupyterlab/services:TerminalManager#models`,
            standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'
        });
        // Initialize internal data.
        this._ready = (async () => {
            await this._pollModels.start();
            await this._pollModels.tick;
            this._isReady = true;
        })();
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._ready;
    }
    /**
     * A signal emitted when the running terminals change.
     */
    get runningChanged() {
        return this._runningChanged;
    }
    /**
     * A signal emitted when there is a connection failure.
     */
    get connectionFailure() {
        return this._connectionFailure;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._names.length = 0;
        this._terminalConnections.forEach(x => x.dispose());
        this._pollModels.dispose();
        super.dispose();
    }
    /**
     * Whether the terminal service is available.
     */
    isAvailable() {
        return (0, restapi_1.isAvailable)();
    }
    /*
     * Connect to a running terminal.
     *
     * @param options - The options used to connect to the terminal.
     *
     * @returns The new terminal connection instance.
     *
     * #### Notes
     * The manager `serverSettings` will be used.
     */
    connectTo(options) {
        const terminalConnection = new default_1.TerminalConnection({
            ...options,
            serverSettings: this.serverSettings
        });
        this._onStarted(terminalConnection);
        if (!this._names.includes(options.model.name)) {
            // We trust the user to connect to an existing session, but we verify
            // asynchronously.
            void this.refreshRunning().catch(() => {
                /* no-op */
            });
        }
        return terminalConnection;
    }
    /**
     * Create an iterator over the most recent running terminals.
     *
     * @returns A new iterator over the running terminals.
     */
    running() {
        return this._models[Symbol.iterator]();
    }
    /**
     * Force a refresh of the running terminals.
     *
     * @returns A promise that with the list of running terminals.
     *
     * #### Notes
     * This is intended to be called only in response to a user action,
     * since the manager maintains its internal state.
     */
    async refreshRunning() {
        await this._pollModels.refresh();
        await this._pollModels.tick;
    }
    /**
     * Create a new terminal session.
     *
     * @param options - The options used to create the terminal.
     *
     * @returns A promise that resolves with the terminal connection instance.
     *
     * #### Notes
     * The manager `serverSettings` will be used unless overridden in the
     * options.
     */
    async startNew(options) {
        const model = await (0, restapi_1.startNew)(this.serverSettings, options === null || options === void 0 ? void 0 : options.name, options === null || options === void 0 ? void 0 : options.cwd);
        await this.refreshRunning();
        return this.connectTo({ model });
    }
    /**
     * Shut down a terminal session by name.
     */
    async shutdown(name) {
        await (0, restapi_1.shutdownTerminal)(name, this.serverSettings);
        await this.refreshRunning();
    }
    /**
     * Shut down all terminal sessions.
     *
     * @returns A promise that resolves when all of the sessions are shut down.
     */
    async shutdownAll() {
        // Update the list of models to make sure our list is current.
        await this.refreshRunning();
        // Shut down all models.
        await Promise.all(this._names.map(name => (0, restapi_1.shutdownTerminal)(name, this.serverSettings)));
        // Update the list of models to clear out our state.
        await this.refreshRunning();
    }
    /**
     * Execute a request to the server to poll running terminals and update state.
     */
    async requestRunning() {
        var _a, _b;
        let models;
        try {
            models = await (0, restapi_1.listRunning)(this.serverSettings);
        }
        catch (err) {
            // Handle network errors, as well as cases where we are on a
            // JupyterHub and the server is not running. JupyterHub returns a
            // 503 (<2.0) or 424 (>2.0) in that case.
            if (err instanceof __1.ServerConnection.NetworkError ||
                ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||
                ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {
                this._connectionFailure.emit(err);
            }
            throw err;
        }
        if (this.isDisposed) {
            return;
        }
        const names = models.map(({ name }) => name).sort();
        if (names === this._names) {
            // Identical models list, so just return
            return;
        }
        this._names = names;
        this._terminalConnections.forEach(tc => {
            if (!names.includes(tc.name)) {
                tc.dispose();
            }
        });
        this._runningChanged.emit(this._models);
    }
    /**
     * Handle a session starting.
     */
    _onStarted(terminalConnection) {
        this._terminalConnections.add(terminalConnection);
        terminalConnection.disposed.connect(this._onDisposed, this);
    }
    /**
     * Handle a session terminating.
     */
    _onDisposed(terminalConnection) {
        this._terminalConnections.delete(terminalConnection);
        // Update the running models to make sure we reflect the server state
        void this.refreshRunning().catch(() => {
            /* no-op */
        });
    }
    get _models() {
        return this._names.map(name => {
            return { name };
        });
    }
}
exports.TerminalManager = TerminalManager;
/**
 * The namespace for TerminalManager statics.
 */
(function (TerminalManager) {
    /**
     * A no-op terminal manager to be used when starting terminals is not supported.
     */
    class NoopManager extends TerminalManager {
        constructor() {
            super(...arguments);
            this._readyPromise = new Promise(() => {
                /* no-op */
            });
        }
        /**
         * Whether the manager is active.
         */
        get isActive() {
            return false;
        }
        /**
         * Used for testing.
         */
        get parentReady() {
            return super.ready;
        }
        /**
         * A promise that fulfills when the manager is ready (never).
         */
        get ready() {
            return this.parentReady.then(() => this._readyPromise);
        }
        /**
         * Create a new terminal session - throw an error since it is not supported.
         *
         */
        async startNew(options) {
            return Promise.reject(new Error('Not implemented in no-op Terminal Manager'));
        }
        /*
         * Connect to a running terminal - throw an error since it is not supported.
         */
        connectTo(options) {
            throw Error('Not implemented in no-op Terminal Manager');
        }
        /**
         * Shut down a session by id - throw an error since it is not supported.
         */
        async shutdown(id) {
            return Promise.reject(new Error('Not implemented in no-op Terminal Manager'));
        }
        /**
         * Execute a request to the server to poll running sessions and update state.
         */
        async requestRunning() {
            return Promise.resolve();
        }
    }
    TerminalManager.NoopManager = NoopManager;
})(TerminalManager || (exports.TerminalManager = TerminalManager = {}));
//# sourceMappingURL=manager.js.map

/***/ }),

/***/ 6134:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.shutdownTerminal = exports.listRunning = exports.startNew = exports.isAvailable = exports.TERMINAL_SERVICE_URL = void 0;
const coreutils_1 = __webpack_require__(8925);
const serverconnection_1 = __webpack_require__(2920);
/**
 * The url for the terminal service.
 */
exports.TERMINAL_SERVICE_URL = 'api/terminals';
/**
 * Whether the terminal service is available.
 */
function isAvailable() {
    const available = String(coreutils_1.PageConfig.getOption('terminalsAvailable'));
    return available.toLowerCase() === 'true';
}
exports.isAvailable = isAvailable;
/**
 * Start a new terminal session.
 *
 * @param settings - The server settings to use.
 *
 * @param name - The name of the target terminal.
 *
 * @param cwd - The path in which the terminal will start.
 *
 * @returns A promise that resolves with the session model.
 */
async function startNew(settings = serverconnection_1.ServerConnection.makeSettings(), name, cwd) {
    Private.errorIfNotAvailable();
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL);
    const init = {
        method: 'POST',
        body: JSON.stringify({ name, cwd })
    };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    // TODO: Validate model
    return data;
}
exports.startNew = startNew;
/**
 * List the running terminal sessions.
 *
 * @param settings - The server settings to use.
 *
 * @returns A promise that resolves with the list of running session models.
 */
async function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {
    Private.errorIfNotAvailable();
    const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL);
    const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);
    if (response.status !== 200) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
    const data = await response.json();
    if (!Array.isArray(data)) {
        throw new Error('Invalid terminal list');
    }
    // TODO: validate each model
    return data;
}
exports.listRunning = listRunning;
/**
 * Shut down a terminal session by name.
 *
 * @param name - The name of the target session.
 *
 * @param settings - The server settings to use.
 *
 * @returns A promise that resolves when the session is shut down.
 */
async function shutdownTerminal(name, settings = serverconnection_1.ServerConnection.makeSettings()) {
    var _a;
    Private.errorIfNotAvailable();
    const workspacesBase = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL);
    const url = coreutils_1.URLExt.join(workspacesBase, name);
    if (!url.startsWith(workspacesBase)) {
        throw new Error('Can only be used for terminal requests');
    }
    const init = { method: 'DELETE' };
    const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);
    if (response.status === 404) {
        const data = await response.json();
        const msg = (_a = data.message) !== null && _a !== void 0 ? _a : `The terminal session "${name}"" does not exist on the server`;
        console.warn(msg);
    }
    else if (response.status !== 204) {
        const err = await serverconnection_1.ServerConnection.ResponseError.create(response);
        throw err;
    }
}
exports.shutdownTerminal = shutdownTerminal;
var Private;
(function (Private) {
    /**
     * Throw an error if terminals are not available.
     */
    function errorIfNotAvailable() {
        if (!isAvailable()) {
            throw new Error('Terminals Unavailable');
        }
    }
    Private.errorIfNotAvailable = errorIfNotAvailable;
})(Private || (Private = {}));
//# sourceMappingURL=restapi.js.map

/***/ }),

/***/ 6994:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isAvailable = void 0;
const restapi_1 = __webpack_require__(6134);
Object.defineProperty(exports, "isAvailable", ({ enumerable: true, get: function () { return restapi_1.isAvailable; } }));
//# sourceMappingURL=terminal.js.map

/***/ }),

/***/ 9191:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.UserManager = void 0;
const coreutils_1 = __webpack_require__(8925);
const coreutils_2 = __webpack_require__(5764);
const polling_1 = __webpack_require__(6049);
const signaling_1 = __webpack_require__(3992);
const serverconnection_1 = __webpack_require__(2920);
const basemanager_1 = __webpack_require__(3867);
/**
 * The url for the lab workspaces service.
 */
const SERVICE_USER_URL = 'api/me';
/**
 * The service's ID.
 * Used to uniquely identify the poll, and
 * the item in local storage.
 */
const SERVICE_ID = '@jupyterlab/services:UserManager#user';
/**
 * The user API service manager.
 */
class UserManager extends basemanager_1.BaseManager {
    /**
     * Create a new user manager.
     */
    constructor(options = {}) {
        var _a;
        super(options);
        this._isReady = false;
        this._userChanged = new signaling_1.Signal(this);
        this._connectionFailure = new signaling_1.Signal(this);
        // Initialize internal data.
        this._ready = this.requestUser()
            .then(() => {
            if (this.isDisposed) {
                return;
            }
            this._isReady = true;
        })
            .catch(_ => 
        // Return a promise that will never resolve, so user service is never ready
        // This typically occurs when the backend has no user service
        new Promise(() => {
            // no-op
        }));
        this._pollSpecs = new polling_1.Poll({
            auto: false,
            factory: () => this.requestUser(),
            frequency: {
                interval: 61 * 1000,
                backoff: true,
                max: 300 * 1000
            },
            name: SERVICE_ID,
            standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'
        });
        void this.ready.then(() => {
            void this._pollSpecs.start();
        });
    }
    /**
     * Test whether the manager is ready.
     */
    get isReady() {
        return this._isReady;
    }
    /**
     * A promise that fulfills when the manager is ready.
     */
    get ready() {
        return this._ready;
    }
    /**
     * Get the most recently fetched identity.
     */
    get identity() {
        return this._identity;
    }
    /**
     * Get the most recently fetched permissions.
     */
    get permissions() {
        return this._permissions;
    }
    /**
     * A signal emitted when the user changes.
     */
    get userChanged() {
        return this._userChanged;
    }
    /**
     * A signal emitted when there is a connection failure.
     */
    get connectionFailure() {
        return this._connectionFailure;
    }
    /**
     * Dispose of the resources used by the manager.
     */
    dispose() {
        this._pollSpecs.dispose();
        super.dispose();
    }
    /**
     * Force a refresh of the specs from the server.
     *
     * @returns A promise that resolves when the specs are fetched.
     *
     * #### Notes
     * This is intended to be called only in response to a user action,
     * since the manager maintains its internal state.
     */
    async refreshUser() {
        await this._pollSpecs.refresh();
        await this._pollSpecs.tick;
    }
    /**
     * Execute a request to the server to poll the user and update state.
     */
    async requestUser() {
        if (this.isDisposed) {
            return;
        }
        const { baseUrl } = this.serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const url = coreutils_1.URLExt.join(baseUrl, SERVICE_USER_URL);
        const response = await makeRequest(url, {}, this.serverSettings);
        if (response.status !== 200) {
            const err = await ResponseError.create(response);
            throw err;
        }
        const oldUser = {
            identity: this._identity,
            permissions: this._permissions
        };
        const newUser = await response.json();
        const identity = newUser.identity;
        // store the color and initials for the user
        // this info is not provided by the server
        const { localStorage } = window;
        const data = localStorage.getItem(SERVICE_ID);
        if (data && (!identity.initials || !identity.color)) {
            const localUser = JSON.parse(data);
            identity.initials =
                identity.initials ||
                    localUser.initials ||
                    identity.name.substring(0, 1);
            identity.color =
                identity.color || localUser.color || Private.getRandomColor();
        }
        if (!coreutils_2.JSONExt.deepEqual(newUser, oldUser)) {
            this._identity = identity;
            this._permissions = newUser.permissions;
            localStorage.setItem(SERVICE_ID, JSON.stringify(identity));
            this._userChanged.emit(newUser);
        }
    }
}
exports.UserManager = UserManager;
/**
 * A namespace for module-private functionality.
 *
 * Note: We do not want to export this function
 * to move it to css variables in the Theme.
 */
var Private;
(function (Private) {
    /**
     * Predefined colors for users
     */
    const userColors = [
        'var(--jp-collaborator-color1)',
        'var(--jp-collaborator-color2)',
        'var(--jp-collaborator-color3)',
        'var(--jp-collaborator-color4)',
        'var(--jp-collaborator-color5)',
        'var(--jp-collaborator-color6)',
        'var(--jp-collaborator-color7)'
    ];
    /**
     * Get a random color from the list of colors.
     */
    Private.getRandomColor = () => userColors[Math.floor(Math.random() * userColors.length)];
})(Private || (Private = {}));
//# sourceMappingURL=index.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateProperty = void 0;
/**
 * Validate a property as being on an object, and optionally
 * of a given type and among a given set of values.
 */
function validateProperty(
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
object, name, typeName, values = []) {
    if (!object.hasOwnProperty(name)) {
        throw Error(`Missing property '${name}'`);
    }
    const value = object[name];
    if (typeName !== void 0) {
        let valid = true;
        switch (typeName) {
            case 'array':
                valid = Array.isArray(value);
                break;
            case 'object':
                valid = typeof value !== 'undefined';
                break;
            default:
                valid = typeof value === typeName;
        }
        if (!valid) {
            throw new Error(`Property '${name}' is not of type '${typeName}'`);
        }
        if (values.length > 0) {
            let valid = true;
            switch (typeName) {
                case 'string':
                case 'number':
                case 'boolean':
                    valid = values.includes(value);
                    break;
                default:
                    valid = values.findIndex(v => v === value) >= 0;
                    break;
            }
            if (!valid) {
                throw new Error(`Property '${name}' is not one of the valid values ${JSON.stringify(values)}`);
            }
        }
    }
}
exports.validateProperty = validateProperty;
//# sourceMappingURL=validate.js.map

/***/ }),

/***/ 8053:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkspaceManager = void 0;
const coreutils_1 = __webpack_require__(8925);
const statedb_1 = __webpack_require__(1670);
const serverconnection_1 = __webpack_require__(2920);
/**
 * The url for the lab workspaces service.
 */
const SERVICE_WORKSPACES_URL = 'api/workspaces';
/**
 * The workspaces API service manager.
 */
class WorkspaceManager extends statedb_1.DataConnector {
    /**
     * Create a new workspace manager.
     */
    constructor(options = {}) {
        var _a;
        super();
        this.serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();
    }
    /**
     * Fetch a workspace.
     *
     * @param id - The workspace's ID.
     *
     * @returns A promise that resolves if successful.
     */
    async fetch(id) {
        const { serverSettings } = this;
        const { baseUrl, appUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const base = baseUrl + appUrl;
        const url = Private.url(base, id);
        const response = await makeRequest(url, {}, serverSettings);
        if (response.status !== 200) {
            const err = await ResponseError.create(response);
            throw err;
        }
        return response.json();
    }
    /**
     * Fetch the list of workspace IDs that exist on the server.
     *
     * @returns A promise that resolves if successful.
     */
    async list() {
        const { serverSettings } = this;
        const { baseUrl, appUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const base = baseUrl + appUrl;
        const url = Private.url(base, '');
        const response = await makeRequest(url, {}, serverSettings);
        if (response.status !== 200) {
            const err = await ResponseError.create(response);
            throw err;
        }
        const result = await response.json();
        return result.workspaces;
    }
    /**
     * Remove a workspace from the server.
     *
     * @param id - The workspaces's ID.
     *
     * @returns A promise that resolves if successful.
     */
    async remove(id) {
        const { serverSettings } = this;
        const { baseUrl, appUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const base = baseUrl + appUrl;
        const url = Private.url(base, id);
        const init = { method: 'DELETE' };
        const response = await makeRequest(url, init, serverSettings);
        if (response.status !== 204) {
            const err = await ResponseError.create(response);
            throw err;
        }
    }
    /**
     * Save a workspace.
     *
     * @param id - The workspace's ID.
     *
     * @param workspace - The workspace being saved.
     *
     * @returns A promise that resolves if successful.
     */
    async save(id, workspace) {
        const { serverSettings } = this;
        const { baseUrl, appUrl } = serverSettings;
        const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;
        const base = baseUrl + appUrl;
        const url = Private.url(base, id);
        const init = { body: JSON.stringify(workspace), method: 'PUT' };
        const response = await makeRequest(url, init, serverSettings);
        if (response.status !== 204) {
            const err = await ResponseError.create(response);
            throw err;
        }
    }
}
exports.WorkspaceManager = WorkspaceManager;
/**
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * Get the url for a workspace.
     */
    function url(base, id) {
        const workspacesBase = coreutils_1.URLExt.join(base, SERVICE_WORKSPACES_URL);
        const result = coreutils_1.URLExt.join(workspacesBase, id);
        if (!result.startsWith(workspacesBase)) {
            throw new Error('Can only be used for workspaces requests');
        }
        return result;
    }
    Private.url = url;
})(Private || (Private = {}));
//# sourceMappingURL=index.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DataConnector = void 0;
/**
 * An abstract class that adheres to the data connector interface.
 *
 * @typeparam T - The basic entity response type a service's connector.
 *
 * @typeparam U - The basic entity request type, which is conventionally the
 * same as the response type but may be different if a service's implementation
 * requires input data to be different from output responses. Defaults to `T`.
 *
 * @typeparam V - The basic token applied to a request, conventionally a string
 * ID or filter, but may be set to a different type when an implementation
 * requires it. Defaults to `string`.
 *
 * @typeparam W - The type of the optional `query` parameter of the `list`
 * method. Defaults to `string`.
 *
 * #### Notes
 * The only abstract method in this class is the `fetch` method, which must be
 * reimplemented by all subclasses. The `remove` and `save` methods have a
 * default implementation that returns a promise that will always reject. This
 * class is a convenience superclass for connectors that only need to `fetch`.
 */
class DataConnector {
    /**
     * Retrieve the list of items available from the data connector.
     *
     * @param query - The optional query filter to apply to the connector request.
     *
     * @returns A promise that always rejects with an error.
     *
     * #### Notes
     * Subclasses should reimplement if they support a back-end that can list.
     */
    async list(query) {
        throw new Error('DataConnector#list method has not been implemented.');
    }
    /**
     * Remove a value using the data connector.
     *
     * @param id - The identifier for the data being removed.
     *
     * @returns A promise that always rejects with an error.
     *
     * #### Notes
     * Subclasses should reimplement if they support a back-end that can remove.
     */
    async remove(id) {
        throw new Error('DataConnector#remove method has not been implemented.');
    }
    /**
     * Save a value using the data connector.
     *
     * @param id - The identifier for the data being saved.
     *
     * @param value - The data being saved.
     *
     * @returns A promise that always rejects with an error.
     *
     * #### Notes
     * Subclasses should reimplement if they support a back-end that can save.
     */
    async save(id, value) {
        throw new Error('DataConnector#save method has not been implemented.');
    }
}
exports.DataConnector = DataConnector;
//# sourceMappingURL=dataconnector.js.map

/***/ }),

/***/ 1670:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
/**
 * @packageDocumentation
 * @module statedb
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
__exportStar(__webpack_require__(4949), exports);
__exportStar(__webpack_require__(9708), exports);
__exportStar(__webpack_require__(4025), exports);
__exportStar(__webpack_require__(2133), exports);
__exportStar(__webpack_require__(8022), exports);
//# sourceMappingURL=index.js.map

/***/ }),

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

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=interfaces.js.map

/***/ }),

/***/ 4025:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.RestorablePool = void 0;
const coreutils_1 = __webpack_require__(5764);
const properties_1 = __webpack_require__(6573);
const signaling_1 = __webpack_require__(3992);
/**
 * An object pool that supports restoration.
 *
 * @typeparam T - The type of object being tracked.
 */
class RestorablePool {
    /**
     * Create a new restorable pool.
     *
     * @param options - The instantiation options for a restorable pool.
     */
    constructor(options) {
        this._added = new signaling_1.Signal(this);
        this._current = null;
        this._currentChanged = new signaling_1.Signal(this);
        this._hasRestored = false;
        this._isDisposed = false;
        this._objects = new Set();
        this._restore = null;
        this._restored = new coreutils_1.PromiseDelegate();
        this._updated = new signaling_1.Signal(this);
        this.namespace = options.namespace;
    }
    /**
     * A signal emitted when an object object is added.
     *
     * #### Notes
     * This signal will only fire when an object is added to the pool.
     * It will not fire if an object injected into the pool.
     */
    get added() {
        return this._added;
    }
    /**
     * The current object.
     *
     * #### Notes
     * The restorable pool does not set `current`. It is intended for client use.
     *
     * If `current` is set to an object that does not exist in the pool, it is a
     * no-op.
     */
    get current() {
        return this._current;
    }
    set current(obj) {
        if (this._current === obj) {
            return;
        }
        if (obj !== null && this._objects.has(obj)) {
            this._current = obj;
            this._currentChanged.emit(this._current);
        }
    }
    /**
     * A signal emitted when the current widget changes.
     */
    get currentChanged() {
        return this._currentChanged;
    }
    /**
     * Test whether the pool is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * A promise resolved when the restorable pool has been restored.
     */
    get restored() {
        return this._restored.promise;
    }
    /**
     * The number of objects held by the pool.
     */
    get size() {
        return this._objects.size;
    }
    /**
     * A signal emitted when an object is updated.
     */
    get updated() {
        return this._updated;
    }
    /**
     * Add a new object to the pool.
     *
     * @param obj - The object object being added.
     *
     * #### Notes
     * The object passed into the pool is added synchronously; its existence in
     * the pool can be checked with the `has()` method. The promise this method
     * returns resolves after the object has been added and saved to an underlying
     * restoration connector, if one is available.
     */
    async add(obj) {
        var _a, _b;
        if (obj.isDisposed) {
            const warning = 'A disposed object cannot be added.';
            console.warn(warning, obj);
            throw new Error(warning);
        }
        if (this._objects.has(obj)) {
            const warning = 'This object already exists in the pool.';
            console.warn(warning, obj);
            throw new Error(warning);
        }
        this._objects.add(obj);
        obj.disposed.connect(this._onInstanceDisposed, this);
        if (Private.injectedProperty.get(obj)) {
            return;
        }
        if (this._restore) {
            const { connector } = this._restore;
            const objName = this._restore.name(obj);
            if (objName) {
                const name = `${this.namespace}:${objName}`;
                const data = (_b = (_a = this._restore).args) === null || _b === void 0 ? void 0 : _b.call(_a, obj);
                Private.nameProperty.set(obj, name);
                await connector.save(name, { data });
            }
        }
        // Emit the added signal.
        this._added.emit(obj);
    }
    /**
     * Dispose of the resources held by the pool.
     *
     * #### Notes
     * Disposing a pool does not affect the underlying data in the data connector,
     * it simply disposes the client-side pool without making any connector calls.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._current = null;
        this._isDisposed = true;
        this._objects.clear();
        signaling_1.Signal.clearData(this);
    }
    /**
     * Find the first object in the pool that satisfies a filter function.
     *
     * @param fn The filter function to call on each object.
     */
    find(fn) {
        const values = this._objects.values();
        for (const value of values) {
            if (fn(value)) {
                return value;
            }
        }
        return undefined;
    }
    /**
     * Iterate through each object in the pool.
     *
     * @param fn - The function to call on each object.
     */
    forEach(fn) {
        this._objects.forEach(fn);
    }
    /**
     * Filter the objects in the pool based on a predicate.
     *
     * @param fn - The function by which to filter.
     */
    filter(fn) {
        const filtered = [];
        this.forEach(obj => {
            if (fn(obj)) {
                filtered.push(obj);
            }
        });
        return filtered;
    }
    /**
     * Inject an object into the restorable pool without the pool handling its
     * restoration lifecycle.
     *
     * @param obj - The object to inject into the pool.
     */
    inject(obj) {
        Private.injectedProperty.set(obj, true);
        return this.add(obj);
    }
    /**
     * Check if this pool has the specified object.
     *
     * @param obj - The object whose existence is being checked.
     */
    has(obj) {
        return this._objects.has(obj);
    }
    /**
     * Restore the objects in this pool's namespace.
     *
     * @param options - The configuration options that describe restoration.
     *
     * @returns A promise that resolves when restoration has completed.
     *
     * #### Notes
     * This function should almost never be invoked by client code. Its primary
     * use case is to be invoked by a layout restorer plugin that handles
     * multiple restorable pools and, when ready, asks them each to restore their
     * respective objects.
     */
    async restore(options) {
        if (this._hasRestored) {
            throw new Error('This pool has already been restored.');
        }
        this._hasRestored = true;
        const { command, connector, registry, when } = options;
        const namespace = this.namespace;
        const promises = when
            ? [connector.list(namespace)].concat(when)
            : [connector.list(namespace)];
        this._restore = options;
        const [saved] = await Promise.all(promises);
        const values = await Promise.all(saved.ids.map(async (id, index) => {
            const value = saved.values[index];
            const args = value && value.data;
            if (args === undefined) {
                return connector.remove(id);
            }
            // Execute the command and if it fails, delete the state restore data.
            return registry
                .execute(command, args)
                .catch(() => connector.remove(id));
        }));
        this._restored.resolve();
        return values;
    }
    /**
     * Save the restore data for a given object.
     *
     * @param obj - The object being saved.
     */
    async save(obj) {
        var _a, _b;
        const injected = Private.injectedProperty.get(obj);
        if (!this._restore || !this.has(obj) || injected) {
            return;
        }
        const { connector } = this._restore;
        const objName = this._restore.name(obj);
        const oldName = Private.nameProperty.get(obj);
        const newName = objName ? `${this.namespace}:${objName}` : '';
        if (oldName && oldName !== newName) {
            await connector.remove(oldName);
        }
        // Set the name property irrespective of whether the new name is null.
        Private.nameProperty.set(obj, newName);
        if (newName) {
            const data = (_b = (_a = this._restore).args) === null || _b === void 0 ? void 0 : _b.call(_a, obj);
            await connector.save(newName, { data });
        }
        if (oldName !== newName) {
            this._updated.emit(obj);
        }
    }
    /**
     * Clean up after disposed objects.
     */
    _onInstanceDisposed(obj) {
        this._objects.delete(obj);
        if (obj === this._current) {
            this._current = null;
            this._currentChanged.emit(this._current);
        }
        if (Private.injectedProperty.get(obj)) {
            return;
        }
        if (!this._restore) {
            return;
        }
        const { connector } = this._restore;
        const name = Private.nameProperty.get(obj);
        if (name) {
            void connector.remove(name);
        }
    }
}
exports.RestorablePool = RestorablePool;
/*
 * A namespace for private data.
 */
var Private;
(function (Private) {
    /**
     * An attached property to indicate whether an object has been injected.
     */
    Private.injectedProperty = new properties_1.AttachedProperty({
        name: 'injected',
        create: () => false
    });
    /**
     * An attached property for an object's ID.
     */
    Private.nameProperty = new properties_1.AttachedProperty({
        name: 'name',
        create: () => ''
    });
})(Private || (Private = {}));
//# sourceMappingURL=restorablepool.js.map

/***/ }),

/***/ 2133:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.StateDB = void 0;
const signaling_1 = __webpack_require__(3992);
/**
 * The default concrete implementation of a state database.
 */
class StateDB {
    /**
     * Create a new state database.
     *
     * @param options - The instantiation options for a state database.
     */
    constructor(options = {}) {
        this._changed = new signaling_1.Signal(this);
        const { connector, transform } = options;
        this._connector = connector || new StateDB.Connector();
        if (!transform) {
            this._ready = Promise.resolve(undefined);
        }
        else {
            this._ready = transform.then(transformation => {
                const { contents, type } = transformation;
                switch (type) {
                    case 'cancel':
                        return;
                    case 'clear':
                        return this._clear();
                    case 'merge':
                        return this._merge(contents || {});
                    case 'overwrite':
                        return this._overwrite(contents || {});
                    default:
                        return;
                }
            });
        }
    }
    /**
     * A signal that emits the change type any time a value changes.
     */
    get changed() {
        return this._changed;
    }
    /**
     * Clear the entire database.
     */
    async clear() {
        await this._ready;
        await this._clear();
    }
    /**
     * Retrieve a saved bundle from the database.
     *
     * @param id - The identifier used to retrieve a data bundle.
     *
     * @returns A promise that bears a data payload if available.
     *
     * #### Notes
     * The `id` values of stored items in the state database are formatted:
     * `'namespace:identifier'`, which is the same convention that command
     * identifiers in JupyterLab use as well. While this is not a technical
     * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for
     * using the `list(namespace: string)` method.
     *
     * The promise returned by this method may be rejected if an error occurs in
     * retrieving the data. Non-existence of an `id` will succeed with the `value`
     * `undefined`.
     */
    async fetch(id) {
        await this._ready;
        return this._fetch(id);
    }
    /**
     * Retrieve all the saved bundles for a namespace.
     *
     * @param namespace The namespace prefix to retrieve.
     *
     * @returns A promise that bears a collection of payloads for a namespace.
     *
     * #### Notes
     * Namespaces are entirely conventional entities. The `id` values of stored
     * items in the state database are formatted: `'namespace:identifier'`, which
     * is the same convention that command identifiers in JupyterLab use as well.
     *
     * If there are any errors in retrieving the data, they will be logged to the
     * console in order to optimistically return any extant data without failing.
     * This promise will always succeed.
     */
    async list(namespace) {
        await this._ready;
        return this._list(namespace);
    }
    /**
     * Remove a value from the database.
     *
     * @param id - The identifier for the data being removed.
     *
     * @returns A promise that is rejected if remove fails and succeeds otherwise.
     */
    async remove(id) {
        await this._ready;
        await this._remove(id);
        this._changed.emit({ id, type: 'remove' });
    }
    /**
     * Save a value in the database.
     *
     * @param id - The identifier for the data being saved.
     *
     * @param value - The data being saved.
     *
     * @returns A promise that is rejected if saving fails and succeeds otherwise.
     *
     * #### Notes
     * The `id` values of stored items in the state database are formatted:
     * `'namespace:identifier'`, which is the same convention that command
     * identifiers in JupyterLab use as well. While this is not a technical
     * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for
     * using the `list(namespace: string)` method.
     */
    async save(id, value) {
        await this._ready;
        await this._save(id, value);
        this._changed.emit({ id, type: 'save' });
    }
    /**
     * Return a serialized copy of the state database's entire contents.
     *
     * @returns A promise that resolves with the database contents as JSON.
     */
    async toJSON() {
        await this._ready;
        const { ids, values } = await this._list();
        return values.reduce((acc, val, idx) => {
            acc[ids[idx]] = val;
            return acc;
        }, {});
    }
    /**
     * Clear the entire database.
     */
    async _clear() {
        await Promise.all((await this._list()).ids.map(id => this._remove(id)));
    }
    /**
     * Fetch a value from the database.
     */
    async _fetch(id) {
        const value = await this._connector.fetch(id);
        if (value) {
            return JSON.parse(value).v;
        }
    }
    /**
     * Fetch a list from the database.
     */
    async _list(namespace = '') {
        const { ids, values } = await this._connector.list(namespace);
        return {
            ids,
            values: values.map(val => JSON.parse(val).v)
        };
    }
    /**
     * Merge data into the state database.
     */
    async _merge(contents) {
        await Promise.all(Object.keys(contents).map(key => contents[key] && this._save(key, contents[key])));
    }
    /**
     * Overwrite the entire database with new contents.
     */
    async _overwrite(contents) {
        await this._clear();
        await this._merge(contents);
    }
    /**
     * Remove a key in the database.
     */
    async _remove(id) {
        return this._connector.remove(id);
    }
    /**
     * Save a key and its value in the database.
     */
    async _save(id, value) {
        return this._connector.save(id, JSON.stringify({ v: value }));
    }
}
exports.StateDB = StateDB;
/**
 * A namespace for StateDB statics.
 */
(function (StateDB) {
    /**
     * An in-memory string key/value data connector.
     */
    class Connector {
        constructor() {
            this._storage = {};
        }
        /**
         * Retrieve an item from the data connector.
         */
        async fetch(id) {
            return this._storage[id];
        }
        /**
         * Retrieve the list of items available from the data connector.
         *
         * @param namespace - If not empty, only keys whose first token before `:`
         * exactly match `namespace` will be returned, e.g. `foo` in `foo:bar`.
         */
        async list(namespace = '') {
            return Object.keys(this._storage).reduce((acc, val) => {
                if (namespace === '' ? true : namespace === val.split(':')[0]) {
                    acc.ids.push(val);
                    acc.values.push(this._storage[val]);
                }
                return acc;
            }, { ids: [], values: [] });
        }
        /**
         * Remove a value using the data connector.
         */
        async remove(id) {
            delete this._storage[id];
        }
        /**
         * Save a value using the data connector.
         */
        async save(id, value) {
            this._storage[id] = value;
        }
    }
    StateDB.Connector = Connector;
})(StateDB || (exports.StateDB = StateDB = {}));
//# sourceMappingURL=statedb.js.map

/***/ }),

/***/ 8022:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.IStateDB = void 0;
const coreutils_1 = __webpack_require__(5764);
/**
 * The default state database token.
 */
exports.IStateDB = new coreutils_1.Token('@jupyterlab/coreutils:IStateDB', `A service for the JupyterLab state database.
  Use this if you want to store data that will persist across page loads.
  See "state database" for more information.`);
//# sourceMappingURL=tokens.js.map

/***/ }),

/***/ 8135:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ArrayExt: () => (/* binding */ ArrayExt),
/* harmony export */   StringExt: () => (/* binding */ StringExt),
/* harmony export */   chain: () => (/* binding */ chain),
/* harmony export */   each: () => (/* binding */ each),
/* harmony export */   empty: () => (/* binding */ empty),
/* harmony export */   enumerate: () => (/* binding */ enumerate),
/* harmony export */   every: () => (/* binding */ every),
/* harmony export */   filter: () => (/* binding */ filter),
/* harmony export */   find: () => (/* binding */ find),
/* harmony export */   findIndex: () => (/* binding */ findIndex),
/* harmony export */   map: () => (/* binding */ map),
/* harmony export */   max: () => (/* binding */ max),
/* harmony export */   min: () => (/* binding */ min),
/* harmony export */   minmax: () => (/* binding */ minmax),
/* harmony export */   once: () => (/* binding */ once),
/* harmony export */   range: () => (/* binding */ range),
/* harmony export */   reduce: () => (/* binding */ reduce),
/* harmony export */   repeat: () => (/* binding */ repeat),
/* harmony export */   retro: () => (/* binding */ retro),
/* harmony export */   some: () => (/* binding */ some),
/* harmony export */   stride: () => (/* binding */ stride),
/* harmony export */   take: () => (/* binding */ take),
/* harmony export */   toArray: () => (/* binding */ toArray),
/* harmony export */   toObject: () => (/* binding */ toObject),
/* harmony export */   topologicSort: () => (/* binding */ topologicSort),
/* harmony export */   zip: () => (/* binding */ zip)
/* harmony export */ });
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * The namespace for array-specific algorithms.
 */
var ArrayExt;
(function (ArrayExt) {
    /**
     * Find the index of the first occurrence of a value in an array.
     *
     * @param array - The array-like object to search.
     *
     * @param value - The value to locate in the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first occurrence of the value, or `-1`
     *   if the value is not found.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = ['one', 'two', 'three', 'four', 'one'];
     * ArrayExt.firstIndexOf(data, 'red');        // -1
     * ArrayExt.firstIndexOf(data, 'one');        // 0
     * ArrayExt.firstIndexOf(data, 'one', 1);     // 4
     * ArrayExt.firstIndexOf(data, 'two', 2);     // -1
     * ArrayExt.firstIndexOf(data, 'two', 2, 1);  // 1
     * ```
     */
    function firstIndexOf(array, value, start = 0, stop = -1) {
        let n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let span;
        if (stop < start) {
            span = stop + 1 + (n - start);
        }
        else {
            span = stop - start + 1;
        }
        for (let i = 0; i < span; ++i) {
            let j = (start + i) % n;
            if (array[j] === value) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.firstIndexOf = firstIndexOf;
    /**
     * Find the index of the last occurrence of a value in an array.
     *
     * @param array - The array-like object to search.
     *
     * @param value - The value to locate in the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the last occurrence of the value, or `-1`
     *   if the value is not found.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the front of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = ['one', 'two', 'three', 'four', 'one'];
     * ArrayExt.lastIndexOf(data, 'red');        // -1
     * ArrayExt.lastIndexOf(data, 'one');        // 4
     * ArrayExt.lastIndexOf(data, 'one', 1);     // 0
     * ArrayExt.lastIndexOf(data, 'two', 0);     // -1
     * ArrayExt.lastIndexOf(data, 'two', 0, 1);  // 1
     * ```
     */
    function lastIndexOf(array, value, start = -1, stop = 0) {
        let n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let span;
        if (start < stop) {
            span = start + 1 + (n - stop);
        }
        else {
            span = start - stop + 1;
        }
        for (let i = 0; i < span; ++i) {
            let j = (start - i + n) % n;
            if (array[j] === value) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.lastIndexOf = lastIndexOf;
    /**
     * Find the index of the first value which matches a predicate.
     *
     * @param array - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first matching value, or `-1` if no
     *   matching value is found.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findFirstIndex(data, isEven);       // 1
     * ArrayExt.findFirstIndex(data, isEven, 4);    // 5
     * ArrayExt.findFirstIndex(data, isEven, 6);    // -1
     * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1
     * ```
     */
    function findFirstIndex(array, fn, start = 0, stop = -1) {
        let n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let span;
        if (stop < start) {
            span = stop + 1 + (n - start);
        }
        else {
            span = stop - start + 1;
        }
        for (let i = 0; i < span; ++i) {
            let j = (start + i) % n;
            if (fn(array[j], j)) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.findFirstIndex = findFirstIndex;
    /**
     * Find the index of the last value which matches a predicate.
     *
     * @param array - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the last matching value, or `-1` if no
     *   matching value is found.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the front of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findLastIndex(data, isEven);        // 5
     * ArrayExt.findLastIndex(data, isEven, 4);     // 3
     * ArrayExt.findLastIndex(data, isEven, 0);     // -1
     * ArrayExt.findLastIndex(data, isEven, 0, 1);  // 5
     * ```
     */
    function findLastIndex(array, fn, start = -1, stop = 0) {
        let n = array.length;
        if (n === 0) {
            return -1;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let d;
        if (start < stop) {
            d = start + 1 + (n - stop);
        }
        else {
            d = start - stop + 1;
        }
        for (let i = 0; i < d; ++i) {
            let j = (start - i + n) % n;
            if (fn(array[j], j)) {
                return j;
            }
        }
        return -1;
    }
    ArrayExt.findLastIndex = findLastIndex;
    /**
     * Find the first value which matches a predicate.
     *
     * @param array - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The first matching value, or `undefined` if no matching
     *   value is found.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findFirstValue(data, isEven);       // 2
     * ArrayExt.findFirstValue(data, isEven, 2);    // 4
     * ArrayExt.findFirstValue(data, isEven, 6);    // undefined
     * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2
     * ```
     */
    function findFirstValue(array, fn, start = 0, stop = -1) {
        let index = findFirstIndex(array, fn, start, stop);
        return index !== -1 ? array[index] : undefined;
    }
    ArrayExt.findFirstValue = findFirstValue;
    /**
     * Find the last value which matches a predicate.
     *
     * @param object - The array-like object to search.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The last matching value, or `undefined` if no matching
     *   value is found.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the front of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [1, 2, 3, 4, 3, 2, 1];
     * ArrayExt.findLastValue(data, isEven);        // 2
     * ArrayExt.findLastValue(data, isEven, 4);     // 4
     * ArrayExt.findLastValue(data, isEven, 0);     // undefined
     * ArrayExt.findLastValue(data, isEven, 0, 1);  // 2
     * ```
     */
    function findLastValue(array, fn, start = -1, stop = 0) {
        let index = findLastIndex(array, fn, start, stop);
        return index !== -1 ? array[index] : undefined;
    }
    ArrayExt.findLastValue = findLastValue;
    /**
     * Find the index of the first element which compares `>=` to a value.
     *
     * @param array - The sorted array-like object to search.
     *
     * @param value - The value to locate in the array.
     *
     * @param fn - The 3-way comparison function to apply to the values.
     *   It should return `< 0` if an element is less than a value, `0` if
     *   an element is equal to a value, or `> 0` if an element is greater
     *   than a value.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first element which compares `>=` to the
     *   value, or `length` if there is no such element. If the computed
     *   index for `stop` is less than `start`, then the computed index
     *   for `start` is returned.
     *
     * #### Notes
     * The array must already be sorted in ascending order according to
     * the comparison function.
     *
     * #### Complexity
     * Logarithmic.
     *
     * #### Undefined Behavior
     * Searching a range which is not sorted in ascending order.
     *
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function numberCmp(a: number, b: number): number {
     *   return a - b;
     * }
     *
     * let data = [0, 3, 4, 7, 7, 9];
     * ArrayExt.lowerBound(data, 0, numberCmp);   // 0
     * ArrayExt.lowerBound(data, 6, numberCmp);   // 3
     * ArrayExt.lowerBound(data, 7, numberCmp);   // 3
     * ArrayExt.lowerBound(data, -1, numberCmp);  // 0
     * ArrayExt.lowerBound(data, 10, numberCmp);  // 6
     * ```
     */
    function lowerBound(array, value, fn, start = 0, stop = -1) {
        let n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let begin = start;
        let span = stop - start + 1;
        while (span > 0) {
            let half = span >> 1;
            let middle = begin + half;
            if (fn(array[middle], value) < 0) {
                begin = middle + 1;
                span -= half + 1;
            }
            else {
                span = half;
            }
        }
        return begin;
    }
    ArrayExt.lowerBound = lowerBound;
    /**
     * Find the index of the first element which compares `>` than a value.
     *
     * @param array - The sorted array-like object to search.
     *
     * @param value - The value to locate in the array.
     *
     * @param fn - The 3-way comparison function to apply to the values.
     *   It should return `< 0` if an element is less than a value, `0` if
     *   an element is equal to a value, or `> 0` if an element is greater
     *   than a value.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the first element which compares `>` than the
     *   value, or `length` if there is no such element. If the computed
     *   index for `stop` is less than `start`, then the computed index
     *   for `start` is returned.
     *
     * #### Notes
     * The array must already be sorted in ascending order according to
     * the comparison function.
     *
     * #### Complexity
     * Logarithmic.
     *
     * #### Undefined Behavior
     * Searching a range which is not sorted in ascending order.
     *
     * A `start` or `stop` which is non-integral.
     *
     * Modifying the length of the array while searching.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function numberCmp(a: number, b: number): number {
     *   return a - b;
     * }
     *
     * let data = [0, 3, 4, 7, 7, 9];
     * ArrayExt.upperBound(data, 0, numberCmp);   // 1
     * ArrayExt.upperBound(data, 6, numberCmp);   // 3
     * ArrayExt.upperBound(data, 7, numberCmp);   // 5
     * ArrayExt.upperBound(data, -1, numberCmp);  // 0
     * ArrayExt.upperBound(data, 10, numberCmp);  // 6
     * ```
     */
    function upperBound(array, value, fn, start = 0, stop = -1) {
        let n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let begin = start;
        let span = stop - start + 1;
        while (span > 0) {
            let half = span >> 1;
            let middle = begin + half;
            if (fn(array[middle], value) > 0) {
                span = half;
            }
            else {
                begin = middle + 1;
                span -= half + 1;
            }
        }
        return begin;
    }
    ArrayExt.upperBound = upperBound;
    /**
     * Test whether two arrays are shallowly equal.
     *
     * @param a - The first array-like object to compare.
     *
     * @param b - The second array-like object to compare.
     *
     * @param fn - The comparison function to apply to the elements. It
     *   should return `true` if the elements are "equal". The default
     *   compares elements using strict `===` equality.
     *
     * @returns Whether the two arrays are shallowly equal.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * Modifying the length of the arrays while comparing.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let d1 = [0, 3, 4, 7, 7, 9];
     * let d2 = [0, 3, 4, 7, 7, 9];
     * let d3 = [42];
     * ArrayExt.shallowEqual(d1, d2);  // true
     * ArrayExt.shallowEqual(d2, d3);  // false
     * ```
     */
    function shallowEqual(a, b, fn) {
        // Check for object identity first.
        if (a === b) {
            return true;
        }
        // Bail early if the lengths are different.
        if (a.length !== b.length) {
            return false;
        }
        // Compare each element for equality.
        for (let i = 0, n = a.length; i < n; ++i) {
            if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {
                return false;
            }
        }
        // The array are shallowly equal.
        return true;
    }
    ArrayExt.shallowEqual = shallowEqual;
    /**
     * Create a slice of an array subject to an optional step.
     *
     * @param array - The array-like object of interest.
     *
     * @param options - The options for configuring the slice.
     *
     * @returns A new array with the specified values.
     *
     * @throws An exception if the slice `step` is `0`.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start`, `stop`, or `step` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [0, 3, 4, 7, 7, 9];
     * ArrayExt.slice(data);                         // [0, 3, 4, 7, 7, 9]
     * ArrayExt.slice(data, { start: 2 });           // [4, 7, 7, 9]
     * ArrayExt.slice(data, { start: 0, stop: 4 });  // [0, 3, 4, 7]
     * ArrayExt.slice(data, { step: 2 });            // [0, 4, 7]
     * ArrayExt.slice(data, { step: -1 });           // [9, 7, 7, 4, 3, 0]
     * ```
     */
    function slice(array, options = {}) {
        // Extract the options.
        let { start, stop, step } = options;
        // Set up the `step` value.
        if (step === undefined) {
            step = 1;
        }
        // Validate the step size.
        if (step === 0) {
            throw new Error('Slice `step` cannot be zero.');
        }
        // Look up the length of the array.
        let n = array.length;
        // Set up the `start` value.
        if (start === undefined) {
            start = step < 0 ? n - 1 : 0;
        }
        else if (start < 0) {
            start = Math.max(start + n, step < 0 ? -1 : 0);
        }
        else if (start >= n) {
            start = step < 0 ? n - 1 : n;
        }
        // Set up the `stop` value.
        if (stop === undefined) {
            stop = step < 0 ? -1 : n;
        }
        else if (stop < 0) {
            stop = Math.max(stop + n, step < 0 ? -1 : 0);
        }
        else if (stop >= n) {
            stop = step < 0 ? n - 1 : n;
        }
        // Compute the slice length.
        let length;
        if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {
            length = 0;
        }
        else if (step < 0) {
            length = Math.floor((stop - start + 1) / step + 1);
        }
        else {
            length = Math.floor((stop - start - 1) / step + 1);
        }
        // Compute the sliced result.
        let result = [];
        for (let i = 0; i < length; ++i) {
            result[i] = array[start + i * step];
        }
        // Return the result.
        return result;
    }
    ArrayExt.slice = slice;
    /**
     * Move an element in an array from one index to another.
     *
     * @param array - The mutable array-like object of interest.
     *
     * @param fromIndex - The index of the element to move. Negative
     *   values are taken as an offset from the end of the array.
     *
     * @param toIndex - The target index of the element. Negative
     *   values are taken as an offset from the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `fromIndex` or `toIndex` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from from '@lumino/algorithm';
     *
     * let data = [0, 1, 2, 3, 4];
     * ArrayExt.move(data, 1, 2);  // [0, 2, 1, 3, 4]
     * ArrayExt.move(data, 4, 2);  // [0, 2, 4, 1, 3]
     * ```
     */
    function move(array, fromIndex, toIndex) {
        let n = array.length;
        if (n <= 1) {
            return;
        }
        if (fromIndex < 0) {
            fromIndex = Math.max(0, fromIndex + n);
        }
        else {
            fromIndex = Math.min(fromIndex, n - 1);
        }
        if (toIndex < 0) {
            toIndex = Math.max(0, toIndex + n);
        }
        else {
            toIndex = Math.min(toIndex, n - 1);
        }
        if (fromIndex === toIndex) {
            return;
        }
        let value = array[fromIndex];
        let d = fromIndex < toIndex ? 1 : -1;
        for (let i = fromIndex; i !== toIndex; i += d) {
            array[i] = array[i + d];
        }
        array[toIndex] = value;
    }
    ArrayExt.move = move;
    /**
     * Reverse an array in-place.
     *
     * @param array - The mutable array-like object of interest.
     *
     * @param start - The index of the first element in the range to be
     *   reversed, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   reversed, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or  `stop` index which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [0, 1, 2, 3, 4];
     * ArrayExt.reverse(data, 1, 3);  // [0, 3, 2, 1, 4]
     * ArrayExt.reverse(data, 3);     // [0, 3, 2, 4, 1]
     * ArrayExt.reverse(data);        // [1, 4, 2, 3, 0]
     * ```
     */
    function reverse(array, start = 0, stop = -1) {
        let n = array.length;
        if (n <= 1) {
            return;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        while (start < stop) {
            let a = array[start];
            let b = array[stop];
            array[start++] = b;
            array[stop--] = a;
        }
    }
    ArrayExt.reverse = reverse;
    /**
     * Rotate the elements of an array in-place.
     *
     * @param array - The mutable array-like object of interest.
     *
     * @param delta - The amount of rotation to apply to the elements. A
     *   positive value will rotate the elements to the left. A negative
     *   value will rotate the elements to the right.
     *
     * @param start - The index of the first element in the range to be
     *   rotated, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   rotated, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `delta`, `start`, or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [0, 1, 2, 3, 4];
     * ArrayExt.rotate(data, 2);        // [2, 3, 4, 0, 1]
     * ArrayExt.rotate(data, -2);       // [0, 1, 2, 3, 4]
     * ArrayExt.rotate(data, 10);       // [0, 1, 2, 3, 4]
     * ArrayExt.rotate(data, 9);        // [4, 0, 1, 2, 3]
     * ArrayExt.rotate(data, 2, 1, 3);  // [4, 2, 0, 1, 3]
     * ```
     */
    function rotate(array, delta, start = 0, stop = -1) {
        let n = array.length;
        if (n <= 1) {
            return;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        if (start >= stop) {
            return;
        }
        let length = stop - start + 1;
        if (delta > 0) {
            delta = delta % length;
        }
        else if (delta < 0) {
            delta = ((delta % length) + length) % length;
        }
        if (delta === 0) {
            return;
        }
        let pivot = start + delta;
        reverse(array, start, pivot - 1);
        reverse(array, pivot, stop);
        reverse(array, start, stop);
    }
    ArrayExt.rotate = rotate;
    /**
     * Fill an array with a static value.
     *
     * @param array - The mutable array-like object to fill.
     *
     * @param value - The static value to use to fill the array.
     *
     * @param start - The index of the first element in the range to be
     *   filled, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   filled, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * #### Notes
     * If `stop < start` the fill will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * A `start` or `stop` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = ['one', 'two', 'three', 'four'];
     * ArrayExt.fill(data, 'r');        // ['r', 'r', 'r', 'r']
     * ArrayExt.fill(data, 'g', 1);     // ['r', 'g', 'g', 'g']
     * ArrayExt.fill(data, 'b', 2, 3);  // ['r', 'g', 'b', 'b']
     * ArrayExt.fill(data, 'z', 3, 1);  // ['z', 'z', 'b', 'z']
     * ```
     */
    function fill(array, value, start = 0, stop = -1) {
        let n = array.length;
        if (n === 0) {
            return;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let span;
        if (stop < start) {
            span = stop + 1 + (n - start);
        }
        else {
            span = stop - start + 1;
        }
        for (let i = 0; i < span; ++i) {
            array[(start + i) % n] = value;
        }
    }
    ArrayExt.fill = fill;
    /**
     * Insert a value into an array at a specific index.
     *
     * @param array - The array of interest.
     *
     * @param index - The index at which to insert the value. Negative
     *   values are taken as an offset from the end of the array.
     *
     * @param value - The value to set at the specified index.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [0, 1, 2];
     * ArrayExt.insert(data, 0, -1);  // [-1, 0, 1, 2]
     * ArrayExt.insert(data, 2, 12);  // [-1, 0, 12, 1, 2]
     * ArrayExt.insert(data, -1, 7);  // [-1, 0, 12, 1, 7, 2]
     * ArrayExt.insert(data, 6, 19);  // [-1, 0, 12, 1, 7, 2, 19]
     * ```
     */
    function insert(array, index, value) {
        let n = array.length;
        if (index < 0) {
            index = Math.max(0, index + n);
        }
        else {
            index = Math.min(index, n);
        }
        for (let i = n; i > index; --i) {
            array[i] = array[i - 1];
        }
        array[index] = value;
    }
    ArrayExt.insert = insert;
    /**
     * Remove and return a value at a specific index in an array.
     *
     * @param array - The array of interest.
     *
     * @param index - The index of the value to remove. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The value at the specified index, or `undefined` if the
     *   index is out of range.
     *
     * #### Complexity
     * Linear.
     *
     * #### Undefined Behavior
     * An `index` which is non-integral.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeAt(data, 2);   // 23
     * ArrayExt.removeAt(data, -2);  // 12
     * ArrayExt.removeAt(data, 10);  // undefined;
     * ```
     */
    function removeAt(array, index) {
        let n = array.length;
        if (index < 0) {
            index += n;
        }
        if (index < 0 || index >= n) {
            return undefined;
        }
        let value = array[index];
        for (let i = index + 1; i < n; ++i) {
            array[i - 1] = array[i];
        }
        array.length = n - 1;
        return value;
    }
    ArrayExt.removeAt = removeAt;
    /**
     * Remove the first occurrence of a value from an array.
     *
     * @param array - The array of interest.
     *
     * @param value - The value to remove from the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the removed value, or `-1` if the value
     *   is not contained in the array.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeFirstOf(data, 12);        // 1
     * ArrayExt.removeFirstOf(data, 17);        // -1
     * ArrayExt.removeFirstOf(data, 39, 3);     // -1
     * ArrayExt.removeFirstOf(data, 39, 3, 2);  // 2
     * ```
     */
    function removeFirstOf(array, value, start = 0, stop = -1) {
        let index = firstIndexOf(array, value, start, stop);
        if (index !== -1) {
            removeAt(array, index);
        }
        return index;
    }
    ArrayExt.removeFirstOf = removeFirstOf;
    /**
     * Remove the last occurrence of a value from an array.
     *
     * @param array - The array of interest.
     *
     * @param value - The value to remove from the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The index of the removed value, or `-1` if the value
     *   is not contained in the array.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeLastOf(data, 12);        // 5
     * ArrayExt.removeLastOf(data, 17);        // -1
     * ArrayExt.removeLastOf(data, 39, 2);     // -1
     * ArrayExt.removeLastOf(data, 39, 2, 3);  // 3
     * ```
     */
    function removeLastOf(array, value, start = -1, stop = 0) {
        let index = lastIndexOf(array, value, start, stop);
        if (index !== -1) {
            removeAt(array, index);
        }
        return index;
    }
    ArrayExt.removeLastOf = removeLastOf;
    /**
     * Remove all occurrences of a value from an array.
     *
     * @param array - The array of interest.
     *
     * @param value - The value to remove from the array. Values are
     *   compared using strict `===` equality.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The number of elements removed from the array.
     *
     * #### Notes
     * If `stop < start` the search will conceptually wrap at the end of
     * the array, however the array will be traversed front-to-back.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * let data = [14, 12, 23, 39, 14, 12, 19, 14];
     * ArrayExt.removeAllOf(data, 12);        // 2
     * ArrayExt.removeAllOf(data, 17);        // 0
     * ArrayExt.removeAllOf(data, 14, 1, 4);  // 1
     * ```
     */
    function removeAllOf(array, value, start = 0, stop = -1) {
        let n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let count = 0;
        for (let i = 0; i < n; ++i) {
            if (start <= stop && i >= start && i <= stop && array[i] === value) {
                count++;
            }
            else if (stop < start &&
                (i <= stop || i >= start) &&
                array[i] === value) {
                count++;
            }
            else if (count > 0) {
                array[i - count] = array[i];
            }
        }
        if (count > 0) {
            array.length = n - count;
        }
        return count;
    }
    ArrayExt.removeAllOf = removeAllOf;
    /**
     * Remove the first occurrence of a value which matches a predicate.
     *
     * @param array - The array of interest.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The removed `{ index, value }`, which will be `-1` and
     *   `undefined` if the value is not contained in the array.
     *
     * #### Notes
     * If `stop < start` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeFirstWhere(data, isEven);     // { index: 0, value: 0 }
     * ArrayExt.removeFirstWhere(data, isEven, 2);  // { index: 3, value: 14 }
     * ArrayExt.removeFirstWhere(data, isEven, 4);  // { index: -1, value: undefined }
     * ```
     */
    function removeFirstWhere(array, fn, start = 0, stop = -1) {
        let value;
        let index = findFirstIndex(array, fn, start, stop);
        if (index !== -1) {
            value = removeAt(array, index);
        }
        return { index, value };
    }
    ArrayExt.removeFirstWhere = removeFirstWhere;
    /**
     * Remove the last occurrence of a value which matches a predicate.
     *
     * @param array - The array of interest.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The removed `{ index, value }`, which will be `-1` and
     *   `undefined` if the value is not contained in the array.
     *
     * #### Notes
     * If `start < stop` the search will wrap at the end of the array.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * let data = [0, 12, 23, 39, 14, 12, 75];
     * ArrayExt.removeLastWhere(data, isEven);        // { index: 5, value: 12 }
     * ArrayExt.removeLastWhere(data, isEven, 2);     // { index: 1, value: 12 }
     * ArrayExt.removeLastWhere(data, isEven, 2, 1);  // { index: -1, value: undefined }
     * ```
     */
    function removeLastWhere(array, fn, start = -1, stop = 0) {
        let value;
        let index = findLastIndex(array, fn, start, stop);
        if (index !== -1) {
            value = removeAt(array, index);
        }
        return { index, value };
    }
    ArrayExt.removeLastWhere = removeLastWhere;
    /**
     * Remove all occurrences of values which match a predicate.
     *
     * @param array - The array of interest.
     *
     * @param fn - The predicate function to apply to the values.
     *
     * @param start - The index of the first element in the range to be
     *   searched, inclusive. The default value is `0`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @param stop - The index of the last element in the range to be
     *   searched, inclusive. The default value is `-1`. Negative values
     *   are taken as an offset from the end of the array.
     *
     * @returns The number of elements removed from the array.
     *
     * #### Notes
     * If `stop < start` the search will conceptually wrap at the end of
     * the array, however the array will be traversed front-to-back.
     *
     * #### Complexity
     * Linear.
     *
     * #### Example
     * ```typescript
     * import { ArrayExt } from '@lumino/algorithm';
     *
     * function isEven(value: number): boolean {
     *   return value % 2 === 0;
     * }
     *
     * function isNegative(value: number): boolean {
     *   return value < 0;
     * }
     *
     * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];
     * ArrayExt.removeAllWhere(data, isEven);            // 4
     * ArrayExt.removeAllWhere(data, isNegative, 0, 3);  // 2
     * ```
     */
    function removeAllWhere(array, fn, start = 0, stop = -1) {
        let n = array.length;
        if (n === 0) {
            return 0;
        }
        if (start < 0) {
            start = Math.max(0, start + n);
        }
        else {
            start = Math.min(start, n - 1);
        }
        if (stop < 0) {
            stop = Math.max(0, stop + n);
        }
        else {
            stop = Math.min(stop, n - 1);
        }
        let count = 0;
        for (let i = 0; i < n; ++i) {
            if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {
                count++;
            }
            else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {
                count++;
            }
            else if (count > 0) {
                array[i - count] = array[i];
            }
        }
        if (count > 0) {
            array.length = n - count;
        }
        return count;
    }
    ArrayExt.removeAllWhere = removeAllWhere;
})(ArrayExt || (ArrayExt = {}));

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Chain together several iterables.
 *
 * @deprecated
 *
 * @param objects - The iterable objects of interest.
 *
 * @returns An iterator which yields the values of the iterables
 *   in the order in which they are supplied.
 *
 * #### Example
 * ```typescript
 * import { chain } from '@lumino/algorithm';
 *
 * let data1 = [1, 2, 3];
 * let data2 = [4, 5, 6];
 *
 * let stream = chain(data1, data2);
 *
 * Array.from(stream);  // [1, 2, 3, 4, 5, 6]
 * ```
 */
function* chain(...objects) {
    for (const object of objects) {
        yield* object;
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Create an empty iterator.
 *
 * @returns A new iterator which yields nothing.
 *
 * #### Example
 * ```typescript
 * import { empty } from '@lumino/algorithm';
 *
 * let stream = empty<number>();
 *
 * Array.from(stream);  // []
 * ```
 */
// eslint-disable-next-line require-yield
function* empty() {
    return;
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Enumerate an iterable object.
 *
 * @param object - The iterable object of interest.
 *
 * @param start - The starting enum value. The default is `0`.
 *
 * @returns An iterator which yields the enumerated values.
 *
 * #### Example
 * ```typescript
 * import { enumerate } from '@lumino/algorithm';
 *
 * let data = ['foo', 'bar', 'baz'];
 *
 * let stream = enumerate(data, 1);
 *
 * Array.from(stream);  // [[1, 'foo'], [2, 'bar'], [3, 'baz']]
 * ```
 */
function* enumerate(object, start = 0) {
    for (const value of object) {
        yield [start++, value];
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Filter an iterable for values which pass a test.
 *
 * @param object - The iterable object of interest.
 *
 * @param fn - The predicate function to invoke for each value.
 *
 * @returns An iterator which yields the values which pass the test.
 *
 * #### Example
 * ```typescript
 * import { filter } from '@lumino/algorithm';
 *
 * let data = [1, 2, 3, 4, 5, 6];
 *
 * let stream = filter(data, value => value % 2 === 0);
 *
 * Array.from(stream);  // [2, 4, 6]
 * ```
 */
function* filter(object, fn) {
    let index = 0;
    for (const value of object) {
        if (fn(value, index++)) {
            yield value;
        }
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Find the first value in an iterable which matches a predicate.
 *
 * @param object - The iterable object to search.
 *
 * @param fn - The predicate function to apply to the values.
 *
 * @returns The first matching value, or `undefined` if no matching
 *   value is found.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { find } from '@lumino/algorithm';
 *
 * interface IAnimal { species: string, name: string };
 *
 * function isCat(value: IAnimal): boolean {
 *   return value.species === 'cat';
 * }
 *
 * let data: IAnimal[] = [
 *   { species: 'dog', name: 'spot' },
 *   { species: 'cat', name: 'fluffy' },
 *   { species: 'alligator', name: 'pocho' }
 * ];
 *
 * find(data, isCat).name;  // 'fluffy'
 * ```
 */
function find(object, fn) {
    let index = 0;
    for (const value of object) {
        if (fn(value, index++)) {
            return value;
        }
    }
    return undefined;
}
/**
 * Find the index of the first value which matches a predicate.
 *
 * @param object - The iterable object to search.
 *
 * @param fn - The predicate function to apply to the values.
 *
 * @returns The index of the first matching value, or `-1` if no
 *   matching value is found.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { findIndex } from '@lumino/algorithm';
 *
 * interface IAnimal { species: string, name: string };
 *
 * function isCat(value: IAnimal): boolean {
 *   return value.species === 'cat';
 * }
 *
 * let data: IAnimal[] = [
 *   { species: 'dog', name: 'spot' },
 *   { species: 'cat', name: 'fluffy' },
 *   { species: 'alligator', name: 'pocho' }
 * ];
 *
 * findIndex(data, isCat);  // 1
 * ```
 */
function findIndex(object, fn) {
    let index = 0;
    for (const value of object) {
        if (fn(value, index++)) {
            return index - 1;
        }
    }
    return -1;
}
/**
 * Find the minimum value in an iterable.
 *
 * @param object - The iterable object to search.
 *
 * @param fn - The 3-way comparison function to apply to the values.
 *   It should return `< 0` if the first value is less than the second.
 *   `0` if the values are equivalent, or `> 0` if the first value is
 *   greater than the second.
 *
 * @returns The minimum value in the iterable. If multiple values are
 *   equivalent to the minimum, the left-most value is returned. If
 *   the iterable is empty, this returns `undefined`.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { min } from '@lumino/algorithm';
 *
 * function numberCmp(a: number, b: number): number {
 *   return a - b;
 * }
 *
 * min([7, 4, 0, 3, 9, 4], numberCmp);  // 0
 * ```
 */
function min(object, fn) {
    let result = undefined;
    for (const value of object) {
        if (result === undefined) {
            result = value;
            continue;
        }
        if (fn(value, result) < 0) {
            result = value;
        }
    }
    return result;
}
/**
 * Find the maximum value in an iterable.
 *
 * @param object - The iterable object to search.
 *
 * @param fn - The 3-way comparison function to apply to the values.
 *   It should return `< 0` if the first value is less than the second.
 *   `0` if the values are equivalent, or `> 0` if the first value is
 *   greater than the second.
 *
 * @returns The maximum value in the iterable. If multiple values are
 *   equivalent to the maximum, the left-most value is returned. If
 *   the iterable is empty, this returns `undefined`.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { max } from '@lumino/algorithm';
 *
 * function numberCmp(a: number, b: number): number {
 *   return a - b;
 * }
 *
 * max([7, 4, 0, 3, 9, 4], numberCmp);  // 9
 * ```
 */
function max(object, fn) {
    let result = undefined;
    for (const value of object) {
        if (result === undefined) {
            result = value;
            continue;
        }
        if (fn(value, result) > 0) {
            result = value;
        }
    }
    return result;
}
/**
 * Find the minimum and maximum values in an iterable.
 *
 * @param object - The iterable object to search.
 *
 * @param fn - The 3-way comparison function to apply to the values.
 *   It should return `< 0` if the first value is less than the second.
 *   `0` if the values are equivalent, or `> 0` if the first value is
 *   greater than the second.
 *
 * @returns A 2-tuple of the `[min, max]` values in the iterable. If
 *   multiple values are equivalent, the left-most values are returned.
 *   If the iterable is empty, this returns `undefined`.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { minmax } from '@lumino/algorithm';
 *
 * function numberCmp(a: number, b: number): number {
 *   return a - b;
 * }
 *
 * minmax([7, 4, 0, 3, 9, 4], numberCmp);  // [0, 9]
 * ```
 */
function minmax(object, fn) {
    let empty = true;
    let vmin;
    let vmax;
    for (const value of object) {
        if (empty) {
            vmin = value;
            vmax = value;
            empty = false;
        }
        else if (fn(value, vmin) < 0) {
            vmin = value;
        }
        else if (fn(value, vmax) > 0) {
            vmax = value;
        }
    }
    return empty ? undefined : [vmin, vmax];
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Create an array from an iterable of values.
 *
 * @deprecated
 *
 * @param object - The iterable object of interest.
 *
 * @returns A new array of values from the given object.
 *
 * #### Example
 * ```typescript
 * import { toArray } from '@lumino/algorithm';
 *
 * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();
 *
 * toArray(stream);  // [1, 2, 3, 4, 5, 6];
 * ```
 */
function toArray(object) {
    return Array.from(object);
}
/**
 * Create an object from an iterable of key/value pairs.
 *
 * @param object - The iterable object of interest.
 *
 * @returns A new object mapping keys to values.
 *
 * #### Example
 * ```typescript
 * import { toObject } from '@lumino/algorithm';
 *
 * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];
 *
 * toObject(data);  // { one: 1, two: 2, three: 3 }
 * ```
 */
function toObject(object) {
    const result = {};
    for (const [key, value] of object) {
        result[key] = value;
    }
    return result;
}
/**
 * Invoke a function for each value in an iterable.
 *
 * @deprecated
 *
 * @param object - The iterable object of interest.
 *
 * @param fn - The callback function to invoke for each value.
 *
 * #### Notes
 * Iteration can be terminated early by returning `false` from the
 * callback function.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { each } from '@lumino/algorithm';
 *
 * let data = [5, 7, 0, -2, 9];
 *
 * each(data, value => { console.log(value); });
 * ```
 */
function each(object, fn) {
    let index = 0;
    for (const value of object) {
        if (false === fn(value, index++)) {
            return;
        }
    }
}
/**
 * Test whether all values in an iterable satisfy a predicate.
 *
 * @param object - The iterable object of interest.
 *
 * @param fn - The predicate function to invoke for each value.
 *
 * @returns `true` if all values pass the test, `false` otherwise.
 *
 * #### Notes
 * Iteration terminates on the first `false` predicate result.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { every } from '@lumino/algorithm';
 *
 * let data = [5, 7, 1];
 *
 * every(data, value => value % 2 === 0);  // false
 * every(data, value => value % 2 === 1);  // true
 * ```
 */
function every(object, fn) {
    let index = 0;
    for (const value of object) {
        if (false === fn(value, index++)) {
            return false;
        }
    }
    return true;
}
/**
 * Test whether any value in an iterable satisfies a predicate.
 *
 * @param object - The iterable object of interest.
 *
 * @param fn - The predicate function to invoke for each value.
 *
 * @returns `true` if any value passes the test, `false` otherwise.
 *
 * #### Notes
 * Iteration terminates on the first `true` predicate result.
 *
 * #### Complexity
 * Linear.
 *
 * #### Example
 * ```typescript
 * import { some } from '@lumino/algorithm';
 *
 * let data = [5, 7, 1];
 *
 * some(data, value => value === 7);  // true
 * some(data, value => value === 3);  // false
 * ```
 */
function some(object, fn) {
    let index = 0;
    for (const value of object) {
        if (fn(value, index++)) {
            return true;
        }
    }
    return false;
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Transform the values of an iterable with a mapping function.
 *
 * @param object - The iterable object of interest.
 *
 * @param fn - The mapping function to invoke for each value.
 *
 * @returns An iterator which yields the transformed values.
 *
 * #### Example
 * ```typescript
 * import { map } from '@lumino/algorithm';
 *
 * let data = [1, 2, 3];
 *
 * let stream = map(data, value => value * 2);
 *
 * Array.from(stream);  // [2, 4, 6]
 * ```
 */
function* map(object, fn) {
    let index = 0;
    for (const value of object) {
        yield fn(value, index++);
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Create an iterator of evenly spaced values.
 *
 * @param start - The starting value for the range, inclusive.
 *
 * @param stop - The stopping value for the range, exclusive.
 *
 * @param step - The distance between each value.
 *
 * @returns An iterator which produces evenly spaced values.
 *
 * #### Notes
 * In the single argument form of `range(stop)`, `start` defaults to
 * `0` and `step` defaults to `1`.
 *
 * In the two argument form of `range(start, stop)`, `step` defaults
 * to `1`.
 *
 * #### Example
 * ```typescript
 * import { range } from '@lumino/algorithm';
 *
 * let stream = range(2, 4);
 *
 * Array.from(stream);  // [2, 3]
 * ```
 */
function* range(start, stop, step) {
    if (stop === undefined) {
        stop = start;
        start = 0;
        step = 1;
    }
    else if (step === undefined) {
        step = 1;
    }
    const length = Private.rangeLength(start, stop, step);
    for (let index = 0; index < length; index++) {
        yield start + step * index;
    }
}
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * Compute the effective length of a range.
     *
     * @param start - The starting value for the range, inclusive.
     *
     * @param stop - The stopping value for the range, exclusive.
     *
     * @param step - The distance between each value.
     *
     * @returns The number of steps need to traverse the range.
     */
    function rangeLength(start, stop, step) {
        if (step === 0) {
            return Infinity;
        }
        if (start > stop && step > 0) {
            return 0;
        }
        if (start < stop && step < 0) {
            return 0;
        }
        return Math.ceil((stop - start) / step);
    }
    Private.rangeLength = rangeLength;
})(Private || (Private = {}));

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
function reduce(object, fn, initial) {
    // Setup the iterator and fetch the first value.
    const it = object[Symbol.iterator]();
    let index = 0;
    let first = it.next();
    // An empty iterator and no initial value is an error.
    if (first.done && initial === undefined) {
        throw new TypeError('Reduce of empty iterable with no initial value.');
    }
    // If the iterator is empty, return the initial value.
    if (first.done) {
        return initial;
    }
    // If the iterator has a single item and no initial value, the
    // reducer is not invoked and the first item is the return value.
    let second = it.next();
    if (second.done && initial === undefined) {
        return first.value;
    }
    // If iterator has a single item and an initial value is provided,
    // the reducer is invoked and that result is the return value.
    if (second.done) {
        return fn(initial, first.value, index++);
    }
    // Setup the initial accumlated value.
    let accumulator;
    if (initial === undefined) {
        accumulator = fn(first.value, second.value, index++);
    }
    else {
        accumulator = fn(fn(initial, first.value, index++), second.value, index++);
    }
    // Iterate the rest of the values, updating the accumulator.
    let next;
    while (!(next = it.next()).done) {
        accumulator = fn(accumulator, next.value, index++);
    }
    // Return the final accumulated value.
    return accumulator;
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Create an iterator which repeats a value a number of times.
 *
 * @deprecated
 *
 * @param value - The value to repeat.
 *
 * @param count - The number of times to repeat the value.
 *
 * @returns A new iterator which repeats the specified value.
 *
 * #### Example
 * ```typescript
 * import { repeat } from '@lumino/algorithm';
 *
 * let stream = repeat(7, 3);
 *
 * Array.from(stream);  // [7, 7, 7]
 * ```
 */
function* repeat(value, count) {
    while (0 < count--) {
        yield value;
    }
}
/**
 * Create an iterator which yields a value a single time.
 *
 * @deprecated
 *
 * @param value - The value to wrap in an iterator.
 *
 * @returns A new iterator which yields the value a single time.
 *
 * #### Example
 * ```typescript
 * import { once } from '@lumino/algorithm';
 *
 * let stream = once(7);
 *
 * Array.from(stream);  // [7]
 * ```
 */
function* once(value) {
    yield value;
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Create an iterator for a retroable object.
 *
 * @param object - The retroable or array-like object of interest.
 *
 * @returns An iterator which traverses the object's values in reverse.
 *
 * #### Example
 * ```typescript
 * import { retro } from '@lumino/algorithm';
 *
 * let data = [1, 2, 3, 4, 5, 6];
 *
 * let stream = retro(data);
 *
 * Array.from(stream);  // [6, 5, 4, 3, 2, 1]
 * ```
 */
function* retro(object) {
    if (typeof object.retro === 'function') {
        yield* object.retro();
    }
    else {
        for (let index = object.length - 1; index > -1; index--) {
            yield object[index];
        }
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Topologically sort an iterable of edges.
 *
 * @param edges - The iterable object of edges to sort.
 *   An edge is represented as a 2-tuple of `[fromNode, toNode]`.
 *
 * @returns The topologically sorted array of nodes.
 *
 * #### Notes
 * If a cycle is present in the graph, the cycle will be ignored and
 * the return value will be only approximately sorted.
 *
 * #### Example
 * ```typescript
 * import { topologicSort } from '@lumino/algorithm';
 *
 * let data = [
 *   ['d', 'e'],
 *   ['c', 'd'],
 *   ['a', 'b'],
 *   ['b', 'c']
 * ];
 *
 * topologicSort(data);  // ['a', 'b', 'c', 'd', 'e']
 * ```
 */
function topologicSort(edges) {
    // Setup the shared sorting state.
    let sorted = [];
    let visited = new Set();
    let graph = new Map();
    // Add the edges to the graph.
    for (const edge of edges) {
        addEdge(edge);
    }
    // Visit each node in the graph.
    for (const [k] of graph) {
        visit(k);
    }
    // Return the sorted results.
    return sorted;
    // Add an edge to the graph.
    function addEdge(edge) {
        let [fromNode, toNode] = edge;
        let children = graph.get(toNode);
        if (children) {
            children.push(fromNode);
        }
        else {
            graph.set(toNode, [fromNode]);
        }
    }
    // Recursively visit the node.
    function visit(node) {
        if (visited.has(node)) {
            return;
        }
        visited.add(node);
        let children = graph.get(node);
        if (children) {
            for (const child of children) {
                visit(child);
            }
        }
        sorted.push(node);
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Iterate over an iterable using a stepped increment.
 *
 * @param object - The iterable object of interest.
 *
 * @param step - The distance to step on each iteration. A value
 *   of less than `1` will behave the same as a value of `1`.
 *
 * @returns An iterator which traverses the iterable step-wise.
 *
 * #### Example
 * ```typescript
 * import { stride } from '@lumino/algorithm';
 *
 * let data = [1, 2, 3, 4, 5, 6];
 *
 * let stream = stride(data, 2);
 *
 * Array.from(stream);  // [1, 3, 5];
 * ```
 */
function* stride(object, step) {
    let count = 0;
    for (const value of object) {
        if (0 === count++ % step) {
            yield value;
        }
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * The namespace for string-specific algorithms.
 */
var StringExt;
(function (StringExt) {
    /**
     * Find the indices of characters in a source text.
     *
     * @param source - The source text which should be searched.
     *
     * @param query - The characters to locate in the source text.
     *
     * @param start - The index to start the search.
     *
     * @returns The matched indices, or `null` if there is no match.
     *
     * #### Complexity
     * Linear on `sourceText`.
     *
     * #### Notes
     * In order for there to be a match, all of the characters in `query`
     * **must** appear in `source` in the order given by `query`.
     *
     * Characters are matched using strict `===` equality.
     */
    function findIndices(source, query, start = 0) {
        let indices = new Array(query.length);
        for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {
            j = source.indexOf(query[i], j);
            if (j === -1) {
                return null;
            }
            indices[i] = j;
        }
        return indices;
    }
    StringExt.findIndices = findIndices;
    /**
     * A string matcher which uses a sum-of-squares algorithm.
     *
     * @param source - The source text which should be searched.
     *
     * @param query - The characters to locate in the source text.
     *
     * @param start - The index to start the search.
     *
     * @returns The match result, or `null` if there is no match.
     *   A lower `score` represents a stronger match.
     *
     * #### Complexity
     * Linear on `sourceText`.
     *
     * #### Notes
     * This scoring algorithm uses a sum-of-squares approach to determine
     * the score. In order for there to be a match, all of the characters
     * in `query` **must** appear in `source` in order. The index of each
     * matching character is squared and added to the score. This means
     * that early and consecutive character matches are preferred, while
     * late matches are heavily penalized.
     */
    function matchSumOfSquares(source, query, start = 0) {
        let indices = findIndices(source, query, start);
        if (!indices) {
            return null;
        }
        let score = 0;
        for (let i = 0, n = indices.length; i < n; ++i) {
            let j = indices[i] - start;
            score += j * j;
        }
        return { score, indices };
    }
    StringExt.matchSumOfSquares = matchSumOfSquares;
    /**
     * A string matcher which uses a sum-of-deltas algorithm.
     *
     * @param source - The source text which should be searched.
     *
     * @param query - The characters to locate in the source text.
     *
     * @param start - The index to start the search.
     *
     * @returns The match result, or `null` if there is no match.
     *   A lower `score` represents a stronger match.
     *
     * #### Complexity
     * Linear on `sourceText`.
     *
     * #### Notes
     * This scoring algorithm uses a sum-of-deltas approach to determine
     * the score. In order for there to be a match, all of the characters
     * in `query` **must** appear in `source` in order. The delta between
     * the indices are summed to create the score. This means that groups
     * of matched characters are preferred, while fragmented matches are
     * penalized.
     */
    function matchSumOfDeltas(source, query, start = 0) {
        let indices = findIndices(source, query, start);
        if (!indices) {
            return null;
        }
        let score = 0;
        let last = start - 1;
        for (let i = 0, n = indices.length; i < n; ++i) {
            let j = indices[i];
            score += j - last - 1;
            last = j;
        }
        return { score, indices };
    }
    StringExt.matchSumOfDeltas = matchSumOfDeltas;
    /**
     * Highlight the matched characters of a source text.
     *
     * @param source - The text which should be highlighted.
     *
     * @param indices - The indices of the matched characters. They must
     *   appear in increasing order and must be in bounds of the source.
     *
     * @param fn - The function to apply to the matched chunks.
     *
     * @returns An array of unmatched and highlighted chunks.
     */
    function highlight(source, indices, fn) {
        // Set up the result array.
        let result = [];
        // Set up the counter variables.
        let k = 0;
        let last = 0;
        let n = indices.length;
        // Iterator over each index.
        while (k < n) {
            // Set up the chunk indices.
            let i = indices[k];
            let j = indices[k];
            // Advance the right chunk index until it's non-contiguous.
            while (++k < n && indices[k] === j + 1) {
                j++;
            }
            // Extract the unmatched text.
            if (last < i) {
                result.push(source.slice(last, i));
            }
            // Extract and highlight the matched text.
            if (i < j + 1) {
                result.push(fn(source.slice(i, j + 1)));
            }
            // Update the last visited index.
            last = j + 1;
        }
        // Extract any remaining unmatched text.
        if (last < source.length) {
            result.push(source.slice(last));
        }
        // Return the highlighted result.
        return result;
    }
    StringExt.highlight = highlight;
    /**
     * A 3-way string comparison function.
     *
     * @param a - The first string of interest.
     *
     * @param b - The second string of interest.
     *
     * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.
     */
    function cmp(a, b) {
        return a < b ? -1 : a > b ? 1 : 0;
    }
    StringExt.cmp = cmp;
})(StringExt || (StringExt = {}));

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Take a fixed number of items from an iterable.
 *
 * @param object - The iterable object of interest.
 *
 * @param count - The number of items to take from the iterable.
 *
 * @returns An iterator which yields the specified number of items
 *   from the source iterable.
 *
 * #### Notes
 * The returned iterator will exhaust early if the source iterable
 * contains an insufficient number of items.
 *
 * #### Example
 * ```typescript
 * import { take } from '@lumino/algorithm';
 *
 * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);
 *
 * Array.from(stream);  // [5, 4, 3]
 * ```
 */
function* take(object, count) {
    if (count < 1) {
        return;
    }
    const it = object[Symbol.iterator]();
    let item;
    while (0 < count-- && !(item = it.next()).done) {
        yield item.value;
    }
}

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * Iterate several iterables in lockstep.
 *
 * @param objects - The iterable objects of interest.
 *
 * @returns An iterator which yields successive tuples of values where
 *   each value is taken in turn from the provided iterables. It will
 *   be as long as the shortest provided iterable.
 *
 * #### Example
 * ```typescript
 * import { zip } from '@lumino/algorithm';
 *
 * let data1 = [1, 2, 3];
 * let data2 = [4, 5, 6];
 *
 * let stream = zip(data1, data2);
 *
 * Array.from(stream);  // [[1, 4], [2, 5], [3, 6]]
 * ```
 */
function* zip(...objects) {
    const iters = objects.map(obj => obj[Symbol.iterator]());
    let tuple = iters.map(it => it.next());
    for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {
        yield tuple.map(item => item.value);
    }
}


//# sourceMappingURL=index.es6.js.map


/***/ }),

/***/ 5764:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

(function (global, factory) {
     true ? factory(exports, __webpack_require__(8135)) :
    0;
})(this, (function (exports, algorithm) { 'use strict';

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    /**
     * The namespace for JSON-specific functions.
     */
    exports.JSONExt = void 0;
    (function (JSONExt) {
        /**
         * A shared frozen empty JSONObject
         */
        JSONExt.emptyObject = Object.freeze({});
        /**
         * A shared frozen empty JSONArray
         */
        JSONExt.emptyArray = Object.freeze([]);
        /**
         * Test whether a JSON value is a primitive.
         *
         * @param value - The JSON value of interest.
         *
         * @returns `true` if the value is a primitive,`false` otherwise.
         */
        function isPrimitive(value) {
            return (value === null ||
                typeof value === 'boolean' ||
                typeof value === 'number' ||
                typeof value === 'string');
        }
        JSONExt.isPrimitive = isPrimitive;
        function isArray(value) {
            return Array.isArray(value);
        }
        JSONExt.isArray = isArray;
        function isObject(value) {
            return !isPrimitive(value) && !isArray(value);
        }
        JSONExt.isObject = isObject;
        /**
         * Compare two JSON values for deep equality.
         *
         * @param first - The first JSON value of interest.
         *
         * @param second - The second JSON value of interest.
         *
         * @returns `true` if the values are equivalent, `false` otherwise.
         */
        function deepEqual(first, second) {
            // Check referential and primitive equality first.
            if (first === second) {
                return true;
            }
            // If one is a primitive, the `===` check ruled out the other.
            if (isPrimitive(first) || isPrimitive(second)) {
                return false;
            }
            // Test whether they are arrays.
            let a1 = isArray(first);
            let a2 = isArray(second);
            // Bail if the types are different.
            if (a1 !== a2) {
                return false;
            }
            // If they are both arrays, compare them.
            if (a1 && a2) {
                return deepArrayEqual(first, second);
            }
            // At this point, they must both be objects.
            return deepObjectEqual(first, second);
        }
        JSONExt.deepEqual = deepEqual;
        /**
         * Create a deep copy of a JSON value.
         *
         * @param value - The JSON value to copy.
         *
         * @returns A deep copy of the given JSON value.
         */
        function deepCopy(value) {
            // Do nothing for primitive values.
            if (isPrimitive(value)) {
                return value;
            }
            // Deep copy an array.
            if (isArray(value)) {
                return deepArrayCopy(value);
            }
            // Deep copy an object.
            return deepObjectCopy(value);
        }
        JSONExt.deepCopy = deepCopy;
        /**
         * Compare two JSON arrays for deep equality.
         */
        function deepArrayEqual(first, second) {
            // Check referential equality first.
            if (first === second) {
                return true;
            }
            // Test the arrays for equal length.
            if (first.length !== second.length) {
                return false;
            }
            // Compare the values for equality.
            for (let i = 0, n = first.length; i < n; ++i) {
                if (!deepEqual(first[i], second[i])) {
                    return false;
                }
            }
            // At this point, the arrays are equal.
            return true;
        }
        /**
         * Compare two JSON objects for deep equality.
         */
        function deepObjectEqual(first, second) {
            // Check referential equality first.
            if (first === second) {
                return true;
            }
            // Check for the first object's keys in the second object.
            for (let key in first) {
                if (first[key] !== undefined && !(key in second)) {
                    return false;
                }
            }
            // Check for the second object's keys in the first object.
            for (let key in second) {
                if (second[key] !== undefined && !(key in first)) {
                    return false;
                }
            }
            // Compare the values for equality.
            for (let key in first) {
                // Get the values.
                let firstValue = first[key];
                let secondValue = second[key];
                // If both are undefined, ignore the key.
                if (firstValue === undefined && secondValue === undefined) {
                    continue;
                }
                // If only one value is undefined, the objects are not equal.
                if (firstValue === undefined || secondValue === undefined) {
                    return false;
                }
                // Compare the values.
                if (!deepEqual(firstValue, secondValue)) {
                    return false;
                }
            }
            // At this point, the objects are equal.
            return true;
        }
        /**
         * Create a deep copy of a JSON array.
         */
        function deepArrayCopy(value) {
            let result = new Array(value.length);
            for (let i = 0, n = value.length; i < n; ++i) {
                result[i] = deepCopy(value[i]);
            }
            return result;
        }
        /**
         * Create a deep copy of a JSON object.
         */
        function deepObjectCopy(value) {
            let result = {};
            for (let key in value) {
                // Ignore undefined values.
                let subvalue = value[key];
                if (subvalue === undefined) {
                    continue;
                }
                result[key] = deepCopy(subvalue);
            }
            return result;
        }
    })(exports.JSONExt || (exports.JSONExt = {}));

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    /**
     * An object which stores MIME data for general application use.
     *
     * #### Notes
     * This class does not attempt to enforce "correctness" of MIME types
     * and their associated data. Since this class is designed to transfer
     * arbitrary data and objects within the same application, it assumes
     * that the user provides correct and accurate data.
     */
    class MimeData {
        constructor() {
            this._types = [];
            this._values = [];
        }
        /**
         * Get an array of the MIME types contained within the dataset.
         *
         * @returns A new array of the MIME types, in order of insertion.
         */
        types() {
            return this._types.slice();
        }
        /**
         * Test whether the dataset has an entry for the given type.
         *
         * @param mime - The MIME type of interest.
         *
         * @returns `true` if the dataset contains a value for the given
         *   MIME type, `false` otherwise.
         */
        hasData(mime) {
            return this._types.indexOf(mime) !== -1;
        }
        /**
         * Get the data value for the given MIME type.
         *
         * @param mime - The MIME type of interest.
         *
         * @returns The value for the given MIME type, or `undefined` if
         *   the dataset does not contain a value for the type.
         */
        getData(mime) {
            let i = this._types.indexOf(mime);
            return i !== -1 ? this._values[i] : undefined;
        }
        /**
         * Set the data value for the given MIME type.
         *
         * @param mime - The MIME type of interest.
         *
         * @param data - The data value for the given MIME type.
         *
         * #### Notes
         * This will overwrite any previous entry for the MIME type.
         */
        setData(mime, data) {
            this.clearData(mime);
            this._types.push(mime);
            this._values.push(data);
        }
        /**
         * Remove the data entry for the given MIME type.
         *
         * @param mime - The MIME type of interest.
         *
         * #### Notes
         * This is a no-op if there is no entry for the given MIME type.
         */
        clearData(mime) {
            let i = this._types.indexOf(mime);
            if (i !== -1) {
                this._types.splice(i, 1);
                this._values.splice(i, 1);
            }
        }
        /**
         * Remove all data entries from the dataset.
         */
        clear() {
            this._types.length = 0;
            this._values.length = 0;
        }
    }

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /**
     * Plugin registry.
     */
    class PluginRegistry {
        constructor(options = {}) {
            this._application = null;
            this._validatePlugin = () => true;
            this._plugins = new Map();
            this._services = new Map();
            if (options.validatePlugin) {
                console.info('Plugins may be rejected by the custom validation plugin method.');
                this._validatePlugin = options.validatePlugin;
            }
        }
        /**
         * The application object.
         *
         * It will be provided as first argument to the
         * plugins activation and deactivation functions.
         *
         * It can only be set once.
         *
         * By default, it is `null`.
         */
        get application() {
            return this._application;
        }
        set application(v) {
            if (this._application !== null) {
                throw Error('PluginRegistry.application is already set. It cannot be overridden.');
            }
            this._application = v;
        }
        /**
         * The list of all the deferred plugins.
         */
        get deferredPlugins() {
            return Array.from(this._plugins)
                .filter(([id, plugin]) => plugin.autoStart === 'defer')
                .map(([id, plugin]) => id);
        }
        /**
         * Get a plugin description.
         *
         * @param id - The ID of the plugin of interest.
         *
         * @returns The plugin description.
         */
        getPluginDescription(id) {
            var _a, _b;
            return (_b = (_a = this._plugins.get(id)) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : '';
        }
        /**
         * Test whether a plugin is registered with the application.
         *
         * @param id - The ID of the plugin of interest.
         *
         * @returns `true` if the plugin is registered, `false` otherwise.
         */
        hasPlugin(id) {
            return this._plugins.has(id);
        }
        /**
         * Test whether a plugin is activated with the application.
         *
         * @param id - The ID of the plugin of interest.
         *
         * @returns `true` if the plugin is activated, `false` otherwise.
         */
        isPluginActivated(id) {
            var _a, _b;
            return (_b = (_a = this._plugins.get(id)) === null || _a === void 0 ? void 0 : _a.activated) !== null && _b !== void 0 ? _b : false;
        }
        /**
         * List the IDs of the plugins registered with the application.
         *
         * @returns A new array of the registered plugin IDs.
         */
        listPlugins() {
            return Array.from(this._plugins.keys());
        }
        /**
         * Register a plugin with the application.
         *
         * @param plugin - The plugin to register.
         *
         * #### Notes
         * An error will be thrown if a plugin with the same ID is already
         * registered, or if the plugin has a circular dependency.
         *
         * If the plugin provides a service which has already been provided
         * by another plugin, the new service will override the old service.
         */
        registerPlugin(plugin) {
            // Throw an error if the plugin ID is already registered.
            if (this._plugins.has(plugin.id)) {
                throw new TypeError(`Plugin '${plugin.id}' is already registered.`);
            }
            if (!this._validatePlugin(plugin)) {
                throw new Error(`Plugin '${plugin.id}' is not valid.`);
            }
            // Create the normalized plugin data.
            const data = Private.createPluginData(plugin);
            // Ensure the plugin does not cause a cyclic dependency.
            Private.ensureNoCycle(data, this._plugins, this._services);
            // Add the service token to the service map.
            if (data.provides) {
                this._services.set(data.provides, data.id);
            }
            // Add the plugin to the plugin map.
            this._plugins.set(data.id, data);
        }
        /**
         * Register multiple plugins with the application.
         *
         * @param plugins - The plugins to register.
         *
         * #### Notes
         * This calls `registerPlugin()` for each of the given plugins.
         */
        registerPlugins(plugins) {
            for (const plugin of plugins) {
                this.registerPlugin(plugin);
            }
        }
        /**
         * Deregister a plugin with the application.
         *
         * @param id - The ID of the plugin of interest.
         *
         * @param force - Whether to deregister the plugin even if it is active.
         */
        deregisterPlugin(id, force) {
            const plugin = this._plugins.get(id);
            if (!plugin) {
                return;
            }
            if (plugin.activated && !force) {
                throw new Error(`Plugin '${id}' is still active.`);
            }
            this._plugins.delete(id);
        }
        /**
         * Activate the plugin with the given ID.
         *
         * @param id - The ID of the plugin of interest.
         *
         * @returns A promise which resolves when the plugin is activated
         *   or rejects with an error if it cannot be activated.
         */
        async activatePlugin(id) {
            // Reject the promise if the plugin is not registered.
            const plugin = this._plugins.get(id);
            if (!plugin) {
                throw new ReferenceError(`Plugin '${id}' is not registered.`);
            }
            // Resolve immediately if the plugin is already activated.
            if (plugin.activated) {
                return;
            }
            // Return the pending resolver promise if it exists.
            if (plugin.promise) {
                return plugin.promise;
            }
            // Resolve the required services for the plugin.
            const required = plugin.requires.map(t => this.resolveRequiredService(t));
            // Resolve the optional services for the plugin.
            const optional = plugin.optional.map(t => this.resolveOptionalService(t));
            // Setup the resolver promise for the plugin.
            plugin.promise = Promise.all([...required, ...optional])
                .then(services => plugin.activate.apply(undefined, [this.application, ...services]))
                .then(service => {
                plugin.service = service;
                plugin.activated = true;
                plugin.promise = null;
            })
                .catch(error => {
                plugin.promise = null;
                throw error;
            });
            // Return the pending resolver promise.
            return plugin.promise;
        }
        /**
         * Activate all the deferred plugins.
         *
         * @returns A promise which will resolve when each plugin is activated
         * or rejects with an error if one cannot be activated.
         */
        async activatePlugins(kind, options = {}) {
            switch (kind) {
                case 'defer': {
                    const promises = this.deferredPlugins
                        .filter(pluginId => this._plugins.get(pluginId).autoStart)
                        .map(pluginId => {
                        return this.activatePlugin(pluginId);
                    });
                    await Promise.all(promises);
                    break;
                }
                case 'startUp': {
                    // Collect the ids of the startup plugins.
                    const startups = Private.collectStartupPlugins(this._plugins, options);
                    // Generate the activation promises.
                    const promises = startups.map(async (id) => {
                        try {
                            return await this.activatePlugin(id);
                        }
                        catch (error) {
                            console.error(`Plugin '${id}' failed to activate.`, error);
                        }
                    });
                    await Promise.all(promises);
                    break;
                }
            }
        }
        /**
         * Deactivate the plugin and its downstream dependents if and only if the
         * plugin and its dependents all support `deactivate`.
         *
         * @param id - The ID of the plugin of interest.
         *
         * @returns A list of IDs of downstream plugins deactivated with this one.
         */
        async deactivatePlugin(id) {
            // Reject the promise if the plugin is not registered.
            const plugin = this._plugins.get(id);
            if (!plugin) {
                throw new ReferenceError(`Plugin '${id}' is not registered.`);
            }
            // Bail early if the plugin is not activated.
            if (!plugin.activated) {
                return [];
            }
            // Check that this plugin can deactivate.
            if (!plugin.deactivate) {
                throw new TypeError(`Plugin '${id}'#deactivate() method missing`);
            }
            // Find the optimal deactivation order for plugins downstream of this one.
            const manifest = Private.findDependents(id, this._plugins, this._services);
            const downstream = manifest.map(id => this._plugins.get(id));
            // Check that all downstream plugins can deactivate.
            for (const plugin of downstream) {
                if (!plugin.deactivate) {
                    throw new TypeError(`Plugin ${plugin.id}#deactivate() method missing (depends on ${id})`);
                }
            }
            // Deactivate all downstream plugins.
            for (const plugin of downstream) {
                const services = [...plugin.requires, ...plugin.optional].map(service => {
                    const id = this._services.get(service);
                    return id ? this._plugins.get(id).service : null;
                });
                // Await deactivation so the next plugins only receive active services.
                await plugin.deactivate(this.application, ...services);
                plugin.service = null;
                plugin.activated = false;
            }
            // Remove plugin ID and return manifest of deactivated plugins.
            manifest.pop();
            return manifest;
        }
        /**
         * Resolve a required service of a given type.
         *
         * @param token - The token for the service type of interest.
         *
         * @returns A promise which resolves to an instance of the requested
         *   service, or rejects with an error if it cannot be resolved.
         *
         * #### Notes
         * Services are singletons. The same instance will be returned each
         * time a given service token is resolved.
         *
         * If the plugin which provides the service has not been activated,
         * resolving the service will automatically activate the plugin.
         *
         * User code will not typically call this method directly. Instead,
         * the required services for the user's plugins will be resolved
         * automatically when the plugin is activated.
         */
        async resolveRequiredService(token) {
            // Reject the promise if there is no provider for the type.
            const id = this._services.get(token);
            if (!id) {
                throw new TypeError(`No provider for: ${token.name}.`);
            }
            // Activate the plugin if necessary.
            const plugin = this._plugins.get(id);
            if (!plugin.activated) {
                await this.activatePlugin(id);
            }
            return plugin.service;
        }
        /**
         * Resolve an optional service of a given type.
         *
         * @param token - The token for the service type of interest.
         *
         * @returns A promise which resolves to an instance of the requested
         *   service, or `null` if it cannot be resolved.
         *
         * #### Notes
         * Services are singletons. The same instance will be returned each
         * time a given service token is resolved.
         *
         * If the plugin which provides the service has not been activated,
         * resolving the service will automatically activate the plugin.
         *
         * User code will not typically call this method directly. Instead,
         * the optional services for the user's plugins will be resolved
         * automatically when the plugin is activated.
         */
        async resolveOptionalService(token) {
            // Resolve with `null` if there is no provider for the type.
            const id = this._services.get(token);
            if (!id) {
                return null;
            }
            // Activate the plugin if necessary.
            const plugin = this._plugins.get(id);
            if (!plugin.activated) {
                try {
                    await this.activatePlugin(id);
                }
                catch (reason) {
                    console.error(reason);
                    return null;
                }
            }
            return plugin.service;
        }
    }
    /**
     * The namespace for the module implementation details.
     */
    var Private;
    (function (Private) {
        class PluginData {
            constructor(plugin) {
                var _a, _b, _c, _d;
                this._activated = false;
                this._promise = null;
                this._service = null;
                this.id = plugin.id;
                this.description = (_a = plugin.description) !== null && _a !== void 0 ? _a : '';
                this.activate = plugin.activate;
                this.deactivate = (_b = plugin.deactivate) !== null && _b !== void 0 ? _b : null;
                this.provides = (_c = plugin.provides) !== null && _c !== void 0 ? _c : null;
                this.autoStart = (_d = plugin.autoStart) !== null && _d !== void 0 ? _d : false;
                this.requires = plugin.requires ? plugin.requires.slice() : [];
                this.optional = plugin.optional ? plugin.optional.slice() : [];
            }
            /**
             * Whether the plugin has been activated.
             */
            get activated() {
                return this._activated;
            }
            set activated(a) {
                this._activated = a;
            }
            /**
             * The resolved service for the plugin, or `null`.
             */
            get service() {
                return this._service;
            }
            set service(s) {
                this._service = s;
            }
            /**
             * The pending resolver promise, or `null`.
             */
            get promise() {
                return this._promise;
            }
            set promise(p) {
                this._promise = p;
            }
        }
        /**
         * Create a normalized plugin data object for the given plugin.
         */
        function createPluginData(plugin) {
            return new PluginData(plugin);
        }
        Private.createPluginData = createPluginData;
        /**
         * Ensure no cycle is present in the plugin resolution graph.
         *
         * If a cycle is detected, an error will be thrown.
         */
        function ensureNoCycle(plugin, plugins, services) {
            const dependencies = [...plugin.requires, ...plugin.optional];
            const visit = (token) => {
                if (token === plugin.provides) {
                    return true;
                }
                const id = services.get(token);
                if (!id) {
                    return false;
                }
                const visited = plugins.get(id);
                const dependencies = [...visited.requires, ...visited.optional];
                if (dependencies.length === 0) {
                    return false;
                }
                trace.push(id);
                if (dependencies.some(visit)) {
                    return true;
                }
                trace.pop();
                return false;
            };
            // Bail early if there cannot be a cycle.
            if (!plugin.provides || dependencies.length === 0) {
                return;
            }
            // Setup a stack to trace service resolution.
            const trace = [plugin.id];
            // Throw an exception if a cycle is present.
            if (dependencies.some(visit)) {
                throw new ReferenceError(`Cycle detected: ${trace.join(' -> ')}.`);
            }
        }
        Private.ensureNoCycle = ensureNoCycle;
        /**
         * Find dependents in deactivation order.
         *
         * @param id - The ID of the plugin of interest.
         *
         * @param plugins - The map containing all plugins.
         *
         * @param services - The map containing all services.
         *
         * @returns A list of dependent plugin IDs in order of deactivation
         *
         * #### Notes
         * The final item of the returned list is always the plugin of interest.
         */
        function findDependents(id, plugins, services) {
            const edges = new Array();
            const add = (id) => {
                const plugin = plugins.get(id);
                // FIXME In the case of missing optional dependencies, we may consider
                // deactivating and reactivating the plugin without the missing service.
                const dependencies = [...plugin.requires, ...plugin.optional];
                edges.push(...dependencies.reduce((acc, dep) => {
                    const service = services.get(dep);
                    if (service) {
                        // An edge is oriented from dependent to provider.
                        acc.push([id, service]);
                    }
                    return acc;
                }, []));
            };
            for (const id of plugins.keys()) {
                add(id);
            }
            // Filter edges
            // - Get all packages that dependent on the package to be deactivated
            const newEdges = edges.filter(edge => edge[1] === id);
            let oldSize = 0;
            while (newEdges.length > oldSize) {
                const previousSize = newEdges.length;
                // Get all packages that dependent on packages that will be deactivated
                const packagesOfInterest = new Set(newEdges.map(edge => edge[0]));
                for (const poi of packagesOfInterest) {
                    edges
                        .filter(edge => edge[1] === poi)
                        .forEach(edge => {
                        // We check it is not already included to deal with circular dependencies
                        if (!newEdges.includes(edge)) {
                            newEdges.push(edge);
                        }
                    });
                }
                oldSize = previousSize;
            }
            const sorted = algorithm.topologicSort(newEdges);
            const index = sorted.findIndex(candidate => candidate === id);
            if (index === -1) {
                return [id];
            }
            return sorted.slice(0, index + 1);
        }
        Private.findDependents = findDependents;
        /**
         * Collect the IDs of the plugins to activate on startup.
         */
        function collectStartupPlugins(plugins, options) {
            // Create a set to hold the plugin IDs.
            const collection = new Set();
            // Collect the auto-start (non deferred) plugins.
            for (const id of plugins.keys()) {
                if (plugins.get(id).autoStart === true) {
                    collection.add(id);
                }
            }
            // Add the startup plugins.
            if (options.startPlugins) {
                for (const id of options.startPlugins) {
                    collection.add(id);
                }
            }
            // Remove the ignored plugins.
            if (options.ignorePlugins) {
                for (const id of options.ignorePlugins) {
                    collection.delete(id);
                }
            }
            // Return the collected startup plugins.
            return Array.from(collection);
        }
        Private.collectStartupPlugins = collectStartupPlugins;
    })(Private || (Private = {}));

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    /**
     * A class which wraps a promise into a delegate object.
     *
     * #### Notes
     * This class is useful when the logic to resolve or reject a promise
     * cannot be defined at the point where the promise is created.
     */
    class PromiseDelegate {
        /**
         * Construct a new promise delegate.
         */
        constructor() {
            this.promise = new Promise((resolve, reject) => {
                this._resolve = resolve;
                this._reject = reject;
            });
        }
        /**
         * Resolve the wrapped promise with the given value.
         *
         * @param value - The value to use for resolving the promise.
         */
        resolve(value) {
            let resolve = this._resolve;
            resolve(value);
        }
        /**
         * Reject the wrapped promise with the given value.
         *
         * @reason - The reason for rejecting the promise.
         */
        reject(reason) {
            let reject = this._reject;
            reject(reason);
        }
    }

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    /**
     * A runtime object which captures compile-time type information.
     *
     * #### Notes
     * A token captures the compile-time type of an interface or class in
     * an object which can be used at runtime in a type-safe fashion.
     */
    class Token {
        /**
         * Construct a new token.
         *
         * @param name - A human readable name for the token.
         * @param description - Token purpose description for documentation.
         */
        constructor(name, description) {
            this.name = name;
            this.description = description !== null && description !== void 0 ? description : '';
            this._tokenStructuralPropertyT = null;
        }
    }

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    // Fallback
    function fallbackRandomValues(buffer) {
        let value = 0;
        for (let i = 0, n = buffer.length; i < n; ++i) {
            if (i % 4 === 0) {
                value = (Math.random() * 0xffffffff) >>> 0;
            }
            buffer[i] = value & 0xff;
            value >>>= 8;
        }
    }

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    /**
     * The namespace for random number related functionality.
     */
    exports.Random = void 0;
    (function (Random) {
        /**
         * A function which generates random bytes.
         *
         * @param buffer - The `Uint8Array` to fill with random bytes.
         *
         * #### Notes
         * A cryptographically strong random number generator will be used if
         * available. Otherwise, `Math.random` will be used as a fallback for
         * randomness.
         *
         * The following RNGs are supported, listed in order of precedence:
         *   - `window.crypto.getRandomValues`
         *   - `window.msCrypto.getRandomValues`
         *   - `require('crypto').randomFillSync
         *   - `require('crypto').randomBytes
         *   - `Math.random`
         */
        Random.getRandomValues = (() => {
            // Look up the crypto module if available.
            const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||
                null;
            // Modern browsers and IE 11
            if (crypto && typeof crypto.getRandomValues === 'function') {
                return function getRandomValues(buffer) {
                    return crypto.getRandomValues(buffer);
                };
            }
            // Fallback
            return fallbackRandomValues;
        })();
    })(exports.Random || (exports.Random = {}));

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    /**
     * A function which creates a function that generates UUID v4 identifiers.
     *
     * @returns A new function that creates a UUID v4 string.
     *
     * #### Notes
     * This implementation complies with RFC 4122.
     *
     * This uses `Random.getRandomValues()` for random bytes, which in
     * turn will use the underlying `crypto` module of the platform if
     * it is available. The fallback for randomness is `Math.random`.
     */
    function uuid4Factory(getRandomValues) {
        // Create a 16 byte array to hold the random values.
        const bytes = new Uint8Array(16);
        // Create a look up table from bytes to hex strings.
        const lut = new Array(256);
        // Pad the single character hex digits with a leading zero.
        for (let i = 0; i < 16; ++i) {
            lut[i] = '0' + i.toString(16);
        }
        // Populate the rest of the hex digits.
        for (let i = 16; i < 256; ++i) {
            lut[i] = i.toString(16);
        }
        // Return a function which generates the UUID.
        return function uuid4() {
            // Get a new batch of random values.
            getRandomValues(bytes);
            // Set the UUID version number to 4.
            bytes[6] = 0x40 | (bytes[6] & 0x0f);
            // Set the clock sequence bit to the RFC spec.
            bytes[8] = 0x80 | (bytes[8] & 0x3f);
            // Assemble the UUID string.
            return (lut[bytes[0]] +
                lut[bytes[1]] +
                lut[bytes[2]] +
                lut[bytes[3]] +
                '-' +
                lut[bytes[4]] +
                lut[bytes[5]] +
                '-' +
                lut[bytes[6]] +
                lut[bytes[7]] +
                '-' +
                lut[bytes[8]] +
                lut[bytes[9]] +
                '-' +
                lut[bytes[10]] +
                lut[bytes[11]] +
                lut[bytes[12]] +
                lut[bytes[13]] +
                lut[bytes[14]] +
                lut[bytes[15]]);
        };
    }

    // Copyright (c) Jupyter Development Team.
    // Distributed under the terms of the Modified BSD License.
    /*-----------------------------------------------------------------------------
    | Copyright (c) 2014-2017, PhosphorJS Contributors
    |
    | Distributed under the terms of the BSD 3-Clause License.
    |
    | The full license is in the file LICENSE, distributed with this software.
    |----------------------------------------------------------------------------*/
    /**
     * The namespace for UUID related functionality.
     */
    exports.UUID = void 0;
    (function (UUID) {
        /**
         * A function which generates UUID v4 identifiers.
         *
         * @returns A new UUID v4 string.
         *
         * #### Notes
         * This implementation complies with RFC 4122.
         *
         * This uses `Random.getRandomValues()` for random bytes, which in
         * turn will use the underlying `crypto` module of the platform if
         * it is available. The fallback for randomness is `Math.random`.
         */
        UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);
    })(exports.UUID || (exports.UUID = {}));

    exports.MimeData = MimeData;
    exports.PluginRegistry = PluginRegistry;
    exports.PromiseDelegate = PromiseDelegate;
    exports.Token = Token;

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


/***/ }),

/***/ 7556:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DisposableDelegate: () => (/* binding */ DisposableDelegate),
/* harmony export */   DisposableSet: () => (/* binding */ DisposableSet),
/* harmony export */   ObservableDisposableDelegate: () => (/* binding */ ObservableDisposableDelegate),
/* harmony export */   ObservableDisposableSet: () => (/* binding */ ObservableDisposableSet)
/* harmony export */ });
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3992);


// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * @packageDocumentation
 * @module disposable
 */
/**
 * A disposable object which delegates to a callback function.
 */
class DisposableDelegate {
    /**
     * Construct a new disposable delegate.
     *
     * @param fn - The callback function to invoke on dispose.
     */
    constructor(fn) {
        this._fn = fn;
    }
    /**
     * Test whether the delegate has been disposed.
     */
    get isDisposed() {
        return !this._fn;
    }
    /**
     * Dispose of the delegate and invoke the callback function.
     */
    dispose() {
        if (!this._fn) {
            return;
        }
        let fn = this._fn;
        this._fn = null;
        fn();
    }
}
/**
 * An observable disposable object which delegates to a callback function.
 */
class ObservableDisposableDelegate extends DisposableDelegate {
    constructor() {
        super(...arguments);
        this._disposed = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_0__.Signal(this);
    }
    /**
     * A signal emitted when the delegate is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * Dispose of the delegate and invoke the callback function.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        this._disposed.emit(undefined);
        _lumino_signaling__WEBPACK_IMPORTED_MODULE_0__.Signal.clearData(this);
    }
}
/**
 * An object which manages a collection of disposable items.
 */
class DisposableSet {
    constructor() {
        this._isDisposed = false;
        this._items = new Set();
    }
    /**
     * Test whether the set has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the set and the items it contains.
     *
     * #### Notes
     * Items are disposed in the order they are added to the set.
     */
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        this._items.forEach(item => {
            item.dispose();
        });
        this._items.clear();
    }
    /**
     * Test whether the set contains a specific item.
     *
     * @param item - The item of interest.
     *
     * @returns `true` if the set contains the item, `false` otherwise.
     */
    contains(item) {
        return this._items.has(item);
    }
    /**
     * Add a disposable item to the set.
     *
     * @param item - The item to add to the set.
     *
     * #### Notes
     * If the item is already contained in the set, this is a no-op.
     */
    add(item) {
        this._items.add(item);
    }
    /**
     * Remove a disposable item from the set.
     *
     * @param item - The item to remove from the set.
     *
     * #### Notes
     * If the item is not contained in the set, this is a no-op.
     */
    remove(item) {
        this._items.delete(item);
    }
    /**
     * Remove all items from the set.
     */
    clear() {
        this._items.clear();
    }
}
/**
 * The namespace for the `DisposableSet` class statics.
 */
(function (DisposableSet) {
    /**
     * Create a disposable set from an iterable of items.
     *
     * @param items - The iterable object of interest.
     *
     * @returns A new disposable initialized with the given items.
     */
    function from(items) {
        let set = new DisposableSet();
        for (const item of items) {
            set.add(item);
        }
        return set;
    }
    DisposableSet.from = from;
})(DisposableSet || (DisposableSet = {}));
/**
 * An observable object which manages a collection of disposable items.
 */
class ObservableDisposableSet extends DisposableSet {
    constructor() {
        super(...arguments);
        this._disposed = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_0__.Signal(this);
    }
    /**
     * A signal emitted when the set is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * Dispose of the set and the items it contains.
     *
     * #### Notes
     * Items are disposed in the order they are added to the set.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        super.dispose();
        this._disposed.emit(undefined);
        _lumino_signaling__WEBPACK_IMPORTED_MODULE_0__.Signal.clearData(this);
    }
}
/**
 * The namespace for the `ObservableDisposableSet` class statics.
 */
(function (ObservableDisposableSet) {
    /**
     * Create an observable disposable set from an iterable of items.
     *
     * @param items - The iterable object of interest.
     *
     * @returns A new disposable initialized with the given items.
     */
    function from(items) {
        let set = new ObservableDisposableSet();
        for (const item of items) {
            set.add(item);
        }
        return set;
    }
    ObservableDisposableSet.from = from;
})(ObservableDisposableSet || (ObservableDisposableSet = {}));


//# sourceMappingURL=index.es6.js.map


/***/ }),

/***/ 6049:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Debouncer: () => (/* binding */ Debouncer),
/* harmony export */   Poll: () => (/* binding */ Poll),
/* harmony export */   RateLimiter: () => (/* binding */ RateLimiter),
/* harmony export */   Throttler: () => (/* binding */ Throttler)
/* harmony export */ });
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5764);
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3992);



// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/**
 * A class that wraps an asynchronous function to poll at a regular interval
 * with exponential increases to the interval length if the poll fails.
 *
 * @typeparam T - The resolved type of the factory's promises.
 * Defaults to `any`.
 *
 * @typeparam U - The rejected type of the factory's promises.
 * Defaults to `any`.
 *
 * @typeparam V - An optional type to extend the phases supported by a poll.
 * Defaults to `standby`, which already exists in the `Phase` type.
 */
class Poll {
    /**
     * Instantiate a new poll with exponential backoff in case of failure.
     *
     * @param options - The poll instantiation options.
     */
    constructor(options) {
        var _a;
        this._disposed = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this._lingered = 0;
        this._tick = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.PromiseDelegate();
        this._ticked = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this._factory = options.factory;
        this._linger = (_a = options.linger) !== null && _a !== void 0 ? _a : Private.DEFAULT_LINGER;
        this._standby = options.standby || Private.DEFAULT_STANDBY;
        this._state = { ...Private.DEFAULT_STATE, timestamp: new Date().getTime() };
        // Normalize poll frequency `max` to be the greater of
        // default `max`, `options.frequency.max`, or `options.frequency.interval`.
        const frequency = options.frequency || {};
        const max = Math.max(frequency.interval || 0, frequency.max || 0, Private.DEFAULT_FREQUENCY.max);
        this.frequency = { ...Private.DEFAULT_FREQUENCY, ...frequency, ...{ max } };
        this.name = options.name || Private.DEFAULT_NAME;
        if ('auto' in options ? options.auto : true) {
            setTimeout(() => this.start());
        }
    }
    /**
     * A signal emitted when the poll is disposed.
     */
    get disposed() {
        return this._disposed;
    }
    /**
     * The polling frequency parameters.
     */
    get frequency() {
        return this._frequency;
    }
    set frequency(frequency) {
        if (this.isDisposed || _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.JSONExt.deepEqual(frequency, this.frequency || {})) {
            return;
        }
        let { backoff, interval, max } = frequency;
        interval = Math.round(interval);
        max = Math.round(max);
        if (typeof backoff === 'number' && backoff < 1) {
            throw new Error('Poll backoff growth factor must be at least 1');
        }
        if ((interval < 0 || interval > max) && interval !== Poll.NEVER) {
            throw new Error('Poll interval must be between 0 and max');
        }
        if (max > Poll.MAX_INTERVAL && max !== Poll.NEVER) {
            throw new Error(`Max interval must be less than ${Poll.MAX_INTERVAL}`);
        }
        this._frequency = { backoff, interval, max };
    }
    /**
     * Whether the poll is disposed.
     */
    get isDisposed() {
        return this.state.phase === 'disposed';
    }
    /**
     * Indicates when the poll switches to standby.
     */
    get standby() {
        return this._standby;
    }
    set standby(standby) {
        if (this.isDisposed || this.standby === standby) {
            return;
        }
        this._standby = standby;
    }
    /**
     * The poll state, which is the content of the current poll tick.
     */
    get state() {
        return this._state;
    }
    /**
     * A promise that resolves when the poll next ticks.
     */
    get tick() {
        return this._tick.promise;
    }
    /**
     * A signal emitted when the poll ticks and fires off a new request.
     */
    get ticked() {
        return this._ticked;
    }
    /**
     * Return an async iterator that yields every tick.
     */
    async *[Symbol.asyncIterator]() {
        while (!this.isDisposed) {
            yield this.state;
            await this.tick.catch(() => undefined);
        }
    }
    /**
     * Dispose the poll.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._state = {
            ...Private.DISPOSED_STATE,
            timestamp: new Date().getTime()
        };
        this._tick.promise.catch(_ => undefined);
        this._tick.reject(new Error(`Poll (${this.name}) is disposed.`));
        this._disposed.emit(undefined);
        _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal.clearData(this);
    }
    /**
     * Refreshes the poll. Schedules `refreshed` tick if necessary.
     *
     * @returns A promise that resolves after tick is scheduled and never rejects.
     *
     * #### Notes
     * The returned promise resolves after the tick is scheduled, but before
     * the polling action is run. To wait until after the poll action executes,
     * await the `poll.tick` promise: `await poll.refresh(); await poll.tick;`
     */
    refresh() {
        return this.schedule({
            cancel: ({ phase }) => phase === 'refreshed',
            interval: Poll.IMMEDIATE,
            phase: 'refreshed'
        });
    }
    /**
     * Schedule the next poll tick.
     *
     * @param next - The next poll state data to schedule. Defaults to standby.
     *
     * @param next.cancel - Cancels state transition if function returns `true`.
     *
     * @returns A promise that resolves when the next poll state is active.
     *
     * #### Notes
     * This method is not meant to be invoked by user code typically. It is public
     * to allow poll instances to be composed into classes that schedule ticks.
     */
    async schedule(next = {}) {
        if (this.isDisposed) {
            return;
        }
        // Check if the phase transition should be canceled.
        if (next.cancel && next.cancel(this.state)) {
            return;
        }
        // Update poll state.
        const pending = this._tick;
        const scheduled = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.PromiseDelegate();
        const state = {
            interval: this.frequency.interval,
            payload: null,
            phase: 'standby',
            timestamp: new Date().getTime(),
            ...next
        };
        this._state = state;
        this._tick = scheduled;
        // Clear the schedule if possible.
        clearTimeout(this._timeout);
        // Emit ticked signal, resolve pending promise, and await its settlement.
        this._ticked.emit(this.state);
        pending.resolve(this);
        await pending.promise;
        if (state.interval === Poll.NEVER) {
            this._timeout = undefined;
            return;
        }
        // Schedule next execution and cache its timeout handle.
        const execute = () => {
            if (this.isDisposed || this.tick !== scheduled.promise) {
                return;
            }
            this._execute();
        };
        // Cache the handle in case it needs to be unscheduled.
        this._timeout = setTimeout(execute, state.interval);
    }
    /**
     * Starts the poll. Schedules `started` tick if necessary.
     *
     * @returns A promise that resolves after tick is scheduled and never rejects.
     */
    start() {
        return this.schedule({
            cancel: ({ phase }) => phase !== 'constructed' && phase !== 'standby' && phase !== 'stopped',
            interval: Poll.IMMEDIATE,
            phase: 'started'
        });
    }
    /**
     * Stops the poll. Schedules `stopped` tick if necessary.
     *
     * @returns A promise that resolves after tick is scheduled and never rejects.
     */
    stop() {
        return this.schedule({
            cancel: ({ phase }) => phase === 'stopped',
            interval: Poll.NEVER,
            phase: 'stopped'
        });
    }
    /**
     * Whether the poll is hidden.
     *
     * #### Notes
     * This property is only relevant in a browser context.
     */
    get hidden() {
        return Private.hidden;
    }
    /**
     * Execute a new poll factory promise or stand by if necessary.
     */
    _execute() {
        let standby = typeof this.standby === 'function' ? this.standby() : this.standby;
        // Check if execution should proceed, linger, or stand by.
        if (standby === 'never') {
            standby = false;
        }
        else if (standby === 'when-hidden') {
            if (this.hidden) {
                standby = ++this._lingered > this._linger;
            }
            else {
                this._lingered = 0;
                standby = false;
            }
        }
        // If in standby mode schedule next tick without calling the factory.
        if (standby) {
            void this.schedule();
            return;
        }
        const pending = this.tick;
        this._factory(this.state)
            .then((resolved) => {
            if (this.isDisposed || this.tick !== pending) {
                return;
            }
            void this.schedule({
                payload: resolved,
                phase: this.state.phase === 'rejected' ? 'reconnected' : 'resolved'
            });
        })
            .catch((rejected) => {
            if (this.isDisposed || this.tick !== pending) {
                return;
            }
            void this.schedule({
                interval: Private.sleep(this.frequency, this.state),
                payload: rejected,
                phase: 'rejected'
            });
        });
    }
}
/**
 * A namespace for `Poll` types, interfaces, and statics.
 */
(function (Poll) {
    /**
     * An interval value in ms that indicates the poll should tick immediately.
     */
    Poll.IMMEDIATE = 0;
    /**
     * Delays are 32-bit integers in many browsers so intervals need to be capped.
     *
     * #### Notes
     * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value
     */
    Poll.MAX_INTERVAL = 2147483647;
    /**
     * An interval value that indicates the poll should never tick.
     */
    Poll.NEVER = Infinity;
})(Poll || (Poll = {}));
/**
 * A namespace for private module data.
 */
var Private;
(function (Private) {
    /**
     * The default backoff growth rate if `backoff` is `true`.
     */
    Private.DEFAULT_BACKOFF = 3;
    /**
     * The default polling frequency.
     */
    Private.DEFAULT_FREQUENCY = {
        backoff: true,
        interval: 1000,
        max: 30 * 1000
    };
    /**
     * The default number of times to `linger` when a poll is hidden.
     */
    Private.DEFAULT_LINGER = 1;
    /**
     * The default poll name.
     */
    Private.DEFAULT_NAME = 'unknown';
    /**
     * The default poll standby behavior.
     */
    Private.DEFAULT_STANDBY = 'when-hidden';
    /**
     * The first poll tick state's default values superseded in constructor.
     */
    Private.DEFAULT_STATE = {
        interval: Poll.NEVER,
        payload: null,
        phase: 'constructed',
        timestamp: new Date(0).getTime()
    };
    /**
     * The disposed tick state values.
     */
    Private.DISPOSED_STATE = {
        interval: Poll.NEVER,
        payload: null,
        phase: 'disposed',
        timestamp: new Date(0).getTime()
    };
    /**
     * Returns the number of milliseconds to sleep before the next tick.
     *
     * @param frequency - The poll's base frequency.
     * @param last - The poll's last tick.
     */
    function sleep(frequency, last) {
        const { backoff, interval, max } = frequency;
        if (interval === Poll.NEVER) {
            return interval;
        }
        const growth = backoff === true ? Private.DEFAULT_BACKOFF : backoff === false ? 1 : backoff;
        const random = getRandomIntInclusive(interval, last.interval * growth);
        return Math.min(max, random);
    }
    Private.sleep = sleep;
    /**
     * Keep track of whether the document is hidden. This flag is only relevant in
     * a browser context.
     *
     * Listen to `visibilitychange` event to set the `hidden` flag.
     *
     * Listening to `pagehide` is also necessary because Safari support for
     * `visibilitychange` events is partial, cf.
     * https://developer.mozilla.org/docs/Web/API/Document/visibilitychange_event
     */
    Private.hidden = (() => {
        if (typeof document === 'undefined') {
            return false;
        }
        document.addEventListener('visibilitychange', () => {
            Private.hidden = document.visibilityState === 'hidden';
        });
        document.addEventListener('pagehide', () => {
            Private.hidden = document.visibilityState === 'hidden';
        });
        return document.visibilityState === 'hidden';
    })();
    /**
     * Get a random integer between min and max, inclusive of both.
     *
     * #### Notes
     * From
     * https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive
     *
     * From the MDN page: It might be tempting to use Math.round() to accomplish
     * that, but doing so would cause your random numbers to follow a non-uniform
     * distribution, which may not be acceptable for your needs.
     */
    function getRandomIntInclusive(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
})(Private || (Private = {}));

// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/**
 * A base class to implement rate limiters with different invocation strategies.
 *
 * @typeparam T - The resolved type of the underlying function.
 *
 * @typeparam U - The rejected type of the underlying function.
 *
 * @typeparam V - Arguments for the underlying function.
 */
class RateLimiter {
    /**
     * Instantiate a rate limiter.
     *
     * @param fn - The function to rate limit.
     *
     * @param limit - The rate limit; defaults to 500ms.
     */
    constructor(fn, limit = 500) {
        /**
         * Arguments for the underlying function.
         */
        this.args = undefined;
        /**
         * A promise that resolves on each successful invocation.
         */
        this.payload = null;
        this.limit = limit;
        this.poll = new Poll({
            auto: false,
            factory: async () => {
                const { args } = this;
                this.args = undefined;
                return fn(...args);
            },
            frequency: { backoff: false, interval: Poll.NEVER, max: Poll.NEVER },
            standby: 'never'
        });
        this.payload = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.PromiseDelegate();
        this.poll.ticked.connect((_, state) => {
            const { payload } = this;
            if (state.phase === 'resolved') {
                this.payload = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.PromiseDelegate();
                payload.resolve(state.payload);
                return;
            }
            if (state.phase === 'rejected' || state.phase === 'stopped') {
                this.payload = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.PromiseDelegate();
                payload.promise.catch(_ => undefined);
                payload.reject(state.payload);
                return;
            }
        }, this);
    }
    /**
     * Whether the rate limiter is disposed.
     */
    get isDisposed() {
        return this.payload === null;
    }
    /**
     * Disposes the rate limiter.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this.args = undefined;
        this.payload = null;
        this.poll.dispose();
    }
    /**
     * Stop the function if it is mid-flight.
     */
    async stop() {
        return this.poll.stop();
    }
}
/**
 * Wraps and debounces a function that can be called multiple times and only
 * executes the underlying function one `interval` after the last invocation.
 *
 * @typeparam T - The resolved type of the underlying function. Defaults to any.
 *
 * @typeparam U - The rejected type of the underlying function. Defaults to any.
 *
 * @typeparam V - Arguments for the underlying function. Defaults to any[].
 */
class Debouncer extends RateLimiter {
    /**
     * Invokes the function and only executes after rate limit has elapsed.
     * Each invocation resets the timer.
     */
    invoke(...args) {
        this.args = args;
        void this.poll.schedule({ interval: this.limit, phase: 'invoked' });
        return this.payload.promise;
    }
}
/**
 * Wraps and throttles a function that can be called multiple times and only
 * executes the underlying function once per `interval`.
 *
 * @typeparam T - The resolved type of the underlying function. Defaults to any.
 *
 * @typeparam U - The rejected type of the underlying function. Defaults to any.
 *
 * @typeparam V - Arguments for the underlying function. Defaults to any[].
 */
class Throttler extends RateLimiter {
    /**
     * Instantiate a throttler.
     *
     * @param fn - The function being throttled.
     *
     * @param options - Throttling configuration or throttling limit in ms.
     *
     * #### Notes
     * The `edge` defaults to `leading`; the `limit` defaults to `500`.
     */
    constructor(fn, options) {
        super(fn, typeof options === 'number' ? options : options && options.limit);
        this._trailing = false;
        if (typeof options !== 'number' && options && options.edge === 'trailing') {
            this._trailing = true;
        }
        this._interval = this._trailing ? this.limit : Poll.IMMEDIATE;
    }
    /**
     * Throttles function invocations if one is currently in flight.
     */
    invoke(...args) {
        const idle = this.poll.state.phase !== 'invoked';
        if (idle || this._trailing) {
            this.args = args;
        }
        if (idle) {
            void this.poll.schedule({ interval: this._interval, phase: 'invoked' });
        }
        return this.payload.promise;
    }
}


//# sourceMappingURL=index.es6.js.map


/***/ }),

/***/ 6573:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AttachedProperty: () => (/* binding */ AttachedProperty)
/* harmony export */ });
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * @packageDocumentation
 * @module properties
 */
/**
 * A class which attaches a value to an external object.
 *
 * #### Notes
 * Attached properties are used to extend the state of an object with
 * semantic data from an unrelated class. They also encapsulate value
 * creation, coercion, and notification.
 *
 * Because attached property values are stored in a hash table, which
 * in turn is stored in a WeakMap keyed on the owner object, there is
 * non-trivial storage overhead involved in their use. The pattern is
 * therefore best used for the storage of rare data.
 */
class AttachedProperty {
    /**
     * Construct a new attached property.
     *
     * @param options - The options for initializing the property.
     */
    constructor(options) {
        this._pid = Private.nextPID();
        this.name = options.name;
        this._create = options.create;
        this._coerce = options.coerce || null;
        this._compare = options.compare || null;
        this._changed = options.changed || null;
    }
    /**
     * Get the current value of the property for a given owner.
     *
     * @param owner - The property owner of interest.
     *
     * @returns The current value of the property.
     *
     * #### Notes
     * If the value has not yet been set, the default value will be
     * computed and assigned as the current value of the property.
     */
    get(owner) {
        let value;
        let map = Private.ensureMap(owner);
        if (this._pid in map) {
            value = map[this._pid];
        }
        else {
            value = map[this._pid] = this._createValue(owner);
        }
        return value;
    }
    /**
     * Set the current value of the property for a given owner.
     *
     * @param owner - The property owner of interest.
     *
     * @param value - The value for the property.
     *
     * #### Notes
     * If the value has not yet been set, the default value will be
     * computed and used as the previous value for the comparison.
     */
    set(owner, value) {
        let oldValue;
        let map = Private.ensureMap(owner);
        if (this._pid in map) {
            oldValue = map[this._pid];
        }
        else {
            oldValue = map[this._pid] = this._createValue(owner);
        }
        let newValue = this._coerceValue(owner, value);
        this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));
    }
    /**
     * Explicitly coerce the current property value for a given owner.
     *
     * @param owner - The property owner of interest.
     *
     * #### Notes
     * If the value has not yet been set, the default value will be
     * computed and used as the previous value for the comparison.
     */
    coerce(owner) {
        let oldValue;
        let map = Private.ensureMap(owner);
        if (this._pid in map) {
            oldValue = map[this._pid];
        }
        else {
            oldValue = map[this._pid] = this._createValue(owner);
        }
        let newValue = this._coerceValue(owner, oldValue);
        this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));
    }
    /**
     * Get or create the default value for the given owner.
     */
    _createValue(owner) {
        let create = this._create;
        return create(owner);
    }
    /**
     * Coerce the value for the given owner.
     */
    _coerceValue(owner, value) {
        let coerce = this._coerce;
        return coerce ? coerce(owner, value) : value;
    }
    /**
     * Compare the old value and new value for equality.
     */
    _compareValue(oldValue, newValue) {
        let compare = this._compare;
        return compare ? compare(oldValue, newValue) : oldValue === newValue;
    }
    /**
     * Run the change notification if the given values are different.
     */
    _maybeNotify(owner, oldValue, newValue) {
        let changed = this._changed;
        if (changed && !this._compareValue(oldValue, newValue)) {
            changed(owner, oldValue, newValue);
        }
    }
}
/**
 * The namespace for the `AttachedProperty` class statics.
 */
(function (AttachedProperty) {
    /**
     * Clear the stored property data for the given owner.
     *
     * @param owner - The property owner of interest.
     *
     * #### Notes
     * This will clear all property values for the owner, but it will
     * **not** run the change notification for any of the properties.
     */
    function clearData(owner) {
        Private.ownerData.delete(owner);
    }
    AttachedProperty.clearData = clearData;
})(AttachedProperty || (AttachedProperty = {}));
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * A weak mapping of property owner to property map.
     */
    Private.ownerData = new WeakMap();
    /**
     * A function which computes successive unique property ids.
     */
    Private.nextPID = (() => {
        let id = 0;
        return () => {
            let rand = Math.random();
            let stem = `${rand}`.slice(2);
            return `pid-${stem}-${id++}`;
        };
    })();
    /**
     * Lookup the data map for the property owner.
     *
     * This will create the map if one does not already exist.
     */
    function ensureMap(owner) {
        let map = Private.ownerData.get(owner);
        if (map) {
            return map;
        }
        map = Object.create(null);
        Private.ownerData.set(owner, map);
        return map;
    }
    Private.ensureMap = ensureMap;
})(Private || (Private = {}));


//# sourceMappingURL=index.es6.js.map


/***/ }),

/***/ 3992:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Signal: () => (/* binding */ Signal),
/* harmony export */   Stream: () => (/* binding */ Stream)
/* harmony export */ });
/* harmony import */ var _lumino_algorithm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8135);
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5764);
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__);



// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2017, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
/**
 * @packageDocumentation
 * @module signaling
 */
/**
 * A concrete implementation of `ISignal`.
 *
 * #### Example
 * ```typescript
 * import { ISignal, Signal } from '@lumino/signaling';
 *
 * class SomeClass {
 *
 *   constructor(name: string) {
 *     this.name = name;
 *   }
 *
 *   readonly name: string;
 *
 *   get valueChanged: ISignal<this, number> {
 *     return this._valueChanged;
 *   }
 *
 *   get value(): number {
 *     return this._value;
 *   }
 *
 *   set value(value: number) {
 *     if (value === this._value) {
 *       return;
 *     }
 *     this._value = value;
 *     this._valueChanged.emit(value);
 *   }
 *
 *   private _value = 0;
 *   private _valueChanged = new Signal<this, number>(this);
 * }
 *
 * function logger(sender: SomeClass, value: number): void {
 *   console.log(sender.name, value);
 * }
 *
 * let m1 = new SomeClass('foo');
 * let m2 = new SomeClass('bar');
 *
 * m1.valueChanged.connect(logger);
 * m2.valueChanged.connect(logger);
 *
 * m1.value = 42;  // logs: foo 42
 * m2.value = 17;  // logs: bar 17
 * ```
 */
class Signal {
    /**
     * Construct a new signal.
     *
     * @param sender - The sender which owns the signal.
     */
    constructor(sender) {
        this.sender = sender;
    }
    /**
     * Connect a slot to the signal.
     *
     * @param slot - The slot to invoke when the signal is emitted.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection succeeds, `false` otherwise.
     */
    connect(slot, thisArg) {
        return Private.connect(this, slot, thisArg);
    }
    /**
     * Disconnect a slot from the signal.
     *
     * @param slot - The slot to disconnect from the signal.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection is removed, `false` otherwise.
     */
    disconnect(slot, thisArg) {
        return Private.disconnect(this, slot, thisArg);
    }
    /**
     * Emit the signal and invoke the connected slots.
     *
     * @param args - The args to pass to the connected slots.
     *
     * #### Notes
     * Slots are invoked synchronously in connection order.
     *
     * Exceptions thrown by connected slots will be caught and logged.
     */
    emit(args) {
        Private.emit(this, args);
    }
}
/**
 * The namespace for the `Signal` class statics.
 */
(function (Signal) {
    /**
     * Remove all connections between a sender and receiver.
     *
     * @param sender - The sender object of interest.
     *
     * @param receiver - The receiver object of interest.
     *
     * #### Notes
     * If a `thisArg` is provided when connecting a signal, that object
     * is considered the receiver. Otherwise, the `slot` is considered
     * the receiver.
     */
    function disconnectBetween(sender, receiver) {
        Private.disconnectBetween(sender, receiver);
    }
    Signal.disconnectBetween = disconnectBetween;
    /**
     * Remove all connections where the given object is the sender.
     *
     * @param sender - The sender object of interest.
     */
    function disconnectSender(sender) {
        Private.disconnectSender(sender);
    }
    Signal.disconnectSender = disconnectSender;
    /**
     * Remove all connections where the given object is the receiver.
     *
     * @param receiver - The receiver object of interest.
     *
     * #### Notes
     * If a `thisArg` is provided when connecting a signal, that object
     * is considered the receiver. Otherwise, the `slot` is considered
     * the receiver.
     */
    function disconnectReceiver(receiver) {
        Private.disconnectReceiver(receiver);
    }
    Signal.disconnectReceiver = disconnectReceiver;
    /**
     * Remove all connections where an object is the sender or receiver.
     *
     * @param object - The object of interest.
     *
     * #### Notes
     * If a `thisArg` is provided when connecting a signal, that object
     * is considered the receiver. Otherwise, the `slot` is considered
     * the receiver.
     */
    function disconnectAll(object) {
        Private.disconnectAll(object);
    }
    Signal.disconnectAll = disconnectAll;
    /**
     * Clear all signal data associated with the given object.
     *
     * @param object - The object for which the data should be cleared.
     *
     * #### Notes
     * This removes all signal connections and any other signal data
     * associated with the object.
     */
    function clearData(object) {
        Private.disconnectAll(object);
    }
    Signal.clearData = clearData;
    /**
     * Get the signal exception handler.
     *
     * @returns The current exception handler.
     *
     * #### Notes
     * The default exception handler is `console.error`.
     */
    function getExceptionHandler() {
        return Private.exceptionHandler;
    }
    Signal.getExceptionHandler = getExceptionHandler;
    /**
     * Set the signal exception handler.
     *
     * @param handler - The function to use as the exception handler.
     *
     * @returns The old exception handler.
     *
     * #### Notes
     * The exception handler is invoked when a slot throws an exception.
     */
    function setExceptionHandler(handler) {
        let old = Private.exceptionHandler;
        Private.exceptionHandler = handler;
        return old;
    }
    Signal.setExceptionHandler = setExceptionHandler;
})(Signal || (Signal = {}));
/**
 * A concrete implementation of `IStream`.
 *
 * #### Example
 * ```typescript
 * import { IStream, Stream } from '@lumino/signaling';
 *
 * class SomeClass {
 *
 *   constructor(name: string) {
 *     this.name = name;
 *   }
 *
 *   readonly name: string;
 *
 *   get pings(): IStream<this, string> {
 *     return this._pings;
 *   }
 *
 *   ping(value: string) {
 *     this._pings.emit(value);
 *   }
 *
 *   private _pings = new Stream<this, string>(this);
 * }
 *
 * let m1 = new SomeClass('foo');
 *
 * m1.pings.connect((_, value: string) => {
 *   console.log('connect', value);
 * });
 *
 * void (async () => {
 *   for await (const ping of m1.pings) {
 *     console.log('iterator', ping);
 *   }
 * })();
 *
 * m1.ping('alpha');  // logs: connect alpha
 *                    // logs: iterator alpha
 * m1.ping('beta');   // logs: connect beta
 *                    // logs: iterator beta
 * ```
 */
class Stream extends Signal {
    constructor() {
        super(...arguments);
        this._pending = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__.PromiseDelegate();
    }
    /**
     * Return an async iterator that yields every emission.
     */
    async *[Symbol.asyncIterator]() {
        let pending = this._pending;
        while (true) {
            try {
                const { args, next } = await pending.promise;
                pending = next;
                yield args;
            }
            catch (_) {
                return; // Any promise rejection stops the iterator.
            }
        }
    }
    /**
     * Emit the signal, invoke the connected slots, and yield the emission.
     *
     * @param args - The args to pass to the connected slots.
     */
    emit(args) {
        const pending = this._pending;
        const next = (this._pending = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__.PromiseDelegate());
        pending.resolve({ args, next });
        super.emit(args);
    }
    /**
     * Stop the stream's async iteration.
     */
    stop() {
        this._pending.promise.catch(() => undefined);
        this._pending.reject('stop');
        this._pending = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__.PromiseDelegate();
    }
}
/**
 * The namespace for the module implementation details.
 */
var Private;
(function (Private) {
    /**
     * The signal exception handler function.
     */
    Private.exceptionHandler = (err) => {
        console.error(err);
    };
    /**
     * Connect a slot to a signal.
     *
     * @param signal - The signal of interest.
     *
     * @param slot - The slot to invoke when the signal is emitted.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection succeeds, `false` otherwise.
     */
    function connect(signal, slot, thisArg) {
        // Coerce a `null` `thisArg` to `undefined`.
        thisArg = thisArg || undefined;
        // Ensure the sender's array of receivers is created.
        let receivers = receiversForSender.get(signal.sender);
        if (!receivers) {
            receivers = [];
            receiversForSender.set(signal.sender, receivers);
        }
        // Bail if a matching connection already exists.
        if (findConnection(receivers, signal, slot, thisArg)) {
            return false;
        }
        // Choose the best object for the receiver.
        let receiver = thisArg || slot;
        // Ensure the receiver's array of senders is created.
        let senders = sendersForReceiver.get(receiver);
        if (!senders) {
            senders = [];
            sendersForReceiver.set(receiver, senders);
        }
        // Create a new connection and add it to the end of each array.
        let connection = { signal, slot, thisArg };
        receivers.push(connection);
        senders.push(connection);
        // Indicate a successful connection.
        return true;
    }
    Private.connect = connect;
    /**
     * Disconnect a slot from a signal.
     *
     * @param signal - The signal of interest.
     *
     * @param slot - The slot to disconnect from the signal.
     *
     * @param thisArg - The `this` context for the slot. If provided,
     *   this must be a non-primitive object.
     *
     * @returns `true` if the connection is removed, `false` otherwise.
     */
    function disconnect(signal, slot, thisArg) {
        // Coerce a `null` `thisArg` to `undefined`.
        thisArg = thisArg || undefined;
        // Lookup the list of receivers, and bail if none exist.
        let receivers = receiversForSender.get(signal.sender);
        if (!receivers || receivers.length === 0) {
            return false;
        }
        // Bail if no matching connection exits.
        let connection = findConnection(receivers, signal, slot, thisArg);
        if (!connection) {
            return false;
        }
        // Choose the best object for the receiver.
        let receiver = thisArg || slot;
        // Lookup the array of senders, which is now known to exist.
        let senders = sendersForReceiver.get(receiver);
        // Clear the connection and schedule cleanup of the arrays.
        connection.signal = null;
        scheduleCleanup(receivers);
        scheduleCleanup(senders);
        // Indicate a successful disconnection.
        return true;
    }
    Private.disconnect = disconnect;
    /**
     * Remove all connections between a sender and receiver.
     *
     * @param sender - The sender object of interest.
     *
     * @param receiver - The receiver object of interest.
     */
    function disconnectBetween(sender, receiver) {
        // If there are no receivers, there is nothing to do.
        let receivers = receiversForSender.get(sender);
        if (!receivers || receivers.length === 0) {
            return;
        }
        // If there are no senders, there is nothing to do.
        let senders = sendersForReceiver.get(receiver);
        if (!senders || senders.length === 0) {
            return;
        }
        // Clear each connection between the sender and receiver.
        for (const connection of senders) {
            // Skip connections which have already been cleared.
            if (!connection.signal) {
                continue;
            }
            // Clear the connection if it matches the sender.
            if (connection.signal.sender === sender) {
                connection.signal = null;
            }
        }
        // Schedule a cleanup of the senders and receivers.
        scheduleCleanup(receivers);
        scheduleCleanup(senders);
    }
    Private.disconnectBetween = disconnectBetween;
    /**
     * Remove all connections where the given object is the sender.
     *
     * @param sender - The sender object of interest.
     */
    function disconnectSender(sender) {
        // If there are no receivers, there is nothing to do.
        let receivers = receiversForSender.get(sender);
        if (!receivers || receivers.length === 0) {
            return;
        }
        // Clear each receiver connection.
        for (const connection of receivers) {
            // Skip connections which have already been cleared.
            if (!connection.signal) {
                continue;
            }
            // Choose the best object for the receiver.
            let receiver = connection.thisArg || connection.slot;
            // Clear the connection.
            connection.signal = null;
            // Cleanup the array of senders, which is now known to exist.
            scheduleCleanup(sendersForReceiver.get(receiver));
        }
        // Schedule a cleanup of the receivers.
        scheduleCleanup(receivers);
    }
    Private.disconnectSender = disconnectSender;
    /**
     * Remove all connections where the given object is the receiver.
     *
     * @param receiver - The receiver object of interest.
     */
    function disconnectReceiver(receiver) {
        // If there are no senders, there is nothing to do.
        let senders = sendersForReceiver.get(receiver);
        if (!senders || senders.length === 0) {
            return;
        }
        // Clear each sender connection.
        for (const connection of senders) {
            // Skip connections which have already been cleared.
            if (!connection.signal) {
                continue;
            }
            // Lookup the sender for the connection.
            let sender = connection.signal.sender;
            // Clear the connection.
            connection.signal = null;
            // Cleanup the array of receivers, which is now known to exist.
            scheduleCleanup(receiversForSender.get(sender));
        }
        // Schedule a cleanup of the list of senders.
        scheduleCleanup(senders);
    }
    Private.disconnectReceiver = disconnectReceiver;
    /**
     * Remove all connections where an object is the sender or receiver.
     *
     * @param object - The object of interest.
     */
    function disconnectAll(object) {
        // Remove all connections where the given object is the sender.
        disconnectSender(object);
        // Remove all connections where the given object is the receiver.
        disconnectReceiver(object);
    }
    Private.disconnectAll = disconnectAll;
    /**
     * Emit a signal and invoke its connected slots.
     *
     * @param signal - The signal of interest.
     *
     * @param args - The args to pass to the connected slots.
     *
     * #### Notes
     * Slots are invoked synchronously in connection order.
     *
     * Exceptions thrown by connected slots will be caught and logged.
     */
    function emit(signal, args) {
        // If there are no receivers, there is nothing to do.
        let receivers = receiversForSender.get(signal.sender);
        if (!receivers || receivers.length === 0) {
            return;
        }
        // Invoke the slots for connections with a matching signal.
        // Any connections added during emission are not invoked.
        for (let i = 0, n = receivers.length; i < n; ++i) {
            let connection = receivers[i];
            if (connection.signal === signal) {
                invokeSlot(connection, args);
            }
        }
    }
    Private.emit = emit;
    /**
     * A weak mapping of sender to array of receiver connections.
     */
    const receiversForSender = new WeakMap();
    /**
     * A weak mapping of receiver to array of sender connections.
     */
    const sendersForReceiver = new WeakMap();
    /**
     * A set of connection arrays which are pending cleanup.
     */
    const dirtySet = new Set();
    /**
     * A function to schedule an event loop callback.
     */
    const schedule = (() => {
        let ok = typeof requestAnimationFrame === 'function';
        return ok ? requestAnimationFrame : setImmediate;
    })();
    /**
     * Find a connection which matches the given parameters.
     */
    function findConnection(connections, signal, slot, thisArg) {
        return (0,_lumino_algorithm__WEBPACK_IMPORTED_MODULE_0__.find)(connections, connection => connection.signal === signal &&
            connection.slot === slot &&
            connection.thisArg === thisArg);
    }
    /**
     * Invoke a slot with the given parameters.
     *
     * The connection is assumed to be valid.
     *
     * Exceptions in the slot will be caught and logged.
     */
    function invokeSlot(connection, args) {
        let { signal, slot, thisArg } = connection;
        try {
            slot.call(thisArg, signal.sender, args);
        }
        catch (err) {
            Private.exceptionHandler(err);
        }
    }
    /**
     * Schedule a cleanup of a connection array.
     *
     * This will add the array to the dirty set and schedule a deferred
     * cleanup of the array contents. On cleanup, any connection with a
     * `null` signal will be removed from the array.
     */
    function scheduleCleanup(array) {
        if (dirtySet.size === 0) {
            schedule(cleanupDirtySet);
        }
        dirtySet.add(array);
    }
    /**
     * Cleanup the connection lists in the dirty set.
     *
     * This function should only be invoked asynchronously, when the
     * stack frame is guaranteed to not be on the path of user code.
     */
    function cleanupDirtySet() {
        dirtySet.forEach(cleanupConnections);
        dirtySet.clear();
    }
    /**
     * Cleanup the dirty connections in a connections array.
     *
     * This will remove any connection with a `null` signal.
     *
     * This function should only be invoked asynchronously, when the
     * stack frame is guaranteed to not be on the path of user code.
     */
    function cleanupConnections(connections) {
        _lumino_algorithm__WEBPACK_IMPORTED_MODULE_0__.ArrayExt.removeAllWhere(connections, isDeadConnection);
    }
    /**
     * Test whether a connection is dead.
     *
     * A dead connection has a `null` signal.
     */
    function isDeadConnection(connection) {
        return connection.signal === null;
    }
})(Private || (Private = {}));


//# sourceMappingURL=index.es6.js.map


/***/ }),

/***/ 8317:
/***/ (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


/***/ }),

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

"use strict";


function hasKey(obj, keys) {
	var o = obj;
	keys.slice(0, -1).forEach(function (key) {
		o = o[key] || {};
	});

	var key = keys[keys.length - 1];
	return key in o;
}

function isNumber(x) {
	if (typeof x === 'number') { return true; }
	if ((/^0x[0-9a-f]+$/i).test(x)) { return true; }
	return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x);
}

function isConstructorOrProto(obj, key) {
	return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__';
}

module.exports = function (args, opts) {
	if (!opts) { opts = {}; }

	var flags = {
		bools: {},
		strings: {},
		unknownFn: null,
	};

	if (typeof opts.unknown === 'function') {
		flags.unknownFn = opts.unknown;
	}

	if (typeof opts.boolean === 'boolean' && opts.boolean) {
		flags.allBools = true;
	} else {
		[].concat(opts.boolean).filter(Boolean).forEach(function (key) {
			flags.bools[key] = true;
		});
	}

	var aliases = {};

	function aliasIsBoolean(key) {
		return aliases[key].some(function (x) {
			return flags.bools[x];
		});
	}

	Object.keys(opts.alias || {}).forEach(function (key) {
		aliases[key] = [].concat(opts.alias[key]);
		aliases[key].forEach(function (x) {
			aliases[x] = [key].concat(aliases[key].filter(function (y) {
				return x !== y;
			}));
		});
	});

	[].concat(opts.string).filter(Boolean).forEach(function (key) {
		flags.strings[key] = true;
		if (aliases[key]) {
			[].concat(aliases[key]).forEach(function (k) {
				flags.strings[k] = true;
			});
		}
	});

	var defaults = opts.default || {};

	var argv = { _: [] };

	function argDefined(key, arg) {
		return (flags.allBools && (/^--[^=]+$/).test(arg))
			|| flags.strings[key]
			|| flags.bools[key]
			|| aliases[key];
	}

	function setKey(obj, keys, value) {
		var o = obj;
		for (var i = 0; i < keys.length - 1; i++) {
			var key = keys[i];
			if (isConstructorOrProto(o, key)) { return; }
			if (o[key] === undefined) { o[key] = {}; }
			if (
				o[key] === Object.prototype
				|| o[key] === Number.prototype
				|| o[key] === String.prototype
			) {
				o[key] = {};
			}
			if (o[key] === Array.prototype) { o[key] = []; }
			o = o[key];
		}

		var lastKey = keys[keys.length - 1];
		if (isConstructorOrProto(o, lastKey)) { return; }
		if (
			o === Object.prototype
			|| o === Number.prototype
			|| o === String.prototype
		) {
			o = {};
		}
		if (o === Array.prototype) { o = []; }
		if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') {
			o[lastKey] = value;
		} else if (Array.isArray(o[lastKey])) {
			o[lastKey].push(value);
		} else {
			o[lastKey] = [o[lastKey], value];
		}
	}

	function setArg(key, val, arg) {
		if (arg && flags.unknownFn && !argDefined(key, arg)) {
			if (flags.unknownFn(arg) === false) { return; }
		}

		var value = !flags.strings[key] && isNumber(val)
			? Number(val)
			: val;
		setKey(argv, key.split('.'), value);

		(aliases[key] || []).forEach(function (x) {
			setKey(argv, x.split('.'), value);
		});
	}

	Object.keys(flags.bools).forEach(function (key) {
		setArg(key, defaults[key] === undefined ? false : defaults[key]);
	});

	var notFlags = [];

	if (args.indexOf('--') !== -1) {
		notFlags = args.slice(args.indexOf('--') + 1);
		args = args.slice(0, args.indexOf('--'));
	}

	for (var i = 0; i < args.length; i++) {
		var arg = args[i];
		var key;
		var next;

		if ((/^--.+=/).test(arg)) {
			// Using [\s\S] instead of . because js doesn't support the
			// 'dotall' regex modifier. See:
			// http://stackoverflow.com/a/1068308/13216
			var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
			key = m[1];
			var value = m[2];
			if (flags.bools[key]) {
				value = value !== 'false';
			}
			setArg(key, value, arg);
		} else if ((/^--no-.+/).test(arg)) {
			key = arg.match(/^--no-(.+)/)[1];
			setArg(key, false, arg);
		} else if ((/^--.+/).test(arg)) {
			key = arg.match(/^--(.+)/)[1];
			next = args[i + 1];
			if (
				next !== undefined
				&& !(/^(-|--)[^-]/).test(next)
				&& !flags.bools[key]
				&& !flags.allBools
				&& (aliases[key] ? !aliasIsBoolean(key) : true)
			) {
				setArg(key, next, arg);
				i += 1;
			} else if ((/^(true|false)$/).test(next)) {
				setArg(key, next === 'true', arg);
				i += 1;
			} else {
				setArg(key, flags.strings[key] ? '' : true, arg);
			}
		} else if ((/^-[^-]+/).test(arg)) {
			var letters = arg.slice(1, -1).split('');

			var broken = false;
			for (var j = 0; j < letters.length; j++) {
				next = arg.slice(j + 2);

				if (next === '-') {
					setArg(letters[j], next, arg);
					continue;
				}

				if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') {
					setArg(letters[j], next.slice(1), arg);
					broken = true;
					break;
				}

				if (
					(/[A-Za-z]/).test(letters[j])
					&& (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next)
				) {
					setArg(letters[j], next, arg);
					broken = true;
					break;
				}

				if (letters[j + 1] && letters[j + 1].match(/\W/)) {
					setArg(letters[j], arg.slice(j + 2), arg);
					broken = true;
					break;
				} else {
					setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
				}
			}

			key = arg.slice(-1)[0];
			if (!broken && key !== '-') {
				if (
					args[i + 1]
					&& !(/^(-|--)[^-]/).test(args[i + 1])
					&& !flags.bools[key]
					&& (aliases[key] ? !aliasIsBoolean(key) : true)
				) {
					setArg(key, args[i + 1], arg);
					i += 1;
				} else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) {
					setArg(key, args[i + 1] === 'true', arg);
					i += 1;
				} else {
					setArg(key, flags.strings[key] ? '' : true, arg);
				}
			}
		} else {
			if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
				argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));
			}
			if (opts.stopEarly) {
				argv._.push.apply(argv._, args.slice(i + 1));
				break;
			}
		}
	}

	Object.keys(defaults).forEach(function (k) {
		if (!hasKey(argv, k.split('.'))) {
			setKey(argv, k.split('.'), defaults[k]);

			(aliases[k] || []).forEach(function (x) {
				setKey(argv, x.split('.'), defaults[k]);
			});
		}
	});

	if (opts['--']) {
		argv['--'] = notFlags.slice();
	} else {
		notFlags.forEach(function (k) {
			argv._.push(k);
		});
	}

	return argv;
};


/***/ }),

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

"use strict";
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
// transplited with Babel

// Copyright Joyent, Inc. and other Node contributors.
//
// 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 assertPath(path) {
  if (typeof path !== 'string') {
    throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
  }
}

// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path, allowAboveRoot) {
  var res = '';
  var lastSegmentLength = 0;
  var lastSlash = -1;
  var dots = 0;
  var code;
  for (var i = 0; i <= path.length; ++i) {
    if (i < path.length)
      code = path.charCodeAt(i);
    else if (code === 47 /*/*/)
      break;
    else
      code = 47 /*/*/;
    if (code === 47 /*/*/) {
      if (lastSlash === i - 1 || dots === 1) {
        // NOOP
      } else if (lastSlash !== i - 1 && dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
          if (res.length > 2) {
            var lastSlashIndex = res.lastIndexOf('/');
            if (lastSlashIndex !== res.length - 1) {
              if (lastSlashIndex === -1) {
                res = '';
                lastSegmentLength = 0;
              } else {
                res = res.slice(0, lastSlashIndex);
                lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
              }
              lastSlash = i;
              dots = 0;
              continue;
            }
          } else if (res.length === 2 || res.length === 1) {
            res = '';
            lastSegmentLength = 0;
            lastSlash = i;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          if (res.length > 0)
            res += '/..';
          else
            res = '..';
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0)
          res += '/' + path.slice(lastSlash + 1, i);
        else
          res = path.slice(lastSlash + 1, i);
        lastSegmentLength = i - lastSlash - 1;
      }
      lastSlash = i;
      dots = 0;
    } else if (code === 46 /*.*/ && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}

function _format(sep, pathObject) {
  var dir = pathObject.dir || pathObject.root;
  var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
  if (!dir) {
    return base;
  }
  if (dir === pathObject.root) {
    return dir + base;
  }
  return dir + sep + base;
}

var posix = {
  // path.resolve([from ...], to)
  resolve: function resolve() {
    var resolvedPath = '';
    var resolvedAbsolute = false;
    var cwd;

    for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
      var path;
      if (i >= 0)
        path = arguments[i];
      else {
        if (cwd === undefined)
          cwd = process.cwd();
        path = cwd;
      }

      assertPath(path);

      // Skip empty entries
      if (path.length === 0) {
        continue;
      }

      resolvedPath = path + '/' + resolvedPath;
      resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
    }

    // At this point the path should be resolved to a full absolute path, but
    // handle relative paths to be safe (might happen when process.cwd() fails)

    // Normalize the path
    resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);

    if (resolvedAbsolute) {
      if (resolvedPath.length > 0)
        return '/' + resolvedPath;
      else
        return '/';
    } else if (resolvedPath.length > 0) {
      return resolvedPath;
    } else {
      return '.';
    }
  },

  normalize: function normalize(path) {
    assertPath(path);

    if (path.length === 0) return '.';

    var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
    var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;

    // Normalize the path
    path = normalizeStringPosix(path, !isAbsolute);

    if (path.length === 0 && !isAbsolute) path = '.';
    if (path.length > 0 && trailingSeparator) path += '/';

    if (isAbsolute) return '/' + path;
    return path;
  },

  isAbsolute: function isAbsolute(path) {
    assertPath(path);
    return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
  },

  join: function join() {
    if (arguments.length === 0)
      return '.';
    var joined;
    for (var i = 0; i < arguments.length; ++i) {
      var arg = arguments[i];
      assertPath(arg);
      if (arg.length > 0) {
        if (joined === undefined)
          joined = arg;
        else
          joined += '/' + arg;
      }
    }
    if (joined === undefined)
      return '.';
    return posix.normalize(joined);
  },

  relative: function relative(from, to) {
    assertPath(from);
    assertPath(to);

    if (from === to) return '';

    from = posix.resolve(from);
    to = posix.resolve(to);

    if (from === to) return '';

    // Trim any leading backslashes
    var fromStart = 1;
    for (; fromStart < from.length; ++fromStart) {
      if (from.charCodeAt(fromStart) !== 47 /*/*/)
        break;
    }
    var fromEnd = from.length;
    var fromLen = fromEnd - fromStart;

    // Trim any leading backslashes
    var toStart = 1;
    for (; toStart < to.length; ++toStart) {
      if (to.charCodeAt(toStart) !== 47 /*/*/)
        break;
    }
    var toEnd = to.length;
    var toLen = toEnd - toStart;

    // Compare paths to find the longest common path from root
    var length = fromLen < toLen ? fromLen : toLen;
    var lastCommonSep = -1;
    var i = 0;
    for (; i <= length; ++i) {
      if (i === length) {
        if (toLen > length) {
          if (to.charCodeAt(toStart + i) === 47 /*/*/) {
            // We get here if `from` is the exact base path for `to`.
            // For example: from='/foo/bar'; to='/foo/bar/baz'
            return to.slice(toStart + i + 1);
          } else if (i === 0) {
            // We get here if `from` is the root
            // For example: from='/'; to='/foo'
            return to.slice(toStart + i);
          }
        } else if (fromLen > length) {
          if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
            // We get here if `to` is the exact base path for `from`.
            // For example: from='/foo/bar/baz'; to='/foo/bar'
            lastCommonSep = i;
          } else if (i === 0) {
            // We get here if `to` is the root.
            // For example: from='/foo'; to='/'
            lastCommonSep = 0;
          }
        }
        break;
      }
      var fromCode = from.charCodeAt(fromStart + i);
      var toCode = to.charCodeAt(toStart + i);
      if (fromCode !== toCode)
        break;
      else if (fromCode === 47 /*/*/)
        lastCommonSep = i;
    }

    var out = '';
    // Generate the relative path based on the path difference between `to`
    // and `from`
    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
      if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
        if (out.length === 0)
          out += '..';
        else
          out += '/..';
      }
    }

    // Lastly, append the rest of the destination (`to`) path that comes after
    // the common path parts
    if (out.length > 0)
      return out + to.slice(toStart + lastCommonSep);
    else {
      toStart += lastCommonSep;
      if (to.charCodeAt(toStart) === 47 /*/*/)
        ++toStart;
      return to.slice(toStart);
    }
  },

  _makeLong: function _makeLong(path) {
    return path;
  },

  dirname: function dirname(path) {
    assertPath(path);
    if (path.length === 0) return '.';
    var code = path.charCodeAt(0);
    var hasRoot = code === 47 /*/*/;
    var end = -1;
    var matchedSlash = true;
    for (var i = path.length - 1; i >= 1; --i) {
      code = path.charCodeAt(i);
      if (code === 47 /*/*/) {
          if (!matchedSlash) {
            end = i;
            break;
          }
        } else {
        // We saw the first non-path separator
        matchedSlash = false;
      }
    }

    if (end === -1) return hasRoot ? '/' : '.';
    if (hasRoot && end === 1) return '//';
    return path.slice(0, end);
  },

  basename: function basename(path, ext) {
    if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
    assertPath(path);

    var start = 0;
    var end = -1;
    var matchedSlash = true;
    var i;

    if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
      if (ext.length === path.length && ext === path) return '';
      var extIdx = ext.length - 1;
      var firstNonSlashEnd = -1;
      for (i = path.length - 1; i >= 0; --i) {
        var code = path.charCodeAt(i);
        if (code === 47 /*/*/) {
            // If we reached a path separator that was not part of a set of path
            // separators at the end of the string, stop now
            if (!matchedSlash) {
              start = i + 1;
              break;
            }
          } else {
          if (firstNonSlashEnd === -1) {
            // We saw the first non-path separator, remember this index in case
            // we need it if the extension ends up not matching
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            // Try to match the explicit extension
            if (code === ext.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                // We matched the extension, so mark this as the end of our path
                // component
                end = i;
              }
            } else {
              // Extension does not match, so our result is the entire path
              // component
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }

      if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;
      return path.slice(start, end);
    } else {
      for (i = path.length - 1; i >= 0; --i) {
        if (path.charCodeAt(i) === 47 /*/*/) {
            // If we reached a path separator that was not part of a set of path
            // separators at the end of the string, stop now
            if (!matchedSlash) {
              start = i + 1;
              break;
            }
          } else if (end === -1) {
          // We saw the first non-path separator, mark this as the end of our
          // path component
          matchedSlash = false;
          end = i + 1;
        }
      }

      if (end === -1) return '';
      return path.slice(start, end);
    }
  },

  extname: function extname(path) {
    assertPath(path);
    var startDot = -1;
    var startPart = 0;
    var end = -1;
    var matchedSlash = true;
    // Track the state of characters (if any) we see before our first dot and
    // after any path separator we find
    var preDotState = 0;
    for (var i = path.length - 1; i >= 0; --i) {
      var code = path.charCodeAt(i);
      if (code === 47 /*/*/) {
          // If we reached a path separator that was not part of a set of path
          // separators at the end of the string, stop now
          if (!matchedSlash) {
            startPart = i + 1;
            break;
          }
          continue;
        }
      if (end === -1) {
        // We saw the first non-path separator, mark this as the end of our
        // extension
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 46 /*.*/) {
          // If this is our first dot, mark it as the start of our extension
          if (startDot === -1)
            startDot = i;
          else if (preDotState !== 1)
            preDotState = 1;
      } else if (startDot !== -1) {
        // We saw a non-dot and non-path separator before our dot, so we should
        // have a good chance at having a non-empty extension
        preDotState = -1;
      }
    }

    if (startDot === -1 || end === -1 ||
        // We saw a non-dot character immediately before the dot
        preDotState === 0 ||
        // The (right-most) trimmed path component is exactly '..'
        preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      return '';
    }
    return path.slice(startDot, end);
  },

  format: function format(pathObject) {
    if (pathObject === null || typeof pathObject !== 'object') {
      throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
    }
    return _format('/', pathObject);
  },

  parse: function parse(path) {
    assertPath(path);

    var ret = { root: '', dir: '', base: '', ext: '', name: '' };
    if (path.length === 0) return ret;
    var code = path.charCodeAt(0);
    var isAbsolute = code === 47 /*/*/;
    var start;
    if (isAbsolute) {
      ret.root = '/';
      start = 1;
    } else {
      start = 0;
    }
    var startDot = -1;
    var startPart = 0;
    var end = -1;
    var matchedSlash = true;
    var i = path.length - 1;

    // Track the state of characters (if any) we see before our first dot and
    // after any path separator we find
    var preDotState = 0;

    // Get non-dir info
    for (; i >= start; --i) {
      code = path.charCodeAt(i);
      if (code === 47 /*/*/) {
          // If we reached a path separator that was not part of a set of path
          // separators at the end of the string, stop now
          if (!matchedSlash) {
            startPart = i + 1;
            break;
          }
          continue;
        }
      if (end === -1) {
        // We saw the first non-path separator, mark this as the end of our
        // extension
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 46 /*.*/) {
          // If this is our first dot, mark it as the start of our extension
          if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;
        } else if (startDot !== -1) {
        // We saw a non-dot and non-path separator before our dot, so we should
        // have a good chance at having a non-empty extension
        preDotState = -1;
      }
    }

    if (startDot === -1 || end === -1 ||
    // We saw a non-dot character immediately before the dot
    preDotState === 0 ||
    // The (right-most) trimmed path component is exactly '..'
    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      if (end !== -1) {
        if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);
      }
    } else {
      if (startPart === 0 && isAbsolute) {
        ret.name = path.slice(1, startDot);
        ret.base = path.slice(1, end);
      } else {
        ret.name = path.slice(startPart, startDot);
        ret.base = path.slice(startPart, end);
      }
      ret.ext = path.slice(startDot, end);
    }

    if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';

    return ret;
  },

  sep: '/',
  delimiter: ':',
  win32: null,
  posix: null
};

posix.posix = posix;

module.exports = posix;


/***/ }),

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

"use strict";


var has = Object.prototype.hasOwnProperty
  , undef;

/**
 * Decode a URI encoded string.
 *
 * @param {String} input The URI encoded string.
 * @returns {String|Null} The decoded string.
 * @api private
 */
function decode(input) {
  try {
    return decodeURIComponent(input.replace(/\+/g, ' '));
  } catch (e) {
    return null;
  }
}

/**
 * Attempts to encode a given input.
 *
 * @param {String} input The string that needs to be encoded.
 * @returns {String|Null} The encoded string.
 * @api private
 */
function encode(input) {
  try {
    return encodeURIComponent(input);
  } catch (e) {
    return null;
  }
}

/**
 * Simple query string parser.
 *
 * @param {String} query The query string that needs to be parsed.
 * @returns {Object}
 * @api public
 */
function querystring(query) {
  var parser = /([^=?#&]+)=?([^&]*)/g
    , result = {}
    , part;

  while (part = parser.exec(query)) {
    var key = decode(part[1])
      , value = decode(part[2]);

    //
    // Prevent overriding of existing properties. This ensures that build-in
    // methods like `toString` or __proto__ are not overriden by malicious
    // querystrings.
    //
    // In the case if failed decoding, we want to omit the key/value pairs
    // from the result.
    //
    if (key === null || value === null || key in result) continue;
    result[key] = value;
  }

  return result;
}

/**
 * Transform a query string to an object.
 *
 * @param {Object} obj Object that should be transformed.
 * @param {String} prefix Optional prefix.
 * @returns {String}
 * @api public
 */
function querystringify(obj, prefix) {
  prefix = prefix || '';

  var pairs = []
    , value
    , key;

  //
  // Optionally prefix with a '?' if needed
  //
  if ('string' !== typeof prefix) prefix = '?';

  for (key in obj) {
    if (has.call(obj, key)) {
      value = obj[key];

      //
      // Edge cases where we actually want to encode the value to an empty
      // string instead of the stringified value.
      //
      if (!value && (value === null || value === undef || isNaN(value))) {
        value = '';
      }

      key = encode(key);
      value = encode(value);

      //
      // If we failed to encode the strings, we should bail out as we don't
      // want to add invalid strings to the query.
      //
      if (key === null || value === null) continue;
      pairs.push(key +'='+ value);
    }
  }

  return pairs.length ? prefix + pairs.join('&') : '';
}

//
// Expose the module.
//
exports.stringify = querystringify;
exports.parse = querystring;


/***/ }),

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

"use strict";


/**
 * Check if we're required to add a port number.
 *
 * @see https://url.spec.whatwg.org/#default-port
 * @param {Number|String} port Port number we need to check
 * @param {String} protocol Protocol we need to check against.
 * @returns {Boolean} Is it a default port for the given protocol
 * @api private
 */
module.exports = function required(port, protocol) {
  protocol = protocol.split(':')[0];
  port = +port;

  if (!port) return false;

  switch (protocol) {
    case 'http':
    case 'ws':
    return port !== 80;

    case 'https':
    case 'wss':
    return port !== 443;

    case 'ftp':
    return port !== 21;

    case 'gopher':
    return port !== 70;

    case 'file':
    return false;
  }

  return port !== 0;
};


/***/ }),

/***/ 2225:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var required = __webpack_require__(3062)
  , qs = __webpack_require__(1359)
  , controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
  , CRHTLF = /[\n\r\t]/g
  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
  , port = /:\d+$/
  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
  , windowsDriveLetter = /^[a-zA-Z]:/;

/**
 * Remove control characters and whitespace from the beginning of a string.
 *
 * @param {Object|String} str String to trim.
 * @returns {String} A new string representing `str` stripped of control
 *     characters and whitespace from its beginning.
 * @public
 */
function trimLeft(str) {
  return (str ? str : '').toString().replace(controlOrWhitespace, '');
}

/**
 * These are the parse rules for the URL parser, it informs the parser
 * about:
 *
 * 0. The char it Needs to parse, if it's a string it should be done using
 *    indexOf, RegExp using exec and NaN means set as current value.
 * 1. The property we should set when parsing this value.
 * 2. Indication if it's backwards or forward parsing, when set as number it's
 *    the value of extra chars that should be split off.
 * 3. Inherit from location if non existing in the parser.
 * 4. `toLowerCase` the resulting value.
 */
var rules = [
  ['#', 'hash'],                        // Extract from the back.
  ['?', 'query'],                       // Extract from the back.
  function sanitize(address, url) {     // Sanitize what is left of the address
    return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address;
  },
  ['/', 'pathname'],                    // Extract from the back.
  ['@', 'auth', 1],                     // Extract from the front.
  [NaN, 'host', undefined, 1, 1],       // Set left over value.
  [/:(\d*)$/, 'port', undefined, 1],    // RegExp the back.
  [NaN, 'hostname', undefined, 1, 1]    // Set left over.
];

/**
 * These properties should not be copied or inherited from. This is only needed
 * for all non blob URL's as a blob URL does not include a hash, only the
 * origin.
 *
 * @type {Object}
 * @private
 */
var ignore = { hash: 1, query: 1 };

/**
 * The location object differs when your code is loaded through a normal page,
 * Worker or through a worker using a blob. And with the blobble begins the
 * trouble as the location object will contain the URL of the blob, not the
 * location of the page where our code is loaded in. The actual origin is
 * encoded in the `pathname` so we can thankfully generate a good "default"
 * location from it so we can generate proper relative URL's again.
 *
 * @param {Object|String} loc Optional default location object.
 * @returns {Object} lolcation object.
 * @public
 */
function lolcation(loc) {
  var globalVar;

  if (typeof window !== 'undefined') globalVar = window;
  else if (typeof __webpack_require__.g !== 'undefined') globalVar = __webpack_require__.g;
  else if (typeof self !== 'undefined') globalVar = self;
  else globalVar = {};

  var location = globalVar.location || {};
  loc = loc || location;

  var finaldestination = {}
    , type = typeof loc
    , key;

  if ('blob:' === loc.protocol) {
    finaldestination = new Url(unescape(loc.pathname), {});
  } else if ('string' === type) {
    finaldestination = new Url(loc, {});
    for (key in ignore) delete finaldestination[key];
  } else if ('object' === type) {
    for (key in loc) {
      if (key in ignore) continue;
      finaldestination[key] = loc[key];
    }

    if (finaldestination.slashes === undefined) {
      finaldestination.slashes = slashes.test(loc.href);
    }
  }

  return finaldestination;
}

/**
 * Check whether a protocol scheme is special.
 *
 * @param {String} The protocol scheme of the URL
 * @return {Boolean} `true` if the protocol scheme is special, else `false`
 * @private
 */
function isSpecial(scheme) {
  return (
    scheme === 'file:' ||
    scheme === 'ftp:' ||
    scheme === 'http:' ||
    scheme === 'https:' ||
    scheme === 'ws:' ||
    scheme === 'wss:'
  );
}

/**
 * @typedef ProtocolExtract
 * @type Object
 * @property {String} protocol Protocol matched in the URL, in lowercase.
 * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
 * @property {String} rest Rest of the URL that is not part of the protocol.
 */

/**
 * Extract protocol information from a URL with/without double slash ("//").
 *
 * @param {String} address URL we want to extract from.
 * @param {Object} location
 * @return {ProtocolExtract} Extracted information.
 * @private
 */
function extractProtocol(address, location) {
  address = trimLeft(address);
  address = address.replace(CRHTLF, '');
  location = location || {};

  var match = protocolre.exec(address);
  var protocol = match[1] ? match[1].toLowerCase() : '';
  var forwardSlashes = !!match[2];
  var otherSlashes = !!match[3];
  var slashesCount = 0;
  var rest;

  if (forwardSlashes) {
    if (otherSlashes) {
      rest = match[2] + match[3] + match[4];
      slashesCount = match[2].length + match[3].length;
    } else {
      rest = match[2] + match[4];
      slashesCount = match[2].length;
    }
  } else {
    if (otherSlashes) {
      rest = match[3] + match[4];
      slashesCount = match[3].length;
    } else {
      rest = match[4]
    }
  }

  if (protocol === 'file:') {
    if (slashesCount >= 2) {
      rest = rest.slice(2);
    }
  } else if (isSpecial(protocol)) {
    rest = match[4];
  } else if (protocol) {
    if (forwardSlashes) {
      rest = rest.slice(2);
    }
  } else if (slashesCount >= 2 && isSpecial(location.protocol)) {
    rest = match[4];
  }

  return {
    protocol: protocol,
    slashes: forwardSlashes || isSpecial(protocol),
    slashesCount: slashesCount,
    rest: rest
  };
}

/**
 * Resolve a relative URL pathname against a base URL pathname.
 *
 * @param {String} relative Pathname of the relative URL.
 * @param {String} base Pathname of the base URL.
 * @return {String} Resolved pathname.
 * @private
 */
function resolve(relative, base) {
  if (relative === '') return base;

  var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
    , i = path.length
    , last = path[i - 1]
    , unshift = false
    , up = 0;

  while (i--) {
    if (path[i] === '.') {
      path.splice(i, 1);
    } else if (path[i] === '..') {
      path.splice(i, 1);
      up++;
    } else if (up) {
      if (i === 0) unshift = true;
      path.splice(i, 1);
      up--;
    }
  }

  if (unshift) path.unshift('');
  if (last === '.' || last === '..') path.push('');

  return path.join('/');
}

/**
 * The actual URL instance. Instead of returning an object we've opted-in to
 * create an actual constructor as it's much more memory efficient and
 * faster and it pleases my OCD.
 *
 * It is worth noting that we should not use `URL` as class name to prevent
 * clashes with the global URL instance that got introduced in browsers.
 *
 * @constructor
 * @param {String} address URL we want to parse.
 * @param {Object|String} [location] Location defaults for relative paths.
 * @param {Boolean|Function} [parser] Parser for the query string.
 * @private
 */
function Url(address, location, parser) {
  address = trimLeft(address);
  address = address.replace(CRHTLF, '');

  if (!(this instanceof Url)) {
    return new Url(address, location, parser);
  }

  var relative, extracted, parse, instruction, index, key
    , instructions = rules.slice()
    , type = typeof location
    , url = this
    , i = 0;

  //
  // The following if statements allows this module two have compatibility with
  // 2 different API:
  //
  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  //    where the boolean indicates that the query string should also be parsed.
  //
  // 2. The `URL` interface of the browser which accepts a URL, object as
  //    arguments. The supplied object will be used as default values / fall-back
  //    for relative paths.
  //
  if ('object' !== type && 'string' !== type) {
    parser = location;
    location = null;
  }

  if (parser && 'function' !== typeof parser) parser = qs.parse;

  location = lolcation(location);

  //
  // Extract protocol information before running the instructions.
  //
  extracted = extractProtocol(address || '', location);
  relative = !extracted.protocol && !extracted.slashes;
  url.slashes = extracted.slashes || relative && location.slashes;
  url.protocol = extracted.protocol || location.protocol || '';
  address = extracted.rest;

  //
  // When the authority component is absent the URL starts with a path
  // component.
  //
  if (
    extracted.protocol === 'file:' && (
      extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||
    (!extracted.slashes &&
      (extracted.protocol ||
        extracted.slashesCount < 2 ||
        !isSpecial(url.protocol)))
  ) {
    instructions[3] = [/(.*)/, 'pathname'];
  }

  for (; i < instructions.length; i++) {
    instruction = instructions[i];

    if (typeof instruction === 'function') {
      address = instruction(address, url);
      continue;
    }

    parse = instruction[0];
    key = instruction[1];

    if (parse !== parse) {
      url[key] = address;
    } else if ('string' === typeof parse) {
      index = parse === '@'
        ? address.lastIndexOf(parse)
        : address.indexOf(parse);

      if (~index) {
        if ('number' === typeof instruction[2]) {
          url[key] = address.slice(0, index);
          address = address.slice(index + instruction[2]);
        } else {
          url[key] = address.slice(index);
          address = address.slice(0, index);
        }
      }
    } else if ((index = parse.exec(address))) {
      url[key] = index[1];
      address = address.slice(0, index.index);
    }

    url[key] = url[key] || (
      relative && instruction[3] ? location[key] || '' : ''
    );

    //
    // Hostname, host and protocol should be lowercased so they can be used to
    // create a proper `origin`.
    //
    if (instruction[4]) url[key] = url[key].toLowerCase();
  }

  //
  // Also parse the supplied query string in to an object. If we're supplied
  // with a custom parser as function use that instead of the default build-in
  // parser.
  //
  if (parser) url.query = parser(url.query);

  //
  // If the URL is relative, resolve the pathname against the base URL.
  //
  if (
      relative
    && location.slashes
    && url.pathname.charAt(0) !== '/'
    && (url.pathname !== '' || location.pathname !== '')
  ) {
    url.pathname = resolve(url.pathname, location.pathname);
  }

  //
  // Default to a / for pathname if none exists. This normalizes the URL
  // to always have a /
  //
  if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {
    url.pathname = '/' + url.pathname;
  }

  //
  // We should not add port numbers if they are already the default port number
  // for a given protocol. As the host also contains the port number we're going
  // override it with the hostname which contains no port number.
  //
  if (!required(url.port, url.protocol)) {
    url.host = url.hostname;
    url.port = '';
  }

  //
  // Parse down the `auth` for the username and password.
  //
  url.username = url.password = '';

  if (url.auth) {
    index = url.auth.indexOf(':');

    if (~index) {
      url.username = url.auth.slice(0, index);
      url.username = encodeURIComponent(decodeURIComponent(url.username));

      url.password = url.auth.slice(index + 1);
      url.password = encodeURIComponent(decodeURIComponent(url.password))
    } else {
      url.username = encodeURIComponent(decodeURIComponent(url.auth));
    }

    url.auth = url.password ? url.username +':'+ url.password : url.username;
  }

  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
    ? url.protocol +'//'+ url.host
    : 'null';

  //
  // The href is just the compiled result.
  //
  url.href = url.toString();
}

/**
 * This is convenience method for changing properties in the URL instance to
 * insure that they all propagate correctly.
 *
 * @param {String} part          Property we need to adjust.
 * @param {Mixed} value          The newly assigned value.
 * @param {Boolean|Function} fn  When setting the query, it will be the function
 *                               used to parse the query.
 *                               When setting the protocol, double slash will be
 *                               removed from the final url if it is true.
 * @returns {URL} URL instance for chaining.
 * @public
 */
function set(part, value, fn) {
  var url = this;

  switch (part) {
    case 'query':
      if ('string' === typeof value && value.length) {
        value = (fn || qs.parse)(value);
      }

      url[part] = value;
      break;

    case 'port':
      url[part] = value;

      if (!required(value, url.protocol)) {
        url.host = url.hostname;
        url[part] = '';
      } else if (value) {
        url.host = url.hostname +':'+ value;
      }

      break;

    case 'hostname':
      url[part] = value;

      if (url.port) value += ':'+ url.port;
      url.host = value;
      break;

    case 'host':
      url[part] = value;

      if (port.test(value)) {
        value = value.split(':');
        url.port = value.pop();
        url.hostname = value.join(':');
      } else {
        url.hostname = value;
        url.port = '';
      }

      break;

    case 'protocol':
      url.protocol = value.toLowerCase();
      url.slashes = !fn;
      break;

    case 'pathname':
    case 'hash':
      if (value) {
        var char = part === 'pathname' ? '/' : '#';
        url[part] = value.charAt(0) !== char ? char + value : value;
      } else {
        url[part] = value;
      }
      break;

    case 'username':
    case 'password':
      url[part] = encodeURIComponent(value);
      break;

    case 'auth':
      var index = value.indexOf(':');

      if (~index) {
        url.username = value.slice(0, index);
        url.username = encodeURIComponent(decodeURIComponent(url.username));

        url.password = value.slice(index + 1);
        url.password = encodeURIComponent(decodeURIComponent(url.password));
      } else {
        url.username = encodeURIComponent(decodeURIComponent(value));
      }
  }

  for (var i = 0; i < rules.length; i++) {
    var ins = rules[i];

    if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  }

  url.auth = url.password ? url.username +':'+ url.password : url.username;

  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
    ? url.protocol +'//'+ url.host
    : 'null';

  url.href = url.toString();

  return url;
}

/**
 * Transform the properties back in to a valid and full URL string.
 *
 * @param {Function} stringify Optional query stringify function.
 * @returns {String} Compiled version of the URL.
 * @public
 */
function toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , host = url.host
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result =
    protocol +
    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  } else if (url.password) {
    result += ':'+ url.password;
    result += '@';
  } else if (
    url.protocol !== 'file:' &&
    isSpecial(url.protocol) &&
    !host &&
    url.pathname !== '/'
  ) {
    //
    // Add back the empty userinfo, otherwise the original invalid URL
    // might be transformed into a valid one with `url.pathname` as host.
    //
    result += '@';
  }

  //
  // Trailing colon is removed from `url.host` when it is parsed. If it still
  // ends with a colon, then add back the trailing colon that was removed. This
  // prevents an invalid URL from being transformed into a valid one.
  //
  if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {
    host += ':';
  }

  result += host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}

Url.prototype = { set: set, toString: toString };

//
// Expose the URL parser and some additional properties that might be useful for
// others or testing.
//
Url.extractProtocol = extractProtocol;
Url.location = lolcation;
Url.trimLeft = trimLeft;
Url.qs = qs;

module.exports = Url;


/***/ }),

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

/*!
 * wavesurfer.js 5.2.0 (2021-08-16)
 * https://wavesurfer-js.org
 * @license BSD-3-Clause
 */
(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory();
	else {}
})(self, function() {
return /******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ "./src/drawer.canvasentry.js":
/*!***********************************!*\
  !*** ./src/drawer.canvasentry.js ***!
  \***********************************/
/***/ ((module, exports, __nested_webpack_require_747__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

var _style = _interopRequireDefault(__nested_webpack_require_747__(/*! ./util/style */ "./src/util/style.js"));

var _getId = _interopRequireDefault(__nested_webpack_require_747__(/*! ./util/get-id */ "./src/util/get-id.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * The `CanvasEntry` class represents an element consisting of a wave `canvas`
 * and an (optional) progress wave `canvas`.
 *
 * The `MultiCanvas` renderer uses one or more `CanvasEntry` instances to
 * render a waveform, depending on the zoom level.
 */
var CanvasEntry = /*#__PURE__*/function () {
  function CanvasEntry() {
    _classCallCheck(this, CanvasEntry);

    /**
     * The wave node
     *
     * @type {HTMLCanvasElement}
     */
    this.wave = null;
    /**
     * The wave canvas rendering context
     *
     * @type {CanvasRenderingContext2D}
     */

    this.waveCtx = null;
    /**
     * The (optional) progress wave node
     *
     * @type {HTMLCanvasElement}
     */

    this.progress = null;
    /**
     * The (optional) progress wave canvas rendering context
     *
     * @type {CanvasRenderingContext2D}
     */

    this.progressCtx = null;
    /**
     * Start of the area the canvas should render, between 0 and 1
     *
     * @type {number}
     */

    this.start = 0;
    /**
     * End of the area the canvas should render, between 0 and 1
     *
     * @type {number}
     */

    this.end = 1;
    /**
     * Unique identifier for this entry
     *
     * @type {string}
     */

    this.id = (0, _getId.default)(typeof this.constructor.name !== 'undefined' ? this.constructor.name.toLowerCase() + '_' : 'canvasentry_');
    /**
     * Canvas 2d context attributes
     *
     * @type {object}
     */

    this.canvasContextAttributes = {};
  }
  /**
   * Store the wave canvas element and create the 2D rendering context
   *
   * @param {HTMLCanvasElement} element The wave `canvas` element.
   */


  _createClass(CanvasEntry, [{
    key: "initWave",
    value: function initWave(element) {
      this.wave = element;
      this.waveCtx = this.wave.getContext('2d', this.canvasContextAttributes);
    }
    /**
     * Store the progress wave canvas element and create the 2D rendering
     * context
     *
     * @param {HTMLCanvasElement} element The progress wave `canvas` element.
     */

  }, {
    key: "initProgress",
    value: function initProgress(element) {
      this.progress = element;
      this.progressCtx = this.progress.getContext('2d', this.canvasContextAttributes);
    }
    /**
     * Update the dimensions
     *
     * @param {number} elementWidth Width of the entry
     * @param {number} totalWidth Total width of the multi canvas renderer
     * @param {number} width The new width of the element
     * @param {number} height The new height of the element
     */

  }, {
    key: "updateDimensions",
    value: function updateDimensions(elementWidth, totalWidth, width, height) {
      // where the canvas starts and ends in the waveform, represented as a
      // decimal between 0 and 1
      this.start = this.wave.offsetLeft / totalWidth || 0;
      this.end = this.start + elementWidth / totalWidth; // set wave canvas dimensions

      this.wave.width = width;
      this.wave.height = height;
      var elementSize = {
        width: elementWidth + 'px'
      };
      (0, _style.default)(this.wave, elementSize);

      if (this.hasProgressCanvas) {
        // set progress canvas dimensions
        this.progress.width = width;
        this.progress.height = height;
        (0, _style.default)(this.progress, elementSize);
      }
    }
    /**
     * Clear the wave and progress rendering contexts
     */

  }, {
    key: "clearWave",
    value: function clearWave() {
      // wave
      this.waveCtx.clearRect(0, 0, this.waveCtx.canvas.width, this.waveCtx.canvas.height); // progress

      if (this.hasProgressCanvas) {
        this.progressCtx.clearRect(0, 0, this.progressCtx.canvas.width, this.progressCtx.canvas.height);
      }
    }
    /**
     * Set the fill styles for wave and progress
     *
     * @param {string} waveColor Fill color for the wave canvas
     * @param {?string} progressColor Fill color for the progress canvas
     */

  }, {
    key: "setFillStyles",
    value: function setFillStyles(waveColor, progressColor) {
      this.waveCtx.fillStyle = waveColor;

      if (this.hasProgressCanvas) {
        this.progressCtx.fillStyle = progressColor;
      }
    }
    /**
     * Set the canvas transforms for wave and progress
     *
     * @param {boolean} vertical Whether to render vertically
     */

  }, {
    key: "applyCanvasTransforms",
    value: function applyCanvasTransforms(vertical) {
      if (vertical) {
        // Reflect the waveform across the line y = -x
        this.waveCtx.setTransform(0, 1, 1, 0, 0, 0);

        if (this.hasProgressCanvas) {
          this.progressCtx.setTransform(0, 1, 1, 0, 0, 0);
        }
      }
    }
    /**
     * Draw a rectangle for wave and progress
     *
     * @param {number} x X start position
     * @param {number} y Y start position
     * @param {number} width Width of the rectangle
     * @param {number} height Height of the rectangle
     * @param {number} radius Radius of the rectangle
     */

  }, {
    key: "fillRects",
    value: function fillRects(x, y, width, height, radius) {
      this.fillRectToContext(this.waveCtx, x, y, width, height, radius);

      if (this.hasProgressCanvas) {
        this.fillRectToContext(this.progressCtx, x, y, width, height, radius);
      }
    }
    /**
     * Draw the actual rectangle on a `canvas` element
     *
     * @param {CanvasRenderingContext2D} ctx Rendering context of target canvas
     * @param {number} x X start position
     * @param {number} y Y start position
     * @param {number} width Width of the rectangle
     * @param {number} height Height of the rectangle
     * @param {number} radius Radius of the rectangle
     */

  }, {
    key: "fillRectToContext",
    value: function fillRectToContext(ctx, x, y, width, height, radius) {
      if (!ctx) {
        return;
      }

      if (radius) {
        this.drawRoundedRect(ctx, x, y, width, height, radius);
      } else {
        ctx.fillRect(x, y, width, height);
      }
    }
    /**
     * Draw a rounded rectangle on Canvas
     *
     * @param {CanvasRenderingContext2D} ctx Canvas context
     * @param {number} x X-position of the rectangle
     * @param {number} y Y-position of the rectangle
     * @param {number} width Width of the rectangle
     * @param {number} height Height of the rectangle
     * @param {number} radius Radius of the rectangle
     *
     * @return {void}
     * @example drawRoundedRect(ctx, 50, 50, 5, 10, 3)
     */

  }, {
    key: "drawRoundedRect",
    value: function drawRoundedRect(ctx, x, y, width, height, radius) {
      if (height === 0) {
        return;
      } // peaks are float values from -1 to 1. Use absolute height values in
      // order to correctly calculate rounded rectangle coordinates


      if (height < 0) {
        height *= -1;
        y -= height;
      }

      ctx.beginPath();
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
      ctx.lineTo(x + radius, y + height);
      ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
      ctx.lineTo(x, y + radius);
      ctx.quadraticCurveTo(x, y, x + radius, y);
      ctx.closePath();
      ctx.fill();
    }
    /**
     * Render the actual wave and progress lines
     *
     * @param {number[]} peaks Array with peaks data
     * @param {number} absmax Maximum peak value (absolute)
     * @param {number} halfH Half the height of the waveform
     * @param {number} offsetY Offset to the top
     * @param {number} start The x-offset of the beginning of the area that
     * should be rendered
     * @param {number} end The x-offset of the end of the area that
     * should be rendered
     */

  }, {
    key: "drawLines",
    value: function drawLines(peaks, absmax, halfH, offsetY, start, end) {
      this.drawLineToContext(this.waveCtx, peaks, absmax, halfH, offsetY, start, end);

      if (this.hasProgressCanvas) {
        this.drawLineToContext(this.progressCtx, peaks, absmax, halfH, offsetY, start, end);
      }
    }
    /**
     * Render the actual waveform line on a `canvas` element
     *
     * @param {CanvasRenderingContext2D} ctx Rendering context of target canvas
     * @param {number[]} peaks Array with peaks data
     * @param {number} absmax Maximum peak value (absolute)
     * @param {number} halfH Half the height of the waveform
     * @param {number} offsetY Offset to the top
     * @param {number} start The x-offset of the beginning of the area that
     * should be rendered
     * @param {number} end The x-offset of the end of the area that
     * should be rendered
     */

  }, {
    key: "drawLineToContext",
    value: function drawLineToContext(ctx, peaks, absmax, halfH, offsetY, start, end) {
      if (!ctx) {
        return;
      }

      var length = peaks.length / 2;
      var first = Math.round(length * this.start); // use one more peak value to make sure we join peaks at ends -- unless,
      // of course, this is the last canvas

      var last = Math.round(length * this.end) + 1;
      var canvasStart = first;
      var canvasEnd = last;
      var scale = this.wave.width / (canvasEnd - canvasStart - 1); // optimization

      var halfOffset = halfH + offsetY;
      var absmaxHalf = absmax / halfH;
      ctx.beginPath();
      ctx.moveTo((canvasStart - first) * scale, halfOffset);
      ctx.lineTo((canvasStart - first) * scale, halfOffset - Math.round((peaks[2 * canvasStart] || 0) / absmaxHalf));
      var i, peak, h;

      for (i = canvasStart; i < canvasEnd; i++) {
        peak = peaks[2 * i] || 0;
        h = Math.round(peak / absmaxHalf);
        ctx.lineTo((i - first) * scale + this.halfPixel, halfOffset - h);
      } // draw the bottom edge going backwards, to make a single
      // closed hull to fill


      var j = canvasEnd - 1;

      for (j; j >= canvasStart; j--) {
        peak = peaks[2 * j + 1] || 0;
        h = Math.round(peak / absmaxHalf);
        ctx.lineTo((j - first) * scale + this.halfPixel, halfOffset - h);
      }

      ctx.lineTo((canvasStart - first) * scale, halfOffset - Math.round((peaks[2 * canvasStart + 1] || 0) / absmaxHalf));
      ctx.closePath();
      ctx.fill();
    }
    /**
     * Destroys this entry
     */

  }, {
    key: "destroy",
    value: function destroy() {
      this.waveCtx = null;
      this.wave = null;
      this.progressCtx = null;
      this.progress = null;
    }
    /**
     * Return image data of the wave `canvas` element
     *
     * When using a `type` of `'blob'`, this will return a `Promise` that
     * resolves with a `Blob` instance.
     *
     * @param {string} format='image/png' An optional value of a format type.
     * @param {number} quality=0.92 An optional value between 0 and 1.
     * @param {string} type='dataURL' Either 'dataURL' or 'blob'.
     * @return {string|Promise} When using the default `'dataURL'` `type` this
     * returns a data URL. When using the `'blob'` `type` this returns a
     * `Promise` that resolves with a `Blob` instance.
     */

  }, {
    key: "getImage",
    value: function getImage(format, quality, type) {
      var _this = this;

      if (type === 'blob') {
        return new Promise(function (resolve) {
          _this.wave.toBlob(resolve, format, quality);
        });
      } else if (type === 'dataURL') {
        return this.wave.toDataURL(format, quality);
      }
    }
  }]);

  return CanvasEntry;
}();

exports.default = CanvasEntry;
module.exports = exports.default;

/***/ }),

/***/ "./src/drawer.js":
/*!***********************!*\
  !*** ./src/drawer.js ***!
  \***********************/
/***/ ((module, exports, __nested_webpack_require_13686__) => {

"use strict";


function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

var util = _interopRequireWildcard(__nested_webpack_require_13686__(/*! ./util */ "./src/util/index.js"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * Parent class for renderers
 *
 * @extends {Observer}
 */
var Drawer = /*#__PURE__*/function (_util$Observer) {
  _inherits(Drawer, _util$Observer);

  var _super = _createSuper(Drawer);

  /**
   * @param {HTMLElement} container The container node of the wavesurfer instance
   * @param {WavesurferParams} params The wavesurfer initialisation options
   */
  function Drawer(container, params) {
    var _this;

    _classCallCheck(this, Drawer);

    _this = _super.call(this);
    _this.container = util.withOrientation(container, params.vertical);
    /**
     * @type {WavesurferParams}
     */

    _this.params = params;
    /**
     * The width of the renderer
     * @type {number}
     */

    _this.width = 0;
    /**
     * The height of the renderer
     * @type {number}
     */

    _this.height = params.height * _this.params.pixelRatio;
    _this.lastPos = 0;
    /**
     * The `<wave>` element which is added to the container
     * @type {HTMLElement}
     */

    _this.wrapper = null;
    return _this;
  }
  /**
   * Alias of `util.style`
   *
   * @param {HTMLElement} el The element that the styles will be applied to
   * @param {Object} styles The map of propName: attribute, both are used as-is
   * @return {HTMLElement} el
   */


  _createClass(Drawer, [{
    key: "style",
    value: function style(el, styles) {
      return util.style(el, styles);
    }
    /**
     * Create the wrapper `<wave>` element, style it and set up the events for
     * interaction
     */

  }, {
    key: "createWrapper",
    value: function createWrapper() {
      this.wrapper = util.withOrientation(this.container.appendChild(document.createElement('wave')), this.params.vertical);
      this.style(this.wrapper, {
        display: 'block',
        position: 'relative',
        userSelect: 'none',
        webkitUserSelect: 'none',
        height: this.params.height + 'px'
      });

      if (this.params.fillParent || this.params.scrollParent) {
        this.style(this.wrapper, {
          width: '100%',
          overflowX: this.params.hideScrollbar ? 'hidden' : 'auto',
          overflowY: 'hidden'
        });
      }

      this.setupWrapperEvents();
    }
    /**
     * Handle click event
     *
     * @param {Event} e Click event
     * @param {?boolean} noPrevent Set to true to not call `e.preventDefault()`
     * @return {number} Playback position from 0 to 1
     */

  }, {
    key: "handleEvent",
    value: function handleEvent(e, noPrevent) {
      !noPrevent && e.preventDefault();
      var clientX = util.withOrientation(e.targetTouches ? e.targetTouches[0] : e, this.params.vertical).clientX;
      var bbox = this.wrapper.getBoundingClientRect();
      var nominalWidth = this.width;
      var parentWidth = this.getWidth();
      var progressPixels = this.getProgressPixels(bbox, clientX);
      var progress;

      if (!this.params.fillParent && nominalWidth < parentWidth) {
        progress = progressPixels * (this.params.pixelRatio / nominalWidth) || 0;
      } else {
        progress = (progressPixels + this.wrapper.scrollLeft) / this.wrapper.scrollWidth || 0;
      }

      return util.clamp(progress, 0, 1);
    }
  }, {
    key: "getProgressPixels",
    value: function getProgressPixels(wrapperBbox, clientX) {
      if (this.params.rtl) {
        return wrapperBbox.right - clientX;
      } else {
        return clientX - wrapperBbox.left;
      }
    }
  }, {
    key: "setupWrapperEvents",
    value: function setupWrapperEvents() {
      var _this2 = this;

      this.wrapper.addEventListener('click', function (e) {
        var orientedEvent = util.withOrientation(e, _this2.params.vertical);
        var scrollbarHeight = _this2.wrapper.offsetHeight - _this2.wrapper.clientHeight;

        if (scrollbarHeight !== 0) {
          // scrollbar is visible.  Check if click was on it
          var bbox = _this2.wrapper.getBoundingClientRect();

          if (orientedEvent.clientY >= bbox.bottom - scrollbarHeight) {
            // ignore mousedown as it was on the scrollbar
            return;
          }
        }

        if (_this2.params.interact) {
          _this2.fireEvent('click', e, _this2.handleEvent(e));
        }
      });
      this.wrapper.addEventListener('dblclick', function (e) {
        if (_this2.params.interact) {
          _this2.fireEvent('dblclick', e, _this2.handleEvent(e));
        }
      });
      this.wrapper.addEventListener('scroll', function (e) {
        return _this2.fireEvent('scroll', e);
      });
    }
    /**
     * Draw peaks on the canvas
     *
     * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays
     * for split channel rendering
     * @param {number} length The width of the area that should be drawn
     * @param {number} start The x-offset of the beginning of the area that
     * should be rendered
     * @param {number} end The x-offset of the end of the area that should be
     * rendered
     */

  }, {
    key: "drawPeaks",
    value: function drawPeaks(peaks, length, start, end) {
      if (!this.setWidth(length)) {
        this.clearWave();
      }

      this.params.barWidth ? this.drawBars(peaks, 0, start, end) : this.drawWave(peaks, 0, start, end);
    }
    /**
     * Scroll to the beginning
     */

  }, {
    key: "resetScroll",
    value: function resetScroll() {
      if (this.wrapper !== null) {
        this.wrapper.scrollLeft = 0;
      }
    }
    /**
     * Recenter the view-port at a certain percent of the waveform
     *
     * @param {number} percent Value from 0 to 1 on the waveform
     */

  }, {
    key: "recenter",
    value: function recenter(percent) {
      var position = this.wrapper.scrollWidth * percent;
      this.recenterOnPosition(position, true);
    }
    /**
     * Recenter the view-port on a position, either scroll there immediately or
     * in steps of 5 pixels
     *
     * @param {number} position X-offset in pixels
     * @param {boolean} immediate Set to true to immediately scroll somewhere
     */

  }, {
    key: "recenterOnPosition",
    value: function recenterOnPosition(position, immediate) {
      var scrollLeft = this.wrapper.scrollLeft;
      var half = ~~(this.wrapper.clientWidth / 2);
      var maxScroll = this.wrapper.scrollWidth - this.wrapper.clientWidth;
      var target = position - half;
      var offset = target - scrollLeft;

      if (maxScroll == 0) {
        // no need to continue if scrollbar is not there
        return;
      } // if the cursor is currently visible...


      if (!immediate && -half <= offset && offset < half) {
        // set rate at which waveform is centered
        var rate = this.params.autoCenterRate; // make rate depend on width of view and length of waveform

        rate /= half;
        rate *= maxScroll;
        offset = Math.max(-rate, Math.min(rate, offset));
        target = scrollLeft + offset;
      } // limit target to valid range (0 to maxScroll)


      target = Math.max(0, Math.min(maxScroll, target)); // no use attempting to scroll if we're not moving

      if (target != scrollLeft) {
        this.wrapper.scrollLeft = target;
      }
    }
    /**
     * Get the current scroll position in pixels
     *
     * @return {number} Horizontal scroll position in pixels
     */

  }, {
    key: "getScrollX",
    value: function getScrollX() {
      var x = 0;

      if (this.wrapper) {
        var pixelRatio = this.params.pixelRatio;
        x = Math.round(this.wrapper.scrollLeft * pixelRatio); // In cases of elastic scroll (safari with mouse wheel) you can
        // scroll beyond the limits of the container
        // Calculate and floor the scrollable extent to make sure an out
        // of bounds value is not returned
        // Ticket #1312

        if (this.params.scrollParent) {
          var maxScroll = ~~(this.wrapper.scrollWidth * pixelRatio - this.getWidth());
          x = Math.min(maxScroll, Math.max(0, x));
        }
      }

      return x;
    }
    /**
     * Get the width of the container
     *
     * @return {number} The width of the container
     */

  }, {
    key: "getWidth",
    value: function getWidth() {
      return Math.round(this.container.clientWidth * this.params.pixelRatio);
    }
    /**
     * Set the width of the container
     *
     * @param {number} width The new width of the container
     * @return {boolean} Whether the width of the container was updated or not
     */

  }, {
    key: "setWidth",
    value: function setWidth(width) {
      if (this.width == width) {
        return false;
      }

      this.width = width;

      if (this.params.fillParent || this.params.scrollParent) {
        this.style(this.wrapper, {
          width: ''
        });
      } else {
        var newWidth = ~~(this.width / this.params.pixelRatio) + 'px';
        this.style(this.wrapper, {
          width: newWidth
        });
      }

      this.updateSize();
      return true;
    }
    /**
     * Set the height of the container
     *
     * @param {number} height The new height of the container.
     * @return {boolean} Whether the height of the container was updated or not
     */

  }, {
    key: "setHeight",
    value: function setHeight(height) {
      if (height == this.height) {
        return false;
      }

      this.height = height;
      this.style(this.wrapper, {
        height: ~~(this.height / this.params.pixelRatio) + 'px'
      });
      this.updateSize();
      return true;
    }
    /**
     * Called by wavesurfer when progress should be rendered
     *
     * @param {number} progress From 0 to 1
     */

  }, {
    key: "progress",
    value: function progress(_progress) {
      var minPxDelta = 1 / this.params.pixelRatio;
      var pos = Math.round(_progress * this.width) * minPxDelta;

      if (pos < this.lastPos || pos - this.lastPos >= minPxDelta) {
        this.lastPos = pos;

        if (this.params.scrollParent && this.params.autoCenter) {
          var newPos = ~~(this.wrapper.scrollWidth * _progress);
          this.recenterOnPosition(newPos, this.params.autoCenterImmediately);
        }

        this.updateProgress(pos);
      }
    }
    /**
     * This is called when wavesurfer is destroyed
     */

  }, {
    key: "destroy",
    value: function destroy() {
      this.unAll();

      if (this.wrapper) {
        if (this.wrapper.parentNode == this.container.domElement) {
          this.container.removeChild(this.wrapper.domElement);
        }

        this.wrapper = null;
      }
    }
    /* Renderer-specific methods */

    /**
     * Called after cursor related params have changed.
     *
     * @abstract
     */

  }, {
    key: "updateCursor",
    value: function updateCursor() {}
    /**
     * Called when the size of the container changes so the renderer can adjust
     *
     * @abstract
     */

  }, {
    key: "updateSize",
    value: function updateSize() {}
    /**
     * Draw a waveform with bars
     *
     * @abstract
     * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays for split channel
     * rendering
     * @param {number} channelIndex The index of the current channel. Normally
     * should be 0
     * @param {number} start The x-offset of the beginning of the area that
     * should be rendered
     * @param {number} end The x-offset of the end of the area that should be
     * rendered
     */

  }, {
    key: "drawBars",
    value: function drawBars(peaks, channelIndex, start, end) {}
    /**
     * Draw a waveform
     *
     * @abstract
     * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays for split channel
     * rendering
     * @param {number} channelIndex The index of the current channel. Normally
     * should be 0
     * @param {number} start The x-offset of the beginning of the area that
     * should be rendered
     * @param {number} end The x-offset of the end of the area that should be
     * rendered
     */

  }, {
    key: "drawWave",
    value: function drawWave(peaks, channelIndex, start, end) {}
    /**
     * Clear the waveform
     *
     * @abstract
     */

  }, {
    key: "clearWave",
    value: function clearWave() {}
    /**
     * Render the new progress
     *
     * @abstract
     * @param {number} position X-Offset of progress position in pixels
     */

  }, {
    key: "updateProgress",
    value: function updateProgress(position) {}
  }]);

  return Drawer;
}(util.Observer);

exports.default = Drawer;
module.exports = exports.default;

/***/ }),

/***/ "./src/drawer.multicanvas.js":
/*!***********************************!*\
  !*** ./src/drawer.multicanvas.js ***!
  \***********************************/
/***/ ((module, exports, __nested_webpack_require_30815__) => {

"use strict";


function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

var _drawer = _interopRequireDefault(__nested_webpack_require_30815__(/*! ./drawer */ "./src/drawer.js"));

var util = _interopRequireWildcard(__nested_webpack_require_30815__(/*! ./util */ "./src/util/index.js"));

var _drawer2 = _interopRequireDefault(__nested_webpack_require_30815__(/*! ./drawer.canvasentry */ "./src/drawer.canvasentry.js"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * MultiCanvas renderer for wavesurfer. Is currently the default and sole
 * builtin renderer.
 *
 * A `MultiCanvas` consists of one or more `CanvasEntry` instances, depending
 * on the zoom level.
 */
var MultiCanvas = /*#__PURE__*/function (_Drawer) {
  _inherits(MultiCanvas, _Drawer);

  var _super = _createSuper(MultiCanvas);

  /**
   * @param {HTMLElement} container The container node of the wavesurfer instance
   * @param {WavesurferParams} params The wavesurfer initialisation options
   */
  function MultiCanvas(container, params) {
    var _this;

    _classCallCheck(this, MultiCanvas);

    _this = _super.call(this, container, params);
    /**
     * @type {number}
     */

    _this.maxCanvasWidth = params.maxCanvasWidth;
    /**
     * @type {number}
     */

    _this.maxCanvasElementWidth = Math.round(params.maxCanvasWidth / params.pixelRatio);
    /**
     * Whether or not the progress wave is rendered. If the `waveColor`
     * and `progressColor` are the same color it is not.
     *
     * @type {boolean}
     */

    _this.hasProgressCanvas = params.waveColor != params.progressColor;
    /**
     * @type {number}
     */

    _this.halfPixel = 0.5 / params.pixelRatio;
    /**
     * List of `CanvasEntry` instances.
     *
     * @type {Array}
     */

    _this.canvases = [];
    /**
     * @type {HTMLElement}
     */

    _this.progressWave = null;
    /**
     * Class used to generate entries.
     *
     * @type {function}
     */

    _this.EntryClass = _drawer2.default;
    /**
     * Canvas 2d context attributes.
     *
     * @type {object}
     */

    _this.canvasContextAttributes = params.drawingContextAttributes;
    /**
     * Overlap added between entries to prevent vertical white stripes
     * between `canvas` elements.
     *
     * @type {number}
     */

    _this.overlap = 2 * Math.ceil(params.pixelRatio / 2);
    /**
     * The radius of the wave bars. Makes bars rounded
     *
     * @type {number}
     */

    _this.barRadius = params.barRadius || 0;
    /**
     * Whether to render the waveform vertically. Defaults to false.
     *
     * @type {boolean}
     */

    _this.vertical = params.vertical;
    return _this;
  }
  /**
   * Initialize the drawer
   */


  _createClass(MultiCanvas, [{
    key: "init",
    value: function init() {
      this.createWrapper();
      this.createElements();
    }
    /**
     * Create the canvas elements and style them
     *
     */

  }, {
    key: "createElements",
    value: function createElements() {
      this.progressWave = util.withOrientation(this.wrapper.appendChild(document.createElement('wave')), this.params.vertical);
      this.style(this.progressWave, {
        position: 'absolute',
        zIndex: 3,
        left: 0,
        top: 0,
        bottom: 0,
        overflow: 'hidden',
        width: '0',
        display: 'none',
        boxSizing: 'border-box',
        borderRightStyle: 'solid',
        pointerEvents: 'none'
      });
      this.addCanvas();
      this.updateCursor();
    }
    /**
     * Update cursor style
     */

  }, {
    key: "updateCursor",
    value: function updateCursor() {
      this.style(this.progressWave, {
        borderRightWidth: this.params.cursorWidth + 'px',
        borderRightColor: this.params.cursorColor
      });
    }
    /**
     * Adjust to the updated size by adding or removing canvases
     */

  }, {
    key: "updateSize",
    value: function updateSize() {
      var _this2 = this;

      var totalWidth = Math.round(this.width / this.params.pixelRatio);
      var requiredCanvases = Math.ceil(totalWidth / (this.maxCanvasElementWidth + this.overlap)); // add required canvases

      while (this.canvases.length < requiredCanvases) {
        this.addCanvas();
      } // remove older existing canvases, if any


      while (this.canvases.length > requiredCanvases) {
        this.removeCanvas();
      }

      var canvasWidth = this.maxCanvasWidth + this.overlap;
      var lastCanvas = this.canvases.length - 1;
      this.canvases.forEach(function (entry, i) {
        if (i == lastCanvas) {
          canvasWidth = _this2.width - _this2.maxCanvasWidth * lastCanvas;
        }

        _this2.updateDimensions(entry, canvasWidth, _this2.height);

        entry.clearWave();
      });
    }
    /**
     * Add a canvas to the canvas list
     *
     */

  }, {
    key: "addCanvas",
    value: function addCanvas() {
      var entry = new this.EntryClass();
      entry.canvasContextAttributes = this.canvasContextAttributes;
      entry.hasProgressCanvas = this.hasProgressCanvas;
      entry.halfPixel = this.halfPixel;
      var leftOffset = this.maxCanvasElementWidth * this.canvases.length; // wave

      var wave = util.withOrientation(this.wrapper.appendChild(document.createElement('canvas')), this.params.vertical);
      this.style(wave, {
        position: 'absolute',
        zIndex: 2,
        left: leftOffset + 'px',
        top: 0,
        bottom: 0,
        height: '100%',
        pointerEvents: 'none'
      });
      entry.initWave(wave); // progress

      if (this.hasProgressCanvas) {
        var progress = util.withOrientation(this.progressWave.appendChild(document.createElement('canvas')), this.params.vertical);
        this.style(progress, {
          position: 'absolute',
          left: leftOffset + 'px',
          top: 0,
          bottom: 0,
          height: '100%'
        });
        entry.initProgress(progress);
      }

      this.canvases.push(entry);
    }
    /**
     * Pop single canvas from the list
     *
     */

  }, {
    key: "removeCanvas",
    value: function removeCanvas() {
      var lastEntry = this.canvases[this.canvases.length - 1]; // wave

      lastEntry.wave.parentElement.removeChild(lastEntry.wave.domElement); // progress

      if (this.hasProgressCanvas) {
        lastEntry.progress.parentElement.removeChild(lastEntry.progress.domElement);
      } // cleanup


      if (lastEntry) {
        lastEntry.destroy();
        lastEntry = null;
      }

      this.canvases.pop();
    }
    /**
     * Update the dimensions of a canvas element
     *
     * @param {CanvasEntry} entry Target entry
     * @param {number} width The new width of the element
     * @param {number} height The new height of the element
     */

  }, {
    key: "updateDimensions",
    value: function updateDimensions(entry, width, height) {
      var elementWidth = Math.round(width / this.params.pixelRatio);
      var totalWidth = Math.round(this.width / this.params.pixelRatio); // update canvas dimensions

      entry.updateDimensions(elementWidth, totalWidth, width, height); // style element

      this.style(this.progressWave, {
        display: 'block'
      });
    }
    /**
     * Clear the whole multi-canvas
     */

  }, {
    key: "clearWave",
    value: function clearWave() {
      var _this3 = this;

      util.frame(function () {
        _this3.canvases.forEach(function (entry) {
          return entry.clearWave();
        });
      })();
    }
    /**
     * Draw a waveform with bars
     *
     * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays
     * for split channel rendering
     * @param {number} channelIndex The index of the current channel. Normally
     * should be 0. Must be an integer.
     * @param {number} start The x-offset of the beginning of the area that
     * should be rendered
     * @param {number} end The x-offset of the end of the area that should be
     * rendered
     * @returns {void}
     */

  }, {
    key: "drawBars",
    value: function drawBars(peaks, channelIndex, start, end) {
      var _this4 = this;

      return this.prepareDraw(peaks, channelIndex, start, end, function (_ref) {
        var absmax = _ref.absmax,
            hasMinVals = _ref.hasMinVals,
            height = _ref.height,
            offsetY = _ref.offsetY,
            halfH = _ref.halfH,
            peaks = _ref.peaks,
            ch = _ref.channelIndex;

        // if drawBars was called within ws.empty we don't pass a start and
        // don't want anything to happen
        if (start === undefined) {
          return;
        } // Skip every other value if there are negatives.


        var peakIndexScale = hasMinVals ? 2 : 1;
        var length = peaks.length / peakIndexScale;
        var bar = _this4.params.barWidth * _this4.params.pixelRatio;
        var gap = _this4.params.barGap === null ? Math.max(_this4.params.pixelRatio, ~~(bar / 2)) : Math.max(_this4.params.pixelRatio, _this4.params.barGap * _this4.params.pixelRatio);
        var step = bar + gap;
        var scale = length / _this4.width;
        var first = start;
        var last = end;
        var i = first;

        for (i; i < last; i += step) {
          var peak = peaks[Math.floor(i * scale * peakIndexScale)] || 0;
          var h = Math.round(peak / absmax * halfH);
          /* in case of silences, allow the user to specify that we
           * always draw *something* (normally a 1px high bar) */

          if (h == 0 && _this4.params.barMinHeight) {
            h = _this4.params.barMinHeight;
          }

          _this4.fillRect(i + _this4.halfPixel, halfH - h + offsetY, bar + _this4.halfPixel, h * 2, _this4.barRadius, ch);
        }
      });
    }
    /**
     * Draw a waveform
     *
     * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays
     * for split channel rendering
     * @param {number} channelIndex The index of the current channel. Normally
     * should be 0
     * @param {number?} start The x-offset of the beginning of the area that
     * should be rendered (If this isn't set only a flat line is rendered)
     * @param {number?} end The x-offset of the end of the area that should be
     * rendered
     * @returns {void}
     */

  }, {
    key: "drawWave",
    value: function drawWave(peaks, channelIndex, start, end) {
      var _this5 = this;

      return this.prepareDraw(peaks, channelIndex, start, end, function (_ref2) {
        var absmax = _ref2.absmax,
            hasMinVals = _ref2.hasMinVals,
            height = _ref2.height,
            offsetY = _ref2.offsetY,
            halfH = _ref2.halfH,
            peaks = _ref2.peaks,
            channelIndex = _ref2.channelIndex;

        if (!hasMinVals) {
          var reflectedPeaks = [];
          var len = peaks.length;
          var i = 0;

          for (i; i < len; i++) {
            reflectedPeaks[2 * i] = peaks[i];
            reflectedPeaks[2 * i + 1] = -peaks[i];
          }

          peaks = reflectedPeaks;
        } // if drawWave was called within ws.empty we don't pass a start and
        // end and simply want a flat line


        if (start !== undefined) {
          _this5.drawLine(peaks, absmax, halfH, offsetY, start, end, channelIndex);
        } // always draw a median line


        _this5.fillRect(0, halfH + offsetY - _this5.halfPixel, _this5.width, _this5.halfPixel, _this5.barRadius, channelIndex);
      });
    }
    /**
     * Tell the canvas entries to render their portion of the waveform
     *
     * @param {number[]} peaks Peaks data
     * @param {number} absmax Maximum peak value (absolute)
     * @param {number} halfH Half the height of the waveform
     * @param {number} offsetY Offset to the top
     * @param {number} start The x-offset of the beginning of the area that
     * should be rendered
     * @param {number} end The x-offset of the end of the area that
     * should be rendered
     * @param {channelIndex} channelIndex The channel index of the line drawn
     */

  }, {
    key: "drawLine",
    value: function drawLine(peaks, absmax, halfH, offsetY, start, end, channelIndex) {
      var _this6 = this;

      var _ref3 = this.params.splitChannelsOptions.channelColors[channelIndex] || {},
          waveColor = _ref3.waveColor,
          progressColor = _ref3.progressColor;

      this.canvases.forEach(function (entry, i) {
        _this6.setFillStyles(entry, waveColor, progressColor);

        _this6.applyCanvasTransforms(entry, _this6.params.vertical);

        entry.drawLines(peaks, absmax, halfH, offsetY, start, end);
      });
    }
    /**
     * Draw a rectangle on the multi-canvas
     *
     * @param {number} x X-position of the rectangle
     * @param {number} y Y-position of the rectangle
     * @param {number} width Width of the rectangle
     * @param {number} height Height of the rectangle
     * @param {number} radius Radius of the rectangle
     * @param {channelIndex} channelIndex The channel index of the bar drawn
     */

  }, {
    key: "fillRect",
    value: function fillRect(x, y, width, height, radius, channelIndex) {
      var startCanvas = Math.floor(x / this.maxCanvasWidth);
      var endCanvas = Math.min(Math.ceil((x + width) / this.maxCanvasWidth) + 1, this.canvases.length);
      var i = startCanvas;

      for (i; i < endCanvas; i++) {
        var entry = this.canvases[i];
        var leftOffset = i * this.maxCanvasWidth;
        var intersection = {
          x1: Math.max(x, i * this.maxCanvasWidth),
          y1: y,
          x2: Math.min(x + width, i * this.maxCanvasWidth + entry.wave.width),
          y2: y + height
        };

        if (intersection.x1 < intersection.x2) {
          var _ref4 = this.params.splitChannelsOptions.channelColors[channelIndex] || {},
              waveColor = _ref4.waveColor,
              progressColor = _ref4.progressColor;

          this.setFillStyles(entry, waveColor, progressColor);
          this.applyCanvasTransforms(entry, this.params.vertical);
          entry.fillRects(intersection.x1 - leftOffset, intersection.y1, intersection.x2 - intersection.x1, intersection.y2 - intersection.y1, radius);
        }
      }
    }
    /**
     * Returns whether to hide the channel from being drawn based on params.
     *
     * @param {number} channelIndex The index of the current channel.
     * @returns {bool} True to hide the channel, false to draw.
     */

  }, {
    key: "hideChannel",
    value: function hideChannel(channelIndex) {
      return this.params.splitChannels && this.params.splitChannelsOptions.filterChannels.includes(channelIndex);
    }
    /**
     * Performs preparation tasks and calculations which are shared by `drawBars`
     * and `drawWave`
     *
     * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays for
     * split channel rendering
     * @param {number} channelIndex The index of the current channel. Normally
     * should be 0
     * @param {number?} start The x-offset of the beginning of the area that
     * should be rendered. If this isn't set only a flat line is rendered
     * @param {number?} end The x-offset of the end of the area that should be
     * rendered
     * @param {function} fn The render function to call, e.g. `drawWave`
     * @param {number} drawIndex The index of the current channel after filtering.
     * @param {number?} normalizedMax Maximum modulation value across channels for use with relativeNormalization. Ignored when undefined
     * @returns {void}
     */

  }, {
    key: "prepareDraw",
    value: function prepareDraw(peaks, channelIndex, start, end, fn, drawIndex, normalizedMax) {
      var _this7 = this;

      return util.frame(function () {
        // Split channels and call this function with the channelIndex set
        if (peaks[0] instanceof Array) {
          var channels = peaks;

          if (_this7.params.splitChannels) {
            var filteredChannels = channels.filter(function (c, i) {
              return !_this7.hideChannel(i);
            });

            if (!_this7.params.splitChannelsOptions.overlay) {
              _this7.setHeight(Math.max(filteredChannels.length, 1) * _this7.params.height * _this7.params.pixelRatio);
            }

            var overallAbsMax;

            if (_this7.params.splitChannelsOptions && _this7.params.splitChannelsOptions.relativeNormalization) {
              // calculate maximum peak across channels to use for normalization
              overallAbsMax = util.max(channels.map(function (channelPeaks) {
                return util.absMax(channelPeaks);
              }));
            }

            return channels.forEach(function (channelPeaks, i) {
              return _this7.prepareDraw(channelPeaks, i, start, end, fn, filteredChannels.indexOf(channelPeaks), overallAbsMax);
            });
          }

          peaks = channels[0];
        } // Return and do not draw channel peaks if hidden.


        if (_this7.hideChannel(channelIndex)) {
          return;
        } // calculate maximum modulation value, either from the barHeight
        // parameter or if normalize=true from the largest value in the peak
        // set


        var absmax = 1 / _this7.params.barHeight;

        if (_this7.params.normalize) {
          absmax = normalizedMax === undefined ? util.absMax(peaks) : normalizedMax;
        } // Bar wave draws the bottom only as a reflection of the top,
        // so we don't need negative values


        var hasMinVals = [].some.call(peaks, function (val) {
          return val < 0;
        });
        var height = _this7.params.height * _this7.params.pixelRatio;
        var halfH = height / 2;
        var offsetY = height * drawIndex || 0; // Override offsetY if overlay is true

        if (_this7.params.splitChannelsOptions && _this7.params.splitChannelsOptions.overlay) {
          offsetY = 0;
        }

        return fn({
          absmax: absmax,
          hasMinVals: hasMinVals,
          height: height,
          offsetY: offsetY,
          halfH: halfH,
          peaks: peaks,
          channelIndex: channelIndex
        });
      })();
    }
    /**
     * Set the fill styles for a certain entry (wave and progress)
     *
     * @param {CanvasEntry} entry Target entry
     * @param {string} waveColor Wave color to draw this entry
     * @param {string} progressColor Progress color to draw this entry
     */

  }, {
    key: "setFillStyles",
    value: function setFillStyles(entry) {
      var waveColor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.params.waveColor;
      var progressColor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.params.progressColor;
      entry.setFillStyles(waveColor, progressColor);
    }
    /**
     * Set the canvas transforms for a certain entry (wave and progress)
     *
     * @param {CanvasEntry} entry Target entry
     * @param {boolean} vertical Whether to render the waveform vertically
     */

  }, {
    key: "applyCanvasTransforms",
    value: function applyCanvasTransforms(entry) {
      var vertical = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      entry.applyCanvasTransforms(vertical);
    }
    /**
     * Return image data of the multi-canvas
     *
     * When using a `type` of `'blob'`, this will return a `Promise`.
     *
     * @param {string} format='image/png' An optional value of a format type.
     * @param {number} quality=0.92 An optional value between 0 and 1.
     * @param {string} type='dataURL' Either 'dataURL' or 'blob'.
     * @return {string|string[]|Promise} When using the default `'dataURL'`
     * `type` this returns a single data URL or an array of data URLs,
     * one for each canvas. When using the `'blob'` `type` this returns a
     * `Promise` that resolves with an array of `Blob` instances, one for each
     * canvas.
     */

  }, {
    key: "getImage",
    value: function getImage(format, quality, type) {
      if (type === 'blob') {
        return Promise.all(this.canvases.map(function (entry) {
          return entry.getImage(format, quality, type);
        }));
      } else if (type === 'dataURL') {
        var images = this.canvases.map(function (entry) {
          return entry.getImage(format, quality, type);
        });
        return images.length > 1 ? images : images[0];
      }
    }
    /**
     * Render the new progress
     *
     * @param {number} position X-offset of progress position in pixels
     */

  }, {
    key: "updateProgress",
    value: function updateProgress(position) {
      this.style(this.progressWave, {
        width: position + 'px'
      });
    }
  }]);

  return MultiCanvas;
}(_drawer.default);

exports.default = MultiCanvas;
module.exports = exports.default;

/***/ }),

/***/ "./src/mediaelement-webaudio.js":
/*!**************************************!*\
  !*** ./src/mediaelement-webaudio.js ***!
  \**************************************/
/***/ ((module, exports, __nested_webpack_require_56119__) => {

"use strict";


function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

var _mediaelement = _interopRequireDefault(__nested_webpack_require_56119__(/*! ./mediaelement */ "./src/mediaelement.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * MediaElementWebAudio backend: load audio via an HTML5 audio tag, but playback with the WebAudio API.
 * The advantage here is that the html5 <audio> tag can perform range requests on the server and not
 * buffer the entire file in one request, and you still get the filtering and scripting functionality
 * of the webaudio API.
 * Note that in order to use range requests and prevent buffering, you must provide peak data.
 *
 * @since 3.2.0
 */
var MediaElementWebAudio = /*#__PURE__*/function (_MediaElement) {
  _inherits(MediaElementWebAudio, _MediaElement);

  var _super = _createSuper(MediaElementWebAudio);

  /**
   * Construct the backend
   *
   * @param {WavesurferParams} params Wavesurfer parameters
   */
  function MediaElementWebAudio(params) {
    var _this;

    _classCallCheck(this, MediaElementWebAudio);

    _this = _super.call(this, params);
    /** @private */

    _this.params = params;
    /** @private */

    _this.sourceMediaElement = null;
    return _this;
  }
  /**
   * Initialise the backend, called in `wavesurfer.createBackend()`
   */


  _createClass(MediaElementWebAudio, [{
    key: "init",
    value: function init() {
      this.setPlaybackRate(this.params.audioRate);
      this.createTimer();
      this.createVolumeNode();
      this.createScriptNode();
      this.createAnalyserNode();
    }
    /**
     * Private method called by both `load` (from url)
     * and `loadElt` (existing media element) methods.
     *
     * @param {HTMLMediaElement} media HTML5 Audio or Video element
     * @param {number[]|Number.<Array[]>} peaks Array of peak data
     * @param {string} preload HTML 5 preload attribute value
     * @private
     */

  }, {
    key: "_load",
    value: function _load(media, peaks, preload) {
      _get(_getPrototypeOf(MediaElementWebAudio.prototype), "_load", this).call(this, media, peaks, preload);

      this.createMediaElementSource(media);
    }
    /**
     * Create MediaElementSource node
     *
     * @since 3.2.0
     * @param {HTMLMediaElement} mediaElement HTML5 Audio to load
     */

  }, {
    key: "createMediaElementSource",
    value: function createMediaElementSource(mediaElement) {
      this.sourceMediaElement = this.ac.createMediaElementSource(mediaElement);
      this.sourceMediaElement.connect(this.analyser);
    }
  }, {
    key: "play",
    value: function play(start, end) {
      this.resumeAudioContext();
      return _get(_getPrototypeOf(MediaElementWebAudio.prototype), "play", this).call(this, start, end);
    }
    /**
     * This is called when wavesurfer is destroyed
     *
     */

  }, {
    key: "destroy",
    value: function destroy() {
      _get(_getPrototypeOf(MediaElementWebAudio.prototype), "destroy", this).call(this);

      this.destroyWebAudio();
    }
  }]);

  return MediaElementWebAudio;
}(_mediaelement.default);

exports.default = MediaElementWebAudio;
module.exports = exports.default;

/***/ }),

/***/ "./src/mediaelement.js":
/*!*****************************!*\
  !*** ./src/mediaelement.js ***!
  \*****************************/
/***/ ((module, exports, __nested_webpack_require_63244__) => {

"use strict";


function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

var _webaudio = _interopRequireDefault(__nested_webpack_require_63244__(/*! ./webaudio */ "./src/webaudio.js"));

var util = _interopRequireWildcard(__nested_webpack_require_63244__(/*! ./util */ "./src/util/index.js"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * MediaElement backend
 */
var MediaElement = /*#__PURE__*/function (_WebAudio) {
  _inherits(MediaElement, _WebAudio);

  var _super = _createSuper(MediaElement);

  /**
   * Construct the backend
   *
   * @param {WavesurferParams} params Wavesurfer parameters
   */
  function MediaElement(params) {
    var _this;

    _classCallCheck(this, MediaElement);

    _this = _super.call(this, params);
    /** @private */

    _this.params = params;
    /**
     * Initially a dummy media element to catch errors. Once `_load` is
     * called, this will contain the actual `HTMLMediaElement`.
     * @private
     */

    _this.media = {
      currentTime: 0,
      duration: 0,
      paused: true,
      playbackRate: 1,
      play: function play() {},
      pause: function pause() {},
      volume: 0
    };
    /** @private */

    _this.mediaType = params.mediaType.toLowerCase();
    /** @private */

    _this.elementPosition = params.elementPosition;
    /** @private */

    _this.peaks = null;
    /** @private */

    _this.playbackRate = 1;
    /** @private */

    _this.volume = 1;
    /** @private */

    _this.isMuted = false;
    /** @private */

    _this.buffer = null;
    /** @private */

    _this.onPlayEnd = null;
    /** @private */

    _this.mediaListeners = {};
    return _this;
  }
  /**
   * Initialise the backend, called in `wavesurfer.createBackend()`
   */


  _createClass(MediaElement, [{
    key: "init",
    value: function init() {
      this.setPlaybackRate(this.params.audioRate);
      this.createTimer();
    }
    /**
     * Attach event listeners to media element.
     */

  }, {
    key: "_setupMediaListeners",
    value: function _setupMediaListeners() {
      var _this2 = this;

      this.mediaListeners.error = function () {
        _this2.fireEvent('error', 'Error loading media element');
      };

      this.mediaListeners.canplay = function () {
        _this2.fireEvent('canplay');
      };

      this.mediaListeners.ended = function () {
        _this2.fireEvent('finish');
      }; // listen to and relay play, pause and seeked events to enable
      // playback control from the external media element


      this.mediaListeners.play = function () {
        _this2.fireEvent('play');
      };

      this.mediaListeners.pause = function () {
        _this2.fireEvent('pause');
      };

      this.mediaListeners.seeked = function (event) {
        _this2.fireEvent('seek');
      };

      this.mediaListeners.volumechange = function (event) {
        _this2.isMuted = _this2.media.muted;

        if (_this2.isMuted) {
          _this2.volume = 0;
        } else {
          _this2.volume = _this2.media.volume;
        }

        _this2.fireEvent('volume');
      }; // reset event listeners


      Object.keys(this.mediaListeners).forEach(function (id) {
        _this2.media.removeEventListener(id, _this2.mediaListeners[id]);

        _this2.media.addEventListener(id, _this2.mediaListeners[id]);
      });
    }
    /**
     * Create a timer to provide a more precise `audioprocess` event.
     */

  }, {
    key: "createTimer",
    value: function createTimer() {
      var _this3 = this;

      var onAudioProcess = function onAudioProcess() {
        if (_this3.isPaused()) {
          return;
        }

        _this3.fireEvent('audioprocess', _this3.getCurrentTime()); // Call again in the next frame


        util.frame(onAudioProcess)();
      };

      this.on('play', onAudioProcess); // Update the progress one more time to prevent it from being stuck in
      // case of lower framerates

      this.on('pause', function () {
        _this3.fireEvent('audioprocess', _this3.getCurrentTime());
      });
    }
    /**
     * Create media element with url as its source,
     * and append to container element.
     *
     * @param {string} url Path to media file
     * @param {HTMLElement} container HTML element
     * @param {number[]|Number.<Array[]>} peaks Array of peak data
     * @param {string} preload HTML 5 preload attribute value
     * @throws Will throw an error if the `url` argument is not a valid media
     * element.
     */

  }, {
    key: "load",
    value: function load(url, container, peaks, preload) {
      var media = document.createElement(this.mediaType);
      media.controls = this.params.mediaControls;
      media.autoplay = this.params.autoplay || false;
      media.preload = preload == null ? 'auto' : preload;
      media.src = url;
      media.style.width = '100%';
      var prevMedia = container.querySelector(this.mediaType);

      if (prevMedia) {
        container.removeChild(prevMedia);
      }

      container.appendChild(media);

      this._load(media, peaks, preload);
    }
    /**
     * Load existing media element.
     *
     * @param {HTMLMediaElement} elt HTML5 Audio or Video element
     * @param {number[]|Number.<Array[]>} peaks Array of peak data
     */

  }, {
    key: "loadElt",
    value: function loadElt(elt, peaks) {
      elt.controls = this.params.mediaControls;
      elt.autoplay = this.params.autoplay || false;

      this._load(elt, peaks, elt.preload);
    }
    /**
     * Method called by both `load` (from url)
     * and `loadElt` (existing media element) methods.
     *
     * @param {HTMLMediaElement} media HTML5 Audio or Video element
     * @param {number[]|Number.<Array[]>} peaks Array of peak data
     * @param {string} preload HTML 5 preload attribute value
     * @throws Will throw an error if the `media` argument is not a valid media
     * element.
     * @private
     */

  }, {
    key: "_load",
    value: function _load(media, peaks, preload) {
      // verify media element is valid
      if (!(media instanceof HTMLMediaElement) || typeof media.addEventListener === 'undefined') {
        throw new Error('media parameter is not a valid media element');
      } // load must be called manually on iOS, otherwise peaks won't draw
      // until a user interaction triggers load --> 'ready' event
      //
      // note that we avoid calling media.load here when given peaks and preload == 'none'
      // as this almost always triggers some browser fetch of the media.


      if (typeof media.load == 'function' && !(peaks && preload == 'none')) {
        // Resets the media element and restarts the media resource. Any
        // pending events are discarded. How much media data is fetched is
        // still affected by the preload attribute.
        media.load();
      }

      this.media = media;

      this._setupMediaListeners();

      this.peaks = peaks;
      this.onPlayEnd = null;
      this.buffer = null;
      this.isMuted = media.muted;
      this.setPlaybackRate(this.playbackRate);
      this.setVolume(this.volume);
    }
    /**
     * Used by `wavesurfer.isPlaying()` and `wavesurfer.playPause()`
     *
     * @return {boolean} Media paused or not
     */

  }, {
    key: "isPaused",
    value: function isPaused() {
      return !this.media || this.media.paused;
    }
    /**
     * Used by `wavesurfer.getDuration()`
     *
     * @return {number} Duration
     */

  }, {
    key: "getDuration",
    value: function getDuration() {
      if (this.explicitDuration) {
        return this.explicitDuration;
      }

      var duration = (this.buffer || this.media).duration;

      if (duration >= Infinity) {
        // streaming audio
        duration = this.media.seekable.end(0);
      }

      return duration;
    }
    /**
     * Returns the current time in seconds relative to the audio-clip's
     * duration.
     *
     * @return {number} Current time
     */

  }, {
    key: "getCurrentTime",
    value: function getCurrentTime() {
      return this.media && this.media.currentTime;
    }
    /**
     * Get the position from 0 to 1
     *
     * @return {number} Current position
     */

  }, {
    key: "getPlayedPercents",
    value: function getPlayedPercents() {
      return this.getCurrentTime() / this.getDuration() || 0;
    }
    /**
     * Get the audio source playback rate.
     *
     * @return {number} Playback rate
     */

  }, {
    key: "getPlaybackRate",
    value: function getPlaybackRate() {
      return this.playbackRate || this.media.playbackRate;
    }
    /**
     * Set the audio source playback rate.
     *
     * @param {number} value Playback rate
     */

  }, {
    key: "setPlaybackRate",
    value: function setPlaybackRate(value) {
      this.playbackRate = value || 1;
      this.media.playbackRate = this.playbackRate;
    }
    /**
     * Used by `wavesurfer.seekTo()`
     *
     * @param {number} start Position to start at in seconds
     */

  }, {
    key: "seekTo",
    value: function seekTo(start) {
      if (start != null) {
        this.media.currentTime = start;
      }

      this.clearPlayEnd();
    }
    /**
     * Plays the loaded audio region.
     *
     * @param {number} start Start offset in seconds, relative to the beginning
     * of a clip.
     * @param {number} end When to stop, relative to the beginning of a clip.
     * @emits MediaElement#play
     * @return {Promise} Result
     */

  }, {
    key: "play",
    value: function play(start, end) {
      this.seekTo(start);
      var promise = this.media.play();
      end && this.setPlayEnd(end);
      return promise;
    }
    /**
     * Pauses the loaded audio.
     *
     * @emits MediaElement#pause
     * @return {Promise} Result
     */

  }, {
    key: "pause",
    value: function pause() {
      var promise;

      if (this.media) {
        promise = this.media.pause();
      }

      this.clearPlayEnd();
      return promise;
    }
    /**
     * Set the play end
     *
     * @param {number} end Where to end
     */

  }, {
    key: "setPlayEnd",
    value: function setPlayEnd(end) {
      var _this4 = this;

      this.clearPlayEnd();

      this._onPlayEnd = function (time) {
        if (time >= end) {
          _this4.pause();

          _this4.seekTo(end);
        }
      };

      this.on('audioprocess', this._onPlayEnd);
    }
    /** @private */

  }, {
    key: "clearPlayEnd",
    value: function clearPlayEnd() {
      if (this._onPlayEnd) {
        this.un('audioprocess', this._onPlayEnd);
        this._onPlayEnd = null;
      }
    }
    /**
     * Compute the max and min value of the waveform when broken into
     * <length> subranges.
     *
     * @param {number} length How many subranges to break the waveform into.
     * @param {number} first First sample in the required range.
     * @param {number} last Last sample in the required range.
     * @return {number[]|Number.<Array[]>} Array of 2*<length> peaks or array of
     * arrays of peaks consisting of (max, min) values for each subrange.
     */

  }, {
    key: "getPeaks",
    value: function getPeaks(length, first, last) {
      if (this.buffer) {
        return _get(_getPrototypeOf(MediaElement.prototype), "getPeaks", this).call(this, length, first, last);
      }

      return this.peaks || [];
    }
    /**
     * Set the sink id for the media player
     *
     * @param {string} deviceId String value representing audio device id.
     * @returns {Promise} A Promise that resolves to `undefined` when there
     * are no errors.
     */

  }, {
    key: "setSinkId",
    value: function setSinkId(deviceId) {
      if (deviceId) {
        if (!this.media.setSinkId) {
          return Promise.reject(new Error('setSinkId is not supported in your browser'));
        }

        return this.media.setSinkId(deviceId);
      }

      return Promise.reject(new Error('Invalid deviceId: ' + deviceId));
    }
    /**
     * Get the current volume
     *
     * @return {number} value A floating point value between 0 and 1.
     */

  }, {
    key: "getVolume",
    value: function getVolume() {
      return this.volume;
    }
    /**
     * Set the audio volume
     *
     * @param {number} value A floating point value between 0 and 1.
     */

  }, {
    key: "setVolume",
    value: function setVolume(value) {
      this.volume = value; // no need to change when it's already at that volume

      if (this.media.volume !== this.volume) {
        this.media.volume = this.volume;
      }
    }
    /**
     * Enable or disable muted audio
     *
     * @since 4.0.0
     * @param {boolean} muted Specify `true` to mute audio.
     */

  }, {
    key: "setMute",
    value: function setMute(muted) {
      // This causes a volume change to be emitted too through the
      // volumechange event listener.
      this.isMuted = this.media.muted = muted;
    }
    /**
     * This is called when wavesurfer is destroyed
     *
     */

  }, {
    key: "destroy",
    value: function destroy() {
      var _this5 = this;

      this.pause();
      this.unAll();
      this.destroyed = true; // cleanup media event listeners

      Object.keys(this.mediaListeners).forEach(function (id) {
        if (_this5.media) {
          _this5.media.removeEventListener(id, _this5.mediaListeners[id]);
        }
      });

      if (this.params.removeMediaElementOnDestroy && this.media && this.media.parentNode) {
        this.media.parentNode.removeChild(this.media);
      }

      this.media = null;
    }
  }]);

  return MediaElement;
}(_webaudio.default);

exports.default = MediaElement;
module.exports = exports.default;

/***/ }),

/***/ "./src/peakcache.js":
/*!**************************!*\
  !*** ./src/peakcache.js ***!
  \**************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * Caches the decoded peaks data to improve rendering speed for large audio
 *
 * Is used if the option parameter `partialRender` is set to `true`
 */
var PeakCache = /*#__PURE__*/function () {
  /**
   * Instantiate cache
   */
  function PeakCache() {
    _classCallCheck(this, PeakCache);

    this.clearPeakCache();
  }
  /**
   * Empty the cache
   */


  _createClass(PeakCache, [{
    key: "clearPeakCache",
    value: function clearPeakCache() {
      /**
       * Flat array with entries that are always in pairs to mark the
       * beginning and end of each subrange.  This is a convenience so we can
       * iterate over the pairs for easy set difference operations.
       * @private
       */
      this.peakCacheRanges = [];
      /**
       * Length of the entire cachable region, used for resetting the cache
       * when this changes (zoom events, for instance).
       * @private
       */

      this.peakCacheLength = -1;
    }
    /**
     * Add a range of peaks to the cache
     *
     * @param {number} length The length of the range
     * @param {number} start The x offset of the start of the range
     * @param {number} end The x offset of the end of the range
     * @return {Number.<Array[]>} Array with arrays of numbers
     */

  }, {
    key: "addRangeToPeakCache",
    value: function addRangeToPeakCache(length, start, end) {
      if (length != this.peakCacheLength) {
        this.clearPeakCache();
        this.peakCacheLength = length;
      } // Return ranges that weren't in the cache before the call.


      var uncachedRanges = [];
      var i = 0; // Skip ranges before the current start.

      while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] < start) {
        i++;
      } // If |i| is even, |start| falls after an existing range.  Otherwise,
      // |start| falls between an existing range, and the uncached region
      // starts when we encounter the next node in |peakCacheRanges| or
      // |end|, whichever comes first.


      if (i % 2 == 0) {
        uncachedRanges.push(start);
      }

      while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] <= end) {
        uncachedRanges.push(this.peakCacheRanges[i]);
        i++;
      } // If |i| is even, |end| is after all existing ranges.


      if (i % 2 == 0) {
        uncachedRanges.push(end);
      } // Filter out the 0-length ranges.


      uncachedRanges = uncachedRanges.filter(function (item, pos, arr) {
        if (pos == 0) {
          return item != arr[pos + 1];
        } else if (pos == arr.length - 1) {
          return item != arr[pos - 1];
        }

        return item != arr[pos - 1] && item != arr[pos + 1];
      }); // Merge the two ranges together, uncachedRanges will either contain
      // wholly new points, or duplicates of points in peakCacheRanges.  If
      // duplicates are detected, remove both and extend the range.

      this.peakCacheRanges = this.peakCacheRanges.concat(uncachedRanges);
      this.peakCacheRanges = this.peakCacheRanges.sort(function (a, b) {
        return a - b;
      }).filter(function (item, pos, arr) {
        if (pos == 0) {
          return item != arr[pos + 1];
        } else if (pos == arr.length - 1) {
          return item != arr[pos - 1];
        }

        return item != arr[pos - 1] && item != arr[pos + 1];
      }); // Push the uncached ranges into an array of arrays for ease of
      // iteration in the functions that call this.

      var uncachedRangePairs = [];

      for (i = 0; i < uncachedRanges.length; i += 2) {
        uncachedRangePairs.push([uncachedRanges[i], uncachedRanges[i + 1]]);
      }

      return uncachedRangePairs;
    }
    /**
     * For testing
     *
     * @return {Number.<Array[]>} Array with arrays of numbers
     */

  }, {
    key: "getCacheRanges",
    value: function getCacheRanges() {
      var peakCacheRangePairs = [];
      var i;

      for (i = 0; i < this.peakCacheRanges.length; i += 2) {
        peakCacheRangePairs.push([this.peakCacheRanges[i], this.peakCacheRanges[i + 1]]);
      }

      return peakCacheRangePairs;
    }
  }]);

  return PeakCache;
}();

exports.default = PeakCache;
module.exports = exports.default;

/***/ }),

/***/ "./src/util/absMax.js":
/*!****************************!*\
  !*** ./src/util/absMax.js ***!
  \****************************/
/***/ ((module, exports, __nested_webpack_require_87138__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = absMax;

var _max = _interopRequireDefault(__nested_webpack_require_87138__(/*! ./max */ "./src/util/max.js"));

var _min = _interopRequireDefault(__nested_webpack_require_87138__(/*! ./min */ "./src/util/min.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Get the largest absolute value in an array
 *
 * @param   {Array} values Array of numbers
 * @returns {Number} Largest number found
 * @example console.log(max([-3, 2, 1]), max([-3, 2, 4])); // logs 3 4
 * @since 4.3.0
 */
function absMax(values) {
  var max = (0, _max.default)(values);
  var min = (0, _min.default)(values);
  return -min > max ? -min : max;
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/clamp.js":
/*!***************************!*\
  !*** ./src/util/clamp.js ***!
  \***************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = clamp;

/**
 * Returns a number limited to the given range.
 *
 * @param {number} val The number to be limited to a range
 * @param {number} min The lower boundary of the limit range
 * @param {number} max The upper boundary of the limit range
 * @returns {number} A number in the range [min, max]
 */
function clamp(val, min, max) {
  return Math.min(Math.max(min, val), max);
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/fetch.js":
/*!***************************!*\
  !*** ./src/util/fetch.js ***!
  \***************************/
/***/ ((module, exports, __nested_webpack_require_88816__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = fetchFile;

var _observer = _interopRequireDefault(__nested_webpack_require_88816__(/*! ./observer */ "./src/util/observer.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var ProgressHandler = /*#__PURE__*/function () {
  /**
   * Instantiate ProgressHandler
   *
   * @param {Observer} instance The `fetchFile` observer instance.
   * @param {Number} contentLength Content length.
   * @param {Response} response Response object.
   */
  function ProgressHandler(instance, contentLength, response) {
    _classCallCheck(this, ProgressHandler);

    this.instance = instance;
    this.instance._reader = response.body.getReader();
    this.total = parseInt(contentLength, 10);
    this.loaded = 0;
  }
  /**
   * A method that is called once, immediately after the `ReadableStream``
   * is constructed.
   *
   * @param {ReadableStreamDefaultController} controller Controller instance
   *     used to control the stream.
   */


  _createClass(ProgressHandler, [{
    key: "start",
    value: function start(controller) {
      var _this = this;

      var read = function read() {
        // instance._reader.read() returns a promise that resolves
        // when a value has been received
        _this.instance._reader.read().then(function (_ref) {
          var done = _ref.done,
              value = _ref.value;

          // result objects contain two properties:
          // done  - true if the stream has already given you all its data.
          // value - some data. Always undefined when done is true.
          if (done) {
            // ensure onProgress called when content-length=0
            if (_this.total === 0) {
              _this.instance.onProgress.call(_this.instance, {
                loaded: _this.loaded,
                total: _this.total,
                lengthComputable: false
              });
            } // no more data needs to be consumed, close the stream


            controller.close();
            return;
          }

          _this.loaded += value.byteLength;

          _this.instance.onProgress.call(_this.instance, {
            loaded: _this.loaded,
            total: _this.total,
            lengthComputable: !(_this.total === 0)
          }); // enqueue the next data chunk into our target stream


          controller.enqueue(value);
          read();
        }).catch(function (error) {
          controller.error(error);
        });
      };

      read();
    }
  }]);

  return ProgressHandler;
}();
/**
 * Load a file using `fetch`.
 *
 * @param {object} options Request options to use. See example below.
 * @returns {Observer} Observer instance
 * @example
 * // default options
 * let options = {
 *     url: undefined,
 *     method: 'GET',
 *     mode: 'cors',
 *     credentials: 'same-origin',
 *     cache: 'default',
 *     responseType: 'json',
 *     requestHeaders: [],
 *     redirect: 'follow',
 *     referrer: 'client'
 * };
 *
 * // override some options
 * options.url = '../media/demo.wav';

 * // available types: 'arraybuffer', 'blob', 'json' or 'text'
 * options.responseType = 'arraybuffer';
 *
 * // make fetch call
 * let request = util.fetchFile(options);
 *
 * // listen for events
 * request.on('progress', e => {
 *     console.log('progress', e);
 * });
 *
 * request.on('success', data => {
 *     console.log('success!', data);
 * });
 *
 * request.on('error', e => {
 *     console.warn('fetchFile error: ', e);
 * });
 */


function fetchFile(options) {
  if (!options) {
    throw new Error('fetch options missing');
  } else if (!options.url) {
    throw new Error('fetch url missing');
  }

  var instance = new _observer.default();
  var fetchHeaders = new Headers();
  var fetchRequest = new Request(options.url); // add ability to abort

  instance.controller = new AbortController(); // check if headers have to be added

  if (options && options.requestHeaders) {
    // add custom request headers
    options.requestHeaders.forEach(function (header) {
      fetchHeaders.append(header.key, header.value);
    });
  } // parse fetch options


  var responseType = options.responseType || 'json';
  var fetchOptions = {
    method: options.method || 'GET',
    headers: fetchHeaders,
    mode: options.mode || 'cors',
    credentials: options.credentials || 'same-origin',
    cache: options.cache || 'default',
    redirect: options.redirect || 'follow',
    referrer: options.referrer || 'client',
    signal: instance.controller.signal
  };
  fetch(fetchRequest, fetchOptions).then(function (response) {
    // store response reference
    instance.response = response;
    var progressAvailable = true;

    if (!response.body) {
      // ReadableStream is not yet supported in this browser
      // see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
      progressAvailable = false;
    } // Server must send CORS header "Access-Control-Expose-Headers: content-length"


    var contentLength = response.headers.get('content-length');

    if (contentLength === null) {
      // Content-Length server response header missing.
      // Don't evaluate download progress if we can't compare against a total size
      // see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Access-Control-Expose-Headers
      progressAvailable = false;
    }

    if (!progressAvailable) {
      // not able to check download progress so skip it
      return response;
    } // fire progress event when during load


    instance.onProgress = function (e) {
      instance.fireEvent('progress', e);
    };

    return new Response(new ReadableStream(new ProgressHandler(instance, contentLength, response)), fetchOptions);
  }).then(function (response) {
    var errMsg;

    if (response.ok) {
      switch (responseType) {
        case 'arraybuffer':
          return response.arrayBuffer();

        case 'json':
          return response.json();

        case 'blob':
          return response.blob();

        case 'text':
          return response.text();

        default:
          errMsg = 'Unknown responseType: ' + responseType;
          break;
      }
    }

    if (!errMsg) {
      errMsg = 'HTTP error status: ' + response.status;
    }

    throw new Error(errMsg);
  }).then(function (response) {
    instance.fireEvent('success', response);
  }).catch(function (error) {
    instance.fireEvent('error', error);
  }); // return the fetch request

  instance.fetchRequest = fetchRequest;
  return instance;
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/frame.js":
/*!***************************!*\
  !*** ./src/util/frame.js ***!
  \***************************/
/***/ ((module, exports, __nested_webpack_require_96321__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = frame;

var _requestAnimationFrame = _interopRequireDefault(__nested_webpack_require_96321__(/*! ./request-animation-frame */ "./src/util/request-animation-frame.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Create a function which will be called at the next requestAnimationFrame
 * cycle
 *
 * @param {function} func The function to call
 *
 * @return {func} The function wrapped within a requestAnimationFrame
 */
function frame(func) {
  return function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return (0, _requestAnimationFrame.default)(function () {
      return func.apply(void 0, args);
    });
  };
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/get-id.js":
/*!****************************!*\
  !*** ./src/util/get-id.js ***!
  \****************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = getId;

/**
 * Get a random prefixed ID
 *
 * @param {String} prefix Prefix to use. Default is `'wavesurfer_'`.
 * @returns {String} Random prefixed ID
 * @example
 * console.log(getId()); // logs 'wavesurfer_b5pors4ru6g'
 *
 * let prefix = 'foo-';
 * console.log(getId(prefix)); // logs 'foo-b5pors4ru6g'
 */
function getId(prefix) {
  if (prefix === undefined) {
    prefix = 'wavesurfer_';
  }

  return prefix + Math.random().toString(32).substring(2);
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/index.js":
/*!***************************!*\
  !*** ./src/util/index.js ***!
  \***************************/
/***/ ((__unused_webpack_module, exports, __nested_webpack_require_98203__) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
Object.defineProperty(exports, "getId", ({
  enumerable: true,
  get: function get() {
    return _getId.default;
  }
}));
Object.defineProperty(exports, "max", ({
  enumerable: true,
  get: function get() {
    return _max.default;
  }
}));
Object.defineProperty(exports, "min", ({
  enumerable: true,
  get: function get() {
    return _min.default;
  }
}));
Object.defineProperty(exports, "absMax", ({
  enumerable: true,
  get: function get() {
    return _absMax.default;
  }
}));
Object.defineProperty(exports, "Observer", ({
  enumerable: true,
  get: function get() {
    return _observer.default;
  }
}));
Object.defineProperty(exports, "style", ({
  enumerable: true,
  get: function get() {
    return _style.default;
  }
}));
Object.defineProperty(exports, "requestAnimationFrame", ({
  enumerable: true,
  get: function get() {
    return _requestAnimationFrame.default;
  }
}));
Object.defineProperty(exports, "frame", ({
  enumerable: true,
  get: function get() {
    return _frame.default;
  }
}));
Object.defineProperty(exports, "debounce", ({
  enumerable: true,
  get: function get() {
    return _debounce.default;
  }
}));
Object.defineProperty(exports, "preventClick", ({
  enumerable: true,
  get: function get() {
    return _preventClick.default;
  }
}));
Object.defineProperty(exports, "fetchFile", ({
  enumerable: true,
  get: function get() {
    return _fetch.default;
  }
}));
Object.defineProperty(exports, "clamp", ({
  enumerable: true,
  get: function get() {
    return _clamp.default;
  }
}));
Object.defineProperty(exports, "withOrientation", ({
  enumerable: true,
  get: function get() {
    return _orientation.default;
  }
}));
Object.defineProperty(exports, "ignoreSilenceMode", ({
  enumerable: true,
  get: function get() {
    return _silenceMode.default;
  }
}));

var _getId = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./get-id */ "./src/util/get-id.js"));

var _max = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./max */ "./src/util/max.js"));

var _min = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./min */ "./src/util/min.js"));

var _absMax = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./absMax */ "./src/util/absMax.js"));

var _observer = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./observer */ "./src/util/observer.js"));

var _style = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./style */ "./src/util/style.js"));

var _requestAnimationFrame = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./request-animation-frame */ "./src/util/request-animation-frame.js"));

var _frame = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./frame */ "./src/util/frame.js"));

var _debounce = _interopRequireDefault(__nested_webpack_require_98203__(/*! debounce */ "./node_modules/debounce/index.js"));

var _preventClick = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./prevent-click */ "./src/util/prevent-click.js"));

var _fetch = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./fetch */ "./src/util/fetch.js"));

var _clamp = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./clamp */ "./src/util/clamp.js"));

var _orientation = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./orientation */ "./src/util/orientation.js"));

var _silenceMode = _interopRequireDefault(__nested_webpack_require_98203__(/*! ./silence-mode */ "./src/util/silence-mode.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/***/ }),

/***/ "./src/util/max.js":
/*!*************************!*\
  !*** ./src/util/max.js ***!
  \*************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = max;

/**
 * Get the largest value
 *
 * @param   {Array} values Array of numbers
 * @returns {Number} Largest number found
 * @example console.log(max([1, 2, 3])); // logs 3
 */
function max(values) {
  var largest = -Infinity;
  Object.keys(values).forEach(function (i) {
    if (values[i] > largest) {
      largest = values[i];
    }
  });
  return largest;
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/min.js":
/*!*************************!*\
  !*** ./src/util/min.js ***!
  \*************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = min;

/**
 * Get the smallest value
 *
 * @param   {Array} values Array of numbers
 * @returns {Number} Smallest number found
 * @example console.log(min([1, 2, 3])); // logs 1
 */
function min(values) {
  var smallest = Number(Infinity);
  Object.keys(values).forEach(function (i) {
    if (values[i] < smallest) {
      smallest = values[i];
    }
  });
  return smallest;
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/observer.js":
/*!******************************!*\
  !*** ./src/util/observer.js ***!
  \******************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/**
 * @typedef {Object} ListenerDescriptor
 * @property {string} name The name of the event
 * @property {function} callback The callback
 * @property {function} un The function to call to remove the listener
 */

/**
 * Observer class
 */
var Observer = /*#__PURE__*/function () {
  /**
   * Instantiate Observer
   */
  function Observer() {
    _classCallCheck(this, Observer);

    /**
     * @private
     * @todo Initialise the handlers here already and remove the conditional
     * assignment in `on()`
     */
    this._disabledEventEmissions = [];
    this.handlers = null;
  }
  /**
   * Attach a handler function for an event.
   *
   * @param {string} event Name of the event to listen to
   * @param {function} fn The callback to trigger when the event is fired
   * @return {ListenerDescriptor} The event descriptor
   */


  _createClass(Observer, [{
    key: "on",
    value: function on(event, fn) {
      var _this = this;

      if (!this.handlers) {
        this.handlers = {};
      }

      var handlers = this.handlers[event];

      if (!handlers) {
        handlers = this.handlers[event] = [];
      }

      handlers.push(fn); // Return an event descriptor

      return {
        name: event,
        callback: fn,
        un: function un(e, fn) {
          return _this.un(e, fn);
        }
      };
    }
    /**
     * Remove an event handler.
     *
     * @param {string} event Name of the event the listener that should be
     * removed listens to
     * @param {function} fn The callback that should be removed
     */

  }, {
    key: "un",
    value: function un(event, fn) {
      if (!this.handlers) {
        return;
      }

      var handlers = this.handlers[event];
      var i;

      if (handlers) {
        if (fn) {
          for (i = handlers.length - 1; i >= 0; i--) {
            if (handlers[i] == fn) {
              handlers.splice(i, 1);
            }
          }
        } else {
          handlers.length = 0;
        }
      }
    }
    /**
     * Remove all event handlers.
     */

  }, {
    key: "unAll",
    value: function unAll() {
      this.handlers = null;
    }
    /**
     * Attach a handler to an event. The handler is executed at most once per
     * event type.
     *
     * @param {string} event The event to listen to
     * @param {function} handler The callback that is only to be called once
     * @return {ListenerDescriptor} The event descriptor
     */

  }, {
    key: "once",
    value: function once(event, handler) {
      var _this2 = this;

      var fn = function fn() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }

        /*  eslint-disable no-invalid-this */
        handler.apply(_this2, args);
        /*  eslint-enable no-invalid-this */

        setTimeout(function () {
          _this2.un(event, fn);
        }, 0);
      };

      return this.on(event, fn);
    }
    /**
     * Disable firing a list of events by name. When specified, event handlers for any event type
     * passed in here will not be called.
     *
     * @since 4.0.0
     * @param {string[]} eventNames an array of event names to disable emissions for
     * @example
     * // disable seek and interaction events
     * wavesurfer.setDisabledEventEmissions(['seek', 'interaction']);
     */

  }, {
    key: "setDisabledEventEmissions",
    value: function setDisabledEventEmissions(eventNames) {
      this._disabledEventEmissions = eventNames;
    }
    /**
     * plugins borrow part of this class without calling the constructor,
     * so we have to be careful about _disabledEventEmissions
     */

  }, {
    key: "_isDisabledEventEmission",
    value: function _isDisabledEventEmission(event) {
      return this._disabledEventEmissions && this._disabledEventEmissions.includes(event);
    }
    /**
     * Manually fire an event
     *
     * @param {string} event The event to fire manually
     * @param {...any} args The arguments with which to call the listeners
     */

  }, {
    key: "fireEvent",
    value: function fireEvent(event) {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      if (!this.handlers || this._isDisabledEventEmission(event)) {
        return;
      }

      var handlers = this.handlers[event];
      handlers && handlers.forEach(function (fn) {
        fn.apply(void 0, args);
      });
    }
  }]);

  return Observer;
}();

exports.default = Observer;
module.exports = exports.default;

/***/ }),

/***/ "./src/util/orientation.js":
/*!*********************************!*\
  !*** ./src/util/orientation.js ***!
  \*********************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = withOrientation;
var verticalPropMap = {
  width: 'height',
  height: 'width',
  overflowX: 'overflowY',
  overflowY: 'overflowX',
  clientWidth: 'clientHeight',
  clientHeight: 'clientWidth',
  clientX: 'clientY',
  clientY: 'clientX',
  scrollWidth: 'scrollHeight',
  scrollLeft: 'scrollTop',
  offsetLeft: 'offsetTop',
  offsetTop: 'offsetLeft',
  offsetHeight: 'offsetWidth',
  offsetWidth: 'offsetHeight',
  left: 'top',
  right: 'bottom',
  top: 'left',
  bottom: 'right',
  borderRightStyle: 'borderBottomStyle',
  borderRightWidth: 'borderBottomWidth',
  borderRightColor: 'borderBottomColor'
};
/**
 * Convert a horizontally-oriented property name to a vertical one.
 *
 * @param {string} prop A property name
 * @param {bool} vertical Whether the element is oriented vertically
 * @returns {string} prop, converted appropriately
 */

function mapProp(prop, vertical) {
  if (Object.prototype.hasOwnProperty.call(verticalPropMap, prop)) {
    return vertical ? verticalPropMap[prop] : prop;
  } else {
    return prop;
  }
}

var isProxy = Symbol("isProxy");
/**
 * Returns an appropriately oriented object based on vertical.
 * If vertical is true, attribute getting and setting will be mapped through
 * verticalPropMap, so that e.g. getting the object's .width will give its
 * .height instead.
 * Certain methods of an oriented object will return oriented objects as well.
 * Oriented objects can't be added to the DOM directly since they are Proxy objects
 * and thus fail typechecks. Use domElement to get the actual element for this.
 *
 * @param {object} target The object to be wrapped and oriented
 * @param {bool} vertical Whether the element is oriented vertically
 * @returns {Proxy} An oriented object with attr translation via verticalAttrMap
 * @since 5.0.0
 */

function withOrientation(target, vertical) {
  if (target[isProxy]) {
    return target;
  } else {
    return new Proxy(target, {
      get: function get(obj, prop, receiver) {
        if (prop === isProxy) {
          return true;
        } else if (prop === 'domElement') {
          return obj;
        } else if (prop === 'style') {
          return withOrientation(obj.style, vertical);
        } else if (prop === 'canvas') {
          return withOrientation(obj.canvas, vertical);
        } else if (prop === 'getBoundingClientRect') {
          return function () {
            return withOrientation(obj.getBoundingClientRect.apply(obj, arguments), vertical);
          };
        } else if (prop === 'getContext') {
          return function () {
            return withOrientation(obj.getContext.apply(obj, arguments), vertical);
          };
        } else {
          var value = obj[mapProp(prop, vertical)];
          return typeof value == 'function' ? value.bind(obj) : value;
        }
      },
      set: function set(obj, prop, value) {
        obj[mapProp(prop, vertical)] = value;
        return true;
      }
    });
  }
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/prevent-click.js":
/*!***********************************!*\
  !*** ./src/util/prevent-click.js ***!
  \***********************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = preventClick;

/**
 * Stops propagation of click event and removes event listener
 *
 * @private
 * @param {object} event The click event
 */
function preventClickHandler(event) {
  event.stopPropagation();
  document.body.removeEventListener('click', preventClickHandler, true);
}
/**
 * Starts listening for click event and prevent propagation
 *
 * @param {object} values Values
 */


function preventClick(values) {
  document.body.addEventListener('click', preventClickHandler, true);
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/request-animation-frame.js":
/*!*********************************************!*\
  !*** ./src/util/request-animation-frame.js ***!
  \*********************************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

/* eslint-disable valid-jsdoc */

/**
 * Returns the `requestAnimationFrame` function for the browser, or a shim with
 * `setTimeout` if the function is not found
 *
 * @return {function} Available `requestAnimationFrame` function for the browser
 */
var _default = (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, element) {
  return setTimeout(callback, 1000 / 60);
}).bind(window);

exports.default = _default;
module.exports = exports.default;

/***/ }),

/***/ "./src/util/silence-mode.js":
/*!**********************************!*\
  !*** ./src/util/silence-mode.js ***!
  \**********************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = ignoreSilenceMode;

/**
 * Ignores device silence mode when using the `WebAudio` backend.
 *
 * Many mobile devices contain a hardware button to mute the ringtone for incoming
 * calls and messages. Unfortunately, on some platforms like iOS, this also mutes
 * wavesurfer's audio when using the `WebAudio` backend. This function creates a
 * temporary `<audio>` element that makes sure the WebAudio backend keeps playing
 * when muting the device ringer.
 *
 * @since 5.2.0
 */
function ignoreSilenceMode() {
  // Set the src to a short bit of url encoded as a silent mp3
  // NOTE The silence MP3 must be high quality, when web audio sounds are played
  // in parallel the web audio sound is mixed to match the bitrate of the html sound
  // 0.01 seconds of silence VBR220-260 Joint Stereo 859B
  var audioData = "data:audio/mpeg;base64,//uQxAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAACcQCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA//////////////////////////////////////////////////////////////////8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//sQxAADgnABGiAAQBCqgCRMAAgEAH///////////////7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq//////////////////9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ=="; // disable iOS Airplay (setting the attribute in js doesn't work)

  var tmp = document.createElement("div");
  tmp.innerHTML = '<audio x-webkit-airplay="deny"></audio>';
  var audioSilentMode = tmp.children.item(0);
  audioSilentMode.src = audioData;
  audioSilentMode.preload = "auto";
  audioSilentMode.type = "audio/mpeg";
  audioSilentMode.disableRemotePlayback = true; // play

  audioSilentMode.play(); // cleanup

  audioSilentMode.remove();
  tmp.remove();
}

module.exports = exports.default;

/***/ }),

/***/ "./src/util/style.js":
/*!***************************!*\
  !*** ./src/util/style.js ***!
  \***************************/
/***/ ((module, exports) => {

"use strict";


Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = style;

/**
 * Apply a map of styles to an element
 *
 * @param {HTMLElement} el The element that the styles will be applied to
 * @param {Object} styles The map of propName: attribute, both are used as-is
 *
 * @return {HTMLElement} el
 */
function style(el, styles) {
  Object.keys(styles).forEach(function (prop) {
    if (el.style[prop] !== styles[prop]) {
      el.style[prop] = styles[prop];
    }
  });
  return el;
}

module.exports = exports.default;

/***/ }),

/***/ "./src/wavesurfer.js":
/*!***************************!*\
  !*** ./src/wavesurfer.js ***!
  \***************************/
/***/ ((module, exports, __nested_webpack_require_117085__) => {

"use strict";


function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

var util = _interopRequireWildcard(__nested_webpack_require_117085__(/*! ./util */ "./src/util/index.js"));

var _drawer = _interopRequireDefault(__nested_webpack_require_117085__(/*! ./drawer.multicanvas */ "./src/drawer.multicanvas.js"));

var _webaudio = _interopRequireDefault(__nested_webpack_require_117085__(/*! ./webaudio */ "./src/webaudio.js"));

var _mediaelement = _interopRequireDefault(__nested_webpack_require_117085__(/*! ./mediaelement */ "./src/mediaelement.js"));

var _peakcache = _interopRequireDefault(__nested_webpack_require_117085__(/*! ./peakcache */ "./src/peakcache.js"));

var _mediaelementWebaudio = _interopRequireDefault(__nested_webpack_require_117085__(/*! ./mediaelement-webaudio */ "./src/mediaelement-webaudio.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

/*
 * This work is licensed under a BSD-3-Clause License.
 */

/** @external {HTMLElement} https://developer.mozilla.org/en/docs/Web/API/HTMLElement */

/** @external {OfflineAudioContext} https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext */

/** @external {File} https://developer.mozilla.org/en-US/docs/Web/API/File */

/** @external {Blob} https://developer.mozilla.org/en-US/docs/Web/API/Blob */

/** @external {CanvasRenderingContext2D} https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D */

/** @external {MediaStreamConstraints} https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints */

/** @external {AudioNode} https://developer.mozilla.org/de/docs/Web/API/AudioNode */

/**
 * @typedef {Object} WavesurferParams
 * @property {AudioContext} audioContext=null Use your own previously
 * initialized AudioContext or leave blank.
 * @property {number} audioRate=1 Speed at which to play audio. Lower number is
 * slower.
 * @property {ScriptProcessorNode} audioScriptProcessor=null Use your own previously
 * initialized ScriptProcessorNode or leave blank.
 * @property {boolean} autoCenter=true If a scrollbar is present, center the
 * waveform on current progress
 * @property {number} autoCenterRate=5 If autoCenter is active, rate at which the
 * waveform is centered
 * @property {boolean} autoCenterImmediately=false If autoCenter is active, immediately
 * center waveform on current progress
 * @property {string} backend='WebAudio' `'WebAudio'|'MediaElement'|'MediaElementWebAudio'` In most cases
 * you don't have to set this manually. MediaElement is a fallback for unsupported browsers.
 * MediaElementWebAudio allows to use WebAudio API also with big audio files, loading audio like with
 * MediaElement backend (HTML5 audio tag). You have to use the same methods of MediaElement backend for loading and
 * playback, giving also peaks, so the audio data are not decoded. In this way you can use WebAudio features, like filters,
 * also with audio with big duration. For example:
 * ` wavesurfer.load(url | HTMLMediaElement, peaks, preload, duration);
 *   wavesurfer.play();
 *   wavesurfer.setFilter(customFilter);
 * `
 * @property {string} backgroundColor=null Change background color of the
 * waveform container.
 * @property {number} barHeight=1 The height of the wave bars.
 * @property {number} barRadius=0 The radius of the wave bars. Makes bars rounded
 * @property {number} barGap=null The optional spacing between bars of the wave,
 * if not provided will be calculated in legacy format.
 * @property {number} barWidth=null Draw the waveform using bars.
 * @property {number} barMinHeight=null If specified, draw at least a bar of this height,
 * eliminating waveform gaps
 * @property {boolean} closeAudioContext=false Close and nullify all audio
 * contexts when the destroy method is called.
 * @property {!string|HTMLElement} container CSS selector or HTML element where
 * the waveform should be drawn. This is the only required parameter.
 * @property {string} cursorColor='#333' The fill color of the cursor indicating
 * the playhead position.
 * @property {number} cursorWidth=1 Measured in pixels.
 * @property {object} drawingContextAttributes={desynchronized: false} Drawing context
 * attributes.
 * @property {number} duration=null Optional audio length so pre-rendered peaks
 * can be display immediately for example.
 * @property {boolean} fillParent=true Whether to fill the entire container or
 * draw only according to `minPxPerSec`.
 * @property {boolean} forceDecode=false Force decoding of audio using web audio
 * when zooming to get a more detailed waveform.
 * @property {number} height=128 The height of the waveform. Measured in
 * pixels.
 * @property {boolean} hideScrollbar=false Whether to hide the horizontal
 * scrollbar when one would normally be shown.
 * @property {boolean} ignoreSilenceMode=false If true, ignores device silence mode
 * when using the `WebAudio` backend.
 * @property {boolean} interact=true Whether the mouse interaction will be
 * enabled at initialization. You can switch this parameter at any time later
 * on.
 * @property {boolean} loopSelection=true (Use with regions plugin) Enable
 * looping of selected regions
 * @property {number} maxCanvasWidth=4000 Maximum width of a single canvas in
 * pixels, excluding a small overlap (2 * `pixelRatio`, rounded up to the next
 * even integer). If the waveform is longer than this value, additional canvases
 * will be used to render the waveform, which is useful for very large waveforms
 * that may be too wide for browsers to draw on a single canvas.
 * @property {boolean} mediaControls=false (Use with backend `MediaElement` or `MediaElementWebAudio`)
 * this enables the native controls for the media element
 * @property {string} mediaType='audio' (Use with backend `MediaElement` or `MediaElementWebAudio`)
 * `'audio'|'video'` ('video' only for `MediaElement`)
 * @property {number} minPxPerSec=20 Minimum number of pixels per second of
 * audio.
 * @property {boolean} normalize=false If true, normalize by the maximum peak
 * instead of 1.0.
 * @property {boolean} partialRender=false Use the PeakCache to improve
 * rendering speed of large waveforms
 * @property {number} pixelRatio=window.devicePixelRatio The pixel ratio used to
 * calculate display
 * @property {PluginDefinition[]} plugins=[] An array of plugin definitions to
 * register during instantiation, they will be directly initialised unless they
 * are added with the `deferInit` property set to true.
 * @property {string} progressColor='#555' The fill color of the part of the
 * waveform behind the cursor. When `progressColor` and `waveColor` are the same
 * the progress wave is not rendered at all.
 * @property {boolean} removeMediaElementOnDestroy=true Set to false to keep the
 * media element in the DOM when the player is destroyed. This is useful when
 * reusing an existing media element via the `loadMediaElement` method.
 * @property {Object} renderer=MultiCanvas Can be used to inject a custom
 * renderer.
 * @property {boolean|number} responsive=false If set to `true` resize the
 * waveform, when the window is resized. This is debounced with a `100ms`
 * timeout by default. If this parameter is a number it represents that timeout.
 * @property {boolean} rtl=false If set to `true`, renders waveform from
 * right-to-left.
 * @property {boolean} scrollParent=false Whether to scroll the container with a
 * lengthy waveform. Otherwise the waveform is shrunk to the container width
 * (see fillParent).
 * @property {number} skipLength=2 Number of seconds to skip with the
 * skipForward() and skipBackward() methods.
 * @property {boolean} splitChannels=false Render with separate waveforms for
 * the channels of the audio
 * @property {SplitChannelOptions} splitChannelsOptions={} Options for splitChannel rendering
 * @property {boolean} vertical=false Render the waveform vertically instead of horizontally.
 * @property {string} waveColor='#999' The fill color of the waveform after the
 * cursor.
 * @property {object} xhr={} XHR options. For example:
 * `let xhr = {
 *     cache: 'default',
 *     mode: 'cors',
 *     method: 'GET',
 *     credentials: 'same-origin',
 *     redirect: 'follow',
 *     referrer: 'client',
 *     requestHeaders: [
 *         {
 *             key: 'Authorization',
 *             value: 'my-token'
 *         }
 *     ]
 * };`
 */

/**
 * @typedef {Object} PluginDefinition
 * @desc The Object used to describe a plugin
 * @example wavesurfer.addPlugin(pluginDefinition);
 * @property {string} name The name of the plugin, the plugin instance will be
 * added as a property to the wavesurfer instance under this name
 * @property {?Object} staticProps The properties that should be added to the
 * wavesurfer instance as static properties
 * @property {?boolean} deferInit Don't initialise plugin
 * automatically
 * @property {Object} params={} The plugin parameters, they are the first parameter
 * passed to the plugin class constructor function
 * @property {PluginClass} instance The plugin instance factory, is called with
 * the dependency specified in extends. Returns the plugin class.
 */

/**
 * @typedef {Object} SplitChannelOptions
 * @desc parameters applied when splitChannels option is true
 * @property {boolean} overlay=false determines whether channels are rendered on top of each other or on separate tracks
 * @property {object} channelColors={} object describing color for each channel. Example:
 * {
 *     0: {
 *         progressColor: 'green',
 *         waveColor: 'pink'
 *     },
 *     1: {
 *         progressColor: 'orange',
 *         waveColor: 'purple'
 *     }
 * }
 * @property {number[]} filterChannels=[] indexes of channels to be hidden from rendering
 * @property {boolean} relativeNormalization=false determines whether
 * normalization is done per channel or maintains proportionality between
 * channels. Only applied when normalize and splitChannels are both true.
 * @since 4.3.0
 */

/**
 * @interface PluginClass
 *
 * @desc This is the interface which is implemented by all plugin classes. Note
 * that this only turns into an observer after being passed through
 * `wavesurfer.addPlugin`.
 *
 * @extends {Observer}
 */
var PluginClass = /*#__PURE__*/function () {
  /**
   * Construct the plugin
   *
   * @param {Object} params={} The plugin params (specific to the plugin)
   * @param {Object} ws The wavesurfer instance
   */
  function PluginClass(params, ws) {
    _classCallCheck(this, PluginClass);
  }
  /**
   * Initialise the plugin
   *
   * Start doing something. This is called by
   * `wavesurfer.initPlugin(pluginName)`
   */


  _createClass(PluginClass, [{
    key: "create",
    value:
    /**
     * Plugin definition factory
     *
     * This function must be used to create a plugin definition which can be
     * used by wavesurfer to correctly instantiate the plugin.
     *
     * It returns a `PluginDefinition` object representing the plugin.
     *
     * @param {Object} params={} The plugin params (specific to the plugin)
     */
    function create(params) {}
  }, {
    key: "init",
    value: function init() {}
    /**
     * Destroy the plugin instance
     *
     * Stop doing something. This is called by
     * `wavesurfer.destroyPlugin(pluginName)`
     */

  }, {
    key: "destroy",
    value: function destroy() {}
  }]);

  return PluginClass;
}();
/**
 * WaveSurfer core library class
 *
 * @extends {Observer}
 * @example
 * const params = {
 *   container: '#waveform',
 *   waveColor: 'violet',
 *   progressColor: 'purple'
 * };
 *
 * // initialise like this
 * const wavesurfer = WaveSurfer.create(params);
 *
 * // or like this ...
 * const wavesurfer = new WaveSurfer(params);
 * wavesurfer.init();
 *
 * // load audio file
 * wavesurfer.load('example/media/demo.wav');
 */


var WaveSurfer = /*#__PURE__*/function (_util$Observer) {
  _inherits(WaveSurfer, _util$Observer);

  var _super = _createSuper(WaveSurfer);

  /**
   * Initialise wavesurfer instance
   *
   * @param {WavesurferParams} params Instantiation options for wavesurfer
   * @example
   * const wavesurfer = new WaveSurfer(params);
   * @returns {this} Wavesurfer instance
   */
  function WaveSurfer(params) {
    var _this;

    _classCallCheck(this, WaveSurfer);

    _this = _super.call(this);
    /**
     * Extract relevant parameters (or defaults)
     * @private
     */

    _this.defaultParams = {
      audioContext: null,
      audioScriptProcessor: null,
      audioRate: 1,
      autoCenter: true,
      autoCenterRate: 5,
      autoCenterImmediately: false,
      backend: 'WebAudio',
      backgroundColor: null,
      barHeight: 1,
      barRadius: 0,
      barGap: null,
      barMinHeight: null,
      container: null,
      cursorColor: '#333',
      cursorWidth: 1,
      dragSelection: true,
      drawingContextAttributes: {
        // Boolean that hints the user agent to reduce the latency
        // by desynchronizing the canvas paint cycle from the event
        // loop
        desynchronized: false
      },
      duration: null,
      fillParent: true,
      forceDecode: false,
      height: 128,
      hideScrollbar: false,
      ignoreSilenceMode: false,
      interact: true,
      loopSelection: true,
      maxCanvasWidth: 4000,
      mediaContainer: null,
      mediaControls: false,
      mediaType: 'audio',
      minPxPerSec: 20,
      normalize: false,
      partialRender: false,
      pixelRatio: window.devicePixelRatio || screen.deviceXDPI / screen.logicalXDPI,
      plugins: [],
      progressColor: '#555',
      removeMediaElementOnDestroy: true,
      renderer: _drawer.default,
      responsive: false,
      rtl: false,
      scrollParent: false,
      skipLength: 2,
      splitChannels: false,
      splitChannelsOptions: {
        overlay: false,
        channelColors: {},
        filterChannels: [],
        relativeNormalization: false
      },
      vertical: false,
      waveColor: '#999',
      xhr: {}
    };
    _this.backends = {
      MediaElement: _mediaelement.default,
      WebAudio: _webaudio.default,
      MediaElementWebAudio: _mediaelementWebaudio.default
    };
    _this.util = util;
    _this.params = Object.assign({}, _this.defaultParams, params);
    _this.params.splitChannelsOptions = Object.assign({}, _this.defaultParams.splitChannelsOptions, params.splitChannelsOptions);
    /** @private */

    _this.container = 'string' == typeof params.container ? document.querySelector(_this.params.container) : _this.params.container;

    if (!_this.container) {
      throw new Error('Container element not found');
    }

    if (_this.params.mediaContainer == null) {
      /** @private */
      _this.mediaContainer = _this.container;
    } else if (typeof _this.params.mediaContainer == 'string') {
      /** @private */
      _this.mediaContainer = document.querySelector(_this.params.mediaContainer);
    } else {
      /** @private */
      _this.mediaContainer = _this.params.mediaContainer;
    }

    if (!_this.mediaContainer) {
      throw new Error('Media Container element not found');
    }

    if (_this.params.maxCanvasWidth <= 1) {
      throw new Error('maxCanvasWidth must be greater than 1');
    } else if (_this.params.maxCanvasWidth % 2 == 1) {
      throw new Error('maxCanvasWidth must be an even number');
    }

    if (_this.params.rtl === true) {
      if (_this.params.vertical === true) {
        util.style(_this.container, {
          transform: 'rotateX(180deg)'
        });
      } else {
        util.style(_this.container, {
          transform: 'rotateY(180deg)'
        });
      }
    }

    if (_this.params.backgroundColor) {
      _this.setBackgroundColor(_this.params.backgroundColor);
    }
    /**
     * @private Used to save the current volume when muting so we can
     * restore once unmuted
     * @type {number}
     */


    _this.savedVolume = 0;
    /**
     * @private The current muted state
     * @type {boolean}
     */

    _this.isMuted = false;
    /**
     * @private Will hold a list of event descriptors that need to be
     * canceled on subsequent loads of audio
     * @type {Object[]}
     */

    _this.tmpEvents = [];
    /**
     * @private Holds any running audio downloads
     * @type {Observer}
     */

    _this.currentRequest = null;
    /** @private */

    _this.arraybuffer = null;
    /** @private */

    _this.drawer = null;
    /** @private */

    _this.backend = null;
    /** @private */

    _this.peakCache = null; // cache constructor objects

    if (typeof _this.params.renderer !== 'function') {
      throw new Error('Renderer parameter is invalid');
    }
    /**
     * @private The uninitialised Drawer class
     */


    _this.Drawer = _this.params.renderer;
    /**
     * @private The uninitialised Backend class
     */
    // Back compat

    if (_this.params.backend == 'AudioElement') {
      _this.params.backend = 'MediaElement';
    }

    if ((_this.params.backend == 'WebAudio' || _this.params.backend === 'MediaElementWebAudio') && !_webaudio.default.prototype.supportsWebAudio.call(null)) {
      _this.params.backend = 'MediaElement';
    }

    _this.Backend = _this.backends[_this.params.backend];
    /**
     * @private map of plugin names that are currently initialised
     */

    _this.initialisedPluginList = {};
    /** @private */

    _this.isDestroyed = false;
    /**
     * Get the current ready status.
     *
     * @example const isReady = wavesurfer.isReady;
     * @return {boolean}
     */

    _this.isReady = false; // responsive debounced event listener. If this.params.responsive is not
    // set, this is never called. Use 100ms or this.params.responsive as
    // timeout for the debounce function.

    var prevWidth = 0;
    _this._onResize = util.debounce(function () {
      if (prevWidth != _this.drawer.wrapper.clientWidth && !_this.params.scrollParent) {
        prevWidth = _this.drawer.wrapper.clientWidth;

        _this.drawer.fireEvent('redraw');
      }
    }, typeof _this.params.responsive === 'number' ? _this.params.responsive : 100);
    return _possibleConstructorReturn(_this, _assertThisInitialized(_this));
  }
  /**
   * Initialise the wave
   *
   * @example
   * var wavesurfer = new WaveSurfer(params);
   * wavesurfer.init();
   * @return {this} The wavesurfer instance
   */


  _createClass(WaveSurfer, [{
    key: "init",
    value: function init() {
      this.registerPlugins(this.params.plugins);
      this.createDrawer();
      this.createBackend();
      this.createPeakCache();
      return this;
    }
    /**
     * Add and initialise array of plugins (if `plugin.deferInit` is falsey),
     * this function is called in the init function of wavesurfer
     *
     * @param {PluginDefinition[]} plugins An array of plugin definitions
     * @emits {WaveSurfer#plugins-registered} Called with the array of plugin definitions
     * @return {this} The wavesurfer instance
     */

  }, {
    key: "registerPlugins",
    value: function registerPlugins(plugins) {
      var _this2 = this;

      // first instantiate all the plugins
      plugins.forEach(function (plugin) {
        return _this2.addPlugin(plugin);
      }); // now run the init functions

      plugins.forEach(function (plugin) {
        // call init function of the plugin if deferInit is falsey
        // in that case you would manually use initPlugins()
        if (!plugin.deferInit) {
          _this2.initPlugin(plugin.name);
        }
      });
      this.fireEvent('plugins-registered', plugins);
      return this;
    }
    /**
     * Get a map of plugin names that are currently initialised
     *
     * @example wavesurfer.getPlugins();
     * @return {Object} Object with plugin names
     */

  }, {
    key: "getActivePlugins",
    value: function getActivePlugins() {
      return this.initialisedPluginList;
    }
    /**
     * Add a plugin object to wavesurfer
     *
     * @param {PluginDefinition} plugin A plugin definition
     * @emits {WaveSurfer#plugin-added} Called with the name of the plugin that was added
     * @example wavesurfer.addPlugin(WaveSurfer.minimap());
     * @return {this} The wavesurfer instance
     */

  }, {
    key: "addPlugin",
    value: function addPlugin(plugin) {
      var _this3 = this;

      if (!plugin.name) {
        throw new Error('Plugin does not have a name!');
      }

      if (!plugin.instance) {
        throw new Error("Plugin ".concat(plugin.name, " does not have an instance property!"));
      } // staticProps properties are applied to wavesurfer instance


      if (plugin.staticProps) {
        Object.keys(plugin.staticProps).forEach(function (pluginStaticProp) {
          /**
           * Properties defined in a plugin definition's `staticProps` property are added as
           * staticProps properties of the WaveSurfer instance
           */
          _this3[pluginStaticProp] = plugin.staticProps[pluginStaticProp];
        });
      }

      var Instance = plugin.instance; // turn the plugin instance into an observer

      var observerPrototypeKeys = Object.getOwnPropertyNames(util.Observer.prototype);
      observerPrototypeKeys.forEach(function (key) {
        Instance.prototype[key] = util.Observer.prototype[key];
      });
      /**
       * Instantiated plugin classes are added as a property of the wavesurfer
       * instance
       * @type {Object}
       */

      this[plugin.name] = new Instance(plugin.params || {}, this);
      this.fireEvent('plugin-added', plugin.name);
      return this;
    }
    /**
     * Initialise a plugin
     *
     * @param {string} name A plugin name
     * @emits WaveSurfer#plugin-initialised
     * @example wavesurfer.initPlugin('minimap');
     * @return {this} The wavesurfer instance
     */

  }, {
    key: "initPlugin",
    value: function initPlugin(name) {
      if (!this[name]) {
        throw new Error("Plugin ".concat(name, " has not been added yet!"));
      }

      if (this.initialisedPluginList[name]) {
        // destroy any already initialised plugins
        this.destroyPlugin(name);
      }

      this[name].init();
      this.initialisedPluginList[name] = true;
      this.fireEvent('plugin-initialised', name);
      return this;
    }
    /**
     * Destroy a plugin
     *
     * @param {string} name A plugin name
     * @emits WaveSurfer#plugin-destroyed
     * @example wavesurfer.destroyPlugin('minimap');
     * @returns {this} The wavesurfer instance
     */

  }, {
    key: "destroyPlugin",
    value: function destroyPlugin(name) {
      if (!this[name]) {
        throw new Error("Plugin ".concat(name, " has not been added yet and cannot be destroyed!"));
      }

      if (!this.initialisedPluginList[name]) {
        throw new Error("Plugin ".concat(name, " is not active and cannot be destroyed!"));
      }

      if (typeof this[name].destroy !== 'function') {
        throw new Error("Plugin ".concat(name, " does not have a destroy function!"));
      }

      this[name].destroy();
      delete this.initialisedPluginList[name];
      this.fireEvent('plugin-destroyed', name);
      return this;
    }
    /**
     * Destroy all initialised plugins. Convenience function to use when
     * wavesurfer is removed
     *
     * @private
     */

  }, {
    key: "destroyAllPlugins",
    value: function destroyAllPlugins() {
      var _this4 = this;

      Object.keys(this.initialisedPluginList).forEach(function (name) {
        return _this4.destroyPlugin(name);
      });
    }
    /**
     * Create the drawer and draw the waveform
     *
     * @private
     * @emits WaveSurfer#drawer-created
     */

  }, {
    key: "createDrawer",
    value: function createDrawer() {
      var _this5 = this;

      this.drawer = new this.Drawer(this.container, this.params);
      this.drawer.init();
      this.fireEvent('drawer-created', this.drawer);

      if (this.params.responsive !== false) {
        window.addEventListener('resize', this._onResize, true);
        window.addEventListener('orientationchange', this._onResize, true);
      }

      this.drawer.on('redraw', function () {
        _this5.drawBuffer();

        _this5.drawer.progress(_this5.backend.getPlayedPercents());
      }); // Click-to-seek

      this.drawer.on('click', function (e, progress) {
        setTimeout(function () {
          return _this5.seekTo(progress);
        }, 0);
      }); // Relay the scroll event from the drawer

      this.drawer.on('scroll', function (e) {
        if (_this5.params.partialRender) {
          _this5.drawBuffer();
        }

        _this5.fireEvent('scroll', e);
      });
    }
    /**
     * Create the backend
     *
     * @private
     * @emits WaveSurfer#backend-created
     */

  }, {
    key: "createBackend",
    value: function createBackend() {
      var _this6 = this;

      if (this.backend) {
        this.backend.destroy();
      }

      this.backend = new this.Backend(this.params);
      this.backend.init();
      this.fireEvent('backend-created', this.backend);
      this.backend.on('finish', function () {
        _this6.drawer.progress(_this6.backend.getPlayedPercents());

        _this6.fireEvent('finish');
      });
      this.backend.on('play', function () {
        return _this6.fireEvent('play');
      });
      this.backend.on('pause', function () {
        return _this6.fireEvent('pause');
      });
      this.backend.on('audioprocess', function (time) {
        _this6.drawer.progress(_this6.backend.getPlayedPercents());

        _this6.fireEvent('audioprocess', time);
      }); // only needed for MediaElement and MediaElementWebAudio backend

      if (this.params.backend === 'MediaElement' || this.params.backend === 'MediaElementWebAudio') {
        this.backend.on('seek', function () {
          _this6.drawer.progress(_this6.backend.getPlayedPercents());
        });
        this.backend.on('volume', function () {
          var newVolume = _this6.getVolume();

          _this6.fireEvent('volume', newVolume);

          if (_this6.backend.isMuted !== _this6.isMuted) {
            _this6.isMuted = _this6.backend.isMuted;

            _this6.fireEvent('mute', _this6.isMuted);
          }
        });
      }
    }
    /**
     * Create the peak cache
     *
     * @private
     */

  }, {
    key: "createPeakCache",
    value: function createPeakCache() {
      if (this.params.partialRender) {
        this.peakCache = new _peakcache.default();
      }
    }
    /**
     * Get the duration of the audio clip
     *
     * @example const duration = wavesurfer.getDuration();
     * @return {number} Duration in seconds
     */

  }, {
    key: "getDuration",
    value: function getDuration() {
      return this.backend.getDuration();
    }
    /**
     * Get the current playback position
     *
     * @example const currentTime = wavesurfer.getCurrentTime();
     * @return {number} Playback position in seconds
     */

  }, {
    key: "getCurrentTime",
    value: function getCurrentTime() {
      return this.backend.getCurrentTime();
    }
    /**
     * Set the current play time in seconds.
     *
     * @param {number} seconds A positive number in seconds. E.g. 10 means 10
     * seconds, 60 means 1 minute
     */

  }, {
    key: "setCurrentTime",
    value: function setCurrentTime(seconds) {
      if (seconds >= this.getDuration()) {
        this.seekTo(1);
      } else {
        this.seekTo(seconds / this.getDuration());
      }
    }
    /**
     * Starts playback from the current position. Optional start and end
     * measured in seconds can be used to set the range of audio to play.
     *
     * @param {?number} start Position to start at
     * @param {?number} end Position to end at
     * @emits WaveSurfer#interaction
     * @return {Promise} Result of the backend play method
     * @example
     * // play from second 1 to 5
     * wavesurfer.play(1, 5);
     */

  }, {
    key: "play",
    value: function play(start, end) {
      var _this7 = this;

      if (this.params.ignoreSilenceMode) {
        // ignores device hardware silence mode
        util.ignoreSilenceMode();
      }

      this.fireEvent('interaction', function () {
        return _this7.play(start, end);
      });
      return this.backend.play(start, end);
    }
    /**
     * Set a point in seconds for playback to stop at.
     *
     * @param {number} position Position (in seconds) to stop at
     * @version 3.3.0
     */

  }, {
    key: "setPlayEnd",
    value: function setPlayEnd(position) {
      this.backend.setPlayEnd(position);
    }
    /**
     * Stops and pauses playback
     *
     * @example wavesurfer.pause();
     * @return {Promise} Result of the backend pause method
     */

  }, {
    key: "pause",
    value: function pause() {
      if (!this.backend.isPaused()) {
        return this.backend.pause();
      }
    }
    /**
     * Toggle playback
     *
     * @example wavesurfer.playPause();
     * @return {Promise} Result of the backend play or pause method
     */

  }, {
    key: "playPause",
    value: function playPause() {
      return this.backend.isPaused() ? this.play() : this.pause();
    }
    /**
     * Get the current playback state
     *
     * @example const isPlaying = wavesurfer.isPlaying();
     * @return {boolean} False if paused, true if playing
     */

  }, {
    key: "isPlaying",
    value: function isPlaying() {
      return !this.backend.isPaused();
    }
    /**
     * Skip backward
     *
     * @param {?number} seconds Amount to skip back, if not specified `skipLength`
     * is used
     * @example wavesurfer.skipBackward();
     */

  }, {
    key: "skipBackward",
    value: function skipBackward(seconds) {
      this.skip(-seconds || -this.params.skipLength);
    }
    /**
     * Skip forward
     *
     * @param {?number} seconds Amount to skip back, if not specified `skipLength`
     * is used
     * @example wavesurfer.skipForward();
     */

  }, {
    key: "skipForward",
    value: function skipForward(seconds) {
      this.skip(seconds || this.params.skipLength);
    }
    /**
     * Skip a number of seconds from the current position (use a negative value
     * to go backwards).
     *
     * @param {number} offset Amount to skip back or forwards
     * @example
     * // go back 2 seconds
     * wavesurfer.skip(-2);
     */

  }, {
    key: "skip",
    value: function skip(offset) {
      var duration = this.getDuration() || 1;
      var position = this.getCurrentTime() || 0;
      position = Math.max(0, Math.min(duration, position + (offset || 0)));
      this.seekAndCenter(position / duration);
    }
    /**
     * Seeks to a position and centers the view
     *
     * @param {number} progress Between 0 (=beginning) and 1 (=end)
     * @example
     * // seek and go to the middle of the audio
     * wavesurfer.seekTo(0.5);
     */

  }, {
    key: "seekAndCenter",
    value: function seekAndCenter(progress) {
      this.seekTo(progress);
      this.drawer.recenter(progress);
    }
    /**
     * Seeks to a position
     *
     * @param {number} progress Between 0 (=beginning) and 1 (=end)
     * @emits WaveSurfer#interaction
     * @emits WaveSurfer#seek
     * @example
     * // seek to the middle of the audio
     * wavesurfer.seekTo(0.5);
     */

  }, {
    key: "seekTo",
    value: function seekTo(progress) {
      var _this8 = this;

      // return an error if progress is not a number between 0 and 1
      if (typeof progress !== 'number' || !isFinite(progress) || progress < 0 || progress > 1) {
        throw new Error('Error calling wavesurfer.seekTo, parameter must be a number between 0 and 1!');
      }

      this.fireEvent('interaction', function () {
        return _this8.seekTo(progress);
      });
      var isWebAudioBackend = this.params.backend === 'WebAudio';
      var paused = this.backend.isPaused();

      if (isWebAudioBackend && !paused) {
        this.backend.pause();
      } // avoid small scrolls while paused seeking


      var oldScrollParent = this.params.scrollParent;
      this.params.scrollParent = false;
      this.backend.seekTo(progress * this.getDuration());
      this.drawer.progress(progress);

      if (isWebAudioBackend && !paused) {
        this.backend.play();
      }

      this.params.scrollParent = oldScrollParent;
      this.fireEvent('seek', progress);
    }
    /**
     * Stops and goes to the beginning.
     *
     * @example wavesurfer.stop();
     */

  }, {
    key: "stop",
    value: function stop() {
      this.pause();
      this.seekTo(0);
      this.drawer.progress(0);
    }
    /**
     * Sets the ID of the audio device to use for output and returns a Promise.
     *
     * @param {string} deviceId String value representing underlying output
     * device
     * @returns {Promise} `Promise` that resolves to `undefined` when there are
     * no errors detected.
     */

  }, {
    key: "setSinkId",
    value: function setSinkId(deviceId) {
      return this.backend.setSinkId(deviceId);
    }
    /**
     * Set the playback volume.
     *
     * @param {number} newVolume A value between 0 and 1, 0 being no
     * volume and 1 being full volume.
     * @emits WaveSurfer#volume
     */

  }, {
    key: "setVolume",
    value: function setVolume(newVolume) {
      this.backend.setVolume(newVolume);
      this.fireEvent('volume', newVolume);
    }
    /**
     * Get the playback volume.
     *
     * @return {number} A value between 0 and 1, 0 being no
     * volume and 1 being full volume.
     */

  }, {
    key: "getVolume",
    value: function getVolume() {
      return this.backend.getVolume();
    }
    /**
     * Set the playback rate.
     *
     * @param {number} rate A positive number. E.g. 0.5 means half the normal
     * speed, 2 means double speed and so on.
     * @example wavesurfer.setPlaybackRate(2);
     */

  }, {
    key: "setPlaybackRate",
    value: function setPlaybackRate(rate) {
      this.backend.setPlaybackRate(rate);
    }
    /**
     * Get the playback rate.
     *
     * @return {number} The current playback rate.
     */

  }, {
    key: "getPlaybackRate",
    value: function getPlaybackRate() {
      return this.backend.getPlaybackRate();
    }
    /**
     * Toggle the volume on and off. If not currently muted it will save the
     * current volume value and turn the volume off. If currently muted then it
     * will restore the volume to the saved value, and then rest the saved
     * value.
     *
     * @example wavesurfer.toggleMute();
     */

  }, {
    key: "toggleMute",
    value: function toggleMute() {
      this.setMute(!this.isMuted);
    }
    /**
     * Enable or disable muted audio
     *
     * @param {boolean} mute Specify `true` to mute audio.
     * @emits WaveSurfer#volume
     * @emits WaveSurfer#mute
     * @example
     * // unmute
     * wavesurfer.setMute(false);
     * console.log(wavesurfer.getMute()) // logs false
     */

  }, {
    key: "setMute",
    value: function setMute(mute) {
      // ignore all muting requests if the audio is already in that state
      if (mute === this.isMuted) {
        this.fireEvent('mute', this.isMuted);
        return;
      }

      if (this.backend.setMute) {
        // Backends such as the MediaElement backend have their own handling
        // of mute, let them handle it.
        this.backend.setMute(mute);
        this.isMuted = mute;
      } else {
        if (mute) {
          // If currently not muted then save current volume,
          // turn off the volume and update the mute properties
          this.savedVolume = this.backend.getVolume();
          this.backend.setVolume(0);
          this.isMuted = true;
          this.fireEvent('volume', 0);
        } else {
          // If currently muted then restore to the saved volume
          // and update the mute properties
          this.backend.setVolume(this.savedVolume);
          this.isMuted = false;
          this.fireEvent('volume', this.savedVolume);
        }
      }

      this.fireEvent('mute', this.isMuted);
    }
    /**
     * Get the current mute status.
     *
     * @example const isMuted = wavesurfer.getMute();
     * @return {boolean} Current mute status
     */

  }, {
    key: "getMute",
    value: function getMute() {
      return this.isMuted;
    }
    /**
     * Get the list of current set filters as an array.
     *
     * Filters must be set with setFilters method first
     *
     * @return {array} List of enabled filters
     */

  }, {
    key: "getFilters",
    value: function getFilters() {
      return this.backend.filters || [];
    }
    /**
     * Toggles `scrollParent` and redraws
     *
     * @example wavesurfer.toggleScroll();
     */

  }, {
    key: "toggleScroll",
    value: function toggleScroll() {
      this.params.scrollParent = !this.params.scrollParent;
      this.drawBuffer();
    }
    /**
     * Toggle mouse interaction
     *
     * @example wavesurfer.toggleInteraction();
     */

  }, {
    key: "toggleInteraction",
    value: function toggleInteraction() {
      this.params.interact = !this.params.interact;
    }
    /**
     * Get the fill color of the waveform after the cursor.
     *
     * @return {string} A CSS color string.
     */

  }, {
    key: "getWaveColor",
    value: function getWaveColor() {
      return this.params.waveColor;
    }
    /**
     * Set the fill color of the waveform after the cursor.
     *
     * @param {string} color A CSS color string.
     * @example wavesurfer.setWaveColor('#ddd');
     */

  }, {
    key: "setWaveColor",
    value: function setWaveColor(color) {
      this.params.waveColor = color;
      this.drawBuffer();
    }
    /**
     * Get the fill color of the waveform behind the cursor.
     *
     * @return {string} A CSS color string.
     */

  }, {
    key: "getProgressColor",
    value: function getProgressColor() {
      return this.params.progressColor;
    }
    /**
     * Set the fill color of the waveform behind the cursor.
     *
     * @param {string} color A CSS color string.
     * @example wavesurfer.setProgressColor('#400');
     */

  }, {
    key: "setProgressColor",
    value: function setProgressColor(color) {
      this.params.progressColor = color;
      this.drawBuffer();
    }
    /**
     * Get the background color of the waveform container.
     *
     * @return {string} A CSS color string.
     */

  }, {
    key: "getBackgroundColor",
    value: function getBackgroundColor() {
      return this.params.backgroundColor;
    }
    /**
     * Set the background color of the waveform container.
     *
     * @param {string} color A CSS color string.
     * @example wavesurfer.setBackgroundColor('#FF00FF');
     */

  }, {
    key: "setBackgroundColor",
    value: function setBackgroundColor(color) {
      this.params.backgroundColor = color;
      util.style(this.container, {
        background: this.params.backgroundColor
      });
    }
    /**
     * Get the fill color of the cursor indicating the playhead
     * position.
     *
     * @return {string} A CSS color string.
     */

  }, {
    key: "getCursorColor",
    value: function getCursorColor() {
      return this.params.cursorColor;
    }
    /**
     * Set the fill color of the cursor indicating the playhead
     * position.
     *
     * @param {string} color A CSS color string.
     * @example wavesurfer.setCursorColor('#222');
     */

  }, {
    key: "setCursorColor",
    value: function setCursorColor(color) {
      this.params.cursorColor = color;
      this.drawer.updateCursor();
    }
    /**
     * Get the height of the waveform.
     *
     * @return {number} Height measured in pixels.
     */

  }, {
    key: "getHeight",
    value: function getHeight() {
      return this.params.height;
    }
    /**
     * Set the height of the waveform.
     *
     * @param {number} height Height measured in pixels.
     * @example wavesurfer.setHeight(200);
     */

  }, {
    key: "setHeight",
    value: function setHeight(height) {
      this.params.height = height;
      this.drawer.setHeight(height * this.params.pixelRatio);
      this.drawBuffer();
    }
    /**
     * Hide channels from being drawn on the waveform if splitting channels.
     *
     * For example, if we want to draw only the peaks for the right stereo channel:
     *
     * const wavesurfer = new WaveSurfer.create({...splitChannels: true});
     * wavesurfer.load('stereo_audio.mp3');
     *
     * wavesurfer.setFilteredChannel([0]); <-- hide left channel peaks.
     *
     * @param {array} channelIndices Channels to be filtered out from drawing.
     * @version 4.0.0
     */

  }, {
    key: "setFilteredChannels",
    value: function setFilteredChannels(channelIndices) {
      this.params.splitChannelsOptions.filterChannels = channelIndices;
      this.drawBuffer();
    }
    /**
     * Get the correct peaks for current wave view-port and render wave
     *
     * @private
     * @emits WaveSurfer#redraw
     */

  }, {
    key: "drawBuffer",
    value: function drawBuffer() {
      var nominalWidth = Math.round(this.getDuration() * this.params.minPxPerSec * this.params.pixelRatio);
      var parentWidth = this.drawer.getWidth();
      var width = nominalWidth; // always start at 0 after zooming for scrolling : issue redraw left part

      var start = 0;
      var end = Math.max(start + parentWidth, width); // Fill container

      if (this.params.fillParent && (!this.params.scrollParent || nominalWidth < parentWidth)) {
        width = parentWidth;
        start = 0;
        end = width;
      }

      var peaks;

      if (this.params.partialRender) {
        var newRanges = this.peakCache.addRangeToPeakCache(width, start, end);
        var i;

        for (i = 0; i < newRanges.length; i++) {
          peaks = this.backend.getPeaks(width, newRanges[i][0], newRanges[i][1]);
          this.drawer.drawPeaks(peaks, width, newRanges[i][0], newRanges[i][1]);
        }
      } else {
        peaks = this.backend.getPeaks(width, start, end);
        this.drawer.drawPeaks(peaks, width, start, end);
      }

      this.fireEvent('redraw', peaks, width);
    }
    /**
     * Horizontally zooms the waveform in and out. It also changes the parameter
     * `minPxPerSec` and enables the `scrollParent` option. Calling the function
     * with a falsey parameter will reset the zoom state.
     *
     * @param {?number} pxPerSec Number of horizontal pixels per second of
     * audio, if none is set the waveform returns to unzoomed state
     * @emits WaveSurfer#zoom
     * @example wavesurfer.zoom(20);
     */

  }, {
    key: "zoom",
    value: function zoom(pxPerSec) {
      if (!pxPerSec) {
        this.params.minPxPerSec = this.defaultParams.minPxPerSec;
        this.params.scrollParent = false;
      } else {
        this.params.minPxPerSec = pxPerSec;
        this.params.scrollParent = true;
      }

      this.drawBuffer();
      this.drawer.progress(this.backend.getPlayedPercents());
      this.drawer.recenter(this.getCurrentTime() / this.getDuration());
      this.fireEvent('zoom', pxPerSec);
    }
    /**
     * Decode buffer and load
     *
     * @private
     * @param {ArrayBuffer} arraybuffer Buffer to process
     */

  }, {
    key: "loadArrayBuffer",
    value: function loadArrayBuffer(arraybuffer) {
      var _this9 = this;

      this.decodeArrayBuffer(arraybuffer, function (data) {
        if (!_this9.isDestroyed) {
          _this9.loadDecodedBuffer(data);
        }
      });
    }
    /**
     * Directly load an externally decoded AudioBuffer
     *
     * @private
     * @param {AudioBuffer} buffer Buffer to process
     * @emits WaveSurfer#ready
     */

  }, {
    key: "loadDecodedBuffer",
    value: function loadDecodedBuffer(buffer) {
      this.backend.load(buffer);
      this.drawBuffer();
      this.isReady = true;
      this.fireEvent('ready');
    }
    /**
     * Loads audio data from a Blob or File object
     *
     * @param {Blob|File} blob Audio data
     * @example
     */

  }, {
    key: "loadBlob",
    value: function loadBlob(blob) {
      var _this10 = this;

      // Create file reader
      var reader = new FileReader();
      reader.addEventListener('progress', function (e) {
        return _this10.onProgress(e);
      });
      reader.addEventListener('load', function (e) {
        return _this10.loadArrayBuffer(e.target.result);
      });
      reader.addEventListener('error', function () {
        return _this10.fireEvent('error', 'Error reading file');
      });
      reader.readAsArrayBuffer(blob);
      this.empty();
    }
    /**
     * Loads audio and re-renders the waveform.
     *
     * @param {string|HTMLMediaElement} url The url of the audio file or the
     * audio element with the audio
     * @param {number[]|Number.<Array[]>} peaks Wavesurfer does not have to decode
     * the audio to render the waveform if this is specified
     * @param {?string} preload (Use with backend `MediaElement` and `MediaElementWebAudio`)
     * `'none'|'metadata'|'auto'` Preload attribute for the media element
     * @param {?number} duration The duration of the audio. This is used to
     * render the peaks data in the correct size for the audio duration (as
     * befits the current `minPxPerSec` and zoom value) without having to decode
     * the audio.
     * @returns {void}
     * @throws Will throw an error if the `url` argument is empty.
     * @example
     * // uses fetch or media element to load file (depending on backend)
     * wavesurfer.load('http://example.com/demo.wav');
     *
     * // setting preload attribute with media element backend and supplying
     * // peaks
     * wavesurfer.load(
     *   'http://example.com/demo.wav',
     *   [0.0218, 0.0183, 0.0165, 0.0198, 0.2137, 0.2888],
     *   true
     * );
     */

  }, {
    key: "load",
    value: function load(url, peaks, preload, duration) {
      if (!url) {
        throw new Error('url parameter cannot be empty');
      }

      this.empty();

      if (preload) {
        // check whether the preload attribute will be usable and if not log
        // a warning listing the reasons why not and nullify the variable
        var preloadIgnoreReasons = {
          "Preload is not 'auto', 'none' or 'metadata'": ['auto', 'metadata', 'none'].indexOf(preload) === -1,
          'Peaks are not provided': !peaks,
          "Backend is not of type 'MediaElement' or 'MediaElementWebAudio'": ['MediaElement', 'MediaElementWebAudio'].indexOf(this.params.backend) === -1,
          'Url is not of type string': typeof url !== 'string'
        };
        var activeReasons = Object.keys(preloadIgnoreReasons).filter(function (reason) {
          return preloadIgnoreReasons[reason];
        });

        if (activeReasons.length) {
          // eslint-disable-next-line no-console
          console.warn('Preload parameter of wavesurfer.load will be ignored because:\n\t- ' + activeReasons.join('\n\t- ')); // stop invalid values from being used

          preload = null;
        }
      } // loadBuffer(url, peaks, duration) requires that url is a string
      // but users can pass in a HTMLMediaElement to WaveSurfer


      if (this.params.backend === 'WebAudio' && url instanceof HTMLMediaElement) {
        url = url.src;
      }

      switch (this.params.backend) {
        case 'WebAudio':
          return this.loadBuffer(url, peaks, duration);

        case 'MediaElement':
        case 'MediaElementWebAudio':
          return this.loadMediaElement(url, peaks, preload, duration);
      }
    }
    /**
     * Loads audio using Web Audio buffer backend.
     *
     * @private
     * @emits WaveSurfer#waveform-ready
     * @param {string} url URL of audio file
     * @param {number[]|Number.<Array[]>} peaks Peaks data
     * @param {?number} duration Optional duration of audio file
     * @returns {void}
     */

  }, {
    key: "loadBuffer",
    value: function loadBuffer(url, peaks, duration) {
      var _this11 = this;

      var load = function load(action) {
        if (action) {
          _this11.tmpEvents.push(_this11.once('ready', action));
        }

        return _this11.getArrayBuffer(url, function (data) {
          return _this11.loadArrayBuffer(data);
        });
      };

      if (peaks) {
        this.backend.setPeaks(peaks, duration);
        this.drawBuffer();
        this.fireEvent('waveform-ready');
        this.tmpEvents.push(this.once('interaction', load));
      } else {
        return load();
      }
    }
    /**
     * Either create a media element, or load an existing media element.
     *
     * @private
     * @emits WaveSurfer#waveform-ready
     * @param {string|HTMLMediaElement} urlOrElt Either a path to a media file, or an
     * existing HTML5 Audio/Video Element
     * @param {number[]|Number.<Array[]>} peaks Array of peaks. Required to bypass web audio
     * dependency
     * @param {?boolean} preload Set to true if the preload attribute of the
     * audio element should be enabled
     * @param {?number} duration Optional duration of audio file
     */

  }, {
    key: "loadMediaElement",
    value: function loadMediaElement(urlOrElt, peaks, preload, duration) {
      var _this12 = this;

      var url = urlOrElt;

      if (typeof urlOrElt === 'string') {
        this.backend.load(url, this.mediaContainer, peaks, preload);
      } else {
        var elt = urlOrElt;
        this.backend.loadElt(elt, peaks); // If peaks are not provided,
        // url = element.src so we can get peaks with web audio

        url = elt.src;
      }

      this.tmpEvents.push(this.backend.once('canplay', function () {
        // ignore when backend was already destroyed
        if (!_this12.backend.destroyed) {
          _this12.drawBuffer();

          _this12.isReady = true;

          _this12.fireEvent('ready');
        }
      }), this.backend.once('error', function (err) {
        return _this12.fireEvent('error', err);
      })); // If peaks are provided, render them and fire the `waveform-ready` event.

      if (peaks) {
        this.backend.setPeaks(peaks, duration);
        this.drawBuffer();
        this.fireEvent('waveform-ready');
      } // If no pre-decoded peaks are provided, or are provided with
      // forceDecode flag, attempt to download the audio file and decode it
      // with Web Audio.


      if ((!peaks || this.params.forceDecode) && this.backend.supportsWebAudio()) {
        this.getArrayBuffer(url, function (arraybuffer) {
          _this12.decodeArrayBuffer(arraybuffer, function (buffer) {
            _this12.backend.buffer = buffer;

            _this12.backend.setPeaks(null);

            _this12.drawBuffer();

            _this12.fireEvent('waveform-ready');
          });
        });
      }
    }
    /**
     * Decode an array buffer and pass data to a callback
     *
     * @private
     * @param {Object} arraybuffer The array buffer to decode
     * @param {function} callback The function to call on complete
     */

  }, {
    key: "decodeArrayBuffer",
    value: function decodeArrayBuffer(arraybuffer, callback) {
      var _this13 = this;

      if (!this.isDestroyed) {
        this.arraybuffer = arraybuffer;
        this.backend.decodeArrayBuffer(arraybuffer, function (data) {
          // Only use the decoded data if we haven't been destroyed or
          // another decode started in the meantime
          if (!_this13.isDestroyed && _this13.arraybuffer == arraybuffer) {
            callback(data);
            _this13.arraybuffer = null;
          }
        }, function () {
          return _this13.fireEvent('error', 'Error decoding audiobuffer');
        });
      }
    }
    /**
     * Load an array buffer using fetch and pass the result to a callback
     *
     * @param {string} url The URL of the file object
     * @param {function} callback The function to call on complete
     * @returns {util.fetchFile} fetch call
     * @private
     */

  }, {
    key: "getArrayBuffer",
    value: function getArrayBuffer(url, callback) {
      var _this14 = this;

      var options = Object.assign({
        url: url,
        responseType: 'arraybuffer'
      }, this.params.xhr);
      var request = util.fetchFile(options);
      this.currentRequest = request;
      this.tmpEvents.push(request.on('progress', function (e) {
        _this14.onProgress(e);
      }), request.on('success', function (data) {
        callback(data);
        _this14.currentRequest = null;
      }), request.on('error', function (e) {
        _this14.fireEvent('error', e);

        _this14.currentRequest = null;
      }));
      return request;
    }
    /**
     * Called while the audio file is loading
     *
     * @private
     * @param {Event} e Progress event
     * @emits WaveSurfer#loading
     */

  }, {
    key: "onProgress",
    value: function onProgress(e) {
      var percentComplete;

      if (e.lengthComputable) {
        percentComplete = e.loaded / e.total;
      } else {
        // Approximate progress with an asymptotic
        // function, and assume downloads in the 1-3 MB range.
        percentComplete = e.loaded / (e.loaded + 1000000);
      }

      this.fireEvent('loading', Math.round(percentComplete * 100), e.target);
    }
    /**
     * Exports PCM data into a JSON array and optionally opens in a new window
     * as valid JSON Blob instance.
     *
     * @param {number} length=1024 The scale in which to export the peaks
     * @param {number} accuracy=10000
     * @param {?boolean} noWindow Set to true to disable opening a new
     * window with the JSON
     * @param {number} start Start index
     * @param {number} end End index
     * @return {Promise} Promise that resolves with array of peaks
     */

  }, {
    key: "exportPCM",
    value: function exportPCM(length, accuracy, noWindow, start, end) {
      length = length || 1024;
      start = start || 0;
      accuracy = accuracy || 10000;
      noWindow = noWindow || false;
      var peaks = this.backend.getPeaks(length, start, end);
      var arr = [].map.call(peaks, function (val) {
        return Math.round(val * accuracy) / accuracy;
      });
      return new Promise(function (resolve, reject) {
        if (!noWindow) {
          var blobJSON = new Blob([JSON.stringify(arr)], {
            type: 'application/json;charset=utf-8'
          });
          var objURL = URL.createObjectURL(blobJSON);
          window.open(objURL);
          URL.revokeObjectURL(objURL);
        }

        resolve(arr);
      });
    }
    /**
     * Save waveform image as data URI.
     *
     * The default format is `'image/png'`. Other supported types are
     * `'image/jpeg'` and `'image/webp'`.
     *
     * @param {string} format='image/png' A string indicating the image format.
     * The default format type is `'image/png'`.
     * @param {number} quality=1 A number between 0 and 1 indicating the image
     * quality to use for image formats that use lossy compression such as
     * `'image/jpeg'`` and `'image/webp'`.
     * @param {string} type Image data type to return. Either 'dataURL' (default)
     * or 'blob'.
     * @return {string|string[]|Promise} When using `'dataURL'` type this returns
     * a single data URL or an array of data URLs, one for each canvas. When using
     * `'blob'` type this returns a `Promise` resolving with an array of `Blob`
     * instances, one for each canvas.
     */

  }, {
    key: "exportImage",
    value: function exportImage(format, quality, type) {
      if (!format) {
        format = 'image/png';
      }

      if (!quality) {
        quality = 1;
      }

      if (!type) {
        type = 'dataURL';
      }

      return this.drawer.getImage(format, quality, type);
    }
    /**
     * Cancel any fetch request currently in progress
     */

  }, {
    key: "cancelAjax",
    value: function cancelAjax() {
      if (this.currentRequest && this.currentRequest.controller) {
        // If the current request has a ProgressHandler, then its ReadableStream might need to be cancelled too
        // See: Wavesurfer issue #2042
        // See Firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1583815
        if (this.currentRequest._reader) {
          // Ignoring exceptions thrown by call to cancel()
          this.currentRequest._reader.cancel().catch(function (err) {});
        }

        this.currentRequest.controller.abort();
        this.currentRequest = null;
      }
    }
    /**
     * @private
     */

  }, {
    key: "clearTmpEvents",
    value: function clearTmpEvents() {
      this.tmpEvents.forEach(function (e) {
        return e.un();
      });
    }
    /**
     * Display empty waveform.
     */

  }, {
    key: "empty",
    value: function empty() {
      if (!this.backend.isPaused()) {
        this.stop();
        this.backend.disconnectSource();
      }

      this.isReady = false;
      this.cancelAjax();
      this.clearTmpEvents(); // empty drawer

      this.drawer.progress(0);
      this.drawer.setWidth(0);
      this.drawer.drawPeaks({
        length: this.drawer.getWidth()
      }, 0);
    }
    /**
     * Remove events, elements and disconnect WebAudio nodes.
     *
     * @emits WaveSurfer#destroy
     */

  }, {
    key: "destroy",
    value: function destroy() {
      this.destroyAllPlugins();
      this.fireEvent('destroy');
      this.cancelAjax();
      this.clearTmpEvents();
      this.unAll();

      if (this.params.responsive !== false) {
        window.removeEventListener('resize', this._onResize, true);
        window.removeEventListener('orientationchange', this._onResize, true);
      }

      if (this.backend) {
        this.backend.destroy(); // clears memory usage

        this.backend = null;
      }

      if (this.drawer) {
        this.drawer.destroy();
      }

      this.isDestroyed = true;
      this.isReady = false;
      this.arraybuffer = null;
    }
  }], [{
    key: "create",
    value:
    /** @private */

    /** @private */

    /**
     * Instantiate this class, call its `init` function and returns it
     *
     * @param {WavesurferParams} params The wavesurfer parameters
     * @return {Object} WaveSurfer instance
     * @example const wavesurfer = WaveSurfer.create(params);
     */
    function create(params) {
      var wavesurfer = new WaveSurfer(params);
      return wavesurfer.init();
    }
    /**
     * The library version number is available as a static property of the
     * WaveSurfer class
     *
     * @type {String}
     * @example
     * console.log('Using wavesurfer.js ' + WaveSurfer.VERSION);
     */

  }]);

  return WaveSurfer;
}(util.Observer);

exports.default = WaveSurfer;
WaveSurfer.VERSION = "5.2.0";
WaveSurfer.util = util;
module.exports = exports.default;

/***/ }),

/***/ "./src/webaudio.js":
/*!*************************!*\
  !*** ./src/webaudio.js ***!
  \*************************/
/***/ ((module, exports, __nested_webpack_require_180241__) => {

"use strict";


function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.default = void 0;

var util = _interopRequireWildcard(__nested_webpack_require_180241__(/*! ./util */ "./src/util/index.js"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

// using constants to prevent someone writing the string wrong
var PLAYING = 'playing';
var PAUSED = 'paused';
var FINISHED = 'finished';
/**
 * WebAudio backend
 *
 * @extends {Observer}
 */

var WebAudio = /*#__PURE__*/function (_util$Observer) {
  _inherits(WebAudio, _util$Observer);

  var _super = _createSuper(WebAudio);

  /**
   * Construct the backend
   *
   * @param {WavesurferParams} params Wavesurfer parameters
   */
  function WebAudio(params) {
    var _this$stateBehaviors, _this$states;

    var _this;

    _classCallCheck(this, WebAudio);

    _this = _super.call(this);
    /** @private */

    _this.audioContext = null;
    _this.offlineAudioContext = null;
    _this.stateBehaviors = (_this$stateBehaviors = {}, _defineProperty(_this$stateBehaviors, PLAYING, {
      init: function init() {
        this.addOnAudioProcess();
      },
      getPlayedPercents: function getPlayedPercents() {
        var duration = this.getDuration();
        return this.getCurrentTime() / duration || 0;
      },
      getCurrentTime: function getCurrentTime() {
        return this.startPosition + this.getPlayedTime();
      }
    }), _defineProperty(_this$stateBehaviors, PAUSED, {
      init: function init() {
        this.removeOnAudioProcess();
      },
      getPlayedPercents: function getPlayedPercents() {
        var duration = this.getDuration();
        return this.getCurrentTime() / duration || 0;
      },
      getCurrentTime: function getCurrentTime() {
        return this.startPosition;
      }
    }), _defineProperty(_this$stateBehaviors, FINISHED, {
      init: function init() {
        this.removeOnAudioProcess();
        this.fireEvent('finish');
      },
      getPlayedPercents: function getPlayedPercents() {
        return 1;
      },
      getCurrentTime: function getCurrentTime() {
        return this.getDuration();
      }
    }), _this$stateBehaviors);
    _this.params = params;
    /** ac: Audio Context instance */

    _this.ac = params.audioContext || (_this.supportsWebAudio() ? _this.getAudioContext() : {});
    /**@private */

    _this.lastPlay = _this.ac.currentTime;
    /** @private */

    _this.startPosition = 0;
    /** @private */

    _this.scheduledPause = null;
    /** @private */

    _this.states = (_this$states = {}, _defineProperty(_this$states, PLAYING, Object.create(_this.stateBehaviors[PLAYING])), _defineProperty(_this$states, PAUSED, Object.create(_this.stateBehaviors[PAUSED])), _defineProperty(_this$states, FINISHED, Object.create(_this.stateBehaviors[FINISHED])), _this$states);
    /** @private */

    _this.buffer = null;
    /** @private */

    _this.filters = [];
    /** gainNode: allows to control audio volume */

    _this.gainNode = null;
    /** @private */

    _this.mergedPeaks = null;
    /** @private */

    _this.offlineAc = null;
    /** @private */

    _this.peaks = null;
    /** @private */

    _this.playbackRate = 1;
    /** analyser: provides audio analysis information */

    _this.analyser = null;
    /** scriptNode: allows processing audio */

    _this.scriptNode = null;
    /** @private */

    _this.source = null;
    /** @private */

    _this.splitPeaks = [];
    /** @private */

    _this.state = null;
    /** @private */

    _this.explicitDuration = params.duration;
    /**
     * Boolean indicating if the backend was destroyed.
     */

    _this.destroyed = false;
    return _this;
  }
  /**
   * Initialise the backend, called in `wavesurfer.createBackend()`
   */


  _createClass(WebAudio, [{
    key: "supportsWebAudio",
    value:
    /** scriptBufferSize: size of the processing buffer */

    /** audioContext: allows to process audio with WebAudio API */

    /** @private */

    /** @private */

    /**
     * Does the browser support this backend
     *
     * @return {boolean} Whether or not this browser supports this backend
     */
    function supportsWebAudio() {
      return !!(window.AudioContext || window.webkitAudioContext);
    }
    /**
     * Get the audio context used by this backend or create one
     *
     * @return {AudioContext} Existing audio context, or creates a new one
     */

  }, {
    key: "getAudioContext",
    value: function getAudioContext() {
      if (!window.WaveSurferAudioContext) {
        window.WaveSurferAudioContext = new (window.AudioContext || window.webkitAudioContext)();
      }

      return window.WaveSurferAudioContext;
    }
    /**
     * Get the offline audio context used by this backend or create one
     *
     * @param {number} sampleRate The sample rate to use
     * @return {OfflineAudioContext} Existing offline audio context, or creates
     * a new one
     */

  }, {
    key: "getOfflineAudioContext",
    value: function getOfflineAudioContext(sampleRate) {
      if (!window.WaveSurferOfflineAudioContext) {
        window.WaveSurferOfflineAudioContext = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)(1, 2, sampleRate);
      }

      return window.WaveSurferOfflineAudioContext;
    }
  }, {
    key: "init",
    value: function init() {
      this.createVolumeNode();
      this.createScriptNode();
      this.createAnalyserNode();
      this.setState(PAUSED);
      this.setPlaybackRate(this.params.audioRate);
      this.setLength(0);
    }
    /** @private */

  }, {
    key: "disconnectFilters",
    value: function disconnectFilters() {
      if (this.filters) {
        this.filters.forEach(function (filter) {
          filter && filter.disconnect();
        });
        this.filters = null; // Reconnect direct path

        this.analyser.connect(this.gainNode);
      }
    }
    /**
     * @private
     *
     * @param {string} state The new state
     */

  }, {
    key: "setState",
    value: function setState(state) {
      if (this.state !== this.states[state]) {
        this.state = this.states[state];
        this.state.init.call(this);
      }
    }
    /**
     * Unpacked `setFilters()`
     *
     * @param {...AudioNode} filters One or more filters to set
     */

  }, {
    key: "setFilter",
    value: function setFilter() {
      for (var _len = arguments.length, filters = new Array(_len), _key = 0; _key < _len; _key++) {
        filters[_key] = arguments[_key];
      }

      this.setFilters(filters);
    }
    /**
     * Insert custom Web Audio nodes into the graph
     *
     * @param {AudioNode[]} filters Packed filters array
     * @example
     * const lowpass = wavesurfer.backend.ac.createBiquadFilter();
     * wavesurfer.backend.setFilter(lowpass);
     */

  }, {
    key: "setFilters",
    value: function setFilters(filters) {
      // Remove existing filters
      this.disconnectFilters(); // Insert filters if filter array not empty

      if (filters && filters.length) {
        this.filters = filters; // Disconnect direct path before inserting filters

        this.analyser.disconnect(); // Connect each filter in turn

        filters.reduce(function (prev, curr) {
          prev.connect(curr);
          return curr;
        }, this.analyser).connect(this.gainNode);
      }
    }
    /** Create ScriptProcessorNode to process audio */

  }, {
    key: "createScriptNode",
    value: function createScriptNode() {
      if (this.params.audioScriptProcessor) {
        this.scriptNode = this.params.audioScriptProcessor;
      } else {
        if (this.ac.createScriptProcessor) {
          this.scriptNode = this.ac.createScriptProcessor(WebAudio.scriptBufferSize);
        } else {
          this.scriptNode = this.ac.createJavaScriptNode(WebAudio.scriptBufferSize);
        }
      }

      this.scriptNode.connect(this.ac.destination);
    }
    /** @private */

  }, {
    key: "addOnAudioProcess",
    value: function addOnAudioProcess() {
      var _this2 = this;

      this.scriptNode.onaudioprocess = function () {
        var time = _this2.getCurrentTime();

        if (time >= _this2.getDuration()) {
          _this2.setState(FINISHED);

          _this2.fireEvent('pause');
        } else if (time >= _this2.scheduledPause) {
          _this2.pause();
        } else if (_this2.state === _this2.states[PLAYING]) {
          _this2.fireEvent('audioprocess', time);
        }
      };
    }
    /** @private */

  }, {
    key: "removeOnAudioProcess",
    value: function removeOnAudioProcess() {
      this.scriptNode.onaudioprocess = null;
    }
    /** Create analyser node to perform audio analysis */

  }, {
    key: "createAnalyserNode",
    value: function createAnalyserNode() {
      this.analyser = this.ac.createAnalyser();
      this.analyser.connect(this.gainNode);
    }
    /**
     * Create the gain node needed to control the playback volume.
     *
     */

  }, {
    key: "createVolumeNode",
    value: function createVolumeNode() {
      // Create gain node using the AudioContext
      if (this.ac.createGain) {
        this.gainNode = this.ac.createGain();
      } else {
        this.gainNode = this.ac.createGainNode();
      } // Add the gain node to the graph


      this.gainNode.connect(this.ac.destination);
    }
    /**
     * Set the sink id for the media player
     *
     * @param {string} deviceId String value representing audio device id.
     * @returns {Promise} A Promise that resolves to `undefined` when there
     * are no errors.
     */

  }, {
    key: "setSinkId",
    value: function setSinkId(deviceId) {
      if (deviceId) {
        /**
         * The webaudio API doesn't currently support setting the device
         * output. Here we create an HTMLAudioElement, connect the
         * webaudio stream to that element and setSinkId there.
         */
        var audio = new window.Audio();

        if (!audio.setSinkId) {
          return Promise.reject(new Error('setSinkId is not supported in your browser'));
        }

        audio.autoplay = true;
        var dest = this.ac.createMediaStreamDestination();
        this.gainNode.disconnect();
        this.gainNode.connect(dest);
        audio.srcObject = dest.stream;
        return audio.setSinkId(deviceId);
      } else {
        return Promise.reject(new Error('Invalid deviceId: ' + deviceId));
      }
    }
    /**
     * Set the audio volume
     *
     * @param {number} value A floating point value between 0 and 1.
     */

  }, {
    key: "setVolume",
    value: function setVolume(value) {
      this.gainNode.gain.setValueAtTime(value, this.ac.currentTime);
    }
    /**
     * Get the current volume
     *
     * @return {number} value A floating point value between 0 and 1.
     */

  }, {
    key: "getVolume",
    value: function getVolume() {
      return this.gainNode.gain.value;
    }
    /**
     * Decode an array buffer and pass data to a callback
     *
     * @private
     * @param {ArrayBuffer} arraybuffer The array buffer to decode
     * @param {function} callback The function to call on complete.
     * @param {function} errback The function to call on error.
     */

  }, {
    key: "decodeArrayBuffer",
    value: function decodeArrayBuffer(arraybuffer, callback, errback) {
      if (!this.offlineAc) {
        this.offlineAc = this.getOfflineAudioContext(this.ac && this.ac.sampleRate ? this.ac.sampleRate : 44100);
      }

      if ('webkitAudioContext' in window) {
        // Safari: no support for Promise-based decodeAudioData enabled
        // Enable it in Safari using the Experimental Features > Modern WebAudio API option
        this.offlineAc.decodeAudioData(arraybuffer, function (data) {
          return callback(data);
        }, errback);
      } else {
        this.offlineAc.decodeAudioData(arraybuffer).then(function (data) {
          return callback(data);
        }).catch(function (err) {
          return errback(err);
        });
      }
    }
    /**
     * Set pre-decoded peaks
     *
     * @param {number[]|Number.<Array[]>} peaks Peaks data
     * @param {?number} duration Explicit duration
     */

  }, {
    key: "setPeaks",
    value: function setPeaks(peaks, duration) {
      if (duration != null) {
        this.explicitDuration = duration;
      }

      this.peaks = peaks;
    }
    /**
     * Set the rendered length (different from the length of the audio)
     *
     * @param {number} length The rendered length
     */

  }, {
    key: "setLength",
    value: function setLength(length) {
      // No resize, we can preserve the cached peaks.
      if (this.mergedPeaks && length == 2 * this.mergedPeaks.length - 1 + 2) {
        return;
      }

      this.splitPeaks = [];
      this.mergedPeaks = []; // Set the last element of the sparse array so the peak arrays are
      // appropriately sized for other calculations.

      var channels = this.buffer ? this.buffer.numberOfChannels : 1;
      var c;

      for (c = 0; c < channels; c++) {
        this.splitPeaks[c] = [];
        this.splitPeaks[c][2 * (length - 1)] = 0;
        this.splitPeaks[c][2 * (length - 1) + 1] = 0;
      }

      this.mergedPeaks[2 * (length - 1)] = 0;
      this.mergedPeaks[2 * (length - 1) + 1] = 0;
    }
    /**
     * Compute the max and min value of the waveform when broken into <length> subranges.
     *
     * @param {number} length How many subranges to break the waveform into.
     * @param {number} first First sample in the required range.
     * @param {number} last Last sample in the required range.
     * @return {number[]|Number.<Array[]>} Array of 2*<length> peaks or array of arrays of
     * peaks consisting of (max, min) values for each subrange.
     */

  }, {
    key: "getPeaks",
    value: function getPeaks(length, first, last) {
      if (this.peaks) {
        return this.peaks;
      }

      if (!this.buffer) {
        return [];
      }

      first = first || 0;
      last = last || length - 1;
      this.setLength(length);

      if (!this.buffer) {
        return this.params.splitChannels ? this.splitPeaks : this.mergedPeaks;
      }
      /**
       * The following snippet fixes a buffering data issue on the Safari
       * browser which returned undefined It creates the missing buffer based
       * on 1 channel, 4096 samples and the sampleRate from the current
       * webaudio context 4096 samples seemed to be the best fit for rendering
       * will review this code once a stable version of Safari TP is out
       */


      if (!this.buffer.length) {
        var newBuffer = this.createBuffer(1, 4096, this.sampleRate);
        this.buffer = newBuffer.buffer;
      }

      var sampleSize = this.buffer.length / length;
      var sampleStep = ~~(sampleSize / 10) || 1;
      var channels = this.buffer.numberOfChannels;
      var c;

      for (c = 0; c < channels; c++) {
        var peaks = this.splitPeaks[c];
        var chan = this.buffer.getChannelData(c);
        var i = void 0;

        for (i = first; i <= last; i++) {
          var start = ~~(i * sampleSize);
          var end = ~~(start + sampleSize);
          /**
           * Initialize the max and min to the first sample of this
           * subrange, so that even if the samples are entirely
           * on one side of zero, we still return the true max and
           * min values in the subrange.
           */

          var min = chan[start];
          var max = min;
          var j = void 0;

          for (j = start; j < end; j += sampleStep) {
            var value = chan[j];

            if (value > max) {
              max = value;
            }

            if (value < min) {
              min = value;
            }
          }

          peaks[2 * i] = max;
          peaks[2 * i + 1] = min;

          if (c == 0 || max > this.mergedPeaks[2 * i]) {
            this.mergedPeaks[2 * i] = max;
          }

          if (c == 0 || min < this.mergedPeaks[2 * i + 1]) {
            this.mergedPeaks[2 * i + 1] = min;
          }
        }
      }

      return this.params.splitChannels ? this.splitPeaks : this.mergedPeaks;
    }
    /**
     * Get the position from 0 to 1
     *
     * @return {number} Position
     */

  }, {
    key: "getPlayedPercents",
    value: function getPlayedPercents() {
      return this.state.getPlayedPercents.call(this);
    }
    /** @private */

  }, {
    key: "disconnectSource",
    value: function disconnectSource() {
      if (this.source) {
        this.source.disconnect();
      }
    }
    /**
     * Destroy all references with WebAudio, disconnecting audio nodes and closing Audio Context
     */

  }, {
    key: "destroyWebAudio",
    value: function destroyWebAudio() {
      this.disconnectFilters();
      this.disconnectSource();
      this.gainNode.disconnect();
      this.scriptNode.disconnect();
      this.analyser.disconnect(); // close the audioContext if closeAudioContext option is set to true

      if (this.params.closeAudioContext) {
        // check if browser supports AudioContext.close()
        if (typeof this.ac.close === 'function' && this.ac.state != 'closed') {
          this.ac.close();
        } // clear the reference to the audiocontext


        this.ac = null; // clear the actual audiocontext, either passed as param or the
        // global singleton

        if (!this.params.audioContext) {
          window.WaveSurferAudioContext = null;
        } else {
          this.params.audioContext = null;
        } // clear the offlineAudioContext


        window.WaveSurferOfflineAudioContext = null;
      }
    }
    /**
     * This is called when wavesurfer is destroyed
     */

  }, {
    key: "destroy",
    value: function destroy() {
      if (!this.isPaused()) {
        this.pause();
      }

      this.unAll();
      this.buffer = null;
      this.destroyed = true;
      this.destroyWebAudio();
    }
    /**
     * Loaded a decoded audio buffer
     *
     * @param {Object} buffer Decoded audio buffer to load
     */

  }, {
    key: "load",
    value: function load(buffer) {
      this.startPosition = 0;
      this.lastPlay = this.ac.currentTime;
      this.buffer = buffer;
      this.createSource();
    }
    /** @private */

  }, {
    key: "createSource",
    value: function createSource() {
      this.disconnectSource();
      this.source = this.ac.createBufferSource(); // adjust for old browsers

      this.source.start = this.source.start || this.source.noteGrainOn;
      this.source.stop = this.source.stop || this.source.noteOff;
      this.setPlaybackRate(this.playbackRate);
      this.source.buffer = this.buffer;
      this.source.connect(this.analyser);
    }
    /**
     * @private
     *
     * some browsers require an explicit call to #resume before they will play back audio
     */

  }, {
    key: "resumeAudioContext",
    value: function resumeAudioContext() {
      if (this.ac.state == 'suspended') {
        this.ac.resume && this.ac.resume();
      }
    }
    /**
     * Used by `wavesurfer.isPlaying()` and `wavesurfer.playPause()`
     *
     * @return {boolean} Whether or not this backend is currently paused
     */

  }, {
    key: "isPaused",
    value: function isPaused() {
      return this.state !== this.states[PLAYING];
    }
    /**
     * Used by `wavesurfer.getDuration()`
     *
     * @return {number} Duration of loaded buffer
     */

  }, {
    key: "getDuration",
    value: function getDuration() {
      if (this.explicitDuration) {
        return this.explicitDuration;
      }

      if (!this.buffer) {
        return 0;
      }

      return this.buffer.duration;
    }
    /**
     * Used by `wavesurfer.seekTo()`
     *
     * @param {number} start Position to start at in seconds
     * @param {number} end Position to end at in seconds
     * @return {{start: number, end: number}} Object containing start and end
     * positions
     */

  }, {
    key: "seekTo",
    value: function seekTo(start, end) {
      if (!this.buffer) {
        return;
      }

      this.scheduledPause = null;

      if (start == null) {
        start = this.getCurrentTime();

        if (start >= this.getDuration()) {
          start = 0;
        }
      }

      if (end == null) {
        end = this.getDuration();
      }

      this.startPosition = start;
      this.lastPlay = this.ac.currentTime;

      if (this.state === this.states[FINISHED]) {
        this.setState(PAUSED);
      }

      return {
        start: start,
        end: end
      };
    }
    /**
     * Get the playback position in seconds
     *
     * @return {number} The playback position in seconds
     */

  }, {
    key: "getPlayedTime",
    value: function getPlayedTime() {
      return (this.ac.currentTime - this.lastPlay) * this.playbackRate;
    }
    /**
     * Plays the loaded audio region.
     *
     * @param {number} start Start offset in seconds, relative to the beginning
     * of a clip.
     * @param {number} end When to stop relative to the beginning of a clip.
     */

  }, {
    key: "play",
    value: function play(start, end) {
      if (!this.buffer) {
        return;
      } // need to re-create source on each playback


      this.createSource();
      var adjustedTime = this.seekTo(start, end);
      start = adjustedTime.start;
      end = adjustedTime.end;
      this.scheduledPause = end;
      this.source.start(0, start);
      this.resumeAudioContext();
      this.setState(PLAYING);
      this.fireEvent('play');
    }
    /**
     * Pauses the loaded audio.
     */

  }, {
    key: "pause",
    value: function pause() {
      this.scheduledPause = null;
      this.startPosition += this.getPlayedTime();

      try {
        this.source && this.source.stop(0);
      } catch (err) {// Calling stop can throw the following 2 errors:
        // - RangeError (The value specified for when is negative.)
        // - InvalidStateNode (The node has not been started by calling start().)
        // We can safely ignore both errors, because:
        // - The range is surely correct
        // - The node might not have been started yet, in which case we just want to carry on without causing any trouble.
      }

      this.setState(PAUSED);
      this.fireEvent('pause');
    }
    /**
     * Returns the current time in seconds relative to the audio-clip's
     * duration.
     *
     * @return {number} The current time in seconds
     */

  }, {
    key: "getCurrentTime",
    value: function getCurrentTime() {
      return this.state.getCurrentTime.call(this);
    }
    /**
     * Returns the current playback rate. (0=no playback, 1=normal playback)
     *
     * @return {number} The current playback rate
     */

  }, {
    key: "getPlaybackRate",
    value: function getPlaybackRate() {
      return this.playbackRate;
    }
    /**
     * Set the audio source playback rate.
     *
     * @param {number} value The playback rate to use
     */

  }, {
    key: "setPlaybackRate",
    value: function setPlaybackRate(value) {
      this.playbackRate = value || 1;
      this.source && this.source.playbackRate.setValueAtTime(this.playbackRate, this.ac.currentTime);
    }
    /**
     * Set a point in seconds for playback to stop at.
     *
     * @param {number} end Position to end at
     * @version 3.3.0
     */

  }, {
    key: "setPlayEnd",
    value: function setPlayEnd(end) {
      this.scheduledPause = end;
    }
  }]);

  return WebAudio;
}(util.Observer);

exports.default = WebAudio;
WebAudio.scriptBufferSize = 256;
module.exports = exports.default;

/***/ }),

/***/ "./node_modules/debounce/index.js":
/*!****************************************!*\
  !*** ./node_modules/debounce/index.js ***!
  \****************************************/
/***/ ((module) => {

/**
 * Returns a function, that, as long as it continues to be invoked, will not
 * be triggered. The function will be called after it stops being called for
 * N milliseconds. If `immediate` is passed, trigger the function on the
 * leading edge, instead of the trailing. The function also has a property 'clear' 
 * that is a function which will clear the timer to prevent previously scheduled executions. 
 *
 * @source underscore.js
 * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
 * @param {Function} function to wrap
 * @param {Number} timeout in ms (`100`)
 * @param {Boolean} whether to execute at the beginning (`false`)
 * @api public
 */
function debounce(func, wait, immediate){
  var timeout, args, context, timestamp, result;
  if (null == wait) wait = 100;

  function later() {
    var last = Date.now() - timestamp;

    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      if (!immediate) {
        result = func.apply(context, args);
        context = args = null;
      }
    }
  };

  var debounced = function(){
    context = this;
    args = arguments;
    timestamp = Date.now();
    var callNow = immediate && !timeout;
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };

  debounced.clear = function() {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
  };
  
  debounced.flush = function() {
    if (timeout) {
      result = func.apply(context, args);
      context = args = null;
      
      clearTimeout(timeout);
      timeout = null;
    }
  };

  return debounced;
};

// Adds compatibility for ES modules
debounce.debounce = debounce;

module.exports = debounce;


/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __nested_webpack_require_210487__(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](module, module.exports, __nested_webpack_require_210487__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __nested_webpack_exports__ = __nested_webpack_require_210487__("./src/wavesurfer.js");
/******/ 	
/******/ 	return __nested_webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=wavesurfer.js.map

/***/ }),

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

"use strict";
module.exports = __WEBPACK_EXTERNAL_MODULE__2055__;

/***/ }),

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

"use strict";
module.exports = /*#__PURE__*/JSON.parse('{"name":"canvas-duplicates","version":"3.6.0","description":"Inspect potential duplicates in a dataset.","private":true,"keywords":["jupyter","jupyterlab","jupyterlab-extension","widgets"],"files":["lib/**/*.js","dist/*.js","standalone/*"],"main":"lib/index.js","types":"./lib/index.d.ts","homepage":"https://github.com/betterwithdata/ml-canvas","bugs":{"url":"https://github.com/betterwithdata/ml-canvas/issues"},"author":"betterwithdata","repository":{"type":"git","url":"https://github.com/betterwithdata/ml-canvas"},"scripts":{"build":"webpack --mode=development --progress && jupyter labextension build --development=True .","build:prod":"webpack --mode=production && jupyter labextension build .","clean":"yarn run clean:lib && yarn run clean:nbextension && yarn run clean:labextension","clean:lib":"rimraf lib","clean:labextension":"rimraf canvas/labextension","clean:nbextension":"rimraf canvas/nbextension/static/index.js","lint":"eslint . --ext .ts,.tsx,.svelte --fix","lint:check":"eslint . --ext .ts,.tsx,.svelte","prepack":"yarn run build:prod","watch":"yarn run watch:nbextension","watch:nbextension":"webpack --watch --mode=development --progress","watch:labextension":"jupyter labextension watch .","dev":"yarn run watch & python -m http.server --directory ./canvas_duplicates/standalone 8082"},"dependencies":{"@betterwithdata/canvas_viz":"^1.0.0","@jupyter-widgets/base":"^1.1.10 || ^2.0.0 || ^3.0.0 || ^4.0.0","arquero":"^4.7.2","svelte-infinite-scroll":"^2.0.0"},"devDependencies":{"@fullhuman/postcss-purgecss":"^4.0.3","@jupyterlab/builder":"^3.1.12","@phosphor/application":"^1.6.0","@phosphor/widgets":"^1.6.0","@tailwindcss/forms":"^0.3.2","@tsconfig/svelte":"^2.0.1","@types/webpack-env":"^1.13.6","@typescript-eslint/eslint-plugin":"^4.31.1","@typescript-eslint/parser":"^4.31.1","@webpack-cli/serve":"^1.2.2","autoprefixer":"^10.3.4","commitizen":"^4.2.4","css-loader":"^6.2.0","css-minimizer-webpack-plugin":"^3.0.1","cz-conventional-changelog":"^3.3.0","eslint":"^7.4.0","eslint-config-prettier":"^8.1.0","eslint-plugin-prettier":"^4.0.0","mini-css-extract-plugin":"^2.3.0","mkdirp":"^1.0.4","postcss":"^8.2.10","postcss-extend":"^1.0.5","postcss-import":"^14.0.1","postcss-load-config":"^3.0.1","postcss-loader":"^6.1.0","precss":"^4.0.0","prettier":"^2.4.0","purgecss-from-svelte":"^2.0.2","rimraf":"^3.0.2","source-map-loader":"^3.0.0","style-loader":"^3.2.1","svelte":"^3.42.5","svelte-loader":"^3.1.1","svelte-preprocess":"^4.9.4","tailwindcss":"^2.2.15","ts-loader":"^9.1.0","typescript":"^4.9.0","webpack":"^5.52.1","webpack-cli":"^4.6.0","webpack-dev-server":"^4.2.1","yarn-run-all":"^3.1.1"},"jupyterlab":{"extension":"lib/index","outputDir":"canvas_duplicates/labextension/","sharedPackages":{"@jupyter-widgets/base":{"bundled":false,"singleton":true}}},"config":{"commitizen":{"path":"./node_modules/cz-conventional-changelog"}}}');

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// 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/global */
/******/ 	(() => {
/******/ 		__webpack_require__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* 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__ = {};
// This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
(() => {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  CanvasDuplicatesModel: () => (/* reexport */ extension_CanvasDuplicatesModel),
  CanvasDuplicatesView: () => (/* reexport */ extension_CanvasDuplicatesView),
  MODULE_NAME: () => (/* reexport */ extension_MODULE_NAME),
  MODULE_VERSION: () => (/* reexport */ extension_MODULE_VERSION)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/buffer.mjs
var extension_buffer_namespaceObject = {};
__webpack_require__.r(extension_buffer_namespaceObject);
__webpack_require__.d(extension_buffer_namespaceObject, {
  compareArrayLike: () => (extension_compareArrayLike),
  joinUint8Arrays: () => (extension_joinUint8Arrays),
  memcpy: () => (extension_memcpy),
  rebaseValueOffsets: () => (extension_rebaseValueOffsets),
  toArrayBufferView: () => (extension_toArrayBufferView),
  toArrayBufferViewAsyncIterator: () => (extension_toArrayBufferViewAsyncIterator),
  toArrayBufferViewIterator: () => (extension_toArrayBufferViewIterator),
  toBigInt64Array: () => (extension_toBigInt64Array),
  toBigUint64Array: () => (extension_toBigUint64Array),
  toFloat32Array: () => (extension_toFloat32Array),
  toFloat32ArrayAsyncIterator: () => (extension_toFloat32ArrayAsyncIterator),
  toFloat32ArrayIterator: () => (extension_toFloat32ArrayIterator),
  toFloat64Array: () => (extension_toFloat64Array),
  toFloat64ArrayAsyncIterator: () => (extension_toFloat64ArrayAsyncIterator),
  toFloat64ArrayIterator: () => (extension_toFloat64ArrayIterator),
  toInt16Array: () => (extension_toInt16Array),
  toInt16ArrayAsyncIterator: () => (extension_toInt16ArrayAsyncIterator),
  toInt16ArrayIterator: () => (extension_toInt16ArrayIterator),
  toInt32Array: () => (extension_toInt32Array),
  toInt32ArrayAsyncIterator: () => (extension_toInt32ArrayAsyncIterator),
  toInt32ArrayIterator: () => (extension_toInt32ArrayIterator),
  toInt8Array: () => (extension_toInt8Array),
  toInt8ArrayAsyncIterator: () => (extension_toInt8ArrayAsyncIterator),
  toInt8ArrayIterator: () => (extension_toInt8ArrayIterator),
  toUint16Array: () => (extension_toUint16Array),
  toUint16ArrayAsyncIterator: () => (extension_toUint16ArrayAsyncIterator),
  toUint16ArrayIterator: () => (extension_toUint16ArrayIterator),
  toUint32Array: () => (extension_toUint32Array),
  toUint32ArrayAsyncIterator: () => (extension_toUint32ArrayAsyncIterator),
  toUint32ArrayIterator: () => (extension_toUint32ArrayIterator),
  toUint8Array: () => (extension_toUint8Array),
  toUint8ArrayAsyncIterator: () => (extension_toUint8ArrayAsyncIterator),
  toUint8ArrayIterator: () => (extension_toUint8ArrayIterator),
  toUint8ClampedArray: () => (extension_toUint8ClampedArray),
  toUint8ClampedArrayAsyncIterator: () => (extension_toUint8ClampedArrayAsyncIterator),
  toUint8ClampedArrayIterator: () => (extension_toUint8ClampedArrayIterator)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/bit.mjs
var extension_bit_namespaceObject = {};
__webpack_require__.r(extension_bit_namespaceObject);
__webpack_require__.d(extension_bit_namespaceObject, {
  getBit: () => (extension_getBit),
  getBool: () => (extension_getBool),
  iterateBits: () => (extension_iterateBits),
  packBools: () => (extension_packBools),
  popcnt_array: () => (extension_popcnt_array),
  popcnt_bit_range: () => (extension_popcnt_bit_range),
  popcnt_uint32: () => (extension_popcnt_uint32),
  setBool: () => (extension_setBool),
  truncateBitmap: () => (extension_truncateBitmap)
});

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

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/bn.mjs
var extension_bn_namespaceObject = {};
__webpack_require__.r(extension_bn_namespaceObject);
__webpack_require__.d(extension_bn_namespaceObject, {
  BN: () => (extension_BN),
  bignumToBigInt: () => (extension_bignumToBigInt),
  bignumToString: () => (extension_bignumToString),
  isArrowBigNumSymbol: () => (extension_isArrowBigNumSymbol)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/vector.mjs
var extension_util_vector_namespaceObject = {};
__webpack_require__.r(extension_util_vector_namespaceObject);
__webpack_require__.d(extension_util_vector_namespaceObject, {
  clampIndex: () => (extension_clampIndex),
  clampRange: () => (extension_clampRange),
  createElementComparator: () => (extension_createElementComparator)
});

// NAMESPACE OBJECT: ../../node_modules/apache-arrow/util/int.mjs
var extension_util_int_namespaceObject = {};
__webpack_require__.r(extension_util_int_namespaceObject);
__webpack_require__.d(extension_util_int_namespaceObject, {
  BaseInt64: () => (extension_BaseInt64),
  Int128: () => (extension_Int128),
  Int64: () => (extension_int_Int64),
  Uint64: () => (extension_int_Uint64)
});

;// ./src/version.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.
 */
// eslint-disable-next-line @typescript-eslint/no-var-requires
const extension_data = __webpack_require__(8330);
/**
 * The _model_module_version/_view_module_version this package implements.
 *
 * The html widget manager assumes that this is the same as the npm package
 * version number.
 */
const extension_MODULE_VERSION = extension_data.version;
/*
 * The current package name.
 */
const extension_MODULE_NAME = extension_data.name;

// EXTERNAL MODULE: external "@jupyter-widgets/base"
var extension_base_ = __webpack_require__(2055);
;// ../../canvas_viz/dist/index.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 extension_serializers = Object.assign(Object.assign({}, extension_base_.DOMWidgetModel.serializers), { table: {
        serialize: (value) => {
            return new DataView(value.buffer.slice(0));
        },
    } });

;// ../../node_modules/svelte/internal/index.mjs
function extension_noop() { }
const extension_internal_identity = x => x;
function extension_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 extension_is_promise(value) {
    return !!value && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function';
}
function extension_add_location(element, file, line, column, char) {
    element.__svelte_meta = {
        loc: { file, line, column, char }
    };
}
function extension_run(fn) {
    return fn();
}
function extension_blank_object() {
    return Object.create(null);
}
function extension_run_all(fns) {
    fns.forEach(extension_run);
}
function extension_internal_is_function(thing) {
    return typeof thing === 'function';
}
function extension_safe_not_equal(a, b) {
    return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
let extension_src_url_equal_anchor;
function extension_src_url_equal(element_src, url) {
    if (!extension_src_url_equal_anchor) {
        extension_src_url_equal_anchor = document.createElement('a');
    }
    extension_src_url_equal_anchor.href = url;
    return element_src === extension_src_url_equal_anchor.href;
}
function extension_not_equal(a, b) {
    return a != a ? b == b : a !== b;
}
function extension_is_empty(obj) {
    return Object.keys(obj).length === 0;
}
function extension_validate_store(store, name) {
    if (store != null && typeof store.subscribe !== 'function') {
        throw new Error(`'${name}' is not a store with a 'subscribe' method`);
    }
}
function extension_subscribe(store, ...callbacks) {
    if (store == null) {
        return extension_noop;
    }
    const unsub = store.subscribe(...callbacks);
    return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function extension_get_store_value(store) {
    let value;
    extension_subscribe(store, _ => value = _)();
    return value;
}
function extension_component_subscribe(component, store, callback) {
    component.$$.on_destroy.push(extension_subscribe(store, callback));
}
function extension_create_slot(definition, ctx, $$scope, fn) {
    if (definition) {
        const slot_ctx = extension_get_slot_context(definition, ctx, $$scope, fn);
        return definition[0](slot_ctx);
    }
}
function extension_get_slot_context(definition, ctx, $$scope, fn) {
    return definition[1] && fn
        ? extension_internal_assign($$scope.ctx.slice(), definition[1](fn(ctx)))
        : $$scope.ctx;
}
function extension_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 extension_update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
    if (slot_changes) {
        const slot_context = extension_get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
        slot.p(slot_context, slot_changes);
    }
}
function extension_update_slot(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) {
    const slot_changes = extension_get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn);
    extension_update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn);
}
function extension_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 extension_exclude_internal_props(props) {
    const result = {};
    for (const k in props)
        if (k[0] !== '$')
            result[k] = props[k];
    return result;
}
function extension_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 extension_compute_slots(slots) {
    const result = {};
    for (const key in slots) {
        result[key] = true;
    }
    return result;
}
function extension_once(fn) {
    let ran = false;
    return function (...args) {
        if (ran)
            return;
        ran = true;
        fn.call(this, ...args);
    };
}
function extension_null_to_empty(value) {
    return value == null ? '' : value;
}
function extension_set_store_value(store, ret, value) {
    store.set(value);
    return ret;
}
const extension_has_prop = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
function extension_action_destroyer(action_result) {
    return action_result && extension_internal_is_function(action_result.destroy) ? action_result.destroy : extension_noop;
}
function extension_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 extension_contenteditable_truthy_values = (/* unused pure expression or super */ null && (['', true, 1, 'true', 'contenteditable']));

const extension_is_client = typeof window !== 'undefined';
let extension_now = extension_is_client
    ? () => window.performance.now()
    : () => Date.now();
let extension_raf = extension_is_client ? cb => requestAnimationFrame(cb) : extension_noop;
// used internally for testing
function extension_set_now(fn) {
    extension_now = fn;
}
function extension_set_raf(fn) {
    extension_raf = fn;
}

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

const extension_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 extension_ResizeObserverSingleton {
    constructor(options) {
        this.options = options;
        this._listeners = 'WeakMap' in extension_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) {
                extension_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
extension_ResizeObserverSingleton.entries = 'WeakMap' in extension_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 extension_is_hydrating = false;
function extension_start_hydrating() {
    extension_is_hydrating = true;
}
function extension_end_hydrating() {
    extension_is_hydrating = false;
}
function extension_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 extension_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 : extension_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 extension_append(target, node) {
    target.appendChild(node);
}
function extension_append_styles(target, style_sheet_id, styles) {
    const append_styles_to = extension_get_root_for_style(target);
    if (!append_styles_to.getElementById(style_sheet_id)) {
        const style = extension_internal_element('style');
        style.id = style_sheet_id;
        style.textContent = styles;
        extension_append_stylesheet(append_styles_to, style);
    }
}
function extension_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 extension_append_empty_stylesheet(node) {
    const style_element = extension_internal_element('style');
    extension_append_stylesheet(extension_get_root_for_style(node), style_element);
    return style_element.sheet;
}
function extension_append_stylesheet(node, style) {
    extension_append(node.head || node, style);
    return style.sheet;
}
function extension_append_hydration(target, node) {
    if (extension_is_hydrating) {
        extension_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 extension_insert(target, node, anchor) {
    target.insertBefore(node, anchor || null);
}
function extension_insert_hydration(target, node, anchor) {
    if (extension_is_hydrating && !anchor) {
        extension_append_hydration(target, node);
    }
    else if (node.parentNode !== target || node.nextSibling != anchor) {
        target.insertBefore(node, anchor || null);
    }
}
function extension_detach(node) {
    if (node.parentNode) {
        node.parentNode.removeChild(node);
    }
}
function extension_destroy_each(iterations, detaching) {
    for (let i = 0; i < iterations.length; i += 1) {
        if (iterations[i])
            iterations[i].d(detaching);
    }
}
function extension_internal_element(name) {
    return document.createElement(name);
}
function extension_element_is(name, is) {
    return document.createElement(name, { is });
}
function extension_object_without_properties(obj, exclude) {
    const target = {};
    for (const k in obj) {
        if (extension_has_prop(obj, k)
            // @ts-ignore
            && exclude.indexOf(k) === -1) {
            // @ts-ignore
            target[k] = obj[k];
        }
    }
    return target;
}
function extension_svg_element(name) {
    return document.createElementNS('http://www.w3.org/2000/svg', name);
}
function extension_internal_text(data) {
    return document.createTextNode(data);
}
function extension_space() {
    return extension_internal_text(' ');
}
function extension_empty() {
    return extension_internal_text('');
}
function extension_comment(content) {
    return document.createComment(content);
}
function extension_listen(node, event, handler, options) {
    node.addEventListener(event, handler, options);
    return () => node.removeEventListener(event, handler, options);
}
function extension_prevent_default(fn) {
    return function (event) {
        event.preventDefault();
        // @ts-ignore
        return fn.call(this, event);
    };
}
function extension_stop_propagation(fn) {
    return function (event) {
        event.stopPropagation();
        // @ts-ignore
        return fn.call(this, event);
    };
}
function extension_stop_immediate_propagation(fn) {
    return function (event) {
        event.stopImmediatePropagation();
        // @ts-ignore
        return fn.call(this, event);
    };
}
function extension_internal_self(fn) {
    return function (event) {
        // @ts-ignore
        if (event.target === this)
            fn.call(this, event);
    };
}
function extension_trusted(fn) {
    return function (event) {
        // @ts-ignore
        if (event.isTrusted)
            fn.call(this, event);
    };
}
function extension_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 extension_always_set_through_set_attribute = (/* unused pure expression or super */ null && (['width', 'height']));
function extension_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 && extension_always_set_through_set_attribute.indexOf(key) === -1) {
            node[key] = attributes[key];
        }
        else {
            extension_attr(node, key, attributes[key]);
        }
    }
}
function extension_set_svg_attributes(node, attributes) {
    for (const key in attributes) {
        extension_attr(node, key, attributes[key]);
    }
}
function extension_set_custom_element_data_map(node, data_map) {
    Object.keys(data_map).forEach((key) => {
        extension_set_custom_element_data(node, key, data_map[key]);
    });
}
function extension_set_custom_element_data(node, prop, value) {
    if (prop in node) {
        node[prop] = typeof node[prop] === 'boolean' && value === '' ? true : value;
    }
    else {
        extension_attr(node, prop, value);
    }
}
function extension_set_dynamic_element_data(tag) {
    return (/-/.test(tag)) ? extension_set_custom_element_data_map : extension_set_attributes;
}
function extension_xlink_attr(node, attribute, value) {
    node.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);
}
function extension_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 extension_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 extension_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 extension_to_number(value) {
    return value === '' ? null : +value;
}
function extension_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 extension_children(element) {
    return Array.from(element.childNodes);
}
function extension_init_claim_info(nodes) {
    if (nodes.claim_info === undefined) {
        nodes.claim_info = { last_index: 0, total_claimed: 0 };
    }
}
function extension_claim_node(nodes, predicate, processNode, createNode, dontUpdateLastIndex = false) {
    // Try to find nodes in an order such that we lengthen the longest increasing subsequence
    extension_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 extension_claim_element_base(nodes, name, attributes, create_element) {
    return extension_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 extension_claim_element(nodes, name, attributes) {
    return extension_claim_element_base(nodes, name, attributes, extension_internal_element);
}
function extension_claim_svg_element(nodes, name, attributes) {
    return extension_claim_element_base(nodes, name, attributes, extension_svg_element);
}
function extension_claim_text(nodes, data) {
    return extension_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;
        }
    }, () => extension_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 extension_claim_space(nodes) {
    return extension_claim_text(nodes, ' ');
}
function extension_claim_comment(nodes, data) {
    return extension_claim_node(nodes, (node) => node.nodeType === 8, (node) => {
        node.data = '' + data;
        return undefined;
    }, () => extension_comment(data), true);
}
function extension_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 extension_claim_html_tag(nodes, is_svg) {
    // find html opening tag
    const start_index = extension_find_comment(nodes, 'HTML_TAG_START', 0);
    const end_index = extension_find_comment(nodes, 'HTML_TAG_END', start_index);
    if (start_index === end_index) {
        return new extension_HtmlTagHydration(undefined, is_svg);
    }
    extension_init_claim_info(nodes);
    const html_tag_nodes = nodes.splice(start_index, end_index - start_index + 1);
    extension_detach(html_tag_nodes[0]);
    extension_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 extension_HtmlTagHydration(claimed_nodes, is_svg);
}
function extension_set_data(text, data) {
    data = '' + data;
    if (text.data === data)
        return;
    text.data = data;
}
function extension_set_data_contenteditable(text, data) {
    data = '' + data;
    if (text.wholeText === data)
        return;
    text.data = data;
}
function extension_set_data_maybe_contenteditable(text, data, attr_value) {
    if (~extension_contenteditable_truthy_values.indexOf(attr_value)) {
        extension_set_data_contenteditable(text, data);
    }
    else {
        extension_set_data(text, data);
    }
}
function extension_set_input_value(input, value) {
    input.value = value == null ? '' : value;
}
function extension_set_input_type(input, type) {
    try {
        input.type = type;
    }
    catch (e) {
        // do nothing
    }
}
function extension_set_style(node, key, value, important) {
    if (value == null) {
        node.style.removeProperty(key);
    }
    else {
        node.style.setProperty(key, value, important ? 'important' : '');
    }
}
function extension_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 extension_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 extension_select_value(select) {
    const selected_option = select.querySelector(':checked');
    return selected_option && selected_option.__value;
}
function extension_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 extension_crossorigin;
function extension_is_crossorigin() {
    if (extension_crossorigin === undefined) {
        extension_crossorigin = false;
        try {
            if (typeof window !== 'undefined' && window.parent) {
                void window.parent.document;
            }
        }
        catch (error) {
            extension_crossorigin = true;
        }
    }
    return extension_crossorigin;
}
function extension_add_iframe_resize_listener(node, fn) {
    const computed_style = getComputedStyle(node);
    if (computed_style.position === 'static') {
        node.style.position = 'relative';
    }
    const iframe = extension_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 = extension_is_crossorigin();
    let unsubscribe;
    if (crossorigin) {
        iframe.src = "data:text/html,<script>onresize=function(){parent.postMessage(0,'*')}</script>";
        unsubscribe = extension_listen(window, 'message', (event) => {
            if (event.source === iframe.contentWindow)
                fn();
        });
    }
    else {
        iframe.src = 'about:blank';
        iframe.onload = () => {
            unsubscribe = extension_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();
        };
    }
    extension_append(node, iframe);
    return () => {
        if (crossorigin) {
            unsubscribe();
        }
        else if (unsubscribe && iframe.contentWindow) {
            unsubscribe();
        }
        extension_detach(iframe);
    };
}
const extension_resize_observer_content_box = /* @__PURE__ */ new extension_ResizeObserverSingleton({ box: 'content-box' });
const extension_resize_observer_border_box = /* @__PURE__ */ new extension_ResizeObserverSingleton({ box: 'border-box' });
const extension_resize_observer_device_pixel_content_box = /* @__PURE__ */ new extension_ResizeObserverSingleton({ box: 'device-pixel-content-box' });
function extension_toggle_class(element, name, toggle) {
    element.classList[toggle ? 'add' : 'remove'](name);
}
function extension_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
    const e = document.createEvent('CustomEvent');
    e.initCustomEvent(type, bubbles, cancelable, detail);
    return e;
}
function extension_query_selector_all(selector, parent = document.body) {
    return Array.from(parent.querySelectorAll(selector));
}
function extension_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 extension_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 = extension_svg_element(target.nodeName);
            /** #7364  target for <template> may be provided as #document-fragment(11) */
            else
                this.e = extension_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) {
            extension_insert(this.t, this.n[i], anchor);
        }
    }
    p(html) {
        this.d();
        this.h(html);
        this.i(this.a);
    }
    d() {
        this.n.forEach(extension_detach);
    }
}
class extension_HtmlTagHydration extends extension_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) {
            extension_insert_hydration(this.t, this.n[i], anchor);
        }
    }
}
function extension_attribute_to_object(attributes) {
    const result = {};
    for (const attribute of attributes) {
        result[attribute.name] = attribute.value;
    }
    return result;
}
function extension_get_custom_elements_slots(element) {
    const result = {};
    element.childNodes.forEach((node) => {
        result[node.slot || 'default'] = true;
    });
    return result;
}
function extension_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 extension_managed_styles = new Map();
let extension_active = 0;
// https://github.com/darkskyapp/string-hash/blob/master/index.js
function extension_hash(str) {
    let hash = 5381;
    let i = str.length;
    while (i--)
        hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
    return hash >>> 0;
}
function extension_create_style_information(doc, node) {
    const info = { stylesheet: extension_append_empty_stylesheet(node), rules: {} };
    extension_managed_styles.set(doc, info);
    return info;
}
function extension_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_${extension_hash(rule)}_${uid}`;
    const doc = extension_get_root_for_style(node);
    const { stylesheet, rules } = extension_managed_styles.get(doc) || extension_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`;
    extension_active += 1;
    return name;
}
function extension_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(', ');
        extension_active -= deleted;
        if (!extension_active)
            extension_clear_rules();
    }
}
function extension_clear_rules() {
    extension_raf(() => {
        if (extension_active)
            return;
        extension_managed_styles.forEach(info => {
            const { ownerNode } = info.stylesheet;
            // there is no ownerNode if it runs on jsdom.
            if (ownerNode)
                extension_detach(ownerNode);
        });
        extension_managed_styles.clear();
    });
}

function extension_create_animation(node, from, fn, params) {
    if (!from)
        return extension_noop;
    const to = node.getBoundingClientRect();
    if (from.left === to.left && from.right === to.right && from.top === to.top && from.bottom === to.bottom)
        return extension_noop;
    const { delay = 0, duration = 300, easing = extension_internal_identity, 
    // @ts-ignore todo: should this be separated from destructuring? Or start/end added to public api and documentation?
    start: start_time = extension_now() + delay, 
    // @ts-ignore todo:
    end = start_time + duration, tick = extension_noop, css } = fn(node, { from, to }, params);
    let running = true;
    let started = false;
    let name;
    function start() {
        if (css) {
            name = extension_create_rule(node, 0, 1, duration, delay, easing, css);
        }
        if (!delay) {
            started = true;
        }
    }
    function stop() {
        if (css)
            extension_delete_rule(node, name);
        running = false;
    }
    extension_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 extension_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;
        extension_add_transform(node, a);
    }
}
function extension_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 extension_current_component;
function extension_set_current_component(component) {
    extension_current_component = component;
}
function extension_get_current_component() {
    if (!extension_current_component)
        throw new Error('Function called outside component initialization');
    return extension_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 extension_beforeUpdate(fn) {
    extension_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 extension_onMount(fn) {
    extension_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 extension_afterUpdate(fn) {
    extension_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 extension_onDestroy(fn) {
    extension_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 extension_createEventDispatcher() {
    const component = extension_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 = extension_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 extension_setContext(key, context) {
    extension_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 extension_getContext(key) {
    return extension_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 extension_getAllContexts() {
    return extension_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 extension_hasContext(key) {
    return extension_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 extension_bubble(component, event) {
    const callbacks = component.$$.callbacks[event.type];
    if (callbacks) {
        // @ts-ignore
        callbacks.slice().forEach(fn => fn.call(this, event));
    }
}

const extension_dirty_components = [];
const extension_intros = { enabled: false };
const extension_binding_callbacks = [];
let extension_render_callbacks = [];
const extension_flush_callbacks = [];
const extension_resolved_promise = /* @__PURE__ */ Promise.resolve();
let extension_update_scheduled = false;
function extension_schedule_update() {
    if (!extension_update_scheduled) {
        extension_update_scheduled = true;
        extension_resolved_promise.then(extension_flush);
    }
}
function extension_tick() {
    extension_schedule_update();
    return extension_resolved_promise;
}
function extension_add_render_callback(fn) {
    extension_render_callbacks.push(fn);
}
function extension_add_flush_callback(fn) {
    extension_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 extension_seen_callbacks = new Set();
let extension_flushidx = 0; // Do *not* move this inside the flush() function
function extension_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 (extension_flushidx !== 0) {
        return;
    }
    const saved_component = extension_current_component;
    do {
        // first, call beforeUpdate functions
        // and update components
        try {
            while (extension_flushidx < extension_dirty_components.length) {
                const component = extension_dirty_components[extension_flushidx];
                extension_flushidx++;
                extension_set_current_component(component);
                extension_update(component.$$);
            }
        }
        catch (e) {
            // reset dirty state to not end up in a deadlocked state and then rethrow
            extension_dirty_components.length = 0;
            extension_flushidx = 0;
            throw e;
        }
        extension_set_current_component(null);
        extension_dirty_components.length = 0;
        extension_flushidx = 0;
        while (extension_binding_callbacks.length)
            extension_binding_callbacks.pop()();
        // then, once components are updated, call
        // afterUpdate functions. This may cause
        // subsequent updates...
        for (let i = 0; i < extension_render_callbacks.length; i += 1) {
            const callback = extension_render_callbacks[i];
            if (!extension_seen_callbacks.has(callback)) {
                // ...so guard against infinite loops
                extension_seen_callbacks.add(callback);
                callback();
            }
        }
        extension_render_callbacks.length = 0;
    } while (extension_dirty_components.length);
    while (extension_flush_callbacks.length) {
        extension_flush_callbacks.pop()();
    }
    extension_update_scheduled = false;
    extension_seen_callbacks.clear();
    extension_set_current_component(saved_component);
}
function extension_update($$) {
    if ($$.fragment !== null) {
        $$.update();
        extension_run_all($$.before_update);
        const dirty = $$.dirty;
        $$.dirty = [-1];
        $$.fragment && $$.fragment.p($$.ctx, dirty);
        $$.after_update.forEach(extension_add_render_callback);
    }
}
/**
 * Useful for example to execute remaining `afterUpdate` callbacks before executing `destroy`.
 */
function extension_flush_render_callbacks(fns) {
    const filtered = [];
    const targets = [];
    extension_render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
    targets.forEach((c) => c());
    extension_render_callbacks = filtered;
}

let extension_promise;
function extension_wait() {
    if (!extension_promise) {
        extension_promise = Promise.resolve();
        extension_promise.then(() => {
            extension_promise = null;
        });
    }
    return extension_promise;
}
function extension_dispatch(node, direction, kind) {
    node.dispatchEvent(extension_custom_event(`${direction ? 'intro' : 'outro'}${kind}`));
}
const extension_outroing = new Set();
let extension_outros;
function extension_group_outros() {
    extension_outros = {
        r: 0,
        c: [],
        p: extension_outros // parent group
    };
}
function extension_check_outros() {
    if (!extension_outros.r) {
        extension_run_all(extension_outros.c);
    }
    extension_outros = extension_outros.p;
}
function extension_transition_in(block, local) {
    if (block && block.i) {
        extension_outroing.delete(block);
        block.i(local);
    }
}
function extension_transition_out(block, local, detach, callback) {
    if (block && block.o) {
        if (extension_outroing.has(block))
            return;
        extension_outroing.add(block);
        extension_outros.c.push(() => {
            extension_outroing.delete(block);
            if (callback) {
                if (detach)
                    block.d(1);
                callback();
            }
        });
        block.o(local);
    }
    else if (callback) {
        callback();
    }
}
const extension_null_transition = { duration: 0 };
function extension_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)
            extension_delete_rule(node, animation_name);
    }
    function go() {
        const { delay = 0, duration = 300, easing = extension_internal_identity, tick = extension_noop, css } = config || extension_null_transition;
        if (css)
            animation_name = extension_create_rule(node, 0, 1, duration, delay, easing, css, uid++);
        tick(0, 1);
        const start_time = extension_now() + delay;
        const end_time = start_time + duration;
        if (task)
            task.abort();
        running = true;
        extension_add_render_callback(() => extension_dispatch(node, true, 'start'));
        task = extension_loop(now => {
            if (running) {
                if (now >= end_time) {
                    tick(1, 0);
                    extension_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;
            extension_delete_rule(node);
            if (extension_internal_is_function(config)) {
                config = config(options);
                extension_wait().then(go);
            }
            else {
                go();
            }
        },
        invalidate() {
            started = false;
        },
        end() {
            if (running) {
                cleanup();
                running = false;
            }
        }
    };
}
function extension_create_out_transition(node, fn, params) {
    const options = { direction: 'out' };
    let config = fn(node, params, options);
    let running = true;
    let animation_name;
    const group = extension_outros;
    group.r += 1;
    function go() {
        const { delay = 0, duration = 300, easing = extension_internal_identity, tick = extension_noop, css } = config || extension_null_transition;
        if (css)
            animation_name = extension_create_rule(node, 1, 0, duration, delay, easing, css);
        const start_time = extension_now() + delay;
        const end_time = start_time + duration;
        extension_add_render_callback(() => extension_dispatch(node, false, 'start'));
        extension_loop(now => {
            if (running) {
                if (now >= end_time) {
                    tick(0, 1);
                    extension_dispatch(node, false, 'end');
                    if (!--group.r) {
                        // this will result in `end()` being called,
                        // so we don't need to clean up here
                        extension_run_all(group.c);
                    }
                    return false;
                }
                if (now >= start_time) {
                    const t = easing((now - start_time) / duration);
                    tick(1 - t, t);
                }
            }
            return running;
        });
    }
    if (extension_internal_is_function(config)) {
        extension_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)
                    extension_delete_rule(node, animation_name);
                running = false;
            }
        }
    };
}
function extension_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)
            extension_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 = extension_internal_identity, tick = extension_noop, css } = config || extension_null_transition;
        const program = {
            start: extension_now() + delay,
            b
        };
        if (!b) {
            // @ts-ignore todo: improve typings
            program.group = extension_outros;
            extension_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 = extension_create_rule(node, t, b, duration, delay, easing, css);
            }
            if (b)
                tick(0, 1);
            running_program = init(program, duration);
            extension_add_render_callback(() => extension_dispatch(node, b, 'start'));
            extension_loop(now => {
                if (pending_program && now > pending_program.start) {
                    running_program = init(pending_program, duration);
                    pending_program = null;
                    extension_dispatch(node, running_program.b, 'start');
                    if (css) {
                        clear_animation();
                        animation_name = extension_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);
                        extension_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)
                                    extension_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 (extension_internal_is_function(config)) {
                extension_wait().then(() => {
                    // @ts-ignore
                    config = config(options);
                    go(b);
                });
            }
            else {
                go(b);
            }
        },
        end() {
            clear_animation();
            running_program = pending_program = null;
        }
    };
}

function extension_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) {
                        extension_group_outros();
                        extension_transition_out(block, 1, 1, () => {
                            if (info.blocks[i] === block) {
                                info.blocks[i] = null;
                            }
                        });
                        extension_check_outros();
                    }
                });
            }
            else {
                info.block.d(1);
            }
            block.c();
            extension_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) {
            extension_flush();
        }
    }
    if (extension_is_promise(promise)) {
        const current_component = extension_get_current_component();
        promise.then(value => {
            extension_set_current_component(current_component);
            update(info.then, 1, info.value, value);
            extension_set_current_component(null);
        }, error => {
            extension_set_current_component(current_component);
            update(info.catch, 2, info.error, error);
            extension_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 extension_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 extension_destroy_block(block, lookup) {
    block.d(1);
    lookup.delete(block.key);
}
function extension_outro_and_destroy_block(block, lookup) {
    extension_transition_out(block, 1, 1, () => {
        lookup.delete(block.key);
    });
}
function extension_fix_and_destroy_block(block, lookup) {
    block.f();
    extension_destroy_block(block, lookup);
}
function extension_fix_and_outro_and_destroy_block(block, lookup) {
    block.f();
    extension_outro_and_destroy_block(block, lookup);
}
function extension_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) {
        extension_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]);
    extension_run_all(updates);
    return new_blocks;
}
function extension_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 extension_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 extension_get_spread_object(spread_props) {
    return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};
}

const extension_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_extension_boolean_attributes = new Set([...extension_boolean_attributes]);

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

const extension_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 extension_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 = extension_style_object_to_string(styles_to_add);
            }
            else {
                attributes.style = extension_style_object_to_string(extension_merge_ssr_styles(attributes.style, styles_to_add));
            }
        }
    }
    let str = '';
    Object.keys(attributes).forEach(name => {
        if (extension_invalid_attribute_name_character.test(name))
            return;
        const value = attributes[name];
        if (value === true)
            str += ' ' + name;
        else if (src_extension_boolean_attributes.has(name.toLowerCase())) {
            if (value)
                str += ' ' + name;
        }
        else if (value != null) {
            str += ` ${name}="${value}"`;
        }
    });
    return str;
}
function extension_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 extension_ATTR_REGEX = /[&"]/g;
const extension_CONTENT_REGEX = /[&<]/g;
/**
 * Note: this method is performance sensitive and has been optimized
 * https://github.com/sveltejs/svelte/pull/5701
 */
function extension_internal_escape(value, is_attr = false) {
    const str = String(value);
    const pattern = is_attr ? extension_ATTR_REGEX : extension_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 extension_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 ? extension_internal_escape(value, true) : value;
}
function extension_escape_object(obj) {
    const result = {};
    for (const key in obj) {
        result[key] = extension_escape_attribute_value(obj[key]);
    }
    return result;
}
function extension_each(items, fn) {
    let str = '';
    for (let i = 0; i < items.length; i += 1) {
        str += fn(items[i], i);
    }
    return str;
}
const extension_missing_component = {
    $$render: () => ''
};
function extension_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 extension_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 extension_on_destroy;
function extension_create_ssr_component(fn) {
    function $$render(result, props, bindings, slots, context) {
        const parent_component = extension_current_component;
        const $$ = {
            on_destroy: extension_on_destroy,
            context: new Map(context || (parent_component ? parent_component.$$.context : [])),
            // these will be immediately discarded
            on_mount: [],
            before_update: [],
            after_update: [],
            callbacks: extension_blank_object()
        };
        extension_set_current_component({ $$ });
        const html = fn(result, props, bindings, slots);
        extension_set_current_component(parent_component);
        return html;
    }
    return {
        render: (props = {}, { $$slots = {}, context = new Map() } = {}) => {
            extension_on_destroy = [];
            const result = { title: '', head: '', css: new Set() };
            const html = $$render(result, props, {}, $$slots, context);
            extension_run_all(extension_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 extension_add_attribute(name, value, boolean) {
    if (value == null || (boolean && !value))
        return '';
    const assignment = (boolean && value === true) ? '' : `="${extension_internal_escape(value, true)}"`;
    return ` ${name}${assignment}`;
}
function extension_add_classes(classes) {
    return classes ? ` class="${classes}"` : '';
}
function extension_style_object_to_string(style_object) {
    return Object.keys(style_object)
        .filter(key => style_object[key])
        .map(key => `${key}: ${extension_escape_attribute_value(style_object[key])};`)
        .join(' ');
}
function extension_add_styles(style_object) {
    const styles = extension_style_object_to_string(style_object);
    return styles ? ` style="${styles}"` : '';
}

function extension_bind(component, name, callback) {
    const index = component.$$.props[name];
    if (index !== undefined) {
        component.$$.bound[index] = callback;
        callback(component.$$.ctx[index]);
    }
}
function extension_create_component(block) {
    block && block.c();
}
function extension_claim_component(block, parent_nodes) {
    block && block.l(parent_nodes);
}
function extension_mount_component(component, target, anchor, customElement) {
    const { fragment, after_update } = component.$$;
    fragment && fragment.m(target, anchor);
    if (!customElement) {
        // onMount happens before the initial afterUpdate
        extension_add_render_callback(() => {
            const new_on_destroy = component.$$.on_mount.map(extension_run).filter(extension_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
                extension_run_all(new_on_destroy);
            }
            component.$$.on_mount = [];
        });
    }
    after_update.forEach(extension_add_render_callback);
}
function extension_destroy_component(component, detaching) {
    const $$ = component.$$;
    if ($$.fragment !== null) {
        extension_flush_render_callbacks($$.after_update);
        extension_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 extension_make_dirty(component, i) {
    if (component.$$.dirty[0] === -1) {
        extension_dirty_components.push(component);
        extension_schedule_update();
        component.$$.dirty.fill(0);
    }
    component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function extension_init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
    const parent_component = extension_current_component;
    extension_set_current_component(component);
    const $$ = component.$$ = {
        fragment: null,
        ctx: [],
        // state
        props,
        update: extension_noop,
        not_equal,
        bound: extension_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: extension_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)
                    extension_make_dirty(component, i);
            }
            return ret;
        })
        : [];
    $$.update();
    ready = true;
    extension_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) {
            extension_start_hydrating();
            const nodes = extension_children(options.target);
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            $$.fragment && $$.fragment.l(nodes);
            nodes.forEach(extension_detach);
        }
        else {
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            $$.fragment && $$.fragment.c();
        }
        if (options.intro)
            extension_transition_in(component.$$.fragment);
        extension_mount_component(component, options.target, options.anchor, options.customElement);
        extension_end_hydrating();
        extension_flush();
    }
    extension_set_current_component(parent_component);
}
let extension_SvelteElement;
if (typeof HTMLElement === 'function') {
    extension_SvelteElement = class extends HTMLElement {
        constructor() {
            super();
            this.attachShadow({ mode: 'open' });
        }
        connectedCallback() {
            const { on_mount } = this.$$;
            this.$$.on_disconnect = on_mount.map(extension_run).filter(extension_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() {
            extension_run_all(this.$$.on_disconnect);
        }
        $destroy() {
            extension_destroy_component(this, 1);
            this.$destroy = extension_noop;
        }
        $on(type, callback) {
            // TODO should this delegate to addEventListener?
            if (!extension_internal_is_function(callback)) {
                return extension_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 && !extension_is_empty($$props)) {
                this.$$.skip_bound = true;
                this.$$set($$props);
                this.$$.skip_bound = false;
            }
        }
    };
}
/**
 * Base class for Svelte components. Used when dev=false.
 */
class extension_SvelteComponent {
    $destroy() {
        extension_destroy_component(this, 1);
        this.$destroy = extension_noop;
    }
    $on(type, callback) {
        if (!extension_internal_is_function(callback)) {
            return extension_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 && !extension_is_empty($$props)) {
            this.$$.skip_bound = true;
            this.$$set($$props);
            this.$$.skip_bound = false;
        }
    }
}

function extension_dispatch_dev(type, detail) {
    document.dispatchEvent(extension_custom_event(type, Object.assign({ version: '3.59.2' }, detail), { bubbles: true }));
}
function extension_append_dev(target, node) {
    extension_dispatch_dev('SvelteDOMInsert', { target, node });
    extension_append(target, node);
}
function extension_append_hydration_dev(target, node) {
    extension_dispatch_dev('SvelteDOMInsert', { target, node });
    extension_append_hydration(target, node);
}
function extension_insert_dev(target, node, anchor) {
    extension_dispatch_dev('SvelteDOMInsert', { target, node, anchor });
    extension_insert(target, node, anchor);
}
function extension_insert_hydration_dev(target, node, anchor) {
    extension_dispatch_dev('SvelteDOMInsert', { target, node, anchor });
    extension_insert_hydration(target, node, anchor);
}
function extension_detach_dev(node) {
    extension_dispatch_dev('SvelteDOMRemove', { node });
    extension_detach(node);
}
function extension_detach_between_dev(before, after) {
    while (before.nextSibling && before.nextSibling !== after) {
        extension_detach_dev(before.nextSibling);
    }
}
function extension_detach_before_dev(after) {
    while (after.previousSibling) {
        extension_detach_dev(after.previousSibling);
    }
}
function extension_detach_after_dev(before) {
    while (before.nextSibling) {
        extension_detach_dev(before.nextSibling);
    }
}
function extension_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');
    extension_dispatch_dev('SvelteDOMAddEventListener', { node, event, handler, modifiers });
    const dispose = extension_listen(node, event, handler, options);
    return () => {
        extension_dispatch_dev('SvelteDOMRemoveEventListener', { node, event, handler, modifiers });
        dispose();
    };
}
function extension_attr_dev(node, attribute, value) {
    extension_attr(node, attribute, value);
    if (value == null)
        extension_dispatch_dev('SvelteDOMRemoveAttribute', { node, attribute });
    else
        extension_dispatch_dev('SvelteDOMSetAttribute', { node, attribute, value });
}
function extension_prop_dev(node, property, value) {
    node[property] = value;
    extension_dispatch_dev('SvelteDOMSetProperty', { node, property, value });
}
function extension_dataset_dev(node, property, value) {
    node.dataset[property] = value;
    extension_dispatch_dev('SvelteDOMSetDataset', { node, property, value });
}
function extension_set_data_dev(text, data) {
    data = '' + data;
    if (text.data === data)
        return;
    extension_dispatch_dev('SvelteDOMSetData', { node: text, data });
    text.data = data;
}
function extension_set_data_contenteditable_dev(text, data) {
    data = '' + data;
    if (text.wholeText === data)
        return;
    extension_dispatch_dev('SvelteDOMSetData', { node: text, data });
    text.data = data;
}
function extension_set_data_maybe_contenteditable_dev(text, data, attr_value) {
    if (~extension_contenteditable_truthy_values.indexOf(attr_value)) {
        extension_set_data_contenteditable_dev(text, data);
    }
    else {
        extension_set_data_dev(text, data);
    }
}
function extension_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 extension_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 extension_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 extension_validate_void_dynamic_element(tag) {
    if (tag && extension_is_void(tag)) {
        console.warn(`<svelte:element this="${tag}"> is self-closing and cannot have content.`);
    }
}
function extension_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 extension_SvelteComponentDev extends extension_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 extension_SvelteComponentTyped extends extension_SvelteComponentDev {
    constructor(options) {
        super(options);
    }
}
function extension_loop_guard(timeout) {
    const start = Date.now();
    return () => {
        if (Date.now() - start > timeout) {
            throw new Error('Infinite loop detected');
        }
    };
}



;// ../../node_modules/arquero/src/util/is-array.js
/* harmony default export */ const extension_is_array = (Array.isArray);

;// ../../node_modules/arquero/src/util/to-array.js


/* harmony default export */ function extension_to_array(value) {
  return value != null
    ? (extension_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 extension_slice(start = 0, end = Infinity) {
  return `${extension_prep(start)} < row_number() && row_number() <= ${extension_prep(end)}`;
}

function extension_prep(index) {
  return index < 0 ? `count() + ${index}` : index;
}
;// ../../node_modules/arquero/src/table/transformable.js



/**
 * Abstract base class for transforming data.
 */
class extension_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(extension_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, extension_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 extension_util_error(message) {
  throw Error(message);
}
;// ../../node_modules/arquero/src/util/is-number.js
/* harmony default export */ function extension_is_number(value) {
  return typeof value === 'number';
}
;// ../../node_modules/arquero/src/util/is-function.js
/* harmony default export */ function extension_util_is_function(value) {
  return typeof value === 'function';
}
;// ../../node_modules/arquero/src/util/repeat.js


/* harmony default export */ function extension_util_repeat(reps, value) {
  const result = Array(reps);
  if (extension_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 extension_Table extends extension_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
    extension_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
    extension_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
    extension_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
    extension_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
    extension_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
    extension_util_error('Not implemented');
  }

  /**
   * Returns an iterator over objects representing table rows.
   * @return {Iterator<object>} An iterator over row objects.
   */
  [Symbol.iterator]() {
    extension_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 (extension_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 = extension_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 extension_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 extension_defaultColumnFactory = function(data) {
  return data && extension_util_is_function(data.get) ? data : new extension_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 extension_columnFactory(factory) {
  return arguments.length
    ? (extension_defaultColumnFactory = factory)
    : extension_defaultColumnFactory;
}
;// ../../node_modules/arquero/src/util/is-date.js
/* harmony default export */ function extension_is_date(value) {
  return value instanceof Date;
}
;// ../../node_modules/arquero/src/util/is-object.js
/* harmony default export */ function extension_is_object(value) {
  return value === Object(value);
}
;// ../../node_modules/arquero/src/util/is-regexp.js
/* harmony default export */ function extension_is_regexp(value) {
  return value instanceof RegExp;
}
;// ../../node_modules/arquero/src/util/is-string.js
/* harmony default export */ function extension_is_string(value) {
  return typeof value === 'string';
}

;// ../../node_modules/arquero/src/table/columns-from.js








/* harmony default export */ function extension_columns_from(values, names) {
  const raise = type => extension_util_error(`Illegal argument type: ${type || typeof values}`);
  return values instanceof Map ? extension_fromKeyValuePairs(values.entries(), names)
    : extension_is_date(values) ? raise('Date')
    : extension_is_regexp(values) ? raise('RegExp')
    : extension_is_string(values) ? raise()
    : extension_is_array(values) ? extension_fromArray(values, names)
    : extension_util_is_function(values[Symbol.iterator]) ? extension_fromIterable(values, names)
    : extension_is_object(values) ? extension_fromKeyValuePairs(Object.entries(values), names)
    : raise();
}

function extension_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 extension_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 extension_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: extension_has_hasOwnProperty } = Object.prototype;

/* harmony default export */ function extension_util_has(object, property) {
  return extension_has_hasOwnProperty.call(object, property);
}
;// ../../node_modules/arquero/src/table/column-set.js


/* harmony default export */ function extension_column_set(table) {
  return table
    ? new extension_ColumnSet({ ...table.data() }, table.columnNames())
    : new extension_ColumnSet();
}

class extension_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 extension_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 extension_util_null = (undefined);
;// ../../node_modules/arquero/src/util/is-typed-array.js
const extension_TypedArray = Object.getPrototypeOf(Int8Array);

/* harmony default export */ function extension_is_typed_array(value) {
  return value instanceof extension_TypedArray;
}
;// ../../node_modules/arquero/src/util/is-array-type.js



function extension_is_array_type_isArrayType(value) {
  return extension_is_array(value) || extension_is_typed_array(value);
}
;// ../../node_modules/arquero/src/util/is-valid.js
/* harmony default export */ function extension_is_valid(value) {
  return value != null && value === value;
}

;// ../../node_modules/arquero/src/op/functions/array.js





const extension_isSeq = (seq) => extension_is_array_type_isArrayType(seq) || extension_is_string(seq);

/* harmony default export */ const extension_array = ({
  compact:      (arr) => extension_is_array_type_isArrayType(arr) ? arr.filter(v => extension_is_valid(v)) : arr,
  concat:       (...values) => [].concat(...values),
  includes:     (seq, value, index) => extension_isSeq(seq)
                  ? seq.includes(value, index)
                  : false,
  indexof:      (seq, value) => extension_isSeq(seq) ? seq.indexOf(value) : -1,
  join:         (arr, delim) => extension_is_array_type_isArrayType(arr) ? arr.join(delim) : extension_util_null,
  lastindexof:  (seq, value) => extension_isSeq(seq) ? seq.lastIndexOf(value) : -1,
  length:       (seq) => extension_isSeq(seq) ? seq.length : 0,
  pluck:        (arr, prop) => extension_is_array_type_isArrayType(arr)
                  ? arr.map(v => extension_is_valid(v) ? v[prop] : extension_util_null)
                  : extension_util_null,
  reverse:      (seq) => extension_is_array_type_isArrayType(seq) ? seq.slice().reverse()
                  : extension_is_string(seq) ? seq.split('').reverse().join('')
                  : extension_util_null,
  slice:        (seq, start, end) => extension_isSeq(seq) ? seq.slice(start, end) : extension_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 extension_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 extension_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 extension_pad2 = v => (v < 10 ? '0' : '') + v;

const extension_formatYear = year => year < 0 ? '-' + extension_pad(-year, 6)
  : year > 9999 ? '+' + extension_pad(year, 6)
  : extension_pad(year, 4);

function extension_formatISO(year, month, date, hours, min, sec, ms, utc, short) {
  const suffix = utc ? 'Z' : '';
  return extension_formatYear(year) + '-' + extension_pad2(month + 1) + '-' + extension_pad2(date) + (
    !short || ms ? 'T' + extension_pad2(hours) + ':' + extension_pad2(min) + ':' + extension_pad2(sec) + '.' + extension_pad(ms, 3) + suffix
    : sec ? 'T' + extension_pad2(hours) + ':' + extension_pad2(min) + ':' + extension_pad2(sec) + suffix
    : min || hours || !utc ? 'T' + extension_pad2(hours) + ':' + extension_pad2(min) + suffix
    : ''
  );
}

function extension_formatDate(d, short) {
  return isNaN(d)
    ? 'Invalid Date'
    : extension_formatISO(
      d.getFullYear(),
      d.getMonth(),
      d.getDate(),
      d.getHours(),
      d.getMinutes(),
      d.getSeconds(),
      d.getMilliseconds(),
      false, short
    );
}

function extension_formatUTCDate(d, short) {
  return isNaN(d)
    ? 'Invalid Date'
    : extension_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 extension_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 extension_is_iso_date_string(value) {
  return value.match(extension_iso_re);
}
;// ../../node_modules/arquero/src/util/parse-iso-date.js


/* harmony default export */ function extension_parse_iso_date(value, parse = Date.parse) {
  return extension_is_iso_date_string(value) ? parse(value) : value;
}
;// ../../node_modules/arquero/src/op/functions/date.js



const extension_msMinute = 6e4;
const extension_msDay = 864e5;
const extension_msWeek = 6048e5;

const extension_t0 = new Date();
const extension_t1 = new Date();
const extension_t = d => (
  extension_t0.setTime(typeof d === 'string' ? extension_parse_iso_date(d) : d),
  extension_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 extension_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 extension_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 extension_dayofyear(date) {
  extension_t1.setTime(+date);
  extension_t1.setHours(0, 0, 0, 0);
  extension_t0.setTime(+extension_t1);
  extension_t0.setMonth(0);
  extension_t0.setDate(1);
  const tz = (extension_t1.getTimezoneOffset() - extension_t0.getTimezoneOffset()) * extension_msMinute;
  return Math.floor(1 + ((extension_t1 - extension_t0) - tz) / extension_msDay);
}

function extension_utcdayofyear(date) {
  extension_t1.setTime(+date);
  extension_t1.setUTCHours(0, 0, 0, 0);
  const t0 = Date.UTC(extension_t1.getUTCFullYear(), 0, 1);
  return Math.floor(1 + (extension_t1 - t0) / extension_msDay);
}

function extension_week(date, firstday) {
  const i = firstday || 0;
  extension_t1.setTime(+date);
  extension_t1.setDate(extension_t1.getDate() - (extension_t1.getDay() + 7 - i) % 7);
  extension_t1.setHours(0, 0, 0, 0);
  extension_t0.setTime(+date);
  extension_t0.setMonth(0);
  extension_t0.setDate(1);
  extension_t0.setDate(1 - (extension_t0.getDay() + 7 - i) % 7);
  extension_t0.setHours(0, 0, 0, 0);
  const tz = (extension_t1.getTimezoneOffset() - extension_t0.getTimezoneOffset()) * extension_msMinute;
  return Math.floor((1 + (extension_t1 - extension_t0) - tz) / extension_msWeek);
}

function extension_utcweek(date, firstday) {
  const i = firstday || 0;
  extension_t1.setTime(+date);
  extension_t1.setUTCDate(extension_t1.getUTCDate() - (extension_t1.getUTCDay() + 7 - i) % 7);
  extension_t1.setUTCHours(0, 0, 0, 0);
  extension_t0.setTime(+date);
  extension_t0.setUTCMonth(0);
  extension_t0.setUTCDate(1);
  extension_t0.setUTCDate(1 - (extension_t0.getUTCDay() + 7 - i) % 7);
  extension_t0.setUTCHours(0, 0, 0, 0);
  return Math.floor((1 + (extension_t1 - extension_t0)) / extension_msWeek);
}

/* harmony default export */ const extension_date = ({
  format_date:     (date, shorten) => extension_formatDate(extension_t(date), !shorten),
  format_utcdate:  (date, shorten) => extension_formatUTCDate(extension_t(date), !shorten),
  timestamp:       (date) => +extension_t(date),
  year:            (date) => extension_t(date).getFullYear(),
  quarter:         (date) => Math.floor(extension_t(date).getMonth() / 3),
  month:           (date) => extension_t(date).getMonth(),
  date:            (date) => extension_t(date).getDate(),
  dayofweek:       (date) => extension_t(date).getDay(),
  hours:           (date) => extension_t(date).getHours(),
  minutes:         (date) => extension_t(date).getMinutes(),
  seconds:         (date) => extension_t(date).getSeconds(),
  milliseconds:    (date) => extension_t(date).getMilliseconds(),
  utcyear:         (date) => extension_t(date).getUTCFullYear(),
  utcquarter:      (date) => Math.floor(extension_t(date).getUTCMonth() / 3),
  utcmonth:        (date) => extension_t(date).getUTCMonth(),
  utcdate:         (date) => extension_t(date).getUTCDate(),
  utcdayofweek:    (date) => extension_t(date).getUTCDay(),
  utchours:        (date) => extension_t(date).getUTCHours(),
  utcminutes:      (date) => extension_t(date).getUTCMinutes(),
  utcseconds:      (date) => extension_t(date).getUTCSeconds(),
  utcmilliseconds: (date) => extension_t(date).getUTCMilliseconds(),
  datetime: extension_datetime,
  dayofyear: extension_dayofyear,
  week: extension_week,
  utcdatetime: extension_utcdatetime,
  utcdayofyear: extension_utcdayofyear,
  utcweek: extension_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 extension_equal(a, b) {
  return (a == null || b == null || a !== a || b !== b) ? false
    : a === b ? true
    : (extension_is_date(a) || extension_is_date(b)) ? +a === +b
    : (extension_is_regexp(a) && extension_is_regexp(b)) ? a + '' === b + ''
    : (extension_is_object(a) && extension_is_object(b)) ? extension_deepEqual(a, b)
    : false;
}

function extension_deepEqual(a, b) {
  if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {
    return false;
  }

  if (a.length || b.length) {
    return extension_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 (!extension_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 (!extension_equal(a[k], b[k])) {
      return false;
    }
  }

  return true;
}

function extension_arrayEqual(a, b, test = extension_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 extension_json = ({
  parse_json: (str) => JSON.parse(str),
  to_json:    (val) => JSON.stringify(val)
});
;// ../../node_modules/arquero/src/util/random.js


let extension_source = Math.random;

function extension_random() {
  return extension_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 extension_seed(seed) {
  extension_source = isValid(seed) && isFinite(seed = +seed) ? extension_lcg(seed) : Math.random;
}

function extension_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 extension_math = ({
  random: extension_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 extension_is_map(value) {
  return value instanceof Map;
}
;// ../../node_modules/arquero/src/util/is-set.js
/* harmony default export */ function extension_is_set(value) {
  return value instanceof Set;
}
;// ../../node_modules/arquero/src/util/is-map-or-set.js



/* harmony default export */ function extension_is_map_or_set(value) {
  return extension_is_map(value) || extension_is_set(value);
}
;// ../../node_modules/arquero/src/op/functions/object.js





function extension_object_array(iter) {
  return Array.from(iter);
}

/* harmony default export */ const extension_object = ({
  has:      (obj, key) => extension_is_map_or_set(obj) ? obj.has(key)
              : obj != null ? extension_util_has(obj, key)
              : false,
  keys:     (obj) => extension_is_map(obj) ? extension_object_array(obj.keys())
              : obj != null ? Object.keys(obj)
              : [],
  values:   (obj) => extension_is_map_or_set(obj) ? extension_object_array(obj.values())
              : obj != null ? Object.values(obj)
              : [],
  entries:  (obj) => extension_is_map_or_set(obj) ? extension_object_array(obj.entries())
              : obj != null ? Object.entries(obj)
              : [],
  object:   (entries) => entries ? Object.fromEntries(entries) : extension_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 extension_recode(value, map, fallback) {
  if (map instanceof Map) {
    if (map.has(value)) return map.get(value);
  } else if (extension_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 extension_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 extension_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 extension_op_functions = ({
  bin: extension_bin,
  equal: extension_equal,
  recode: extension_recode,
  sequence: extension_sequence,
  ...extension_array,
  ...extension_date,
  ...extension_json,
  ...extension_math,
  ...extension_object,
  ...extension_string
});
;// ../../node_modules/arquero/src/util/is-bigint.js
/* harmony default export */ function extension_is_bigint(value) {
  return typeof value === 'bigint';
}
;// ../../node_modules/arquero/src/util/to-string.js


/* harmony default export */ function extension_to_string(v) {
  return v === undefined ? v + ''
    : extension_is_bigint(v) ? v + 'n'
    : JSON.stringify(v);
}
;// ../../node_modules/arquero/src/op/op.js



/* harmony default export */ function extension_op_op(name, fields = [], params = []) {
  return new extension_Op(name, extension_to_array(fields), extension_to_array(params));
}

class extension_Op {
  constructor(name, fields, params) {
    this.name = name;
    this.fields = fields;
    this.params = params;
  }
  toString() {
    const args = [
      ...this.fields.map(f => `d[${extension_to_string(f)}]`),
      ...this.params.map(extension_to_string)
    ];
    return `d => op.${this.name}(${args})`;
  }
  toObject() {
    return { expr: this.toString(), func: true };
  }
}
;// ../../node_modules/arquero/src/op/op-api.js



const extension_any = (field) => extension_op_op('any', field);
const extension_count = () => extension_op_op('count');
const extension_array_agg = (field) => extension_op_op('array_agg', field);
const extension_array_agg_distinct = (field) => extension_op_op('array_agg_distinct', field);
const extension_map_agg = (key, value) => extension_op_op('map_agg', [key, value]);
const extension_object_agg = (key, value) => extension_op_op('object_agg', [key, value]);
const extension_entries_agg = (key, value) => extension_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 extension_op_api = ({
  ...extension_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) => extension_op_op('row_object', null, names.flat()),

  /**
   * Aggregate function to count the number of records (rows).
   * @returns {number} The count of records.
   */
  count: extension_count,

  /**
   * Aggregate function returning an arbitrary observed value.
   * @param {*} field The data field.
   * @return {*} An arbitrary observed value.
   */
  any: extension_any,

  /**
   * Aggregate function to collect an array of values.
   * @param {*} field The data field.
   * @return {Array} A list of values.
   */
  array_agg: extension_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: extension_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: extension_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: extension_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: extension_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) => extension_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) => extension_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) => extension_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) => extension_op_op('mode', field),

  /**
   * Aggregate function to sum values.
   * @param {string} field The data field.
   * @return {number} The sum of the values.
   */
  sum: (field) => extension_op_op('sum', field),

  /**
   * Aggregate function to multiply values.
   * @param {*} field The data field.
   * @return {number} The product of the values.
   */
  product: (field) => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) => extension_op_op('stdevp', field),

  /**
   * Aggregate function for the minimum value.
   * @param {*} field The data field.
   * @return {number} The minimum value.
   */
  min: (field) => extension_op_op('min', field),

  /**
   * Aggregate function for the maximum value.
   * @param {*} field The data field.
   * @return {number} The maximum value.
   */
  max: (field) => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) =>
    extension_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: () => extension_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: () => extension_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: () => extension_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: () => extension_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: () => extension_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: () => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) => extension_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) => extension_op_op('fill_up', field, defaultValue)
});
;// ../../node_modules/arquero/src/util/unique-name.js


/* harmony default export */ function extension_unique_name(names, name) {
  names = extension_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 extension_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 extension_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 extension_nest(table, idx, obj, type) {
  const agg = type === 'map' || type === true ? extension_map_agg
    : type === 'entries' ? extension_entries_agg
    : type === 'object' ? extension_object_agg
    : extension_util_error('groups option must be "map", "entries", or "object".');

  const { names } = table.groups();
  const col = extension_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]: extension_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 extension_ArrayPattern = 'ArrayPattern';
const extension_ArrowFunctionExpression = 'ArrowFunctionExpression';
const extension_FunctionExpression = 'FunctionExpression';
const extension_Identifier = 'Identifier';
const extension_Literal = 'Literal';
const extension_MemberExpression = 'MemberExpression';
const extension_ObjectExpression = 'ObjectExpression';
const extension_ObjectPattern = 'ObjectPattern';
const extension_Property = 'Property';

const extension_constants_Column = 'Column';
const extension_Constant = 'Constant';
const extension_Dictionary = 'Dictionary';
const extension_constants_Function = 'Function';
const extension_Parameter = 'Parameter';
const extension_constants_Op = 'Op';
;// ../../node_modules/arquero/src/expression/codegen.js



const extension_visit = (node, opt) => {
  const f = extension_visitors[node.type];
  return f
    ? f(node, opt)
    : extension_util_error(`Unsupported expression construct: ${node.type}`);
};

const extension_binary = (node, opt) => {
  return '(' + extension_visit(node.left, opt) + ' ' + node.operator + ' ' + extension_visit(node.right, opt) + ')';
};

const extension_func = (node, opt) => {
  return '(' + extension_list(node.params, opt) + ')=>' + extension_visit(node.body, opt);
};

const extension_call = (node, opt) => {
  return extension_visit(node.callee, opt) + '(' + extension_list(node.arguments, opt) + ')';
};

const extension_list = (array, opt, delim = ',') => {
  return array.map(node => extension_visit(node, opt)).join(delim);
};

const extension_codegen_name = node => node.computed
  ? `[${extension_to_string(node.name)}]`
  : `.${node.name}`;

const extension_ref = (node, opt, method) => {
  const table = node.table || '';
  return `data${table}${extension_codegen_name(node)}.${method}(${opt.index}${table})`;
};

const extension_visitors = {
  Constant: node => node.raw,
  Column: (node, opt) => extension_ref(node, opt, 'get'),
  Dictionary: (node, opt) => extension_ref(node, opt, 'key'),
  Function: node => `fn.${node.name}`,
  Parameter: node => `$${extension_codegen_name(node)}`,
  Op: (node, opt) => `op(${extension_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 += '${' + extension_visit(expressions[i], opt) + '}' + quasis[++i].value.raw;
    }
    return '`' + t + '`';
  },
  MemberExpression: (node, opt) => {
    const d = !node.computed;
    const o = extension_visit(node.object, opt);
    const p = extension_visit(node.property, opt);
    return o + (d ? '.' + p : '[' + p + ']');
  },
  CallExpression: extension_call,
  NewExpression: (node, opt) => {
    return 'new ' + extension_call(node, opt);
  },
  ArrayExpression: (node, opt) => {
    return '[' + extension_list(node.elements, opt) + ']';
  },
  AssignmentExpression: extension_binary,
  BinaryExpression: extension_binary,
  LogicalExpression: extension_binary,
  UnaryExpression: (node, opt) => {
    return '(' + node.operator + extension_visit(node.argument, opt) + ')';
  },
  ConditionalExpression: (node, opt) => {
    return '(' + extension_visit(node.test, opt) +
      '?' + extension_visit(node.consequent, opt) +
      ':' + extension_visit(node.alternate, opt) + ')';
  },
  ObjectExpression: (node, opt) => {
    return '({' + extension_list(node.properties, opt) + '})';
  },
  Property: (node, opt) => {
    const key = extension_visit(node.key, opt);
    return (node.computed ? `[${key}]` : key) + ':' + extension_visit(node.value, opt);
  },

  ArrowFunctionExpression: extension_func,
  FunctionExpression: extension_func,
  FunctionDeclaration: extension_func,

  ArrayPattern: (node, opt) => {
    return '[' + extension_list(node.elements, opt) + ']';
  },
  ObjectPattern: (node, opt) => {
    return '{' + extension_list(node.properties, opt) + '}';
  },
  VariableDeclaration: (node, opt) => {
    return node.kind + ' ' + extension_list(node.declarations, opt, ',');
  },
  VariableDeclarator: (node, opt) => {
    return extension_visit(node.id, opt) + '=' + extension_visit(node.init, opt);
  },
  SpreadElement: (node, opt) => {
    return '...' + extension_visit(node.argument, opt);
  },

  BlockStatement: (node, opt) => {
    return '{' + extension_list(node.body, opt, ';') + ';}';
  },
  BreakStatement: () => {
    return 'break';
  },
  ExpressionStatement: (node, opt) => {
    return extension_visit(node.expression, opt);
  },
  IfStatement: (node, opt) => {
    return 'if (' + extension_visit(node.test, opt) + ')'
      + extension_visit(node.consequent, opt)
      + (node.alternate ? ' else ' + extension_visit(node.alternate, opt) : '');
  },
  SwitchStatement: (node, opt) => {
    return 'switch (' + extension_visit(node.discriminant, opt) + ') {'
     + extension_list(node.cases, opt, '')
     + '}';
  },
  SwitchCase: (node, opt) => {
    return (node.test ? 'case ' + extension_visit(node.test, opt) : 'default')
      + ': '
      + extension_list(node.consequent, opt, ';') + ';';
  },
  ReturnStatement: (node, opt) => {
    return 'return ' + extension_visit(node.argument, opt);
  },
  Program: (node, opt) => extension_visit(node.body[0], opt)
};

/* harmony default export */ function extension_codegen(node, opt = { index: 'row' }) {
  return extension_visit(node, opt);
}
;// ../../node_modules/arquero/src/util/bins.js
/* harmony default export */ function extension_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 extension_key(value) {
  const type = typeof value;
  return type === 'string' ? `"${value}"`
    : type !== 'object' || !value ? value
    : extension_is_date(value) ? +value
    : extension_is_array(value) || extension_is_typed_array(value) ? `[${value.map(extension_key)}]`
    : extension_is_regexp(value) ? value + ''
    : extension_objectKey(value);
}

function extension_objectKey(value) {
  let s = '{';
  let i = -1;
  for (const k in value) {
    if (++i > 0) s += ',';
    s += `"${k}":${extension_key(value[k])}`;
  }
  s += '}';
  return s;
}

/* harmony default export */ function extension_key_function(get, nulls) {
  const n = get.length;
  return n === 1
    ? (row, data) => extension_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 += extension_key(v);
        }
        return s;
      };
}
;// ../../node_modules/arquero/src/util/distinct-map.js


/* harmony default export */ function extension_distinct_map() {
  const map = new Map();
  return {
    count() {
      return map.size;
    },
    values() {
      return Array.from(map.values(), _ => _.v);
    },
    increment(v) {
      const k = extension_key(v);
      const e = map.get(k);
      e ? ++e.n : map.set(k, { v, n: 1 });
    },
    decrement(v) {
      const k = extension_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 extension_no_op() {}
;// ../../node_modules/arquero/src/util/product.js
/* harmony default export */ function extension_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 extension_initOp(op) {
  op.init = op.init || extension_no_op;
  op.add = op.add || extension_no_op;
  op.rem = op.rem || extension_no_op;
  return op;
}

function extension_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 extension_aggregate_functions = ({
  /** @type {AggregateDef} */
  count: {
    create: () => extension_initOp({
      value: s => s.count
    }),
    param: []
  },

  /** @type {AggregateDef} */
  array_agg: {
    create: () => extension_initOp({
      init: s => s.values = true,
      value: s => s.list.values(s.stream)
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  object_agg: {
    create: () => extension_initOp({
      init:  s => s.values = true,
      value: s => Object.fromEntries(s.list.values())
    }),
    param: [2]
  },

  /** @type {AggregateDef} */
  map_agg: {
    create: () => extension_initOp({
      init:  s => s.values = true,
      value: s => new Map(s.list.values())
    }),
    param: [2]
  },

  /** @type {AggregateDef} */
  entries_agg: {
    create: () => extension_initOp({
      init:  s => s.values = true,
      value: s => s.list.values(s.stream)
    }),
    param: [2]
  },

  /** @type {AggregateDef} */
  any: {
    create: () => extension_initOp({
      add: (s, v) => { if (s.any == null) s.any = v; },
      value: s => s.valid ? s.any : extension_util_null
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  valid: {
    create: () => extension_initOp({
      value: s => s.valid
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  invalid: {
    create: () => extension_initOp({
      value: s => s.count - s.valid
    }),
    param: [1]
  },

  /** @type {AggregateDef} */
  distinct: {
    create: () => ({
      init: s => s.distinct = extension_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: () => extension_initOp({
      value: s => s.distinct.values()
    }),
    param: [1],
    req: ['distinct']
  },

  /** @type {AggregateDef} */
  mode: {
    create: () => extension_initOp({
      value: s => {
        let mode = extension_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 : extension_util_null,
      add: (s, v) => extension_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 => extension_initProduct(s, 1),
      value: s => s.valid
        ? (
            s.product_v
              ? extension_initProduct(s, extension_product(s.list.values()))
              : s.product
          )
        : undefined,
      add: (s, v) => extension_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 : extension_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: () => extension_initOp({
      value: s => s.valid ? s.mean : extension_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) : extension_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: () => extension_initOp({
      value: s => s.valid > 1 ? s.dev / s.valid : extension_util_null
    }),
    param: [1],
    req: ['variance']
  },

  /** @type {AggregateDef} */
  stdev: {
    create: () => extension_initOp({
      value: s => s.valid > 1 ? Math.sqrt(s.dev / (s.valid - 1)) : extension_util_null
    }),
    param: [1],
    req: ['variance']
  },

  /** @type {AggregateDef} */
  stdevp: {
    create: () => extension_initOp({
      value: s => s.valid > 1 ? Math.sqrt(s.dev / s.valid) : extension_util_null
    }),
    param: [1],
    req: ['variance']
  },

  /** @type {AggregateDef} */
  min: {
    create: () => ({
      init:  s => s.min = extension_util_null,
      value: s => s.min = (Number.isNaN(s.min) ? s.list.min() : s.min),
      add: (s, v) => { if (v < s.min || s.min === extension_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 = extension_util_null,
      value: s => s.max = (Number.isNaN(s.max) ? s.list.max() : s.max),
      add: (s, v) => { if (v > s.max || s.max === extension_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) => extension_initOp({
      value: s => s.list.quantile(p)
    }),
    param: [1, 1],
    req: ['array_agg']
  },

  /** @type {AggregateDef} */
  median: {
    create: () => extension_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) : extension_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: () => extension_initOp({
      value: s => s.valid > 1 ? s.cov / s.valid : extension_util_null
    }),
    param: [2],
    req: ['covariance']
  },

  /** @type {AggregateDef} */
  corr: {
    create: () => extension_initOp({
      value: s => s.valid > 1
        ? s.cov / (Math.sqrt(s.dev_x) * Math.sqrt(s.dev_y))
        : extension_util_null
    }),
    param: [2],
    req: ['covariance']
  },

  /** @type {AggregateDef} */
  bins: {
    create: (maxbins, nice, minstep, step) => extension_initOp({
      value: s => extension_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 extension_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 extension_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 extension_window_functions = ({
  /** @type {WindowDef} */
  row_number: {
    create() {
      return {
        init: extension_no_op,
        value: w => w.index + 1
      };
    },
    param: []
  },

  /** @type {WindowDef} */
  rank: extension_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 } = extension_rank.create();
      return {
        init,
        value: w => (value(w) - 1) / (w.size - 1)
      };
    },
    param: []
  },

  /** @type {WindowDef} */
  cume_dist: extension_cume_dist,

  /** @type {WindowDef} */
  ntile: {
    create(num) {
      num = +num;
      if (!(num > 0)) extension_util_error('ntile num must be greater than zero.');
      const { init, value } = extension_cume_dist.create();
      return {
        init,
        value: w => Math.ceil(num * value(w))
      };
    },
    param: [0, 1]
  },

  /** @type {WindowDef} */
  lag: {
    create(offset, defaultValue = extension_util_null) {
      offset = +offset || 1;
      return {
        init: extension_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 = extension_util_null) {
      offset = +offset || 1;
      return {
        init: extension_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: extension_no_op,
        value: (w, f) => w.value(w.i0, f)
      };
    },
    param: [1]
  },

  /** @type {WindowDef} */
  last_value: {
    create() {
      return {
        init: extension_no_op,
        value: (w, f) => w.value(w.i1 - 1, f)
      };
    },
    param: [1]
  },

  /** @type {WindowDef} */
  nth_value: {
    create(nth) {
      nth = +nth;
      if (!(nth > 0)) extension_util_error('nth_value nth must be greater than zero.');
      return {
        init: extension_no_op,
        value: (w, f) => {
          const i = w.i0 + (nth - 1);
          return i < w.i1 ? w.value(i, f) : extension_util_null;
        }
      };
    },
    param: [1, 1]
  },

  /** @type {WindowDef} */
  fill_down: {
    create(defaultValue = extension_util_null) {
      let value;
      return {
        init: () => value = defaultValue,
        value: (w, f) => {
          const v = w.value(w.index, f);
          return extension_is_valid(v) ? (value = v) : value;
        }
      };
    },
    param: [1, 1]
  },

  /** @type {WindowDef} */
  fill_up: {
    create(defaultValue = extension_util_null) {
      let value, idx;
      return {
        init: () => (value = defaultValue, idx = -1),
        value: (w, f) => w.index <= idx ? value
          : (idx = extension_find(w, f, w.index)) >= 0 ? (value = w.value(idx, f))
          : (idx = w.size, value = defaultValue)
      };
    },
    param: [1, 1]
  }
});

function extension_find(w, f, i) {
  for (const n = w.size; i < n; ++i) {
    if (extension_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 extension_hasAggregate(name) {
  return extension_util_has(extension_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 extension_hasWindow(name) {
  return extension_util_has(extension_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 extension_hasFunction(name) {
  return extension_util_has(extension_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 extension_getAggregate(name) {
  return extension_hasAggregate(name) && extension_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 extension_getWindow(name) {
  return extension_hasWindow(name) && extension_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 extension_getFunction(name) {
  return extension_hasFunction(name) && functions[name];
}
;// ../../node_modules/arquero/src/expression/compile.js


function extension_compile(code, fn, params) {
  code = `"use strict"; return ${code};`;
  return (Function('fn', '$', code))(fn, params);
}

/* harmony default export */ const extension_expression_compile = ({
  escape: (code, func, params) => extension_compile(code, func, params),
  expr:   (code, params) => extension_compile(`(row,data,op)=>${code}`, extension_op_functions, params),
  expr2:  (code, params) => extension_compile(`(row0,data0,row,data)=>${code}`, extension_op_functions, params),
  join:   (code, params) => extension_compile(`(row1,data1,row2,data2)=>${code}`, extension_op_functions, params),
  param:  (code, params) => extension_compile(code, extension_op_functions, params)
});
;// ../../node_modules/arquero/src/expression/rewrite.js



const extension_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 extension_rewrite(ref, name, index = 0, col, op) {
  ref.type = extension_constants_Column;
  ref.name = name;
  ref.table = index;

  // proceed only if has parent op and is a dictionary column
  if (op && col && extension_util_is_function(col.keyFor)) {
    // get other arg if op is an optimizeable operation
    const lit = extension_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 === extension_Literal) {
      extension_rewriteDictionary(op, ref, lit, col.keyFor(lit.value));
    }
  }

  return ref;
}

function extension_rewriteDictionary(op, ref, lit, key) {
  if (key < 0) {
    // value not in dictionary, rewrite op as false literal
    op.type = extension_Literal;
    op.value = false;
    op.raw = 'false';
  } else {
    // rewrite ref as dict key access
    ref.type = extension_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 extension_entries(value) {
  return extension_is_array(value) ? value
    : extension_is_map(value) ? value.entries()
    : value ? Object.entries(value)
    : [];
}
;// ../../node_modules/arquero/src/expression/row-object.js








const extension_row_object_ROW_OBJECT = 'row_object';

function extension_rowObjectExpression(node, props) {
  node.type = extension_ObjectExpression;

  const p = node.properties = [];
  for (const prop of extension_entries(props)) {
    const [name, key] = extension_is_array(prop) ? prop : [prop, prop];
    p.push({
      type: extension_Property,
      key: { type: extension_Literal, raw: extension_to_string(key) },
      value: extension_rewrite({ computed: true }, name)
    });
  }

  return node;
}

function extension_rowObjectCode(props) {
  return extension_codegen(extension_rowObjectExpression({}, props));
}

function extension_rowObjectBuilder(props) {
  return extension_expression_compile.expr(extension_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 extension_flatbuffers = {};

/**
 * @typedef {number}
 */
extension_flatbuffers.Offset;

/**
 * @typedef {{
 *   bb: flatbuffers.ByteBuffer,
 *   bb_pos: number
 * }}
 */
extension_flatbuffers.Table;

/**
 * @type {number}
 * @const
 */
extension_flatbuffers.SIZEOF_SHORT = 2;

/**
 * @type {number}
 * @const
 */
extension_flatbuffers.SIZEOF_INT = 4;

/**
 * @type {number}
 * @const
 */
extension_flatbuffers.FILE_IDENTIFIER_LENGTH = 4;

/**
 * @enum {number}
 */
extension_flatbuffers.Encoding = {
  UTF8_BYTES: 1,
  UTF16_STRING: 2
};

/**
 * @type {Int32Array}
 * @const
 */
extension_flatbuffers.int32 = new Int32Array(2);

/**
 * @type {Float32Array}
 * @const
 */
extension_flatbuffers.float32 = new Float32Array(extension_flatbuffers.int32.buffer);

/**
 * @type {Float64Array}
 * @const
 */
extension_flatbuffers.float64 = new Float64Array(extension_flatbuffers.int32.buffer);

/**
 * @type {boolean}
 * @const
 */
extension_flatbuffers.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;

////////////////////////////////////////////////////////////////////////////////

/**
 * @constructor
 * @param {number} low
 * @param {number} high
 */
extension_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}
 */
extension_flatbuffers.Long.create = function(low, high) {
  // Special-case zero to avoid GC overhead for default values
  return low == 0 && high == 0 ? extension_flatbuffers.Long.ZERO : new extension_flatbuffers.Long(low, high);
};

/**
 * @returns {number}
 */
extension_flatbuffers.Long.prototype.toFloat64 = function() {
  return (this.low >>> 0) + this.high * 0x100000000;
};

/**
 * @param {flatbuffers.Long} other
 * @returns {boolean}
 */
extension_flatbuffers.Long.prototype.equals = function(other) {
  return this.low == other.low && this.high == other.high;
};

/**
 * @type {flatbuffers.Long}
 * @const
 */
extension_flatbuffers.Long.ZERO = new extension_flatbuffers.Long(0, 0);

/// @endcond
////////////////////////////////////////////////////////////////////////////////
/**
 * Create a FlatBufferBuilder.
 *
 * @constructor
 * @param {number=} opt_initial_size
 */
extension_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 = extension_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;
};

extension_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
 */
extension_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}
 */
extension_flatbuffers.Builder.prototype.dataBuffer = function() {
  return this.bb;
};

/**
 * Get the bytes representing the FlatBuffer. Only call this after you've
 * called finish().
 *
 * @returns {Uint8Array}
 */
extension_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
 */
extension_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 = extension_flatbuffers.Builder.growByteBuffer(this.bb);
    this.space += this.bb.capacity() - old_buf_size;
  }

  this.pad(align_size);
};

/**
 * @param {number} byte_size
 */
extension_flatbuffers.Builder.prototype.pad = function(byte_size) {
  for (var i = 0; i < byte_size; i++) {
    this.bb.writeInt8(--this.space, 0);
  }
};

/**
 * @param {number} value
 */
extension_flatbuffers.Builder.prototype.writeInt8 = function(value) {
  this.bb.writeInt8(this.space -= 1, value);
};

/**
 * @param {number} value
 */
extension_flatbuffers.Builder.prototype.writeInt16 = function(value) {
  this.bb.writeInt16(this.space -= 2, value);
};

/**
 * @param {number} value
 */
extension_flatbuffers.Builder.prototype.writeInt32 = function(value) {
  this.bb.writeInt32(this.space -= 4, value);
};

/**
 * @param {flatbuffers.Long} value
 */
extension_flatbuffers.Builder.prototype.writeInt64 = function(value) {
  this.bb.writeInt64(this.space -= 8, value);
};

/**
 * @param {number} value
 */
extension_flatbuffers.Builder.prototype.writeFloat32 = function(value) {
  this.bb.writeFloat32(this.space -= 4, value);
};

/**
 * @param {number} value
 */
extension_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.
 */
extension_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.
 */
extension_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.
 */
extension_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.
 */
extension_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.
 */
extension_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.
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_flatbuffers.Builder.prototype.slot = function(voffset) {
  this.vtable[voffset] = this.offset();
};

/**
 * @returns {flatbuffers.Offset} Offset relative to the end of the buffer.
 */
extension_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}
 */
extension_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 = extension_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.
 */
extension_flatbuffers.Builder.prototype.addOffset = function(offset) {
  this.prep(extension_flatbuffers.SIZEOF_INT, 0); // Ensure alignment is already done.
  this.writeInt32(this.offset() - offset + extension_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
 */
extension_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`
 */
extension_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) * extension_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 = extension_flatbuffers.SIZEOF_SHORT; j < len; j += extension_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
 */
extension_flatbuffers.Builder.prototype.finish = function(root_table, opt_file_identifier) {
  if (opt_file_identifier) {
    var file_identifier = opt_file_identifier;
    this.prep(this.minalign, extension_flatbuffers.SIZEOF_INT +
      extension_flatbuffers.FILE_IDENTIFIER_LENGTH);
    if (file_identifier.length != extension_flatbuffers.FILE_IDENTIFIER_LENGTH) {
      throw new Error('FlatBuffers: file identifier must be length ' +
        extension_flatbuffers.FILE_IDENTIFIER_LENGTH);
    }
    for (var i = extension_flatbuffers.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
      this.writeInt8(file_identifier.charCodeAt(i));
    }
  }
  this.prep(this.minalign, extension_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
 */
extension_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
 */
extension_flatbuffers.Builder.prototype.startVector = function(elem_size, num_elems, alignment) {
  this.notNested();
  this.vector_num_elems = num_elems;
  this.prep(extension_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.
 */
extension_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
 */
extension_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}
 */
extension_flatbuffers.Builder.prototype.createLong = function(low, high) {
  return extension_flatbuffers.Long.create(low, high);
};
////////////////////////////////////////////////////////////////////////////////
/// @cond FLATBUFFERS_INTERNAL
/**
 * Create a new ByteBuffer with a given array of bytes (`Uint8Array`).
 *
 * @constructor
 * @param {Uint8Array} bytes
 */
extension_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}
 */
extension_flatbuffers.ByteBuffer.allocate = function(byte_size) {
  return new extension_flatbuffers.ByteBuffer(new Uint8Array(byte_size));
};

extension_flatbuffers.ByteBuffer.prototype.clear = function() {
  this.position_ = 0;
};

/**
 * Get the underlying `Uint8Array`.
 *
 * @returns {Uint8Array}
 */
extension_flatbuffers.ByteBuffer.prototype.bytes = function() {
  return this.bytes_;
};

/**
 * Get the buffer's position.
 *
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.position = function() {
  return this.position_;
};

/**
 * Set the buffer's position.
 *
 * @param {number} position
 */
extension_flatbuffers.ByteBuffer.prototype.setPosition = function(position) {
  this.position_ = position;
};

/**
 * Get the buffer's capacity.
 *
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.capacity = function() {
  return this.bytes_.length;
};

/**
 * @param {number} offset
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.readInt8 = function(offset) {
  return this.readUint8(offset) << 24 >> 24;
};

/**
 * @param {number} offset
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.readUint8 = function(offset) {
  return this.bytes_[offset];
};

/**
 * @param {number} offset
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.readInt16 = function(offset) {
  return this.readUint16(offset) << 16 >> 16;
};

/**
 * @param {number} offset
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.readUint16 = function(offset) {
  return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
};

/**
 * @param {number} offset
 * @returns {number}
 */
extension_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}
 */
extension_flatbuffers.ByteBuffer.prototype.readUint32 = function(offset) {
  return this.readInt32(offset) >>> 0;
};

/**
 * @param {number} offset
 * @returns {flatbuffers.Long}
 */
extension_flatbuffers.ByteBuffer.prototype.readInt64 = function(offset) {
  return new extension_flatbuffers.Long(this.readInt32(offset), this.readInt32(offset + 4));
};

/**
 * @param {number} offset
 * @returns {flatbuffers.Long}
 */
extension_flatbuffers.ByteBuffer.prototype.readUint64 = function(offset) {
  return new extension_flatbuffers.Long(this.readUint32(offset), this.readUint32(offset + 4));
};

/**
 * @param {number} offset
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.readFloat32 = function(offset) {
  extension_flatbuffers.int32[0] = this.readInt32(offset);
  return extension_flatbuffers.float32[0];
};

/**
 * @param {number} offset
 * @returns {number}
 */
extension_flatbuffers.ByteBuffer.prototype.readFloat64 = function(offset) {
  extension_flatbuffers.int32[extension_flatbuffers.isLittleEndian ? 0 : 1] = this.readInt32(offset);
  extension_flatbuffers.int32[extension_flatbuffers.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4);
  return extension_flatbuffers.float64[0];
};

/**
 * @param {number} offset
 * @param {number|boolean} value
 */
extension_flatbuffers.ByteBuffer.prototype.writeInt8 = function(offset, value) {
  this.bytes_[offset] = /** @type {number} */(value);
};

/**
 * @param {number} offset
 * @param {number} value
 */
extension_flatbuffers.ByteBuffer.prototype.writeUint8 = function(offset, value) {
  this.bytes_[offset] = value;
};

/**
 * @param {number} offset
 * @param {number} value
 */
extension_flatbuffers.ByteBuffer.prototype.writeInt16 = function(offset, value) {
  this.bytes_[offset] = value;
  this.bytes_[offset + 1] = value >> 8;
};

/**
 * @param {number} offset
 * @param {number} value
 */
extension_flatbuffers.ByteBuffer.prototype.writeUint16 = function(offset, value) {
    this.bytes_[offset] = value;
    this.bytes_[offset + 1] = value >> 8;
};

/**
 * @param {number} offset
 * @param {number} value
 */
extension_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
 */
extension_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
 */
extension_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
 */
extension_flatbuffers.ByteBuffer.prototype.writeUint64 = function(offset, value) {
    this.writeUint32(offset, value.low);
    this.writeUint32(offset + 4, value.high);
};

/**
 * @param {number} offset
 * @param {number} value
 */
extension_flatbuffers.ByteBuffer.prototype.writeFloat32 = function(offset, value) {
  extension_flatbuffers.float32[0] = value;
  this.writeInt32(offset, extension_flatbuffers.int32[0]);
};

/**
 * @param {number} offset
 * @param {number} value
 */
extension_flatbuffers.ByteBuffer.prototype.writeFloat64 = function(offset, value) {
  extension_flatbuffers.float64[0] = value;
  this.writeInt32(offset, extension_flatbuffers.int32[extension_flatbuffers.isLittleEndian ? 0 : 1]);
  this.writeInt32(offset + 4, extension_flatbuffers.int32[extension_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}
 */
extension_flatbuffers.ByteBuffer.prototype.getBufferIdentifier = function() {
  if (this.bytes_.length < this.position_ + extension_flatbuffers.SIZEOF_INT +
      extension_flatbuffers.FILE_IDENTIFIER_LENGTH) {
    throw new Error(
        'FlatBuffers: ByteBuffer is too short to contain an identifier.');
  }
  var result = "";
  for (var i = 0; i < extension_flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
    result += String.fromCharCode(
        this.readInt8(this.position_ + extension_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}
 */
extension_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}
 */
extension_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}
 */
extension_flatbuffers.ByteBuffer.prototype.__string = function(offset, opt_encoding) {
  offset += this.readInt32(offset);

  var length = this.readInt32(offset);
  var result = '';
  var i = 0;

  offset += extension_flatbuffers.SIZEOF_INT;

  if (opt_encoding === extension_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}
 */
extension_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}
 */
extension_flatbuffers.ByteBuffer.prototype.__vector = function(offset) {
  return offset + this.readInt32(offset) + extension_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}
 */
extension_flatbuffers.ByteBuffer.prototype.__vector_len = function(offset) {
  return this.readInt32(offset + this.readInt32(offset));
};

/**
 * @param {string} ident
 * @returns {boolean}
 */
extension_flatbuffers.ByteBuffer.prototype.__has_identifier = function(ident) {
  if (ident.length != extension_flatbuffers.FILE_IDENTIFIER_LENGTH) {
    throw new Error('FlatBuffers: file identifier must be length ' +
                    extension_flatbuffers.FILE_IDENTIFIER_LENGTH);
  }
  for (var i = 0; i < extension_flatbuffers.FILE_IDENTIFIER_LENGTH; i++) {
    if (ident.charCodeAt(i) != this.readInt8(this.position_ + extension_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}
 */
extension_flatbuffers.ByteBuffer.prototype.createLong = function(low, high) {
  return extension_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 extension_inRange(a, min, max) {
  return min <= a && a <= max;
}

/**
 * @param {*} o
 * @return {Object}
 */
function extension_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 extension_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 extension_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 extension_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 extension_Stream(tokens) {
  /** @type {!Array.<number>} */
  this.tokens = [].slice.call(tokens);
}

extension_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 extension_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 extension_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 extension_decoderError(fatal, opt_code_point) {
  if (fatal)
    throw TypeError('Decoder error');
  return opt_code_point || 0xFFFD;
}

/** @interface */
function extension_Decoder() {}
extension_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 extension_Encoder() {}
extension_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 extension_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 extension_encoding_lib_TextDecoder(encoding, options) {
  if (!(this instanceof extension_encoding_lib_TextDecoder)) {
    return new extension_encoding_lib_TextDecoder(encoding, options);
  }
  encoding = encoding !== undefined ? String(encoding).toLowerCase() : extension_DEFAULT_ENCODING;
  if (encoding !== extension_DEFAULT_ENCODING) {
    throw new Error('Encoding not supported. Only utf-8 is supported');
  }
  options = extension_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});
}

extension_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 = extension_ToDictionary(options);

    if (!this._streaming) {
      this._decoder = new extension_UTF8Decoder({fatal: this._fatal});
      this._BOMseen = false;
    }
    this._streaming = Boolean(options['stream']);

    var input_stream = new extension_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 === extension_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 === extension_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 extension_codePointsToString(code_points);
  }
};

// 7.2 Interface TextEncoder

/**
 * @constructor
 * @param {string=} encoding The label of the encoding;
 *     defaults to 'utf-8'.
 * @param {Object=} options
 */
function extension_encoding_lib_TextEncoder(encoding, options) {
  if (!(this instanceof extension_encoding_lib_TextEncoder))
    return new extension_encoding_lib_TextEncoder(encoding, options);
  encoding = encoding !== undefined ? String(encoding).toLowerCase() : extension_DEFAULT_ENCODING;
  if (encoding !== extension_DEFAULT_ENCODING) {
    throw new Error('Encoding not supported. Only utf-8 is supported');
  }
  options = extension_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'});
}

extension_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 = extension_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 extension_UTF8Encoder(this._options);
    this._streaming = Boolean(options['stream']);

    var bytes = [];
    var input_stream = new extension_Stream(extension_stringToCodePoints(opt_string));
    /** @type {?(number|!Array.<number>)} */
    var result;
    while (!input_stream.endOfStream()) {
      result = this._encoder.handler(input_stream, input_stream.read());
      if (result === extension_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 === extension_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 extension_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 === extension_end_of_stream && utf8_bytes_needed !== 0) {
      utf8_bytes_needed = 0;
      return extension_decoderError(fatal);
    }

    // 2. If byte is end-of-stream, return finished.
    if (bite === extension_end_of_stream)
      return extension_finished;

    // 3. If utf-8 bytes needed is 0, based on byte:
    if (utf8_bytes_needed === 0) {

      // 0x00 to 0x7F
      if (extension_inRange(bite, 0x00, 0x7F)) {
        // Return a code point whose value is byte.
        return bite;
      }

      // 0xC2 to 0xDF
      if (extension_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 (extension_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 (extension_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 extension_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 (!extension_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 extension_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 extension_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 === extension_end_of_stream)
      return extension_finished;

    // 2. If code point is in the range U+0000 to U+007F, return a
    // byte whose value is code point.
    if (extension_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 (extension_inRange(code_point, 0x0080, 0x07FF)) {
      count = 1;
      offset = 0xC0;
    }
    // U+0800 to U+FFFF:    2 and 0xE0
    else if (extension_inRange(code_point, 0x0800, 0xFFFF)) {
      count = 2;
      offset = 0xE0;
    }
    // U+10000 to U+10FFFF: 3 and 0xF0
    else if (extension_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 extension_Buffer = typeof Buffer === 'function' ? Buffer : null;
/** @ignore */
const extension_useNativeEncoders = typeof TextDecoder === 'function' && typeof TextEncoder === 'function';
/** @ignore */
const extension_decodeUtf8 = ((TextDecoder) => {
    if (extension_useNativeEncoders || !extension_Buffer) {
        const decoder = new TextDecoder('utf-8');
        return (buffer) => decoder.decode(buffer);
    }
    return (input) => {
        const { buffer, byteOffset, length } = extension_toUint8Array(input);
        return extension_Buffer.from(buffer, byteOffset, length).toString();
    };
})(typeof TextDecoder !== 'undefined' ? TextDecoder : extension_encoding_lib_TextDecoder);
/** @ignore */
const extension_encodeUtf8 = ((TextEncoder) => {
    if (extension_useNativeEncoders || !extension_Buffer) {
        const encoder = new TextEncoder();
        return (value) => encoder.encode(value);
    }
    return (input = '') => extension_toUint8Array(extension_Buffer.from(input, 'utf8'));
})(typeof TextEncoder !== 'undefined' ? TextEncoder : extension_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 extension_ITERATOR_DONE = Object.freeze({ done: true, value: void (0) });
/** @ignore */
class extension_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 extension_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 extension_AsyncQueue extends extension_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(extension_ITERATOR_DONE);
            }
            this._closedPromiseResolve();
            this._closedPromiseResolve = undefined;
        }
    }
    [Symbol.asyncIterator]() { return this; }
    toDOMStream(options) {
        return extension_adapters.toDOMStream((this._closedPromiseResolve || this._error)
            ? this
            : this._values, options);
    }
    toNodeStream(options) {
        return extension_adapters.toNodeStream((this._closedPromiseResolve || this._error)
            ? this
            : this._values, options);
    }
    async throw(_) { await this.abort(_); return extension_ITERATOR_DONE; }
    async return(_) { await this.close(); return extension_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(extension_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 [extension_BigIntCtor, extension_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 [extension_BigInt64ArrayCtor, extension_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 [extension_BigUint64ArrayCtor, extension_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 extension_isNumber = (x) => typeof x === 'number';
/** @ignore */ const extension_isBoolean = (x) => typeof x === 'boolean';
/** @ignore */ const extension_compat_isFunction = (x) => typeof x === 'function';
/** @ignore */
const extension_compat_isObject = (x) => x != null && Object(x) === x;
/** @ignore */
const extension_isPromise = (x) => {
    return extension_compat_isObject(x) && extension_compat_isFunction(x.then);
};
/** @ignore */
const extension_isObservable = (x) => {
    return extension_compat_isObject(x) && extension_compat_isFunction(x.subscribe);
};
/** @ignore */
const extension_isIterable = (x) => {
    return extension_compat_isObject(x) && extension_compat_isFunction(x[Symbol.iterator]);
};
/** @ignore */
const extension_isAsyncIterable = (x) => {
    return extension_compat_isObject(x) && extension_compat_isFunction(x[Symbol.asyncIterator]);
};
/** @ignore */
const extension_isArrowJSON = (x) => {
    return extension_compat_isObject(x) && extension_compat_isObject(x['schema']);
};
/** @ignore */
const extension_isArrayLike = (x) => {
    return extension_compat_isObject(x) && extension_isNumber(x['length']);
};
/** @ignore */
const extension_isIteratorResult = (x) => {
    return extension_compat_isObject(x) && ('done' in x) && ('value' in x);
};
/** @ignore */
const extension_isUnderlyingSink = (x) => {
    return extension_compat_isObject(x) &&
        extension_compat_isFunction(x['abort']) &&
        extension_compat_isFunction(x['close']) &&
        extension_compat_isFunction(x['start']) &&
        extension_compat_isFunction(x['write']);
};
/** @ignore */
const extension_isFileHandle = (x) => {
    return extension_compat_isObject(x) && extension_compat_isFunction(x['stat']) && extension_isNumber(x['fd']);
};
/** @ignore */
const extension_isFSReadStream = (x) => {
    return extension_isReadableNodeStream(x) && extension_isNumber(x['bytesRead']);
};
/** @ignore */
const extension_isFetchResponse = (x) => {
    return extension_compat_isObject(x) && extension_isReadableDOMStream(x['body']);
};
/** @ignore */
const extension_isWritableDOMStream = (x) => {
    return extension_compat_isObject(x) &&
        extension_compat_isFunction(x['abort']) &&
        extension_compat_isFunction(x['getWriter']) &&
        !(x instanceof extension_ReadableInterop);
};
/** @ignore */
const extension_isReadableDOMStream = (x) => {
    return extension_compat_isObject(x) &&
        extension_compat_isFunction(x['cancel']) &&
        extension_compat_isFunction(x['getReader']) &&
        !(x instanceof extension_ReadableInterop);
};
/** @ignore */
const extension_isWritableNodeStream = (x) => {
    return extension_compat_isObject(x) &&
        extension_compat_isFunction(x['end']) &&
        extension_compat_isFunction(x['write']) &&
        extension_isBoolean(x['writable']) &&
        !(x instanceof extension_ReadableInterop);
};
/** @ignore */
const extension_isReadableNodeStream = (x) => {
    return extension_compat_isObject(x) &&
        extension_compat_isFunction(x['read']) &&
        extension_compat_isFunction(x['pipe']) &&
        extension_isBoolean(x['readable']) &&
        !(x instanceof extension_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 extension_ByteBuffer = extension_flatbuffers.ByteBuffer;

/** @ignore */
const extension_SharedArrayBuf = (typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : ArrayBuffer);
/** @ignore */
function extension_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 extension_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 extension_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 = extension_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 ? extension_memcpy(buffer, sliced, offset) : (buffer = sliced);
            break;
        }
        extension_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 extension_toArrayBufferView(ArrayBufferViewCtor, input) {
    let value = extension_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 = extension_encodeUtf8(value);
    }
    if (value instanceof ArrayBuffer) {
        return new ArrayBufferViewCtor(value);
    }
    if (value instanceof extension_SharedArrayBuf) {
        return new ArrayBufferViewCtor(value);
    }
    if (value instanceof extension_ByteBuffer) {
        return extension_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 extension_toInt8Array = (input) => extension_toArrayBufferView(Int8Array, input);
/** @ignore */ const extension_toInt16Array = (input) => extension_toArrayBufferView(Int16Array, input);
/** @ignore */ const extension_toInt32Array = (input) => extension_toArrayBufferView(Int32Array, input);
/** @ignore */ const extension_toBigInt64Array = (input) => extension_toArrayBufferView(extension_BigInt64ArrayCtor, input);
/** @ignore */ const extension_toUint8Array = (input) => extension_toArrayBufferView(Uint8Array, input);
/** @ignore */ const extension_toUint16Array = (input) => extension_toArrayBufferView(Uint16Array, input);
/** @ignore */ const extension_toUint32Array = (input) => extension_toArrayBufferView(Uint32Array, input);
/** @ignore */ const extension_toBigUint64Array = (input) => extension_toArrayBufferView(extension_BigUint64ArrayCtor, input);
/** @ignore */ const extension_toFloat32Array = (input) => extension_toArrayBufferView(Float32Array, input);
/** @ignore */ const extension_toFloat64Array = (input) => extension_toArrayBufferView(Float64Array, input);
/** @ignore */ const extension_toUint8ClampedArray = (input) => extension_toArrayBufferView(Uint8ClampedArray, input);
/** @ignore */
const extension_pump = (iterator) => { iterator.next(); return iterator; };
/** @ignore */
function* extension_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 extension_SharedArrayBuf) ? wrap(source)
                    : !extension_isIterable(source) ? wrap(source) : source;
    yield* extension_pump((function* (it) {
        let r = null;
        do {
            r = it.next(yield extension_toArrayBufferView(ArrayCtor, r));
        } while (!r.done);
    })(buffers[Symbol.iterator]()));
    return new ArrayCtor();
}
/** @ignore */ const extension_toInt8ArrayIterator = (input) => extension_toArrayBufferViewIterator(Int8Array, input);
/** @ignore */ const extension_toInt16ArrayIterator = (input) => extension_toArrayBufferViewIterator(Int16Array, input);
/** @ignore */ const extension_toInt32ArrayIterator = (input) => extension_toArrayBufferViewIterator(Int32Array, input);
/** @ignore */ const extension_toUint8ArrayIterator = (input) => extension_toArrayBufferViewIterator(Uint8Array, input);
/** @ignore */ const extension_toUint16ArrayIterator = (input) => extension_toArrayBufferViewIterator(Uint16Array, input);
/** @ignore */ const extension_toUint32ArrayIterator = (input) => extension_toArrayBufferViewIterator(Uint32Array, input);
/** @ignore */ const extension_toFloat32ArrayIterator = (input) => extension_toArrayBufferViewIterator(Float32Array, input);
/** @ignore */ const extension_toFloat64ArrayIterator = (input) => extension_toArrayBufferViewIterator(Float64Array, input);
/** @ignore */ const extension_toUint8ClampedArrayIterator = (input) => extension_toArrayBufferViewIterator(Uint8ClampedArray, input);
/** @ignore */
async function* extension_toArrayBufferViewAsyncIterator(ArrayCtor, source) {
    // if a Promise, unwrap the Promise and iterate the resolved value
    if (extension_isPromise(source)) {
        return yield* extension_toArrayBufferViewAsyncIterator(ArrayCtor, await source);
    }
    const wrap = async function* (x) { yield await x; };
    const emit = async function* (source) {
        yield* extension_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 extension_SharedArrayBuf) ? wrap(source) // if SharedArrayBuffer, wrap in an AsyncIterableIterator
                    : extension_isIterable(source) ? emit(source) // If Iterable, wrap in an AsyncIterableIterator and compose the `next` values
                        : !extension_isAsyncIterable(source) ? wrap(source) // If not an AsyncIterable, treat as a sentinel and wrap in an AsyncIterableIterator
                            : source; // otherwise if AsyncIterable, use it
    yield* extension_pump((async function* (it) {
        let r = null;
        do {
            r = await it.next(yield extension_toArrayBufferView(ArrayCtor, r));
        } while (!r.done);
    })(buffers[Symbol.asyncIterator]()));
    return new ArrayCtor();
}
/** @ignore */ const extension_toInt8ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Int8Array, input);
/** @ignore */ const extension_toInt16ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Int16Array, input);
/** @ignore */ const extension_toInt32ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Int32Array, input);
/** @ignore */ const extension_toUint8ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Uint8Array, input);
/** @ignore */ const extension_toUint16ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Uint16Array, input);
/** @ignore */ const extension_toUint32ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Uint32Array, input);
/** @ignore */ const extension_toFloat32ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Float32Array, input);
/** @ignore */ const extension_toFloat64ArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Float64Array, input);
/** @ignore */ const extension_toUint8ClampedArrayAsyncIterator = (input) => extension_toArrayBufferViewAsyncIterator(Uint8ClampedArray, input);
/** @ignore */
function extension_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 extension_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 extension_adapters = ({
    fromIterable(source) {
        return extension_adapters_pump(extension_adapters_fromIterable(source));
    },
    fromAsyncIterable(source) {
        return extension_adapters_pump(extension_fromAsyncIterable(source));
    },
    fromDOMStream(source) {
        return extension_adapters_pump(extension_fromDOMStream(source));
    },
    fromNodeStream(stream) {
        return extension_adapters_pump(extension_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 extension_adapters_pump = (iterator) => { iterator.next(); return iterator; };
/** @ignore */
function* extension_adapters_fromIterable(source) {
    let done, threw = false;
    let buffers = [], buffer;
    let cmd, size, bufferLength = 0;
    function byteRange() {
        if (cmd === 'peek') {
            return extension_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = extension_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 = extension_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* extension_fromAsyncIterable(source) {
    let done, threw = false;
    let buffers = [], buffer;
    let cmd, size, bufferLength = 0;
    function byteRange() {
        if (cmd === 'peek') {
            return extension_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = extension_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 = extension_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* extension_fromDOMStream(source) {
    let done = false, threw = false;
    let buffers = [], buffer;
    let cmd, size, bufferLength = 0;
    function byteRange() {
        if (cmd === 'peek') {
            return extension_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = extension_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 extension_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(extension_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 extension_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 = extension_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 extension_readInto(this.getBYOBReader(), new ArrayBuffer(size), 0, size);
    }
}
/** @ignore */
async function extension_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 extension_readInto(reader, value.buffer, offset, size);
    }
    return { done, value: new Uint8Array(value.buffer, 0, offset) };
}
/** @ignore */
const extension_onEvent = (stream, event) => {
    let handler = (_) => resolve([event, _]);
    let resolve;
    return [event, handler, new Promise((r) => (resolve = r) && stream['once'](event, handler))];
};
/** @ignore */
async function* extension_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 extension_joinUint8Arrays(buffers, size)[0];
        }
        [buffer, buffers, bufferLength] = extension_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] = extension_onEvent(stream, 'end');
        events[1] = extension_onEvent(stream, 'error');
        do {
            events[2] = extension_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 = extension_toUint8Array(stream['read'](undefined));
                }
                else {
                    buffer = extension_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 = extension_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 extension_AbstractVector {
}
extension_AbstractVector.prototype.data = null;


//# sourceMappingURL=vector.mjs.map

;// ../../node_modules/apache-arrow/fb/Schema.mjs
/* tslint:disable:class-name */
/**
 * @enum {number}
 */
var extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_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 = {}));
})(extension_Schema_org || (extension_Schema_org = {}));

//# sourceMappingURL=Schema.mjs.map

;// ../../node_modules/apache-arrow/fb/Message.mjs
// automatically generated by the FlatBuffers compiler, do not modify

var extension_org;
(function (org) {
    var apache;
    (function (apache) {
        var arrow;
        (function (arrow) {
            var flatbuf;
            (function (flatbuf) {
                flatbuf.Schema = extension_Schema_org.apache.arrow.flatbuf.Schema;
            })(flatbuf = arrow.flatbuf || (arrow.flatbuf = {}));
        })(arrow = apache.arrow || (apache.arrow = {}));
    })(apache = org.apache || (org.apache = {}));
})(extension_org || (extension_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 = {}));
})(extension_org || (extension_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 = {}));
})(extension_org || (extension_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 extension_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 = {}));
})(extension_org || (extension_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 = {}));
})(extension_org || (extension_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)) : extension_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 extension_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, extension_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 = {}));
})(extension_org || (extension_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 extension_ArrowType = extension_Schema_org.apache.arrow.flatbuf.Type;
var extension_DateUnit = extension_Schema_org.apache.arrow.flatbuf.DateUnit;
var extension_TimeUnit = extension_Schema_org.apache.arrow.flatbuf.TimeUnit;
var extension_Precision = extension_Schema_org.apache.arrow.flatbuf.Precision;
var extension_UnionMode = extension_Schema_org.apache.arrow.flatbuf.UnionMode;
var extension_IntervalUnit = extension_Schema_org.apache.arrow.flatbuf.IntervalUnit;
var extension_MessageHeader = extension_org.apache.arrow.flatbuf.MessageHeader;
var extension_MetadataVersion = extension_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 extension_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";
})(extension_Type || (extension_Type = {}));
var extension_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";
})(extension_BufferType || (extension_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 extension_getBool(_data, _index, byte, bit) {
    return (byte & 1 << bit) !== 0;
}
/** @ignore */
function extension_getBit(_data, _index, byte, bit) {
    return (byte & 1 << bit) >> bit;
}
/** @ignore */
function extension_setBool(bytes, index, value) {
    return value ?
        !!(bytes[index >> 3] |= (1 << (index % 8))) || true :
        !(bytes[index >> 3] &= ~(1 << (index % 8))) && false;
}
/** @ignore */
function extension_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
            extension_packBools(extension_iterateBits(bitmap, offset, length, null, extension_getBool)).subarray(0, alignedSize));
        return bytes;
    }
    return bitmap;
}
/** @ignore */
function extension_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* extension_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 extension_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 extension_iterateBits(data, lhs, rhs - lhs, data, extension_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
    extension_popcnt_bit_range(data, lhs, lhsInside) +
        // Get the popcnt of bits between the right hand side, and the next lowest multiple of 8
        extension_popcnt_bit_range(data, rhsInside, rhs) +
        // Get the popcnt of all bits between the left and right hand sides' multiples of 8
        extension_popcnt_array(data, lhsInside >> 3, (rhsInside - lhsInside) >> 3));
}
/** @ignore */
function extension_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 += extension_popcnt_uint32(view.getUint32(pos));
        pos += 4;
    }
    while (len - pos >= 2) {
        cnt += extension_popcnt_uint32(view.getUint16(pos));
        pos += 2;
    }
    while (len - pos >= 1) {
        cnt += extension_popcnt_uint32(view.getUint8(pos));
        pos += 1;
    }
    return cnt;
}
/** @ignore */
function extension_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 extension_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 extension_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 extension_getVisitFn(visitor, node, throwIfNotFound = true) {
    let fn = null;
    let dtype = extension_Type.NONE;
    // tslint:disable
    if (node instanceof extension_Data) {
        dtype = extension_inferDType(node.type);
    }
    else if (node instanceof extension_AbstractVector) {
        dtype = extension_inferDType(node.type);
    }
    else if (node instanceof extension_DataType) {
        dtype = extension_inferDType(node);
    }
    else if (typeof (dtype = node) !== 'number') {
        dtype = extension_Type[node];
    }
    switch (dtype) {
        case extension_Type.Null:
            fn = visitor.visitNull;
            break;
        case extension_Type.Bool:
            fn = visitor.visitBool;
            break;
        case extension_Type.Int:
            fn = visitor.visitInt;
            break;
        case extension_Type.Int8:
            fn = visitor.visitInt8 || visitor.visitInt;
            break;
        case extension_Type.Int16:
            fn = visitor.visitInt16 || visitor.visitInt;
            break;
        case extension_Type.Int32:
            fn = visitor.visitInt32 || visitor.visitInt;
            break;
        case extension_Type.Int64:
            fn = visitor.visitInt64 || visitor.visitInt;
            break;
        case extension_Type.Uint8:
            fn = visitor.visitUint8 || visitor.visitInt;
            break;
        case extension_Type.Uint16:
            fn = visitor.visitUint16 || visitor.visitInt;
            break;
        case extension_Type.Uint32:
            fn = visitor.visitUint32 || visitor.visitInt;
            break;
        case extension_Type.Uint64:
            fn = visitor.visitUint64 || visitor.visitInt;
            break;
        case extension_Type.Float:
            fn = visitor.visitFloat;
            break;
        case extension_Type.Float16:
            fn = visitor.visitFloat16 || visitor.visitFloat;
            break;
        case extension_Type.Float32:
            fn = visitor.visitFloat32 || visitor.visitFloat;
            break;
        case extension_Type.Float64:
            fn = visitor.visitFloat64 || visitor.visitFloat;
            break;
        case extension_Type.Utf8:
            fn = visitor.visitUtf8;
            break;
        case extension_Type.Binary:
            fn = visitor.visitBinary;
            break;
        case extension_Type.FixedSizeBinary:
            fn = visitor.visitFixedSizeBinary;
            break;
        case extension_Type.Date:
            fn = visitor.visitDate;
            break;
        case extension_Type.DateDay:
            fn = visitor.visitDateDay || visitor.visitDate;
            break;
        case extension_Type.DateMillisecond:
            fn = visitor.visitDateMillisecond || visitor.visitDate;
            break;
        case extension_Type.Timestamp:
            fn = visitor.visitTimestamp;
            break;
        case extension_Type.TimestampSecond:
            fn = visitor.visitTimestampSecond || visitor.visitTimestamp;
            break;
        case extension_Type.TimestampMillisecond:
            fn = visitor.visitTimestampMillisecond || visitor.visitTimestamp;
            break;
        case extension_Type.TimestampMicrosecond:
            fn = visitor.visitTimestampMicrosecond || visitor.visitTimestamp;
            break;
        case extension_Type.TimestampNanosecond:
            fn = visitor.visitTimestampNanosecond || visitor.visitTimestamp;
            break;
        case extension_Type.Time:
            fn = visitor.visitTime;
            break;
        case extension_Type.TimeSecond:
            fn = visitor.visitTimeSecond || visitor.visitTime;
            break;
        case extension_Type.TimeMillisecond:
            fn = visitor.visitTimeMillisecond || visitor.visitTime;
            break;
        case extension_Type.TimeMicrosecond:
            fn = visitor.visitTimeMicrosecond || visitor.visitTime;
            break;
        case extension_Type.TimeNanosecond:
            fn = visitor.visitTimeNanosecond || visitor.visitTime;
            break;
        case extension_Type.Decimal:
            fn = visitor.visitDecimal;
            break;
        case extension_Type.List:
            fn = visitor.visitList;
            break;
        case extension_Type.Struct:
            fn = visitor.visitStruct;
            break;
        case extension_Type.Union:
            fn = visitor.visitUnion;
            break;
        case extension_Type.DenseUnion:
            fn = visitor.visitDenseUnion || visitor.visitUnion;
            break;
        case extension_Type.SparseUnion:
            fn = visitor.visitSparseUnion || visitor.visitUnion;
            break;
        case extension_Type.Dictionary:
            fn = visitor.visitDictionary;
            break;
        case extension_Type.Interval:
            fn = visitor.visitInterval;
            break;
        case extension_Type.IntervalDayTime:
            fn = visitor.visitIntervalDayTime || visitor.visitInterval;
            break;
        case extension_Type.IntervalYearMonth:
            fn = visitor.visitIntervalYearMonth || visitor.visitInterval;
            break;
        case extension_Type.FixedSizeList:
            fn = visitor.visitFixedSizeList;
            break;
        case extension_Type.Map:
            fn = visitor.visitMap;
            break;
    }
    if (typeof fn === 'function')
        return fn;
    if (!throwIfNotFound)
        return () => null;
    throw new Error(`Unrecognized type '${extension_Type[dtype]}'`);
}
/** @ignore */
function extension_inferDType(type) {
    switch (type.typeId) {
        case extension_Type.Null: return extension_Type.Null;
        case extension_Type.Int:
            const { bitWidth, isSigned } = type;
            switch (bitWidth) {
                case 8: return isSigned ? extension_Type.Int8 : extension_Type.Uint8;
                case 16: return isSigned ? extension_Type.Int16 : extension_Type.Uint16;
                case 32: return isSigned ? extension_Type.Int32 : extension_Type.Uint32;
                case 64: return isSigned ? extension_Type.Int64 : extension_Type.Uint64;
            }
            // @ts-ignore
            return extension_Type.Int;
        case extension_Type.Float:
            switch (type.precision) {
                case extension_Precision.HALF: return extension_Type.Float16;
                case extension_Precision.SINGLE: return extension_Type.Float32;
                case extension_Precision.DOUBLE: return extension_Type.Float64;
            }
            // @ts-ignore
            return extension_Type.Float;
        case extension_Type.Binary: return extension_Type.Binary;
        case extension_Type.Utf8: return extension_Type.Utf8;
        case extension_Type.Bool: return extension_Type.Bool;
        case extension_Type.Decimal: return extension_Type.Decimal;
        case extension_Type.Time:
            switch (type.unit) {
                case extension_TimeUnit.SECOND: return extension_Type.TimeSecond;
                case extension_TimeUnit.MILLISECOND: return extension_Type.TimeMillisecond;
                case extension_TimeUnit.MICROSECOND: return extension_Type.TimeMicrosecond;
                case extension_TimeUnit.NANOSECOND: return extension_Type.TimeNanosecond;
            }
            // @ts-ignore
            return extension_Type.Time;
        case extension_Type.Timestamp:
            switch (type.unit) {
                case extension_TimeUnit.SECOND: return extension_Type.TimestampSecond;
                case extension_TimeUnit.MILLISECOND: return extension_Type.TimestampMillisecond;
                case extension_TimeUnit.MICROSECOND: return extension_Type.TimestampMicrosecond;
                case extension_TimeUnit.NANOSECOND: return extension_Type.TimestampNanosecond;
            }
            // @ts-ignore
            return extension_Type.Timestamp;
        case extension_Type.Date:
            switch (type.unit) {
                case extension_DateUnit.DAY: return extension_Type.DateDay;
                case extension_DateUnit.MILLISECOND: return extension_Type.DateMillisecond;
            }
            // @ts-ignore
            return extension_Type.Date;
        case extension_Type.Interval:
            switch (type.unit) {
                case extension_IntervalUnit.DAY_TIME: return extension_Type.IntervalDayTime;
                case extension_IntervalUnit.YEAR_MONTH: return extension_Type.IntervalYearMonth;
            }
            // @ts-ignore
            return extension_Type.Interval;
        case extension_Type.Map: return extension_Type.Map;
        case extension_Type.List: return extension_Type.List;
        case extension_Type.Struct: return extension_Type.Struct;
        case extension_Type.Union:
            switch (type.mode) {
                case extension_UnionMode.Dense: return extension_Type.DenseUnion;
                case extension_UnionMode.Sparse: return extension_Type.SparseUnion;
            }
            // @ts-ignore
            return extension_Type.Union;
        case extension_Type.FixedSizeBinary: return extension_Type.FixedSizeBinary;
        case extension_Type.FixedSizeList: return extension_Type.FixedSizeList;
        case extension_Type.Dictionary: return extension_Type.Dictionary;
    }
    throw new Error(`Unrecognized type '${extension_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
extension_Visitor.prototype.visitInt8 = null;
extension_Visitor.prototype.visitInt16 = null;
extension_Visitor.prototype.visitInt32 = null;
extension_Visitor.prototype.visitInt64 = null;
extension_Visitor.prototype.visitUint8 = null;
extension_Visitor.prototype.visitUint16 = null;
extension_Visitor.prototype.visitUint32 = null;
extension_Visitor.prototype.visitUint64 = null;
extension_Visitor.prototype.visitFloat16 = null;
extension_Visitor.prototype.visitFloat32 = null;
extension_Visitor.prototype.visitFloat64 = null;
extension_Visitor.prototype.visitDateDay = null;
extension_Visitor.prototype.visitDateMillisecond = null;
extension_Visitor.prototype.visitTimestampSecond = null;
extension_Visitor.prototype.visitTimestampMillisecond = null;
extension_Visitor.prototype.visitTimestampMicrosecond = null;
extension_Visitor.prototype.visitTimestampNanosecond = null;
extension_Visitor.prototype.visitTimeSecond = null;
extension_Visitor.prototype.visitTimeMillisecond = null;
extension_Visitor.prototype.visitTimeMicrosecond = null;
extension_Visitor.prototype.visitTimeNanosecond = null;
extension_Visitor.prototype.visitDenseUnion = null;
extension_Visitor.prototype.visitSparseUnion = null;
extension_Visitor.prototype.visitIntervalDayTime = null;
extension_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 extension_TypeComparator extends extension_Visitor {
    compareSchemas(schema, other) {
        return (schema === other) || (other instanceof schema.constructor &&
            extension_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) => extension_instance.compareField(f, others[i])));
    }
    compareField(field, other) {
        return (field === other) || (other instanceof field.constructor &&
            field.name === other.name &&
            field.nullable === other.nullable &&
            extension_instance.visit(field.type, other.type));
    }
}
function extension_compareConstructor(type, other) {
    return other instanceof type.constructor;
}
function extension_compareAny(type, other) {
    return (type === other) || extension_compareConstructor(type, other);
}
function extension_compareInt(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.bitWidth === other.bitWidth &&
        type.isSigned === other.isSigned);
}
function extension_compareFloat(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.precision === other.precision);
}
function extension_compareFixedSizeBinary(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.byteWidth === other.byteWidth);
}
function extension_compareDate(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.unit === other.unit);
}
function extension_compareTimestamp(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.unit === other.unit &&
        type.timezone === other.timezone);
}
function extension_compareTime(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.unit === other.unit &&
        type.bitWidth === other.bitWidth);
}
function extension_compareList(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.children.length === other.children.length &&
        extension_instance.compareFields(type.children, other.children));
}
function extension_compareStruct(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.children.length === other.children.length &&
        extension_instance.compareFields(type.children, other.children));
}
function extension_compareUnion(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.mode === other.mode &&
        type.typeIds.every((x, i) => x === other.typeIds[i]) &&
        extension_instance.compareFields(type.children, other.children));
}
function extension_compareDictionary(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.id === other.id &&
        type.isOrdered === other.isOrdered &&
        extension_instance.visit(type.indices, other.indices) &&
        extension_instance.visit(type.dictionary, other.dictionary));
}
function extension_compareInterval(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.unit === other.unit);
}
function extension_compareFixedSizeList(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.listSize === other.listSize &&
        type.children.length === other.children.length &&
        extension_instance.compareFields(type.children, other.children));
}
function extension_compareMap(type, other) {
    return (type === other) || (extension_compareConstructor(type, other) &&
        type.keysSorted === other.keysSorted &&
        type.children.length === other.children.length &&
        extension_instance.compareFields(type.children, other.children));
}
extension_TypeComparator.prototype.visitNull = extension_compareAny;
extension_TypeComparator.prototype.visitBool = extension_compareAny;
extension_TypeComparator.prototype.visitInt = extension_compareInt;
extension_TypeComparator.prototype.visitInt8 = extension_compareInt;
extension_TypeComparator.prototype.visitInt16 = extension_compareInt;
extension_TypeComparator.prototype.visitInt32 = extension_compareInt;
extension_TypeComparator.prototype.visitInt64 = extension_compareInt;
extension_TypeComparator.prototype.visitUint8 = extension_compareInt;
extension_TypeComparator.prototype.visitUint16 = extension_compareInt;
extension_TypeComparator.prototype.visitUint32 = extension_compareInt;
extension_TypeComparator.prototype.visitUint64 = extension_compareInt;
extension_TypeComparator.prototype.visitFloat = extension_compareFloat;
extension_TypeComparator.prototype.visitFloat16 = extension_compareFloat;
extension_TypeComparator.prototype.visitFloat32 = extension_compareFloat;
extension_TypeComparator.prototype.visitFloat64 = extension_compareFloat;
extension_TypeComparator.prototype.visitUtf8 = extension_compareAny;
extension_TypeComparator.prototype.visitBinary = extension_compareAny;
extension_TypeComparator.prototype.visitFixedSizeBinary = extension_compareFixedSizeBinary;
extension_TypeComparator.prototype.visitDate = extension_compareDate;
extension_TypeComparator.prototype.visitDateDay = extension_compareDate;
extension_TypeComparator.prototype.visitDateMillisecond = extension_compareDate;
extension_TypeComparator.prototype.visitTimestamp = extension_compareTimestamp;
extension_TypeComparator.prototype.visitTimestampSecond = extension_compareTimestamp;
extension_TypeComparator.prototype.visitTimestampMillisecond = extension_compareTimestamp;
extension_TypeComparator.prototype.visitTimestampMicrosecond = extension_compareTimestamp;
extension_TypeComparator.prototype.visitTimestampNanosecond = extension_compareTimestamp;
extension_TypeComparator.prototype.visitTime = extension_compareTime;
extension_TypeComparator.prototype.visitTimeSecond = extension_compareTime;
extension_TypeComparator.prototype.visitTimeMillisecond = extension_compareTime;
extension_TypeComparator.prototype.visitTimeMicrosecond = extension_compareTime;
extension_TypeComparator.prototype.visitTimeNanosecond = extension_compareTime;
extension_TypeComparator.prototype.visitDecimal = extension_compareAny;
extension_TypeComparator.prototype.visitList = extension_compareList;
extension_TypeComparator.prototype.visitStruct = extension_compareStruct;
extension_TypeComparator.prototype.visitUnion = extension_compareUnion;
extension_TypeComparator.prototype.visitDenseUnion = extension_compareUnion;
extension_TypeComparator.prototype.visitSparseUnion = extension_compareUnion;
extension_TypeComparator.prototype.visitDictionary = extension_compareDictionary;
extension_TypeComparator.prototype.visitInterval = extension_compareInterval;
extension_TypeComparator.prototype.visitIntervalDayTime = extension_compareInterval;
extension_TypeComparator.prototype.visitIntervalYearMonth = extension_compareInterval;
extension_TypeComparator.prototype.visitFixedSizeList = extension_compareFixedSizeList;
extension_TypeComparator.prototype.visitMap = extension_compareMap;
/** @ignore */
const extension_instance = new extension_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 extension_DataType {
    /** @nocollapse */ static isNull(x) { return x && x.typeId === extension_Type.Null; }
    /** @nocollapse */ static isInt(x) { return x && x.typeId === extension_Type.Int; }
    /** @nocollapse */ static isFloat(x) { return x && x.typeId === extension_Type.Float; }
    /** @nocollapse */ static isBinary(x) { return x && x.typeId === extension_Type.Binary; }
    /** @nocollapse */ static isUtf8(x) { return x && x.typeId === extension_Type.Utf8; }
    /** @nocollapse */ static isBool(x) { return x && x.typeId === extension_Type.Bool; }
    /** @nocollapse */ static isDecimal(x) { return x && x.typeId === extension_Type.Decimal; }
    /** @nocollapse */ static isDate(x) { return x && x.typeId === extension_Type.Date; }
    /** @nocollapse */ static isTime(x) { return x && x.typeId === extension_Type.Time; }
    /** @nocollapse */ static isTimestamp(x) { return x && x.typeId === extension_Type.Timestamp; }
    /** @nocollapse */ static isInterval(x) { return x && x.typeId === extension_Type.Interval; }
    /** @nocollapse */ static isList(x) { return x && x.typeId === extension_Type.List; }
    /** @nocollapse */ static isStruct(x) { return x && x.typeId === extension_Type.Struct; }
    /** @nocollapse */ static isUnion(x) { return x && x.typeId === extension_Type.Union; }
    /** @nocollapse */ static isFixedSizeBinary(x) { return x && x.typeId === extension_Type.FixedSizeBinary; }
    /** @nocollapse */ static isFixedSizeList(x) { return x && x.typeId === extension_Type.FixedSizeList; }
    /** @nocollapse */ static isMap(x) { return x && x.typeId === extension_Type.Map; }
    /** @nocollapse */ static isDictionary(x) { return x && x.typeId === extension_Type.Dictionary; }
    get typeId() { return extension_Type.NONE; }
    compareTo(other) {
        return extension_instance.visit(this, other);
    }
}
extension_DataType[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    proto.ArrayType = Array;
    return proto[Symbol.toStringTag] = 'DataType';
})(extension_DataType.prototype);
/** @ignore */
class extension_Null extends extension_DataType {
    toString() { return `Null`; }
    get typeId() { return extension_Type.Null; }
}
extension_Null[Symbol.toStringTag] = ((proto) => {
    return proto[Symbol.toStringTag] = 'Null';
})(extension_Null.prototype);
/** @ignore */
class extension_Int_ extends extension_DataType {
    constructor(isSigned, bitWidth) {
        super();
        this.isSigned = isSigned;
        this.bitWidth = bitWidth;
    }
    get typeId() { return extension_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}`; }
}
extension_Int_[Symbol.toStringTag] = ((proto) => {
    proto.isSigned = null;
    proto.bitWidth = null;
    return proto[Symbol.toStringTag] = 'Int';
})(extension_Int_.prototype);

/** @ignore */
class extension_Int8 extends extension_Int_ {
    constructor() { super(true, 8); }
}
/** @ignore */
class extension_Int16 extends extension_Int_ {
    constructor() { super(true, 16); }
}
/** @ignore */
class extension_Int32 extends extension_Int_ {
    constructor() { super(true, 32); }
}
/** @ignore */
class extension_Int64 extends extension_Int_ {
    constructor() { super(true, 64); }
}
/** @ignore */
class extension_Uint8 extends extension_Int_ {
    constructor() { super(false, 8); }
}
/** @ignore */
class extension_Uint16 extends extension_Int_ {
    constructor() { super(false, 16); }
}
/** @ignore */
class extension_Uint32 extends extension_Int_ {
    constructor() { super(false, 32); }
}
/** @ignore */
class extension_Uint64 extends extension_Int_ {
    constructor() { super(false, 64); }
}
Object.defineProperty(extension_Int8.prototype, 'ArrayType', { value: Int8Array });
Object.defineProperty(extension_Int16.prototype, 'ArrayType', { value: Int16Array });
Object.defineProperty(extension_Int32.prototype, 'ArrayType', { value: Int32Array });
Object.defineProperty(extension_Int64.prototype, 'ArrayType', { value: Int32Array });
Object.defineProperty(extension_Uint8.prototype, 'ArrayType', { value: Uint8Array });
Object.defineProperty(extension_Uint16.prototype, 'ArrayType', { value: Uint16Array });
Object.defineProperty(extension_Uint32.prototype, 'ArrayType', { value: Uint32Array });
Object.defineProperty(extension_Uint64.prototype, 'ArrayType', { value: Uint32Array });
/** @ignore */
class extension_Float extends extension_DataType {
    constructor(precision) {
        super();
        this.precision = precision;
    }
    get typeId() { return extension_Type.Float; }
    get ArrayType() {
        switch (this.precision) {
            case extension_Precision.HALF: return Uint16Array;
            case extension_Precision.SINGLE: return Float32Array;
            case extension_Precision.DOUBLE: return Float64Array;
        }
        // @ts-ignore
        throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);
    }
    toString() { return `Float${(this.precision << 5) || 16}`; }
}
extension_Float[Symbol.toStringTag] = ((proto) => {
    proto.precision = null;
    return proto[Symbol.toStringTag] = 'Float';
})(extension_Float.prototype);
/** @ignore */
class extension_Float16 extends extension_Float {
    constructor() { super(extension_Precision.HALF); }
}
/** @ignore */
class extension_Float32 extends extension_Float {
    constructor() { super(extension_Precision.SINGLE); }
}
/** @ignore */
class extension_Float64 extends extension_Float {
    constructor() { super(extension_Precision.DOUBLE); }
}
Object.defineProperty(extension_Float16.prototype, 'ArrayType', { value: Uint16Array });
Object.defineProperty(extension_Float32.prototype, 'ArrayType', { value: Float32Array });
Object.defineProperty(extension_Float64.prototype, 'ArrayType', { value: Float64Array });
/** @ignore */
class extension_Binary extends extension_DataType {
    constructor() {
        super();
    }
    get typeId() { return extension_Type.Binary; }
    toString() { return `Binary`; }
}
extension_Binary[Symbol.toStringTag] = ((proto) => {
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'Binary';
})(extension_Binary.prototype);
/** @ignore */
class extension_Utf8 extends extension_DataType {
    constructor() {
        super();
    }
    get typeId() { return extension_Type.Utf8; }
    toString() { return `Utf8`; }
}
extension_Utf8[Symbol.toStringTag] = ((proto) => {
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'Utf8';
})(extension_Utf8.prototype);
/** @ignore */
class extension_Bool extends extension_DataType {
    constructor() {
        super();
    }
    get typeId() { return extension_Type.Bool; }
    toString() { return `Bool`; }
}
extension_Bool[Symbol.toStringTag] = ((proto) => {
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'Bool';
})(extension_Bool.prototype);
/** @ignore */
class extension_Decimal extends extension_DataType {
    constructor(scale, precision) {
        super();
        this.scale = scale;
        this.precision = precision;
    }
    get typeId() { return extension_Type.Decimal; }
    toString() { return `Decimal[${this.precision}e${this.scale > 0 ? `+` : ``}${this.scale}]`; }
}
extension_Decimal[Symbol.toStringTag] = ((proto) => {
    proto.scale = null;
    proto.precision = null;
    proto.ArrayType = Uint32Array;
    return proto[Symbol.toStringTag] = 'Decimal';
})(extension_Decimal.prototype);
/** @ignore */
class extension_Date_ extends extension_DataType {
    constructor(unit) {
        super();
        this.unit = unit;
    }
    get typeId() { return extension_Type.Date; }
    toString() { return `Date${(this.unit + 1) * 32}<${extension_DateUnit[this.unit]}>`; }
}
extension_Date_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Date';
})(extension_Date_.prototype);
/** @ignore */
class extension_DateDay extends extension_Date_ {
    constructor() { super(extension_DateUnit.DAY); }
}
/** @ignore */
class extension_DateMillisecond extends extension_Date_ {
    constructor() { super(extension_DateUnit.MILLISECOND); }
}
/** @ignore */
class extension_Time_ extends extension_DataType {
    constructor(unit, bitWidth) {
        super();
        this.unit = unit;
        this.bitWidth = bitWidth;
    }
    get typeId() { return extension_Type.Time; }
    toString() { return `Time${this.bitWidth}<${extension_TimeUnit[this.unit]}>`; }
}
extension_Time_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.bitWidth = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Time';
})(extension_Time_.prototype);

/** @ignore */
class extension_TimeSecond extends extension_Time_ {
    constructor() { super(extension_TimeUnit.SECOND, 32); }
}
/** @ignore */
class extension_TimeMillisecond extends extension_Time_ {
    constructor() { super(extension_TimeUnit.MILLISECOND, 32); }
}
/** @ignore */
class extension_TimeMicrosecond extends extension_Time_ {
    constructor() { super(extension_TimeUnit.MICROSECOND, 64); }
}
/** @ignore */
class extension_TimeNanosecond extends extension_Time_ {
    constructor() { super(extension_TimeUnit.NANOSECOND, 64); }
}
/** @ignore */
class extension_Timestamp_ extends extension_DataType {
    constructor(unit, timezone) {
        super();
        this.unit = unit;
        this.timezone = timezone;
    }
    get typeId() { return extension_Type.Timestamp; }
    toString() { return `Timestamp<${extension_TimeUnit[this.unit]}${this.timezone ? `, ${this.timezone}` : ``}>`; }
}
extension_Timestamp_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.timezone = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Timestamp';
})(extension_Timestamp_.prototype);

/** @ignore */
class extension_TimestampSecond extends extension_Timestamp_ {
    constructor(timezone) { super(extension_TimeUnit.SECOND, timezone); }
}
/** @ignore */
class extension_TimestampMillisecond extends extension_Timestamp_ {
    constructor(timezone) { super(extension_TimeUnit.MILLISECOND, timezone); }
}
/** @ignore */
class extension_TimestampMicrosecond extends extension_Timestamp_ {
    constructor(timezone) { super(extension_TimeUnit.MICROSECOND, timezone); }
}
/** @ignore */
class extension_TimestampNanosecond extends extension_Timestamp_ {
    constructor(timezone) { super(extension_TimeUnit.NANOSECOND, timezone); }
}
/** @ignore */
class extension_Interval_ extends extension_DataType {
    constructor(unit) {
        super();
        this.unit = unit;
    }
    get typeId() { return extension_Type.Interval; }
    toString() { return `Interval<${extension_IntervalUnit[this.unit]}>`; }
}
extension_Interval_[Symbol.toStringTag] = ((proto) => {
    proto.unit = null;
    proto.ArrayType = Int32Array;
    return proto[Symbol.toStringTag] = 'Interval';
})(extension_Interval_.prototype);

/** @ignore */
class extension_IntervalDayTime extends extension_Interval_ {
    constructor() { super(extension_IntervalUnit.DAY_TIME); }
}
/** @ignore */
class extension_IntervalYearMonth extends extension_Interval_ {
    constructor() { super(extension_IntervalUnit.YEAR_MONTH); }
}
/** @ignore */
class extension_List extends extension_DataType {
    constructor(child) {
        super();
        this.children = [child];
    }
    get typeId() { return extension_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; }
}
extension_List[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    return proto[Symbol.toStringTag] = 'List';
})(extension_List.prototype);
/** @ignore */
class extension_Struct extends extension_DataType {
    constructor(children) {
        super();
        this.children = children;
    }
    get typeId() { return extension_Type.Struct; }
    toString() { return `Struct<{${this.children.map((f) => `${f.name}:${f.type}`).join(`, `)}}>`; }
}
extension_Struct[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    return proto[Symbol.toStringTag] = 'Struct';
})(extension_Struct.prototype);
/** @ignore */
class extension_Union_ extends extension_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 extension_Type.Union; }
    toString() {
        return `${this[Symbol.toStringTag]}<${this.children.map((x) => `${x.type}`).join(` | `)}>`;
    }
}
extension_Union_[Symbol.toStringTag] = ((proto) => {
    proto.mode = null;
    proto.typeIds = null;
    proto.children = null;
    proto.typeIdToChildIndex = null;
    proto.ArrayType = Int8Array;
    return proto[Symbol.toStringTag] = 'Union';
})(extension_Union_.prototype);

/** @ignore */
class extension_DenseUnion extends extension_Union_ {
    constructor(typeIds, children) {
        super(extension_UnionMode.Dense, typeIds, children);
    }
}
/** @ignore */
class extension_SparseUnion extends extension_Union_ {
    constructor(typeIds, children) {
        super(extension_UnionMode.Sparse, typeIds, children);
    }
}
/** @ignore */
class extension_FixedSizeBinary extends extension_DataType {
    constructor(byteWidth) {
        super();
        this.byteWidth = byteWidth;
    }
    get typeId() { return extension_Type.FixedSizeBinary; }
    toString() { return `FixedSizeBinary[${this.byteWidth}]`; }
}
extension_FixedSizeBinary[Symbol.toStringTag] = ((proto) => {
    proto.byteWidth = null;
    proto.ArrayType = Uint8Array;
    return proto[Symbol.toStringTag] = 'FixedSizeBinary';
})(extension_FixedSizeBinary.prototype);
/** @ignore */
class extension_FixedSizeList extends extension_DataType {
    constructor(listSize, child) {
        super();
        this.listSize = listSize;
        this.children = [child];
    }
    get typeId() { return extension_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}>`; }
}
extension_FixedSizeList[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    proto.listSize = null;
    return proto[Symbol.toStringTag] = 'FixedSizeList';
})(extension_FixedSizeList.prototype);
/** @ignore */
class extension_Map_ extends extension_DataType {
    constructor(child, keysSorted = false) {
        super();
        this.children = [child];
        this.keysSorted = keysSorted;
    }
    get typeId() { return extension_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(`, `)}}>`; }
}
extension_Map_[Symbol.toStringTag] = ((proto) => {
    proto.children = null;
    proto.keysSorted = null;
    return proto[Symbol.toStringTag] = 'Map_';
})(extension_Map_.prototype);
/** @ignore */
const extension_getId = ((atomicDictionaryId) => () => ++atomicDictionaryId)(-1);
/** @ignore */
class extension_type_Dictionary extends extension_DataType {
    constructor(dictionary, indices, id, isOrdered) {
        super();
        this.indices = indices;
        this.dictionary = dictionary;
        this.isOrdered = isOrdered || false;
        this.id = id == null ? extension_getId() : typeof id === 'number' ? id : id.low;
    }
    get typeId() { return extension_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}>`; }
}
extension_type_Dictionary[Symbol.toStringTag] = ((proto) => {
    proto.id = null;
    proto.indices = null;
    proto.isOrdered = null;
    proto.dictionary = null;
    return proto[Symbol.toStringTag] = 'Dictionary';
})(extension_type_Dictionary.prototype);
/** @ignore */
function extension_strideForType(type) {
    let t = type;
    switch (type.typeId) {
        case extension_Type.Decimal: return 4;
        case extension_Type.Timestamp: return 2;
        case extension_Type.Date: return 1 + t.unit;
        case extension_Type.Interval: return 1 + t.unit;
        case extension_Type.Int: return 1 + +(t.bitWidth > 32);
        case extension_Type.Time: return 1 + +(t.bitWidth > 32);
        case extension_Type.FixedSizeList: return t.listSize;
        case extension_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 extension_kUnknownNullCount = -1;
/** @ignore */
class extension_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 extension_Data ? x : x.data);
        let buffer;
        if (buffers instanceof extension_Data) {
            this.stride = buffers.stride;
            this.values = buffers.values;
            this.typeIds = buffers.typeIds;
            this.nullBitmap = buffers.nullBitmap;
            this.valueOffsets = buffers.valueOffsets;
        }
        else {
            this.stride = extension_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 <= extension_kUnknownNullCount && (nullBitmap = this.nullBitmap)) {
            this._nullCount = nullCount = this.length - extension_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 extension_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 === extension_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(extension_truncateBitmap(this.offset, length, this.nullBitmap), 0);
        }
        const buffers = this.buffers;
        buffers[extension_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[extension_BufferType.TYPE]) && (buffers[extension_BufferType.TYPE] = arr.subarray(offset, offset + length));
        // If offsets exist, only slice the offsets buffer
        (arr = buffers[extension_BufferType.OFFSET]) && (buffers[extension_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[extension_BufferType.DATA]) && (buffers[extension_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 extension_Data) {
            buffers = buffers.buffers;
        }
        else if (!buffers) {
            buffers = [];
        }
        switch (type.typeId) {
            case extension_Type.Null: return extension_Data.Null(type, offset, length);
            case extension_Type.Int: return extension_Data.Int(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Dictionary: return extension_Data.Dictionary(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || [], dictionary);
            case extension_Type.Float: return extension_Data.Float(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Bool: return extension_Data.Bool(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Decimal: return extension_Data.Decimal(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Date: return extension_Data.Date(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Time: return extension_Data.Time(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Timestamp: return extension_Data.Timestamp(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Interval: return extension_Data.Interval(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.FixedSizeBinary: return extension_Data.FixedSizeBinary(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Binary: return extension_Data.Binary(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.OFFSET] || [], buffers[extension_BufferType.DATA] || []);
            case extension_Type.Utf8: return extension_Data.Utf8(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.OFFSET] || [], buffers[extension_BufferType.DATA] || []);
            case extension_Type.List: return extension_Data.List(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.OFFSET] || [], (childData || [])[0]);
            case extension_Type.FixedSizeList: return extension_Data.FixedSizeList(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], (childData || [])[0]);
            case extension_Type.Struct: return extension_Data.Struct(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], childData || []);
            case extension_Type.Map: return extension_Data.Map(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.OFFSET] || [], (childData || [])[0]);
            case extension_Type.Union: return extension_Data.Union(type, offset, length, nullCount || 0, buffers[extension_BufferType.VALIDITY], buffers[extension_BufferType.TYPE] || [], buffers[extension_BufferType.OFFSET] || childData, childData);
        }
        throw new Error(`Unrecognized typeId ${type.typeId}`);
    }
    /** @nocollapse */
    static Null(type, offset, length) {
        return new extension_Data(type, offset, length, 0);
    }
    /** @nocollapse */
    static Int(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Dictionary(type, offset, length, nullCount, nullBitmap, data, dictionary) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.indices.ArrayType, data), extension_toUint8Array(nullBitmap)], [], dictionary);
    }
    /** @nocollapse */
    static Float(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Bool(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Decimal(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Date(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Time(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Timestamp(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Interval(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static FixedSizeBinary(type, offset, length, nullCount, nullBitmap, data) {
        return new extension_Data(type, offset, length, nullCount, [undefined, extension_toArrayBufferView(type.ArrayType, data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Binary(type, offset, length, nullCount, nullBitmap, valueOffsets, data) {
        return new extension_Data(type, offset, length, nullCount, [extension_toInt32Array(valueOffsets), extension_toUint8Array(data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static Utf8(type, offset, length, nullCount, nullBitmap, valueOffsets, data) {
        return new extension_Data(type, offset, length, nullCount, [extension_toInt32Array(valueOffsets), extension_toUint8Array(data), extension_toUint8Array(nullBitmap)]);
    }
    /** @nocollapse */
    static List(type, offset, length, nullCount, nullBitmap, valueOffsets, child) {
        return new extension_Data(type, offset, length, nullCount, [extension_toInt32Array(valueOffsets), undefined, extension_toUint8Array(nullBitmap)], child ? [child] : []);
    }
    /** @nocollapse */
    static FixedSizeList(type, offset, length, nullCount, nullBitmap, child) {
        return new extension_Data(type, offset, length, nullCount, [undefined, undefined, extension_toUint8Array(nullBitmap)], child ? [child] : []);
    }
    /** @nocollapse */
    static Struct(type, offset, length, nullCount, nullBitmap, children) {
        return new extension_Data(type, offset, length, nullCount, [undefined, undefined, extension_toUint8Array(nullBitmap)], children);
    }
    /** @nocollapse */
    static Map(type, offset, length, nullCount, nullBitmap, valueOffsets, child) {
        return new extension_Data(type, offset, length, nullCount, [extension_toInt32Array(valueOffsets), undefined, extension_toUint8Array(nullBitmap)], child ? [child] : []);
    }
    /** @nocollapse */
    static Union(type, offset, length, nullCount, nullBitmap, typeIds, valueOffsetsOrChildren, children) {
        const buffers = [
            undefined, undefined,
            extension_toUint8Array(nullBitmap),
            extension_toArrayBufferView(type.ArrayType, typeIds)
        ];
        if (type.mode === extension_UnionMode.Sparse) {
            return new extension_Data(type, offset, length, nullCount, buffers, valueOffsetsOrChildren);
        }
        buffers[extension_BufferType.OFFSET] = extension_toInt32Array(valueOffsetsOrChildren);
        return new extension_Data(type, offset, length, nullCount, buffers, children);
    }
}
extension_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 extension_undf = void (0);
/** @ignore */
function extension_valueToString(x) {
    if (x === null) {
        return 'null';
    }
    if (x === extension_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 extension_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 ${extension_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 extension_valueToCase(x) {
    if (typeof x !== 'bigint') {
        return extension_valueToString(x);
    }
    else if (extension_BigIntAvailable) {
        return `${extension_valueToString(x)}n`;
    }
    return `"${extension_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 extension_roundLengthUpToNearest64Bytes = (len, BPE) => ((((len * BPE) + 63) & ~63) || 64) / BPE;
/** @ignore */
const extension_sliceOrExtendArray = (arr, len = 0) => (arr.length >= len ? arr.subarray(0, len) : extension_memcpy(new arr.constructor(len), arr, 0));
/** @ignore */
class extension_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
                    ? extension_roundLengthUpToNearest64Bytes(length * 1, this.BYTES_PER_ELEMENT)
                    : extension_roundLengthUpToNearest64Bytes(length * 2, this.BYTES_PER_ELEMENT));
            }
        }
        return this;
    }
    flush(length = this.length) {
        length = extension_roundLengthUpToNearest64Bytes(length * this.stride, this.BYTES_PER_ELEMENT);
        const array = extension_sliceOrExtendArray(this.buffer, length);
        this.clear();
        return array;
    }
    clear() {
        this.length = 0;
        this._resize(0);
        return this;
    }
    _resize(newLength) {
        return this.buffer = extension_memcpy(new this.ArrayType(newLength), this.buffer);
    }
}
extension_BufferBuilder.prototype.offset = 0;
/** @ignore */
class extension_DataBufferBuilder extends extension_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 extension_BitmapBufferBuilder extends extension_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 extension_OffsetsBufferBuilder extends extension_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 extension_WideBufferBuilder extends extension_BufferBuilder {
    get ArrayType64() {
        return this._ArrayType64 || (this._ArrayType64 = (this.buffer instanceof Int32Array ? extension_BigInt64ArrayCtor : extension_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 (extension_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 extension_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 = extension_strideForType(type);
        this._nulls = new extension_BitmapBufferBuilder();
        if (nulls && nulls.length > 0) {
            this._isValid = extension_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 extension_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 extension_throughAsyncIterable(options);
    }
    /**
     * Flush the `Builder` and return a `Vector<T>`.
     * @returns {Vector<T>} A `Vector<T>` of the flushed values.
     */
    toVector() { return extension_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[extension_BufferType.TYPE] = typeIds.flush(length);
            // DenseUnions
            offsets && (buffers[extension_BufferType.OFFSET] = offsets.flush(length));
        }
        else if (offsets) { /* Variable-width primitives (Binary, Utf8) and Lists */
            // Binary, Utf8
            values && (buffers[extension_BufferType.DATA] = values.flush(offsets.last()));
            buffers[extension_BufferType.OFFSET] = offsets.flush(length);
        }
        else if (values) { /* Fixed-width primitives (Int, Float, Decimal, Time, Timestamp, and Interval) */
            buffers[extension_BufferType.DATA] = values.flush(length);
        }
        nullCount > 0 && (buffers[extension_BufferType.VALIDITY] = this._nulls.flush(length));
        const data = extension_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;
    }
}
extension_Builder.prototype.length = 1;
extension_Builder.prototype.stride = 1;
extension_Builder.prototype.children = null;
extension_Builder.prototype.finished = false;
extension_Builder.prototype.nullValues = null;
extension_Builder.prototype._isValid = () => true;
/** @ignore */
class extension_FixedWidthBuilder extends extension_Builder {
    constructor(opts) {
        super(opts);
        this._values = new extension_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 extension_VariableWidthBuilder extends extension_Builder {
    constructor(opts) {
        super(opts);
        this._pendingLength = 0;
        this._offsets = new extension_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 extension_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 = extension_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 extension_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 = extension_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 extension_BoolBuilder extends extension_Builder {
    constructor(options) {
        super(options);
        this._values = new extension_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 extension_NullBuilder extends extension_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 extension_DateBuilder extends extension_FixedWidthBuilder {
}
/** @ignore */
class extension_DateDayBuilder extends extension_DateBuilder {
}
/** @ignore */
class extension_DateMillisecondBuilder extends extension_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 extension_DecimalBuilder extends extension_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 extension_DictionaryBuilder extends extension_Builder {
    constructor({ 'type': type, 'nullValues': nulls, 'dictionaryHashFunction': hashFn }) {
        super({ type: new extension_type_Dictionary(type.dictionary, type.indices, type.id, type.isOrdered) });
        this._nulls = null;
        this._dictionaryOffset = 0;
        this._keysToIndices = Object.create(null);
        this.indices = extension_Builder.new({ 'type': this.type.indices, 'nullValues': nulls });
        this.dictionary = extension_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 extension_FixedSizeBinaryBuilder extends extension_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 extension_f64 = new Float64Array(1);
const extension_u32 = new Uint32Array(extension_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 extension_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 extension_float64ToUint16(d) {
    if (d !== d) {
        return 0x7E00;
    } // NaN
    extension_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 = (extension_u32[1] & 0x80000000) >> 16 & 0xFFFF;
    let expo = (extension_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 (extension_u32[0] > 0) {
            expo = 0x7C00;
        }
        else {
            expo = (expo & 0x7C000000) >> 16;
            sigf = (extension_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 + (extension_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 = ((extension_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 extension_FloatBuilder extends extension_FixedWidthBuilder {
}
/** @ignore */
class extension_Float16Builder extends extension_FloatBuilder {
    setValue(index, value) {
        // convert JS float64 to a uint16
        this._values.set(index, extension_float64ToUint16(value));
    }
}
/** @ignore */
class extension_Float32Builder extends extension_FloatBuilder {
    setValue(index, value) {
        this._values.set(index, value);
    }
}
/** @ignore */
class extension_Float64Builder extends extension_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 extension_isArrowBigNumSymbol = Symbol.for('isArrowBigNum');
/** @ignore */
function extension_BigNum(x, ...xs) {
    if (xs.length === 0) {
        return Object.setPrototypeOf(extension_toArrayBufferView(this['TypedArray'], x), this.constructor.prototype);
    }
    return Object.setPrototypeOf(new this['TypedArray'](x, ...xs), this.constructor.prototype);
}
extension_BigNum.prototype[extension_isArrowBigNumSymbol] = true;
extension_BigNum.prototype.toJSON = function () { return `"${extension_bignumToString(this)}"`; };
extension_BigNum.prototype.valueOf = function () { return extension_bignumToNumber(this); };
extension_BigNum.prototype.toString = function () { return extension_bignumToString(this); };
extension_BigNum.prototype[Symbol.toPrimitive] = function (hint = 'default') {
    switch (hint) {
        case 'number': return extension_bignumToNumber(this);
        case 'string': return extension_bignumToString(this);
        case 'default': return extension_bignumToBigInt(this);
    }
    // @ts-ignore
    return extension_bignumToString(this);
};
/** @ignore */
function extension_SignedBigNum(...args) { return extension_BigNum.apply(this, args); }
/** @ignore */
function extension_UnsignedBigNum(...args) { return extension_BigNum.apply(this, args); }
/** @ignore */
function extension_DecimalBigNum(...args) { return extension_BigNum.apply(this, args); }
Object.setPrototypeOf(extension_SignedBigNum.prototype, Object.create(Int32Array.prototype));
Object.setPrototypeOf(extension_UnsignedBigNum.prototype, Object.create(Uint32Array.prototype));
Object.setPrototypeOf(extension_DecimalBigNum.prototype, Object.create(Uint32Array.prototype));
Object.assign(extension_SignedBigNum.prototype, extension_BigNum.prototype, { 'constructor': extension_SignedBigNum, 'signed': true, 'TypedArray': Int32Array, 'BigIntArray': extension_BigInt64ArrayCtor });
Object.assign(extension_UnsignedBigNum.prototype, extension_BigNum.prototype, { 'constructor': extension_UnsignedBigNum, 'signed': false, 'TypedArray': Uint32Array, 'BigIntArray': extension_BigUint64ArrayCtor });
Object.assign(extension_DecimalBigNum.prototype, extension_BigNum.prototype, { 'constructor': extension_DecimalBigNum, 'signed': true, 'TypedArray': Uint32Array, 'BigIntArray': extension_BigUint64ArrayCtor });
/** @ignore */
function extension_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 extension_bignumToString;
/** @ignore */
let extension_bignumToBigInt;
if (!extension_BigIntAvailable) {
    extension_bignumToString = extension_decimalToString;
    extension_bignumToBigInt = extension_bignumToString;
}
else {
    extension_bignumToBigInt = ((a) => a.byteLength === 8 ? new a['BigIntArray'](a.buffer, a.byteOffset, 1)[0] : extension_decimalToString(a));
    extension_bignumToString = ((a) => a.byteLength === 8 ? `${new a['BigIntArray'](a.buffer, a.byteOffset, 1)[0]}` : extension_decimalToString(a));
}
/** @ignore */
function extension_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 extension_BN {
    /** @nocollapse */
    static new(num, isSigned) {
        switch (isSigned) {
            case true: return new extension_SignedBigNum(num);
            case false: return new extension_UnsignedBigNum(num);
        }
        switch (num.constructor) {
            case Int8Array:
            case Int16Array:
            case Int32Array:
            case extension_BigInt64ArrayCtor:
                return new extension_SignedBigNum(num);
        }
        if (num.byteLength === 16) {
            return new extension_DecimalBigNum(num);
        }
        return new extension_UnsignedBigNum(num);
    }
    /** @nocollapse */
    static signed(num) {
        return new extension_SignedBigNum(num);
    }
    /** @nocollapse */
    static unsigned(num) {
        return new extension_UnsignedBigNum(num);
    }
    /** @nocollapse */
    static decimal(num) {
        return new extension_DecimalBigNum(num);
    }
    constructor(num, isSigned) {
        return extension_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 extension_IntBuilder extends extension_FixedWidthBuilder {
    setValue(index, value) {
        this._values.set(index, value);
    }
}
/** @ignore */
class extension_Int8Builder extends extension_IntBuilder {
}
/** @ignore */
class extension_Int16Builder extends extension_IntBuilder {
}
/** @ignore */
class extension_Int32Builder extends extension_IntBuilder {
}
/** @ignore */
class extension_Int64Builder extends extension_IntBuilder {
    constructor(options) {
        if (options['nullValues']) {
            options['nullValues'] = options['nullValues'].map(extension_toBigInt);
        }
        super(options);
        this._values = new extension_WideBufferBuilder(new Int32Array(0), 2);
    }
    get values64() { return this._values.buffer64; }
    isValid(value) { return super.isValid(extension_toBigInt(value)); }
}
/** @ignore */
class extension_Uint8Builder extends extension_IntBuilder {
}
/** @ignore */
class extension_Uint16Builder extends extension_IntBuilder {
}
/** @ignore */
class extension_Uint32Builder extends extension_IntBuilder {
}
/** @ignore */
class extension_Uint64Builder extends extension_IntBuilder {
    constructor(options) {
        if (options['nullValues']) {
            options['nullValues'] = options['nullValues'].map(extension_toBigInt);
        }
        super(options);
        this._values = new extension_WideBufferBuilder(new Uint32Array(0), 2);
    }
    get values64() { return this._values.buffer64; }
    isValid(value) { return super.isValid(extension_toBigInt(value)); }
}
const extension_toBigInt = ((memo) => (value) => {
    if (ArrayBuffer.isView(value)) {
        memo.buffer = value.buffer;
        memo.byteOffset = value.byteOffset;
        memo.byteLength = value.byteLength;
        value = extension_bignumToBigInt(memo);
        memo.buffer = null;
    }
    return value;
})({ 'BigIntArray': extension_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 extension_TimeBuilder extends extension_FixedWidthBuilder {
}
/** @ignore */
class extension_TimeSecondBuilder extends extension_TimeBuilder {
}
/** @ignore */
class extension_TimeMillisecondBuilder extends extension_TimeBuilder {
}
/** @ignore */
class extension_TimeMicrosecondBuilder extends extension_TimeBuilder {
}
/** @ignore */
class extension_TimeNanosecondBuilder extends extension_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 extension_TimestampBuilder extends extension_FixedWidthBuilder {
}
/** @ignore */
class extension_TimestampSecondBuilder extends extension_TimestampBuilder {
}
/** @ignore */
class extension_TimestampMillisecondBuilder extends extension_TimestampBuilder {
}
/** @ignore */
class extension_TimestampMicrosecondBuilder extends extension_TimestampBuilder {
}
/** @ignore */
class extension_TimestampNanosecondBuilder extends extension_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 extension_IntervalBuilder extends extension_FixedWidthBuilder {
}
/** @ignore */
class extension_IntervalDayTimeBuilder extends extension_IntervalBuilder {
}
/** @ignore */
class extension_IntervalYearMonthBuilder extends extension_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 extension_BinaryBuilder extends extension_VariableWidthBuilder {
    constructor(opts) {
        super(opts);
        this._values = new extension_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, extension_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 extension_Utf8Builder extends extension_VariableWidthBuilder {
    constructor(opts) {
        super(opts);
        this._values = new extension_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, extension_encodeUtf8(value));
    }
    // @ts-ignore
    _flushPending(pending, pendingLength) { }
}
extension_Utf8Builder.prototype._flushPending = extension_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 extension_Run {
    get length() { return this._values.length; }
    get(index) { return this._values[index]; }
    clear() { this._values = null; return this; }
    bind(values) {
        if (values instanceof extension_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 extension_kParent = Symbol.for('parent');
/** @ignore */ const extension_kRowIndex = Symbol.for('rowIndex');
/** @ignore */ const extension_kKeyToIdx = Symbol.for('keyToIdx');
/** @ignore */ const extension_kIdxToVal = Symbol.for('idxToVal');
/** @ignore */ const extension_kCustomInspect = Symbol.for('nodejs.util.inspect.custom');
class extension_Row {
    constructor(parent, numKeys) {
        this[extension_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[extension_kKeyToIdx] || (this[extension_kKeyToIdx] = new Map());
            let idx = ktoi.get(key);
            if (idx !== undefined) {
                const itov = this[extension_kIdxToVal] || (this[extension_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[extension_kIdxToVal] || (this[extension_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[extension_kKeyToIdx] || (this[extension_kKeyToIdx] = new Map());
            let idx = ktoi.get(key);
            if (idx === undefined) {
                ktoi.set(key, idx = this.getIndex(key));
            }
            if (idx > -1) {
                const itov = this[extension_kIdxToVal] || (this[extension_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[extension_kKeyToIdx] || (this[extension_kKeyToIdx] = new Map());
        const itov = this[extension_kIdxToVal] || (this[extension_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[extension_kKeyToIdx] || (this[extension_kKeyToIdx] = new Map());
        const itov = this[extension_kIdxToVal] || (this[extension_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(); }
    [extension_kCustomInspect]() { return this.toString(); }
    toString() {
        const str = [];
        this.forEach((val, key) => {
            key = extension_valueToString(key);
            val = extension_valueToString(val);
            str.push(`${key}: ${val}`);
        });
        return `{ ${str.join(', ')} }`;
    }
}
extension_Row[Symbol.toStringTag] = ((proto) => {
    Object.defineProperties(proto, {
        'size': { writable: true, enumerable: false, configurable: false, value: 0 },
        [extension_kParent]: { writable: true, enumerable: false, configurable: false, value: null },
        [extension_kRowIndex]: { writable: true, enumerable: false, configurable: false, value: -1 },
    });
    return proto[Symbol.toStringTag] = 'Row';
})(extension_Row.prototype);
class extension_MapRow extends extension_Row {
    constructor(slice) {
        super(slice, slice.length);
        return extension_createRowProxy(this);
    }
    keys() {
        return this[extension_kParent].getChildAt(0)[Symbol.iterator]();
    }
    values() {
        return this[extension_kParent].getChildAt(1)[Symbol.iterator]();
    }
    getKey(idx) {
        return this[extension_kParent].getChildAt(0).get(idx);
    }
    getIndex(key) {
        return this[extension_kParent].getChildAt(0).indexOf(key);
    }
    getValue(index) {
        return this[extension_kParent].getChildAt(1).get(index);
    }
    setValue(index, value) {
        this[extension_kParent].getChildAt(1).set(index, value);
    }
}
class extension_StructRow extends extension_Row {
    constructor(parent) {
        super(parent, parent.type.children.length);
        return extension_defineRowProxyProperties(this);
    }
    *keys() {
        for (const field of this[extension_kParent].type.children) {
            yield field.name;
        }
    }
    *values() {
        for (const field of this[extension_kParent].type.children) {
            yield this[field.name];
        }
    }
    getKey(idx) {
        return this[extension_kParent].type.children[idx].name;
    }
    getIndex(key) {
        return this[extension_kParent].type.children.findIndex((f) => f.name === key);
    }
    getValue(index) {
        return this[extension_kParent].getChildAt(index).get(this[extension_kRowIndex]);
    }
    setValue(index, value) {
        return this[extension_kParent].getChildAt(index).set(this[extension_kRowIndex], value);
    }
}
Object.setPrototypeOf(extension_Row.prototype, Map.prototype);
/** @ignore */
const extension_defineRowProxyProperties = (() => {
    const desc = { enumerable: true, configurable: false, get: null, set: null };
    return (row) => {
        let idx = -1, ktoi = row[extension_kKeyToIdx] || (row[extension_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 extension_createRowProxy = (() => {
    if (typeof Proxy === 'undefined') {
        return extension_defineRowProxyProperties;
    }
    const has = extension_Row.prototype.has;
    const get = extension_Row.prototype.get;
    const set = extension_Row.prototype.set;
    const getKey = extension_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 extension_kParent:
                case extension_kRowIndex:
                case extension_kIdxToVal:
                case extension_kKeyToIdx:
                case extension_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 extension_kParent:
                case extension_kRowIndex:
                case extension_kIdxToVal:
                case extension_kKeyToIdx:
                case extension_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 extension_kParent:
                case extension_kRowIndex:
                case extension_kIdxToVal:
                case extension_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 extension_clampIndex(source, index, then) {
    const length = source.length;
    const adjust = index > -1 ? index : (length + (index % length));
    return then ? then(source, adjust) : adjust;
}
/** @ignore */
let extension_tmp;
/** @ignore */
function extension_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) && (extension_tmp = lhs, lhs = rhs, rhs = extension_tmp);
    // ensure rhs <= length
    (rhs > len) && (rhs = len);
    return then ? then(source, lhs, rhs) : [lhs, rhs];
}
const extension_big0 = extension_BigIntAvailable ? extension_BigIntCtor(0) : 0;
const extension_isNaNFast = (value) => value !== value;
/** @ignore */
function extension_createElementComparator(search) {
    let typeofSearch = typeof search;
    // Compare primitives
    if (typeofSearch !== 'object' || search === null) {
        // Compare NaN
        if (extension_isNaNFast(search)) {
            return extension_isNaNFast;
        }
        return typeofSearch !== 'bigint'
            ? (value) => value === search
            : (value) => (extension_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 ? extension_compareArrayLike(search, value) : false;
    }
    // Compare Maps and Rows
    if (search instanceof Map) {
        return extension_creatMapComparator(search);
    }
    // Compare Array-likes
    if (Array.isArray(search)) {
        return extension_createArrayLikeComparator(search);
    }
    // Compare Vectors
    if (search instanceof extension_AbstractVector) {
        return extension_createVectorComparator(search);
    }
    // Compare non-empty Objects
    return extension_createObjectComparator(search);
}
/** @ignore */
function extension_createArrayLikeComparator(lhs) {
    const comparators = [];
    for (let i = -1, n = lhs.length; ++i < n;) {
        comparators[i] = extension_createElementComparator(lhs[i]);
    }
    return extension_createSubElementsComparator(comparators);
}
/** @ignore */
function extension_creatMapComparator(lhs) {
    let i = -1;
    const comparators = [];
    lhs.forEach((v) => comparators[++i] = extension_createElementComparator(v));
    return extension_createSubElementsComparator(comparators);
}
/** @ignore */
function extension_createVectorComparator(lhs) {
    const comparators = [];
    for (let i = -1, n = lhs.length; ++i < n;) {
        comparators[i] = extension_createElementComparator(lhs.get(i));
    }
    return extension_createSubElementsComparator(comparators);
}
/** @ignore */
function extension_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] = extension_createElementComparator(lhs[keys[i]]);
    }
    return extension_createSubElementsComparator(comparators, keys);
}
function extension_createSubElementsComparator(comparators, keys) {
    return (rhs) => {
        if (!rhs || typeof rhs !== 'object') {
            return false;
        }
        switch (rhs.constructor) {
            case Array: return extension_compareArray(comparators, rhs);
            case Map:
            case extension_MapRow:
            case extension_StructRow:
                return extension_compareObject(comparators, rhs, rhs.keys());
            case Object:
            case undefined: // support `Object.create(null)` objects
                return extension_compareObject(comparators, rhs, keys || Object.keys(rhs));
        }
        return rhs instanceof extension_AbstractVector ? extension_compareVector(comparators, rhs) : false;
    };
}
function extension_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 extension_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 extension_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 extension_Chunked extends extension_AbstractVector {
    constructor(type, chunks = [], offsets = extension_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 extension_selectChunkArgs(extension_AbstractVector, vectors);
    }
    /** @nocollapse */
    static concat(...vectors) {
        const chunks = extension_Chunked.flatten(...vectors);
        return new extension_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 (extension_DataType.isDictionary(this._type)) {
            if (!this._indices) {
                const chunks = this._chunks;
                this._indices = (chunks.length === 1
                    ? chunks[0].indices
                    : extension_Chunked.concat(...chunks.map((x) => x.indices)));
            }
            return this._indices;
        }
        return null;
    }
    get dictionary() {
        if (extension_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 extension_Chunked(this._type, chunks);
    }
    concat(...others) {
        return this.clone(extension_Chunked.flatten(this, ...others));
    }
    slice(begin, end) {
        return extension_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 extension_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 ? extension_arraySet : extension_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 extension_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 extension_typedSet = (src, dst, offset) => {
    dst.set(src, offset);
    return (offset + src.length);
};
/** @ignore */
const extension_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 extension_column_Column extends extension_Chunked {
    constructor(field, vectors = [], offsets) {
        vectors = extension_Chunked.flatten(...vectors);
        super(field.type, vectors, offsets);
        this._field = field;
        if (vectors.length === 1 && !(this instanceof extension_SingleChunkColumn)) {
            return new extension_SingleChunkColumn(field, vectors[0], this._chunkOffsets);
        }
    }
    /** @nocollapse */
    static new(...args) {
        let [field, data, ...rest] = args;
        if (typeof field !== 'string' && !(field instanceof extension_Field)) {
            data = field;
            field = '';
        }
        const chunks = extension_Chunked.flatten(Array.isArray(data) ? [...data, ...rest] :
            data instanceof extension_AbstractVector ? [data, ...rest] :
                [extension_AbstractVector.new(data, ...rest)]);
        if (typeof field === 'string') {
            const type = chunks[0].data.type;
            field = new extension_Field(field, type, true);
        }
        else if (!field.nullable && chunks.some(({ nullCount }) => nullCount > 0)) {
            field = field.clone({ nullable: true });
        }
        return new extension_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 extension_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 extension_column_Column(field, chunks));
            }
        }
        return null;
    }
}
/** @ignore */
class extension_SingleChunkColumn extends extension_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 extension_args_isArray = Array.isArray;
/** @ignore */
const extension_selectArgs = (Ctor, vals) => src_extension_selectArgs(Ctor, vals, [], 0);
/** @ignore */
const extension_selectColumnArgs = (args) => {
    const [fields, values] = src_extension_selectFieldArgs(args, [[], []]);
    return values.map((x, i) => x instanceof extension_column_Column ? extension_column_Column.new(x.field.clone(fields[i]), x) :
        x instanceof extension_AbstractVector ? extension_column_Column.new(fields[i], x) :
            extension_column_Column.new(fields[i], []));
};
/** @ignore */
const extension_selectFieldArgs = (args) => src_extension_selectFieldArgs(args, [[], []]);
/** @ignore */
const extension_selectChunkArgs = (Ctor, vals) => src_extension_selectChunkArgs(Ctor, vals, [], 0);
/** @ignore */
const extension_selectVectorChildrenArgs = (Ctor, vals) => src_extension_selectVectorChildrenArgs(Ctor, vals, [], 0);
/** @ignore */
const extension_selectColumnChildrenArgs = (Ctor, vals) => src_extension_selectColumnChildrenArgs(Ctor, vals, [], 0);
/** @ignore */
function src_extension_selectArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (extension_args_isArray(value = vals[i])) {
            j = src_extension_selectArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof Ctor) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
function src_extension_selectChunkArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (extension_args_isArray(value = vals[i])) {
            j = src_extension_selectChunkArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof extension_Chunked) {
            j = src_extension_selectChunkArgs(Ctor, value.chunks, res, j).length;
        }
        else if (value instanceof Ctor) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
function src_extension_selectVectorChildrenArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (extension_args_isArray(value = vals[i])) {
            j = src_extension_selectVectorChildrenArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof Ctor) {
            j = src_extension_selectArgs(extension_AbstractVector, value.schema.fields.map((_, i) => value.getChildAt(i)), res, j).length;
        }
        else if (value instanceof extension_AbstractVector) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
function src_extension_selectColumnChildrenArgs(Ctor, vals, res, idx) {
    let value, j = idx;
    let i = -1, n = vals.length;
    while (++i < n) {
        if (extension_args_isArray(value = vals[i])) {
            j = src_extension_selectColumnChildrenArgs(Ctor, value, res, j).length;
        }
        else if (value instanceof Ctor) {
            j = src_extension_selectArgs(extension_column_Column, value.schema.fields.map((f, i) => extension_column_Column.new(f, value.getChildAt(i))), res, j).length;
        }
        else if (value instanceof extension_column_Column) {
            res[j++] = value;
        }
    }
    return res;
}
/** @ignore */
const extension_toKeysAndValues = (xs, [k, v], i) => (xs[0][i] = k, xs[1][i] = v, xs);
/** @ignore */
function src_extension_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 (extension_args_isArray(vals[0])) {
                return src_extension_selectFieldArgs(vals[0], ret);
            }
            if (!(vals[0] instanceof extension_Data || vals[0] instanceof extension_AbstractVector || vals[0] instanceof extension_DataType)) {
                [keys, vals] = Object.entries(vals[0]).reduce(extension_toKeysAndValues, ret);
            }
            break;
        default:
            !extension_args_isArray(keys = vals[n - 1])
                ? (vals = extension_args_isArray(vals[0]) ? vals[0] : vals, keys = [])
                : (vals = extension_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 extension_column_Column && (values[++valueIndex] = val)) {
            fields[++fieldIndex] = val.field.clone(keys[idx], val.type, true);
        }
        else {
            ({ [idx]: field = idx } = keys);
            if (val instanceof extension_DataType && (values[++valueIndex] = val)) {
                fields[++fieldIndex] = extension_Field.new(field, val, true);
            }
            else if (val && val.type && (values[++valueIndex] = val)) {
                val instanceof extension_Data && (values[valueIndex] = val = extension_AbstractVector.new(val));
                fields[++fieldIndex] = extension_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 extension_Schema {
    constructor(fields = [], metadata, dictionaries) {
        this.fields = (fields || []);
        this.metadata = metadata || new Map();
        if (!dictionaries) {
            dictionaries = extension_generateDictionaryMap(fields);
        }
        this.dictionaries = dictionaries;
    }
    /** @nocollapse */
    static from(...args) {
        return extension_Schema.new(args[0], args[1]);
    }
    /** @nocollapse */
    static new(...args) {
        return new extension_Schema(extension_selectFieldArgs(args)[0]);
    }
    get [Symbol.toStringTag]() { return 'Schema'; }
    toString() {
        return `Schema<{ ${this.fields.map((f, i) => `${i}: ${f}`).join(', ')} }>`;
    }
    compareTo(other) {
        return extension_instance.compareSchemas(this, other);
    }
    select(...columnNames) {
        const names = columnNames.reduce((xs, x) => (xs[x] = true) && xs, Object.create(null));
        return new extension_Schema(this.fields.filter((f) => names[f.name]), this.metadata);
    }
    selectAt(...columnIndices) {
        return new extension_Schema(columnIndices.map((i) => this.fields[i]).filter(Boolean), this.metadata);
    }
    assign(...args) {
        const other = args[0] instanceof extension_Schema ? args[0]
            : new extension_Schema(extension_selectArgs(extension_Field, args));
        const curFields = [...this.fields];
        const metadata = extension_mergeMaps(extension_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: extension_mergeMaps(extension_mergeMaps(new Map(), curFields[i].metadata), f2.metadata)
            })) && false : true;
        });
        const newDictionaries = extension_generateDictionaryMap(newFields, new Map());
        return new extension_Schema([...curFields, ...newFields], metadata, new Map([...this.dictionaries, ...newDictionaries]));
    }
}
class extension_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 extension_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 extension_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 extension_Field.new(name, type, nullable, metadata);
    }
}
/** @ignore */
function extension_mergeMaps(m1, m2) {
    return new Map([...(m1 || new Map()), ...(m2 || new Map())]);
}
/** @ignore */
function extension_generateDictionaryMap(fields, dictionaries = new Map()) {
    for (let i = -1, n = fields.length; ++i < n;) {
        const field = fields[i];
        const type = field.type;
        if (extension_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) {
            extension_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
extension_Schema.prototype.fields = null;
extension_Schema.prototype.metadata = null;
extension_Schema.prototype.dictionaries = null;
extension_Field.prototype.type = null;
extension_Field.prototype.name = null;
extension_Field.prototype.nullable = null;
extension_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 extension_ListBuilder extends extension_VariableWidthBuilder {
    constructor(opts) {
        super(opts);
        this._run = new extension_Run();
        this._offsets = new extension_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 extension_List(new extension_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 extension_FixedSizeListBuilder extends extension_Builder {
    constructor() {
        super(...arguments);
        this._run = new extension_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 extension_FixedSizeList(this.type.listSize, new extension_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 extension_MapBuilder extends extension_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 extension_Map_(new extension_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 extension_StructBuilder extends extension_Builder {
    addChild(child, name = `${this.numChildren}`) {
        const childIndex = this.children.push(child);
        this.type = new extension_Struct([...this.type.children, new extension_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 extension_UnionBuilder extends extension_Builder {
    constructor(options) {
        super(options);
        this._typeIds = new extension_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 extension_Field(name, child.type)];
        this.type = new extension_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 extension_SparseUnionBuilder extends extension_UnionBuilder {
}
/** @ignore */
class extension_DenseUnionBuilder extends extension_UnionBuilder {
    constructor(options) {
        super(options);
        this._offsets = new extension_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 extension_SetVisitor extends extension_Visitor {
}
/** @ignore */
const extension_setEpochMsToDays = (data, index, epochMs) => { data[index] = (epochMs / 86400000) | 0; };
/** @ignore */
const extension_setEpochMsToMillisecondsLong = (data, index, epochMs) => {
    data[index] = (epochMs % 4294967296) | 0;
    data[index + 1] = (epochMs / 4294967296) | 0;
};
/** @ignore */
const extension_setEpochMsToMicrosecondsLong = (data, index, epochMs) => {
    data[index] = ((epochMs * 1000) % 4294967296) | 0;
    data[index + 1] = ((epochMs * 1000) / 4294967296) | 0;
};
/** @ignore */
const extension_setEpochMsToNanosecondsLong = (data, index, epochMs) => {
    data[index] = ((epochMs * 1000000) % 4294967296) | 0;
    data[index + 1] = ((epochMs * 1000000) / 4294967296) | 0;
};
/** @ignore */
const extension_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 extension_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 extension_setDateDay = ({ values }, index, value) => { extension_setEpochMsToDays(values, index, value.valueOf()); };
/** @ignore */
const extension_setDateMillisecond = ({ values }, index, value) => { extension_setEpochMsToMillisecondsLong(values, index * 2, value.valueOf()); };
/** @ignore */
const extension_setNumeric = ({ stride, values }, index, value) => { values[stride * index] = value; };
/** @ignore */
const extension_setFloat16 = ({ stride, values }, index, value) => { values[stride * index] = extension_float64ToUint16(value); };
/** @ignore */
const extension_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 = extension_toArrayBufferView(ArrayType, val);
            vector.values.set(long.subarray(0, stride), stride * index);
    }
};
/** @ignore */
const extension_setFixedSizeBinary = ({ stride, values }, index, value) => { values.set(value.subarray(0, stride), stride * index); };
/** @ignore */
const extension_setBinary = ({ values, valueOffsets }, index, value) => extension_setVariableWidthBytes(values, valueOffsets, index, value);
/** @ignore */
const extension_setUtf8 = ({ values, valueOffsets }, index, value) => {
    extension_setVariableWidthBytes(values, valueOffsets, index, extension_encodeUtf8(value));
};
/* istanbul ignore next */
/** @ignore */
const extension_setInt = (vector, index, value) => {
    vector.type.bitWidth < 64
        ? extension_setNumeric(vector, index, value)
        : extension_setNumericX2(vector, index, value);
};
/* istanbul ignore next */
/** @ignore */
const extension_setFloat = (vector, index, value) => {
    vector.type.precision !== extension_Precision.HALF
        ? extension_setNumeric(vector, index, value)
        : extension_setFloat16(vector, index, value);
};
/* istanbul ignore next */
const extension_setDate = (vector, index, value) => {
    vector.type.unit === extension_DateUnit.DAY
        ? extension_setDateDay(vector, index, value)
        : extension_setDateMillisecond(vector, index, value);
};
/** @ignore */
const extension_setTimestampSecond = ({ values }, index, value) => extension_setEpochMsToMillisecondsLong(values, index * 2, value / 1000);
/** @ignore */
const extension_setTimestampMillisecond = ({ values }, index, value) => extension_setEpochMsToMillisecondsLong(values, index * 2, value);
/** @ignore */
const extension_setTimestampMicrosecond = ({ values }, index, value) => extension_setEpochMsToMicrosecondsLong(values, index * 2, value);
/** @ignore */
const extension_setTimestampNanosecond = ({ values }, index, value) => extension_setEpochMsToNanosecondsLong(values, index * 2, value);
/* istanbul ignore next */
/** @ignore */
const extension_setTimestamp = (vector, index, value) => {
    switch (vector.type.unit) {
        case extension_TimeUnit.SECOND: return extension_setTimestampSecond(vector, index, value);
        case extension_TimeUnit.MILLISECOND: return extension_setTimestampMillisecond(vector, index, value);
        case extension_TimeUnit.MICROSECOND: return extension_setTimestampMicrosecond(vector, index, value);
        case extension_TimeUnit.NANOSECOND: return extension_setTimestampNanosecond(vector, index, value);
    }
};
/** @ignore */
const extension_setTimeSecond = ({ values, stride }, index, value) => { values[stride * index] = value; };
/** @ignore */
const extension_setTimeMillisecond = ({ values, stride }, index, value) => { values[stride * index] = value; };
/** @ignore */
const extension_setTimeMicrosecond = ({ values }, index, value) => { values.set(value.subarray(0, 2), 2 * index); };
/** @ignore */
const extension_setTimeNanosecond = ({ values }, index, value) => { values.set(value.subarray(0, 2), 2 * index); };
/* istanbul ignore next */
/** @ignore */
const extension_setTime = (vector, index, value) => {
    switch (vector.type.unit) {
        case extension_TimeUnit.SECOND: return extension_setTimeSecond(vector, index, value);
        case extension_TimeUnit.MILLISECOND: return extension_setTimeMillisecond(vector, index, value);
        case extension_TimeUnit.MICROSECOND: return extension_setTimeMicrosecond(vector, index, value);
        case extension_TimeUnit.NANOSECOND: return extension_setTimeNanosecond(vector, index, value);
    }
};
/** @ignore */
const extension_setDecimal = ({ values }, index, value) => { values.set(value.subarray(0, 4), 4 * index); };
/** @ignore */
const extension_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 extension_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 extension_setStructArrayValue = (o, v) => (c, _, i) => c && c.set(o, v[i]);
/** @ignore */ const extension_setStructVectorValue = (o, v) => (c, _, i) => c && c.set(o, v.get(i));
/** @ignore */ const extension_setStructMapValue = (o, v) => (c, f, _) => c && c.set(o, v.get(f.name));
/** @ignore */ const extension_setStructObjectValue = (o, v) => (c, f, _) => c && c.set(o, v[f.name]);
/** @ignore */
const extension_setStruct = (vector, index, value) => {
    const setValue = value instanceof Map ? extension_setStructMapValue(index, value) :
        value instanceof extension_AbstractVector ? extension_setStructVectorValue(index, value) :
            Array.isArray(value) ? extension_setStructArrayValue(index, value) :
                extension_setStructObjectValue(index, value);
    vector.type.children.forEach((f, i) => setValue(vector.getChildAt(i), f, i));
};
/* istanbul ignore next */
/** @ignore */
const extension_setUnion = (vector, index, value) => {
    vector.type.mode === extension_UnionMode.Dense ?
        extension_setDenseUnion(vector, index, value) :
        extension_setSparseUnion(vector, index, value);
};
/** @ignore */
const extension_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 extension_setSparseUnion = (vector, index, value) => {
    const childIndex = vector.typeIdToChildIndex[vector.typeIds[index]];
    const child = vector.getChildAt(childIndex);
    child && child.set(index, value);
};
/** @ignore */
const extension_setDictionary = (vector, index, value) => {
    const key = vector.getKey(index);
    if (key !== null) {
        vector.setValue(key, value);
    }
};
/* istanbul ignore next */
/** @ignore */
const extension_setIntervalValue = (vector, index, value) => {
    (vector.type.unit === extension_IntervalUnit.DAY_TIME)
        ? extension_setIntervalDayTime(vector, index, value)
        : extension_setIntervalYearMonth(vector, index, value);
};
/** @ignore */
const extension_setIntervalDayTime = ({ values }, index, value) => { values.set(value.subarray(0, 2), 2 * index); };
/** @ignore */
const extension_setIntervalYearMonth = ({ values }, index, value) => { values[index] = (value[0] * 12) + (value[1] % 12); };
/** @ignore */
const extension_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));
    }
};
extension_SetVisitor.prototype.visitBool = extension_set_setBool;
extension_SetVisitor.prototype.visitInt = extension_setInt;
extension_SetVisitor.prototype.visitInt8 = extension_setNumeric;
extension_SetVisitor.prototype.visitInt16 = extension_setNumeric;
extension_SetVisitor.prototype.visitInt32 = extension_setNumeric;
extension_SetVisitor.prototype.visitInt64 = extension_setNumericX2;
extension_SetVisitor.prototype.visitUint8 = extension_setNumeric;
extension_SetVisitor.prototype.visitUint16 = extension_setNumeric;
extension_SetVisitor.prototype.visitUint32 = extension_setNumeric;
extension_SetVisitor.prototype.visitUint64 = extension_setNumericX2;
extension_SetVisitor.prototype.visitFloat = extension_setFloat;
extension_SetVisitor.prototype.visitFloat16 = extension_setFloat16;
extension_SetVisitor.prototype.visitFloat32 = extension_setNumeric;
extension_SetVisitor.prototype.visitFloat64 = extension_setNumeric;
extension_SetVisitor.prototype.visitUtf8 = extension_setUtf8;
extension_SetVisitor.prototype.visitBinary = extension_setBinary;
extension_SetVisitor.prototype.visitFixedSizeBinary = extension_setFixedSizeBinary;
extension_SetVisitor.prototype.visitDate = extension_setDate;
extension_SetVisitor.prototype.visitDateDay = extension_setDateDay;
extension_SetVisitor.prototype.visitDateMillisecond = extension_setDateMillisecond;
extension_SetVisitor.prototype.visitTimestamp = extension_setTimestamp;
extension_SetVisitor.prototype.visitTimestampSecond = extension_setTimestampSecond;
extension_SetVisitor.prototype.visitTimestampMillisecond = extension_setTimestampMillisecond;
extension_SetVisitor.prototype.visitTimestampMicrosecond = extension_setTimestampMicrosecond;
extension_SetVisitor.prototype.visitTimestampNanosecond = extension_setTimestampNanosecond;
extension_SetVisitor.prototype.visitTime = extension_setTime;
extension_SetVisitor.prototype.visitTimeSecond = extension_setTimeSecond;
extension_SetVisitor.prototype.visitTimeMillisecond = extension_setTimeMillisecond;
extension_SetVisitor.prototype.visitTimeMicrosecond = extension_setTimeMicrosecond;
extension_SetVisitor.prototype.visitTimeNanosecond = extension_setTimeNanosecond;
extension_SetVisitor.prototype.visitDecimal = extension_setDecimal;
extension_SetVisitor.prototype.visitList = extension_setList;
extension_SetVisitor.prototype.visitStruct = extension_setStruct;
extension_SetVisitor.prototype.visitUnion = extension_setUnion;
extension_SetVisitor.prototype.visitDenseUnion = extension_setDenseUnion;
extension_SetVisitor.prototype.visitSparseUnion = extension_setSparseUnion;
extension_SetVisitor.prototype.visitDictionary = extension_setDictionary;
extension_SetVisitor.prototype.visitInterval = extension_setIntervalValue;
extension_SetVisitor.prototype.visitIntervalDayTime = extension_setIntervalDayTime;
extension_SetVisitor.prototype.visitIntervalYearMonth = extension_setIntervalYearMonth;
extension_SetVisitor.prototype.visitFixedSizeList = extension_setFixedSizeList;
extension_SetVisitor.prototype.visitMap = extension_setMap;
/** @ignore */
const extension_set_instance = new extension_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 extension_GetBuilderCtor extends extension_Visitor {
    visitNull() { return extension_NullBuilder; }
    visitBool() { return extension_BoolBuilder; }
    visitInt() { return extension_IntBuilder; }
    visitInt8() { return extension_Int8Builder; }
    visitInt16() { return extension_Int16Builder; }
    visitInt32() { return extension_Int32Builder; }
    visitInt64() { return extension_Int64Builder; }
    visitUint8() { return extension_Uint8Builder; }
    visitUint16() { return extension_Uint16Builder; }
    visitUint32() { return extension_Uint32Builder; }
    visitUint64() { return extension_Uint64Builder; }
    visitFloat() { return extension_FloatBuilder; }
    visitFloat16() { return extension_Float16Builder; }
    visitFloat32() { return extension_Float32Builder; }
    visitFloat64() { return extension_Float64Builder; }
    visitUtf8() { return extension_Utf8Builder; }
    visitBinary() { return extension_BinaryBuilder; }
    visitFixedSizeBinary() { return extension_FixedSizeBinaryBuilder; }
    visitDate() { return extension_DateBuilder; }
    visitDateDay() { return extension_DateDayBuilder; }
    visitDateMillisecond() { return extension_DateMillisecondBuilder; }
    visitTimestamp() { return extension_TimestampBuilder; }
    visitTimestampSecond() { return extension_TimestampSecondBuilder; }
    visitTimestampMillisecond() { return extension_TimestampMillisecondBuilder; }
    visitTimestampMicrosecond() { return extension_TimestampMicrosecondBuilder; }
    visitTimestampNanosecond() { return extension_TimestampNanosecondBuilder; }
    visitTime() { return extension_TimeBuilder; }
    visitTimeSecond() { return extension_TimeSecondBuilder; }
    visitTimeMillisecond() { return extension_TimeMillisecondBuilder; }
    visitTimeMicrosecond() { return extension_TimeMicrosecondBuilder; }
    visitTimeNanosecond() { return extension_TimeNanosecondBuilder; }
    visitDecimal() { return extension_DecimalBuilder; }
    visitList() { return extension_ListBuilder; }
    visitStruct() { return extension_StructBuilder; }
    visitUnion() { return extension_UnionBuilder; }
    visitDenseUnion() { return extension_DenseUnionBuilder; }
    visitSparseUnion() { return extension_SparseUnionBuilder; }
    visitDictionary() { return extension_DictionaryBuilder; }
    visitInterval() { return extension_IntervalBuilder; }
    visitIntervalDayTime() { return extension_IntervalDayTimeBuilder; }
    visitIntervalYearMonth() { return extension_IntervalYearMonthBuilder; }
    visitFixedSizeList() { return extension_FixedSizeListBuilder; }
    visitMap() { return extension_MapBuilder; }
}
/** @ignore */
const extension_builderctor_instance = new extension_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 */
extension_Builder.new = extension_newBuilder;
function extension_newBuilder(options) {
    const type = options.type;
    const builder = new (extension_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(extension_newBuilder({ ...opts, type }));
        });
    }
    return builder;
}
Object.keys(extension_Type)
    .map((T) => extension_Type[T])
    .filter((T) => typeof T === 'number' && T !== extension_Type.NONE)
    .forEach((typeId) => {
    const BuilderCtor = extension_builderctor_instance.visit(typeId);
    BuilderCtor.prototype._setValue = extension_set_instance.getVisitFn(typeId);
});
extension_Utf8Builder.prototype._setValue = extension_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 extension_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)) : extension_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 extension_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, extension_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 = {}));
})(extension_File_org || (extension_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 = {}));
})(extension_File_org || (extension_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 extension_Long = extension_flatbuffers.Long;
var extension_file_Builder = extension_flatbuffers.Builder;
var extension_file_ByteBuffer = extension_flatbuffers.ByteBuffer;
var extension_Block = extension_File_org.apache.arrow.flatbuf.Block;
var extension_Footer = extension_File_org.apache.arrow.flatbuf.Footer;



/** @ignore */
class extension_Footer_ {
    constructor(schema, version = extension_MetadataVersion.V4, recordBatches, dictionaryBatches) {
        this.schema = schema;
        this.version = version;
        recordBatches && (this._recordBatches = recordBatches);
        dictionaryBatches && (this._dictionaryBatches = dictionaryBatches);
    }
    /** @nocollapse */
    static decode(buf) {
        buf = new extension_file_ByteBuffer(extension_toUint8Array(buf));
        const footer = extension_Footer.getRootAsFooter(buf);
        const schema = extension_Schema.decode(footer.schema());
        return new extension_OffHeapFooter(schema, footer);
    }
    /** @nocollapse */
    static encode(footer) {
        const b = new extension_file_Builder();
        const schemaOffset = extension_Schema.encode(b, footer.schema);
        extension_Footer.startRecordBatchesVector(b, footer.numRecordBatches);
        [...footer.recordBatches()].slice().reverse().forEach((rb) => extension_FileBlock.encode(b, rb));
        const recordBatchesOffset = b.endVector();
        extension_Footer.startDictionariesVector(b, footer.numDictionaries);
        [...footer.dictionaryBatches()].slice().reverse().forEach((db) => extension_FileBlock.encode(b, db));
        const dictionaryBatchesOffset = b.endVector();
        extension_Footer.startFooter(b);
        extension_Footer.addSchema(b, schemaOffset);
        extension_Footer.addVersion(b, extension_MetadataVersion.V4);
        extension_Footer.addRecordBatches(b, recordBatchesOffset);
        extension_Footer.addDictionaries(b, dictionaryBatchesOffset);
        extension_Footer.finishFooterBuffer(b, extension_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 extension_OffHeapFooter extends extension_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 extension_FileBlock.decode(fileBlock);
            }
        }
        return null;
    }
    getDictionaryBatch(index) {
        if (index >= 0 && index < this.numDictionaries) {
            const fileBlock = this._footer.dictionaries(index);
            if (fileBlock) {
                return extension_FileBlock.decode(fileBlock);
            }
        }
        return null;
    }
}
/** @ignore */
class extension_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 extension_FileBlock(block.metaDataLength(), block.bodyLength(), block.offset());
    }
    /** @nocollapse */
    static encode(b, fileBlock) {
        const { metaDataLength } = fileBlock;
        const offset = new extension_Long(fileBlock.offset, 0);
        const bodyLength = new extension_Long(fileBlock.bodyLength, 0);
        return extension_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 extension_AsyncByteQueue extends extension_AsyncQueue {
    write(value) {
        if ((value = extension_toUint8Array(value)).byteLength > 0) {
            return super.write(value);
        }
    }
    toString(sync = false) {
        return sync
            ? extension_decodeUtf8(this.toUint8Array(true))
            : this.toUint8Array(false).then(extension_decodeUtf8);
    }
    toUint8Array(sync = false) {
        return sync ? extension_joinUint8Arrays(this._values)[0] : (async () => {
            let buffers = [], byteLength = 0;
            for await (const chunk of this) {
                buffers.push(chunk);
                byteLength += chunk.byteLength;
            }
            return extension_joinUint8Arrays(buffers, byteLength)[0];
        })();
    }
}
/** @ignore */
class extension_ByteStream {
    constructor(source) {
        if (source) {
            this.source = new extension_ByteStreamSource(extension_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 extension_AsyncByteStream {
    constructor(source) {
        if (source instanceof extension_AsyncByteStream) {
            this.source = source.source;
        }
        else if (source instanceof extension_AsyncByteQueue) {
            this.source = new extension_AsyncByteStreamSource(extension_adapters.fromAsyncIterable(source));
        }
        else if (extension_isReadableNodeStream(source)) {
            this.source = new extension_AsyncByteStreamSource(extension_adapters.fromNodeStream(source));
        }
        else if (extension_isReadableDOMStream(source)) {
            this.source = new extension_AsyncByteStreamSource(extension_adapters.fromDOMStream(source));
        }
        else if (extension_isFetchResponse(source)) {
            this.source = new extension_AsyncByteStreamSource(extension_adapters.fromDOMStream(source.body));
        }
        else if (extension_isIterable(source)) {
            this.source = new extension_AsyncByteStreamSource(extension_adapters.fromIterable(source));
        }
        else if (extension_isPromise(source)) {
            this.source = new extension_AsyncByteStreamSource(extension_adapters.fromAsyncIterable(source));
        }
        else if (extension_isAsyncIterable(source)) {
            this.source = new extension_AsyncByteStreamSource(extension_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 extension_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)) || extension_ITERATOR_DONE); }
    return(value) { return Object.create((this.source.return && this.source.return(value)) || extension_ITERATOR_DONE); }
}
/** @ignore */
class extension_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)) || extension_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)) || extension_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 extension_RandomAccessFile extends extension_ByteStream {
    constructor(buffer, byteLength) {
        super();
        this.position = 0;
        this.buffer = extension_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 extension_AsyncRandomAccessFile extends extension_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 extension_carryBit16 = 1 << 16;
/** @ignore */
function extension_intAsHex(value) {
    if (value < 0) {
        value = 0xFFFFFFFF + value + 1;
    }
    return `0x${value.toString(16)}`;
}
/** @ignore */
const extension_kInt32DecimalDigits = 8;
/** @ignore */
const extension_kPowersOfTen = [1,
    10,
    100,
    1000,
    10000,
    100000,
    1000000,
    10000000,
    100000000];
/** @ignore */
class extension_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 ? extension_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 `${extension_intAsHex(this.buffer[1])} ${extension_intAsHex(this.buffer[0])}`;
    }
}
/** @ignore */
class extension_int_Uint64 extends extension_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 extension_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 extension_int_Uint64.fromString(num.toString(), out_buffer);
    }
    /** @nocollapse */
    static fromString(str, out_buffer = new Uint32Array(2)) {
        const length = str.length;
        let out = new extension_int_Uint64(out_buffer);
        for (let posn = 0; posn < length;) {
            const group = extension_kInt32DecimalDigits < length - posn ?
                extension_kInt32DecimalDigits : length - posn;
            const chunk = new extension_int_Uint64(new Uint32Array([parseInt(str.substr(posn, group), 10), 0]));
            const multiple = new extension_int_Uint64(new Uint32Array([extension_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;) {
            extension_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 extension_int_Uint64(new Uint32Array(left.buffer));
        return rtrn.times(right);
    }
    /** @nocollapse */
    static add(left, right) {
        let rtrn = new extension_int_Uint64(new Uint32Array(left.buffer));
        return rtrn.plus(right);
    }
}
/** @ignore */
class extension_int_Int64 extends extension_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 extension_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 extension_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 extension_int_Int64(out_buffer);
        for (let posn = negate ? 1 : 0; posn < length;) {
            const group = extension_kInt32DecimalDigits < length - posn ?
                extension_kInt32DecimalDigits : length - posn;
            const chunk = new extension_int_Int64(new Uint32Array([parseInt(str.substr(posn, group), 10), 0]));
            const multiple = new extension_int_Int64(new Uint32Array([extension_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;) {
            extension_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 extension_int_Int64(new Uint32Array(left.buffer));
        return rtrn.times(right);
    }
    /** @nocollapse */
    static add(left, right) {
        let rtrn = new extension_int_Int64(new Uint32Array(left.buffer));
        return rtrn.plus(right);
    }
}
/** @ignore */
class extension_Int128 {
    constructor(buffer) {
        this.buffer = buffer;
        // buffer[3] MSB (high)
        // buffer[2]
        // buffer[1]
        // buffer[0] LSB (low)
    }
    high() {
        return new extension_int_Int64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2));
    }
    low() {
        return new extension_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 extension_int_Uint64(new Uint32Array([this.buffer[3], 0]));
        const L1 = new extension_int_Uint64(new Uint32Array([this.buffer[2], 0]));
        const L2 = new extension_int_Uint64(new Uint32Array([this.buffer[1], 0]));
        const L3 = new extension_int_Uint64(new Uint32Array([this.buffer[0], 0]));
        const R0 = new extension_int_Uint64(new Uint32Array([other.buffer[3], 0]));
        const R1 = new extension_int_Uint64(new Uint32Array([other.buffer[2], 0]));
        const R2 = new extension_int_Uint64(new Uint32Array([other.buffer[1], 0]));
        const R3 = new extension_int_Uint64(new Uint32Array([other.buffer[0], 0]));
        let product = extension_int_Uint64.multiply(L3, R3);
        this.buffer[0] = product.low();
        let sum = new extension_int_Uint64(new Uint32Array([product.high(), 0]));
        product = extension_int_Uint64.multiply(L2, R3);
        sum.plus(product);
        product = extension_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 extension_int_Uint64(new Uint32Array(this.buffer.buffer, this.buffer.byteOffset + 8, 2));
        high.plus(extension_int_Uint64.multiply(L1, R3))
            .plus(extension_int_Uint64.multiply(L2, R2))
            .plus(extension_int_Uint64.multiply(L3, R1));
        this.buffer[3] += extension_int_Uint64.multiply(L0, R3)
            .plus(extension_int_Uint64.multiply(L1, R2))
            .plus(extension_int_Uint64.multiply(L2, R1))
            .plus(extension_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 `${extension_intAsHex(this.buffer[3])} ${extension_intAsHex(this.buffer[2])} ${extension_intAsHex(this.buffer[1])} ${extension_intAsHex(this.buffer[0])}`;
    }
    /** @nocollapse */
    static multiply(left, right) {
        let rtrn = new extension_Int128(new Uint32Array(left.buffer));
        return rtrn.times(right);
    }
    /** @nocollapse */
    static add(left, right) {
        let rtrn = new extension_Int128(new Uint32Array(left.buffer));
        return rtrn.plus(right);
    }
    /** @nocollapse */
    static from(val, out_buffer = new Uint32Array(4)) {
        return extension_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 extension_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 extension_Int128(out_buffer);
        for (let posn = negate ? 1 : 0; posn < length;) {
            const group = extension_kInt32DecimalDigits < length - posn ?
                extension_kInt32DecimalDigits : length - posn;
            const chunk = new extension_Int128(new Uint32Array([parseInt(str.substr(posn, group), 10), 0, 0, 0]));
            const multiple = new extension_Int128(new Uint32Array([extension_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;) {
            extension_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 extension_VectorLoader extends extension_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 extension_Field ? node.type : node);
    }
    visitNull(type, { length, } = this.nextFieldNode()) { return extension_Data.Null(type, 0, length); }
    visitBool(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Bool(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitInt(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Int(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitFloat(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Float(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitUtf8(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Utf8(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readOffsets(type), this.readData(type)); }
    visitBinary(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Binary(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readOffsets(type), this.readData(type)); }
    visitFixedSizeBinary(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.FixedSizeBinary(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitDate(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Date(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitTimestamp(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Timestamp(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitTime(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Time(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitDecimal(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Decimal(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitList(type, { length, nullCount } = this.nextFieldNode()) { return extension_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 extension_Data.Struct(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.visitMany(type.children)); }
    visitUnion(type) { return type.mode === extension_UnionMode.Sparse ? this.visitSparseUnion(type) : this.visitDenseUnion(type); }
    visitDenseUnion(type, { length, nullCount } = this.nextFieldNode()) { return extension_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 extension_Data.Union(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readTypeIds(type), this.visitMany(type.children)); }
    visitDictionary(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Dictionary(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type.indices), this.readDictionary(type)); }
    visitInterval(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.Interval(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.readData(type)); }
    visitFixedSizeList(type, { length, nullCount } = this.nextFieldNode()) { return extension_Data.FixedSizeList(type, 0, length, nullCount, this.readNullBitmap(type, nullCount), this.visit(type.children[0])); }
    visitMap(type, { length, nullCount } = this.nextFieldNode()) { return extension_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 extension_JSONVectorLoader extends extension_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) : extension_packBools(this.sources[offset]);
    }
    readOffsets(_type, { offset } = this.nextBufferRange()) {
        return extension_toArrayBufferView(Uint8Array, extension_toArrayBufferView(Int32Array, this.sources[offset]));
    }
    readTypeIds(type, { offset } = this.nextBufferRange()) {
        return extension_toArrayBufferView(Uint8Array, extension_toArrayBufferView(type.ArrayType, this.sources[offset]));
    }
    readData(type, { offset } = this.nextBufferRange()) {
        const { sources } = this;
        if (extension_DataType.isTimestamp(type)) {
            return extension_toArrayBufferView(Uint8Array, extension_int_Int64.convertArray(sources[offset]));
        }
        else if ((extension_DataType.isInt(type) || extension_DataType.isTime(type)) && type.bitWidth === 64) {
            return extension_toArrayBufferView(Uint8Array, extension_int_Int64.convertArray(sources[offset]));
        }
        else if (extension_DataType.isDate(type) && type.unit === extension_DateUnit.MILLISECOND) {
            return extension_toArrayBufferView(Uint8Array, extension_int_Int64.convertArray(sources[offset]));
        }
        else if (extension_DataType.isDecimal(type)) {
            return extension_toArrayBufferView(Uint8Array, extension_Int128.convertArray(sources[offset]));
        }
        else if (extension_DataType.isBinary(type) || extension_DataType.isFixedSizeBinary(type)) {
            return extension_binaryDataFromJSON(sources[offset]);
        }
        else if (extension_DataType.isBool(type)) {
            return extension_packBools(sources[offset]);
        }
        else if (extension_DataType.isUtf8(type)) {
            return extension_encodeUtf8(sources[offset].join(''));
        }
        return extension_toArrayBufferView(Uint8Array, extension_toArrayBufferView(type.ArrayType, sources[offset].map((x) => +x)));
    }
}
/** @ignore */
function extension_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 extension_typeassembler_Long = extension_flatbuffers.Long;


var extension_typeassembler_Null = extension_Schema_org.apache.arrow.flatbuf.Null;
var extension_Int = extension_Schema_org.apache.arrow.flatbuf.Int;
var extension_FloatingPoint = extension_Schema_org.apache.arrow.flatbuf.FloatingPoint;
var extension_typeassembler_Binary = extension_Schema_org.apache.arrow.flatbuf.Binary;
var extension_typeassembler_Bool = extension_Schema_org.apache.arrow.flatbuf.Bool;
var extension_typeassembler_Utf8 = extension_Schema_org.apache.arrow.flatbuf.Utf8;
var extension_typeassembler_Decimal = extension_Schema_org.apache.arrow.flatbuf.Decimal;
var extension_typeassembler_Date = extension_Schema_org.apache.arrow.flatbuf.Date;
var extension_Time = extension_Schema_org.apache.arrow.flatbuf.Time;
var extension_Timestamp = extension_Schema_org.apache.arrow.flatbuf.Timestamp;
var extension_Interval = extension_Schema_org.apache.arrow.flatbuf.Interval;
var extension_typeassembler_List = extension_Schema_org.apache.arrow.flatbuf.List;
var extension_typeassembler_Struct = extension_Schema_org.apache.arrow.flatbuf.Struct_;
var extension_Union = extension_Schema_org.apache.arrow.flatbuf.Union;
var extension_DictionaryEncoding = extension_Schema_org.apache.arrow.flatbuf.DictionaryEncoding;
var extension_typeassembler_FixedSizeBinary = extension_Schema_org.apache.arrow.flatbuf.FixedSizeBinary;
var extension_typeassembler_FixedSizeList = extension_Schema_org.apache.arrow.flatbuf.FixedSizeList;
var extension_typeassembler_Map_ = extension_Schema_org.apache.arrow.flatbuf.Map;
/** @ignore */
class extension_TypeAssembler extends extension_Visitor {
    visit(node, builder) {
        return (node == null || builder == null) ? undefined : super.visit(node, builder);
    }
    visitNull(_node, b) {
        extension_typeassembler_Null.startNull(b);
        return extension_typeassembler_Null.endNull(b);
    }
    visitInt(node, b) {
        extension_Int.startInt(b);
        extension_Int.addBitWidth(b, node.bitWidth);
        extension_Int.addIsSigned(b, node.isSigned);
        return extension_Int.endInt(b);
    }
    visitFloat(node, b) {
        extension_FloatingPoint.startFloatingPoint(b);
        extension_FloatingPoint.addPrecision(b, node.precision);
        return extension_FloatingPoint.endFloatingPoint(b);
    }
    visitBinary(_node, b) {
        extension_typeassembler_Binary.startBinary(b);
        return extension_typeassembler_Binary.endBinary(b);
    }
    visitBool(_node, b) {
        extension_typeassembler_Bool.startBool(b);
        return extension_typeassembler_Bool.endBool(b);
    }
    visitUtf8(_node, b) {
        extension_typeassembler_Utf8.startUtf8(b);
        return extension_typeassembler_Utf8.endUtf8(b);
    }
    visitDecimal(node, b) {
        extension_typeassembler_Decimal.startDecimal(b);
        extension_typeassembler_Decimal.addScale(b, node.scale);
        extension_typeassembler_Decimal.addPrecision(b, node.precision);
        return extension_typeassembler_Decimal.endDecimal(b);
    }
    visitDate(node, b) {
        extension_typeassembler_Date.startDate(b);
        extension_typeassembler_Date.addUnit(b, node.unit);
        return extension_typeassembler_Date.endDate(b);
    }
    visitTime(node, b) {
        extension_Time.startTime(b);
        extension_Time.addUnit(b, node.unit);
        extension_Time.addBitWidth(b, node.bitWidth);
        return extension_Time.endTime(b);
    }
    visitTimestamp(node, b) {
        const timezone = (node.timezone && b.createString(node.timezone)) || undefined;
        extension_Timestamp.startTimestamp(b);
        extension_Timestamp.addUnit(b, node.unit);
        if (timezone !== undefined) {
            extension_Timestamp.addTimezone(b, timezone);
        }
        return extension_Timestamp.endTimestamp(b);
    }
    visitInterval(node, b) {
        extension_Interval.startInterval(b);
        extension_Interval.addUnit(b, node.unit);
        return extension_Interval.endInterval(b);
    }
    visitList(_node, b) {
        extension_typeassembler_List.startList(b);
        return extension_typeassembler_List.endList(b);
    }
    visitStruct(_node, b) {
        extension_typeassembler_Struct.startStruct_(b);
        return extension_typeassembler_Struct.endStruct_(b);
    }
    visitUnion(node, b) {
        extension_Union.startTypeIdsVector(b, node.typeIds.length);
        const typeIds = extension_Union.createTypeIdsVector(b, node.typeIds);
        extension_Union.startUnion(b);
        extension_Union.addMode(b, node.mode);
        extension_Union.addTypeIds(b, typeIds);
        return extension_Union.endUnion(b);
    }
    visitDictionary(node, b) {
        const indexType = this.visit(node.indices, b);
        extension_DictionaryEncoding.startDictionaryEncoding(b);
        extension_DictionaryEncoding.addId(b, new extension_typeassembler_Long(node.id, 0));
        extension_DictionaryEncoding.addIsOrdered(b, node.isOrdered);
        if (indexType !== undefined) {
            extension_DictionaryEncoding.addIndexType(b, indexType);
        }
        return extension_DictionaryEncoding.endDictionaryEncoding(b);
    }
    visitFixedSizeBinary(node, b) {
        extension_typeassembler_FixedSizeBinary.startFixedSizeBinary(b);
        extension_typeassembler_FixedSizeBinary.addByteWidth(b, node.byteWidth);
        return extension_typeassembler_FixedSizeBinary.endFixedSizeBinary(b);
    }
    visitFixedSizeList(node, b) {
        extension_typeassembler_FixedSizeList.startFixedSizeList(b);
        extension_typeassembler_FixedSizeList.addListSize(b, node.listSize);
        return extension_typeassembler_FixedSizeList.endFixedSizeList(b);
    }
    visitMap(node, b) {
        extension_typeassembler_Map_.startMap(b);
        extension_typeassembler_Map_.addKeysSorted(b, node.keysSorted);
        return extension_typeassembler_Map_.endMap(b);
    }
}
/** @ignore */
const extension_typeassembler_instance = new extension_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 extension_schemaFromJSON(_schema, dictionaries = new Map()) {
    return new extension_Schema(extension_schemaFieldsFromJSON(_schema, dictionaries), extension_customMetadataFromJSON(_schema['customMetadata']), dictionaries);
}
/** @ignore */
function extension_recordBatchFromJSON(b) {
    return new src_extension_RecordBatch(b['count'], extension_fieldNodesFromJSON(b['columns']), extension_buffersFromJSON(b['columns']));
}
/** @ignore */
function extension_dictionaryBatchFromJSON(b) {
    return new src_extension_DictionaryBatch(extension_recordBatchFromJSON(b['data']), b['id'], b['isDelta']);
}
/** @ignore */
function extension_schemaFieldsFromJSON(_schema, dictionaries) {
    return (_schema['fields'] || []).filter(Boolean).map((f) => extension_Field.fromJSON(f, dictionaries));
}
/** @ignore */
function extension_fieldChildrenFromJSON(_field, dictionaries) {
    return (_field['children'] || []).filter(Boolean).map((f) => extension_Field.fromJSON(f, dictionaries));
}
/** @ignore */
function extension_fieldNodesFromJSON(xs) {
    return (xs || []).reduce((fieldNodes, column) => [
        ...fieldNodes,
        new src_extension_FieldNode(column['count'], extension_nullCountFromJSON(column['VALIDITY'])),
        ...extension_fieldNodesFromJSON(column['children'])
    ], []);
}
/** @ignore */
function extension_buffersFromJSON(xs, buffers = []) {
    for (let i = -1, n = (xs || []).length; ++i < n;) {
        const column = xs[i];
        column['VALIDITY'] && buffers.push(new extension_BufferRegion(buffers.length, column['VALIDITY'].length));
        column['TYPE'] && buffers.push(new extension_BufferRegion(buffers.length, column['TYPE'].length));
        column['OFFSET'] && buffers.push(new extension_BufferRegion(buffers.length, column['OFFSET'].length));
        column['DATA'] && buffers.push(new extension_BufferRegion(buffers.length, column['DATA'].length));
        buffers = extension_buffersFromJSON(column['children'], buffers);
    }
    return buffers;
}
/** @ignore */
function extension_nullCountFromJSON(validity) {
    return (validity || []).reduce((sum, val) => sum + +(val === 0), 0);
}
/** @ignore */
function extension_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 = extension_typeFromJSON(_field, extension_fieldChildrenFromJSON(_field, dictionaries));
        field = new extension_Field(_field['name'], type, _field['nullable'], extension_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']) ? extension_indexTypeFromJSON(keys) : new extension_Int32();
        dictionaries.set(id, type = extension_typeFromJSON(_field, extension_fieldChildrenFromJSON(_field, dictionaries)));
        dictType = new extension_type_Dictionary(type, keys, id, dictMeta['isOrdered']);
        field = new extension_Field(_field['name'], dictType, _field['nullable'], extension_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']) ? extension_indexTypeFromJSON(keys) : new extension_Int32();
        dictType = new extension_type_Dictionary(dictionaries.get(id), keys, id, dictMeta['isOrdered']);
        field = new extension_Field(_field['name'], dictType, _field['nullable'], extension_customMetadataFromJSON(_field['customMetadata']));
    }
    return field || null;
}
/** @ignore */
function extension_customMetadataFromJSON(_metadata) {
    return new Map(Object.entries(_metadata || {}));
}
/** @ignore */
function extension_indexTypeFromJSON(_type) {
    return new extension_Int_(_type['isSigned'], _type['bitWidth']);
}
/** @ignore */
function extension_typeFromJSON(f, children) {
    const typeId = f['type']['name'];
    switch (typeId) {
        case 'NONE': return new extension_Null();
        case 'null': return new extension_Null();
        case 'binary': return new extension_Binary();
        case 'utf8': return new extension_Utf8();
        case 'bool': return new extension_Bool();
        case 'list': return new extension_List((children || [])[0]);
        case 'struct': return new extension_Struct(children || []);
        case 'struct_': return new extension_Struct(children || []);
    }
    switch (typeId) {
        case 'int': {
            const t = f['type'];
            return new extension_Int_(t['isSigned'], t['bitWidth']);
        }
        case 'floatingpoint': {
            const t = f['type'];
            return new extension_Float(extension_Precision[t['precision']]);
        }
        case 'decimal': {
            const t = f['type'];
            return new extension_Decimal(t['scale'], t['precision']);
        }
        case 'date': {
            const t = f['type'];
            return new extension_Date_(extension_DateUnit[t['unit']]);
        }
        case 'time': {
            const t = f['type'];
            return new extension_Time_(extension_TimeUnit[t['unit']], t['bitWidth']);
        }
        case 'timestamp': {
            const t = f['type'];
            return new extension_Timestamp_(extension_TimeUnit[t['unit']], t['timezone']);
        }
        case 'interval': {
            const t = f['type'];
            return new extension_Interval_(extension_IntervalUnit[t['unit']]);
        }
        case 'union': {
            const t = f['type'];
            return new extension_Union_(extension_UnionMode[t['mode']], (t['typeIds'] || []), children || []);
        }
        case 'fixedsizebinary': {
            const t = f['type'];
            return new extension_FixedSizeBinary(t['byteWidth']);
        }
        case 'fixedsizelist': {
            const t = f['type'];
            return new extension_FixedSizeList(t['listSize'], (children || [])[0]);
        }
        case 'map': {
            const t = f['type'];
            return new extension_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 extension_message_Long = extension_flatbuffers.Long;
var extension_message_Builder = extension_flatbuffers.Builder;
var extension_message_ByteBuffer = extension_flatbuffers.ByteBuffer;
var extension_message_Type = extension_Schema_org.apache.arrow.flatbuf.Type;
var src_extension_Field = extension_Schema_org.apache.arrow.flatbuf.Field;
var src_extension_Schema = extension_Schema_org.apache.arrow.flatbuf.Schema;
var extension_message_Buffer = extension_Schema_org.apache.arrow.flatbuf.Buffer;
var extension_Message = extension_org.apache.arrow.flatbuf.Message;
var extension_KeyValue = extension_Schema_org.apache.arrow.flatbuf.KeyValue;
var extension_FieldNode = extension_org.apache.arrow.flatbuf.FieldNode;
var extension_Endianness = extension_Schema_org.apache.arrow.flatbuf.Endianness;
var extension_RecordBatch = extension_org.apache.arrow.flatbuf.RecordBatch;
var extension_DictionaryBatch = extension_org.apache.arrow.flatbuf.DictionaryBatch;

/**
 * @ignore
 * @private
 **/
class src_extension_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_extension_Message(0, extension_MetadataVersion.V4, headerType);
        message._createHeader = extension_messageHeaderFromJSON(msg, headerType);
        return message;
    }
    /** @nocollapse */
    static decode(buf) {
        buf = new extension_message_ByteBuffer(extension_toUint8Array(buf));
        const _message = extension_Message.getRootAsMessage(buf);
        const bodyLength = _message.bodyLength();
        const version = _message.version();
        const headerType = _message.headerType();
        const message = new src_extension_Message(bodyLength, version, headerType);
        message._createHeader = extension_decodeMessageHeader(_message, headerType);
        return message;
    }
    /** @nocollapse */
    static encode(message) {
        let b = new extension_message_Builder(), headerOffset = -1;
        if (message.isSchema()) {
            headerOffset = extension_Schema.encode(b, message.header());
        }
        else if (message.isRecordBatch()) {
            headerOffset = src_extension_RecordBatch.encode(b, message.header());
        }
        else if (message.isDictionaryBatch()) {
            headerOffset = src_extension_DictionaryBatch.encode(b, message.header());
        }
        extension_Message.startMessage(b);
        extension_Message.addVersion(b, extension_MetadataVersion.V4);
        extension_Message.addHeader(b, headerOffset);
        extension_Message.addHeaderType(b, message.headerType);
        extension_Message.addBodyLength(b, new extension_message_Long(message.bodyLength, 0));
        extension_Message.finishMessageBuffer(b, extension_Message.endMessage(b));
        return b.asUint8Array();
    }
    /** @nocollapse */
    static from(header, bodyLength = 0) {
        if (header instanceof extension_Schema) {
            return new src_extension_Message(0, extension_MetadataVersion.V4, extension_MessageHeader.Schema, header);
        }
        if (header instanceof src_extension_RecordBatch) {
            return new src_extension_Message(bodyLength, extension_MetadataVersion.V4, extension_MessageHeader.RecordBatch, header);
        }
        if (header instanceof src_extension_DictionaryBatch) {
            return new src_extension_Message(bodyLength, extension_MetadataVersion.V4, extension_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 === extension_MessageHeader.Schema; }
    isRecordBatch() { return this.headerType === extension_MessageHeader.RecordBatch; }
    isDictionaryBatch() { return this.headerType === extension_MessageHeader.DictionaryBatch; }
}
/**
 * @ignore
 * @private
 **/
class src_extension_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_extension_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 extension_BufferRegion {
    constructor(offset, length) {
        this.offset = typeof offset === 'number' ? offset : offset.low;
        this.length = typeof length === 'number' ? length : length.low;
    }
}
/**
 * @ignore
 * @private
 **/
class src_extension_FieldNode {
    constructor(length, nullCount) {
        this.length = typeof length === 'number' ? length : length.low;
        this.nullCount = typeof nullCount === 'number' ? nullCount : nullCount.low;
    }
}
/** @ignore */
function extension_messageHeaderFromJSON(message, type) {
    return (() => {
        switch (type) {
            case extension_MessageHeader.Schema: return extension_Schema.fromJSON(message);
            case extension_MessageHeader.RecordBatch: return src_extension_RecordBatch.fromJSON(message);
            case extension_MessageHeader.DictionaryBatch: return src_extension_DictionaryBatch.fromJSON(message);
        }
        throw new Error(`Unrecognized Message type: { name: ${extension_MessageHeader[type]}, type: ${type} }`);
    });
}
/** @ignore */
function extension_decodeMessageHeader(message, type) {
    return (() => {
        switch (type) {
            case extension_MessageHeader.Schema: return extension_Schema.decode(message.header(new src_extension_Schema()));
            case extension_MessageHeader.RecordBatch: return src_extension_RecordBatch.decode(message.header(new extension_RecordBatch()), message.version());
            case extension_MessageHeader.DictionaryBatch: return src_extension_DictionaryBatch.decode(message.header(new extension_DictionaryBatch()), message.version());
        }
        throw new Error(`Unrecognized Message type: { name: ${extension_MessageHeader[type]}, type: ${type} }`);
    });
}
extension_Field['encode'] = extension_encodeField;
extension_Field['decode'] = extension_decodeField;
extension_Field['fromJSON'] = extension_fieldFromJSON;
extension_Schema['encode'] = extension_encodeSchema;
extension_Schema['decode'] = extension_decodeSchema;
extension_Schema['fromJSON'] = extension_schemaFromJSON;
src_extension_RecordBatch['encode'] = extension_encodeRecordBatch;
src_extension_RecordBatch['decode'] = extension_decodeRecordBatch;
src_extension_RecordBatch['fromJSON'] = extension_recordBatchFromJSON;
src_extension_DictionaryBatch['encode'] = extension_encodeDictionaryBatch;
src_extension_DictionaryBatch['decode'] = extension_decodeDictionaryBatch;
src_extension_DictionaryBatch['fromJSON'] = extension_dictionaryBatchFromJSON;
src_extension_FieldNode['encode'] = extension_encodeFieldNode;
src_extension_FieldNode['decode'] = extension_decodeFieldNode;
extension_BufferRegion['encode'] = extension_encodeBufferRegion;
extension_BufferRegion['decode'] = extension_decodeBufferRegion;
/** @ignore */
function extension_decodeSchema(_schema, dictionaries = new Map()) {
    const fields = extension_decodeSchemaFields(_schema, dictionaries);
    return new extension_Schema(fields, extension_decodeCustomMetadata(_schema), dictionaries);
}
/** @ignore */
function extension_decodeRecordBatch(batch, version = extension_MetadataVersion.V4) {
    return new src_extension_RecordBatch(batch.length(), extension_decodeFieldNodes(batch), extension_decodeBuffers(batch, version));
}
/** @ignore */
function extension_decodeDictionaryBatch(batch, version = extension_MetadataVersion.V4) {
    return new src_extension_DictionaryBatch(src_extension_RecordBatch.decode(batch.data(), version), batch.id(), batch.isDelta());
}
/** @ignore */
function extension_decodeBufferRegion(b) {
    return new extension_BufferRegion(b.offset(), b.length());
}
/** @ignore */
function extension_decodeFieldNode(f) {
    return new src_extension_FieldNode(f.length(), f.nullCount());
}
/** @ignore */
function extension_decodeFieldNodes(batch) {
    const nodes = [];
    for (let f, i = -1, j = -1, n = batch.nodesLength(); ++i < n;) {
        if (f = batch.nodes(i)) {
            nodes[++j] = src_extension_FieldNode.decode(f);
        }
    }
    return nodes;
}
/** @ignore */
function extension_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 < extension_MetadataVersion.V4) {
                b.bb_pos += (8 * (i + 1));
            }
            bufferRegions[++j] = extension_BufferRegion.decode(b);
        }
    }
    return bufferRegions;
}
/** @ignore */
function extension_decodeSchemaFields(schema, dictionaries) {
    const fields = [];
    for (let f, i = -1, j = -1, n = schema.fieldsLength(); ++i < n;) {
        if (f = schema.fields(i)) {
            fields[++j] = extension_Field.decode(f, dictionaries);
        }
    }
    return fields;
}
/** @ignore */
function extension_decodeFieldChildren(field, dictionaries) {
    const children = [];
    for (let f, i = -1, j = -1, n = field.childrenLength(); ++i < n;) {
        if (f = field.children(i)) {
            children[++j] = extension_Field.decode(f, dictionaries);
        }
    }
    return children;
}
/** @ignore */
function extension_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 = extension_decodeFieldType(f, extension_decodeFieldChildren(f, dictionaries));
        field = new extension_Field(f.name(), type, f.nullable(), extension_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()) ? extension_decodeIndexType(keys) : new extension_Int32();
        dictionaries.set(id, type = extension_decodeFieldType(f, extension_decodeFieldChildren(f, dictionaries)));
        dictType = new extension_type_Dictionary(type, keys, id, dictMeta.isOrdered());
        field = new extension_Field(f.name(), dictType, f.nullable(), extension_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()) ? extension_decodeIndexType(keys) : new extension_Int32();
        dictType = new extension_type_Dictionary(dictionaries.get(id), keys, id, dictMeta.isOrdered());
        field = new extension_Field(f.name(), dictType, f.nullable(), extension_decodeCustomMetadata(f));
    }
    return field || null;
}
/** @ignore */
function extension_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 extension_decodeIndexType(_type) {
    return new extension_Int_(_type.isSigned(), _type.bitWidth());
}
/** @ignore */
function extension_decodeFieldType(f, children) {
    const typeId = f.typeType();
    switch (typeId) {
        case extension_message_Type.NONE: return new extension_Null();
        case extension_message_Type.Null: return new extension_Null();
        case extension_message_Type.Binary: return new extension_Binary();
        case extension_message_Type.Utf8: return new extension_Utf8();
        case extension_message_Type.Bool: return new extension_Bool();
        case extension_message_Type.List: return new extension_List((children || [])[0]);
        case extension_message_Type.Struct_: return new extension_Struct(children || []);
    }
    switch (typeId) {
        case extension_message_Type.Int: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Int());
            return new extension_Int_(t.isSigned(), t.bitWidth());
        }
        case extension_message_Type.FloatingPoint: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.FloatingPoint());
            return new extension_Float(t.precision());
        }
        case extension_message_Type.Decimal: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Decimal());
            return new extension_Decimal(t.scale(), t.precision());
        }
        case extension_message_Type.Date: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Date());
            return new extension_Date_(t.unit());
        }
        case extension_message_Type.Time: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Time());
            return new extension_Time_(t.unit(), t.bitWidth());
        }
        case extension_message_Type.Timestamp: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Timestamp());
            return new extension_Timestamp_(t.unit(), t.timezone());
        }
        case extension_message_Type.Interval: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Interval());
            return new extension_Interval_(t.unit());
        }
        case extension_message_Type.Union: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Union());
            return new extension_Union_(t.mode(), t.typeIdsArray() || [], children || []);
        }
        case extension_message_Type.FixedSizeBinary: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.FixedSizeBinary());
            return new extension_FixedSizeBinary(t.byteWidth());
        }
        case extension_message_Type.FixedSizeList: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.FixedSizeList());
            return new extension_FixedSizeList(t.listSize(), (children || [])[0]);
        }
        case extension_message_Type.Map: {
            const t = f.type(new extension_Schema_org.apache.arrow.flatbuf.Map());
            return new extension_Map_((children || [])[0], t.keysSorted());
        }
    }
    throw new Error(`Unrecognized type: "${extension_message_Type[typeId]}" (${typeId})`);
}
/** @ignore */
function extension_encodeSchema(b, schema) {
    const fieldOffsets = schema.fields.map((f) => extension_Field.encode(b, f));
    src_extension_Schema.startFieldsVector(b, fieldOffsets.length);
    const fieldsVectorOffset = src_extension_Schema.createFieldsVector(b, fieldOffsets);
    const metadataOffset = !(schema.metadata && schema.metadata.size > 0) ? -1 :
        src_extension_Schema.createCustomMetadataVector(b, [...schema.metadata].map(([k, v]) => {
            const key = b.createString(`${k}`);
            const val = b.createString(`${v}`);
            extension_KeyValue.startKeyValue(b);
            extension_KeyValue.addKey(b, key);
            extension_KeyValue.addValue(b, val);
            return extension_KeyValue.endKeyValue(b);
        }));
    src_extension_Schema.startSchema(b);
    src_extension_Schema.addFields(b, fieldsVectorOffset);
    src_extension_Schema.addEndianness(b, extension_platformIsLittleEndian ? extension_Endianness.Little : extension_Endianness.Big);
    if (metadataOffset !== -1) {
        src_extension_Schema.addCustomMetadata(b, metadataOffset);
    }
    return src_extension_Schema.endSchema(b);
}
/** @ignore */
function extension_encodeField(b, field) {
    let nameOffset = -1;
    let typeOffset = -1;
    let dictionaryOffset = -1;
    let type = field.type;
    let typeId = field.typeId;
    if (!extension_DataType.isDictionary(type)) {
        typeOffset = extension_typeassembler_instance.visit(type, b);
    }
    else {
        typeId = type.dictionary.typeId;
        dictionaryOffset = extension_typeassembler_instance.visit(type, b);
        typeOffset = extension_typeassembler_instance.visit(type.dictionary, b);
    }
    const childOffsets = (type.children || []).map((f) => extension_Field.encode(b, f));
    const childrenVectorOffset = src_extension_Field.createChildrenVector(b, childOffsets);
    const metadataOffset = !(field.metadata && field.metadata.size > 0) ? -1 :
        src_extension_Field.createCustomMetadataVector(b, [...field.metadata].map(([k, v]) => {
            const key = b.createString(`${k}`);
            const val = b.createString(`${v}`);
            extension_KeyValue.startKeyValue(b);
            extension_KeyValue.addKey(b, key);
            extension_KeyValue.addValue(b, val);
            return extension_KeyValue.endKeyValue(b);
        }));
    if (field.name) {
        nameOffset = b.createString(field.name);
    }
    src_extension_Field.startField(b);
    src_extension_Field.addType(b, typeOffset);
    src_extension_Field.addTypeType(b, typeId);
    src_extension_Field.addChildren(b, childrenVectorOffset);
    src_extension_Field.addNullable(b, !!field.nullable);
    if (nameOffset !== -1) {
        src_extension_Field.addName(b, nameOffset);
    }
    if (dictionaryOffset !== -1) {
        src_extension_Field.addDictionary(b, dictionaryOffset);
    }
    if (metadataOffset !== -1) {
        src_extension_Field.addCustomMetadata(b, metadataOffset);
    }
    return src_extension_Field.endField(b);
}
/** @ignore */
function extension_encodeRecordBatch(b, recordBatch) {
    const nodes = recordBatch.nodes || [];
    const buffers = recordBatch.buffers || [];
    extension_RecordBatch.startNodesVector(b, nodes.length);
    nodes.slice().reverse().forEach((n) => src_extension_FieldNode.encode(b, n));
    const nodesVectorOffset = b.endVector();
    extension_RecordBatch.startBuffersVector(b, buffers.length);
    buffers.slice().reverse().forEach((b_) => extension_BufferRegion.encode(b, b_));
    const buffersVectorOffset = b.endVector();
    extension_RecordBatch.startRecordBatch(b);
    extension_RecordBatch.addLength(b, new extension_message_Long(recordBatch.length, 0));
    extension_RecordBatch.addNodes(b, nodesVectorOffset);
    extension_RecordBatch.addBuffers(b, buffersVectorOffset);
    return extension_RecordBatch.endRecordBatch(b);
}
/** @ignore */
function extension_encodeDictionaryBatch(b, dictionaryBatch) {
    const dataOffset = src_extension_RecordBatch.encode(b, dictionaryBatch.data);
    extension_DictionaryBatch.startDictionaryBatch(b);
    extension_DictionaryBatch.addId(b, new extension_message_Long(dictionaryBatch.id, 0));
    extension_DictionaryBatch.addIsDelta(b, dictionaryBatch.isDelta);
    extension_DictionaryBatch.addData(b, dataOffset);
    return extension_DictionaryBatch.endDictionaryBatch(b);
}
/** @ignore */
function extension_encodeFieldNode(b, node) {
    return extension_FieldNode.createFieldNode(b, new extension_message_Long(node.length, 0), new extension_message_Long(node.nullCount, 0));
}
/** @ignore */
function extension_encodeBufferRegion(b, node) {
    return extension_message_Buffer.createBuffer(b, new extension_message_Long(node.offset, 0), new extension_message_Long(node.length, 0));
}
/** @ignore */
const extension_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 extension_ipc_message_ByteBuffer = extension_flatbuffers.ByteBuffer;






/** @ignore */ const extension_invalidMessageType = (type) => `Expected ${extension_MessageHeader[type]} Message in stream, but was null or length 0.`;
/** @ignore */ const extension_nullMessage = (type) => `Header pointer of flatbuffer-encoded ${extension_MessageHeader[type]} Message is null or length 0.`;
/** @ignore */ const extension_invalidMessageMetadata = (expected, actual) => `Expected to read ${expected} metadata bytes, but only read ${actual}.`;
/** @ignore */ const extension_invalidMessageBodyLength = (expected, actual) => `Expected to read ${expected} bytes for message body, but only read ${actual}.`;
/** @ignore */
class extension_MessageReader {
    constructor(source) {
        this.source = source instanceof extension_ByteStream ? source : new extension_ByteStream(source);
    }
    [Symbol.iterator]() { return this; }
    next() {
        let r;
        if ((r = this.readMetadataLength()).done) {
            return extension_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 extension_ITERATOR_DONE;
        }
        if ((r = this.readMetadata(r.value)).done) {
            return extension_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(extension_invalidMessageType(type));
        }
        return r.value;
    }
    readMessageBody(bodyLength) {
        if (bodyLength <= 0) {
            return new Uint8Array(0);
        }
        const buf = extension_toUint8Array(this.source.read(bodyLength));
        if (buf.byteLength < bodyLength) {
            throw new Error(extension_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 = extension_MessageHeader.Schema;
        const message = this.readMessage(type);
        const schema = message && message.header();
        if (throwIfNull && !schema) {
            throw new Error(extension_nullMessage(type));
        }
        return schema;
    }
    readMetadataLength() {
        const buf = this.source.read(extension_PADDING);
        const bb = buf && new extension_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 extension_ITERATOR_DONE;
        }
        if (buf.byteLength < metadataLength) {
            throw new Error(extension_invalidMessageMetadata(metadataLength, buf.byteLength));
        }
        return { done: false, value: src_extension_Message.decode(buf) };
    }
}
/** @ignore */
class extension_AsyncMessageReader {
    constructor(source, byteLength) {
        this.source = source instanceof extension_AsyncByteStream ? source
            : extension_isFileHandle(source)
                ? new extension_AsyncRandomAccessFile(source, byteLength)
                : new extension_AsyncByteStream(source);
    }
    [Symbol.asyncIterator]() { return this; }
    async next() {
        let r;
        if ((r = await this.readMetadataLength()).done) {
            return extension_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 extension_ITERATOR_DONE;
        }
        if ((r = await this.readMetadata(r.value)).done) {
            return extension_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(extension_invalidMessageType(type));
        }
        return r.value;
    }
    async readMessageBody(bodyLength) {
        if (bodyLength <= 0) {
            return new Uint8Array(0);
        }
        const buf = extension_toUint8Array(await this.source.read(bodyLength));
        if (buf.byteLength < bodyLength) {
            throw new Error(extension_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 = extension_MessageHeader.Schema;
        const message = await this.readMessage(type);
        const schema = message && message.header();
        if (throwIfNull && !schema) {
            throw new Error(extension_nullMessage(type));
        }
        return schema;
    }
    async readMetadataLength() {
        const buf = await this.source.read(extension_PADDING);
        const bb = buf && new extension_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 extension_ITERATOR_DONE;
        }
        if (buf.byteLength < metadataLength) {
            throw new Error(extension_invalidMessageMetadata(metadataLength, buf.byteLength));
        }
        return { done: false, value: src_extension_Message.decode(buf) };
    }
}
/** @ignore */
class extension_JSONMessageReader extends extension_MessageReader {
    constructor(source) {
        super(new Uint8Array(0));
        this._schema = false;
        this._body = [];
        this._batchIndex = 0;
        this._dictionaryIndex = 0;
        this._json = source instanceof extension_ArrowJSON ? source : new extension_ArrowJSON(source);
    }
    next() {
        const { _json } = this;
        if (!this._schema) {
            this._schema = true;
            const message = src_extension_Message.fromJSON(_json.schema, extension_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_extension_Message.fromJSON(batch, extension_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_extension_Message.fromJSON(batch, extension_MessageHeader.RecordBatch);
            return { done: false, value: message };
        }
        this._body = [];
        return extension_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(extension_invalidMessageType(type));
        }
        return r.value;
    }
    readSchema() {
        const type = extension_MessageHeader.Schema;
        const message = this.readMessage(type);
        const schema = message && message.header();
        if (!message || !schema) {
            throw new Error(extension_nullMessage(type));
        }
        return schema;
    }
}
/** @ignore */
const extension_PADDING = 4;
/** @ignore */
const extension_MAGIC_STR = 'ARROW1';
/** @ignore */
const extension_MAGIC = new Uint8Array(extension_MAGIC_STR.length);
for (let i = 0; i < extension_MAGIC_STR.length; i += 1 | 0) {
    extension_MAGIC[i] = extension_MAGIC_STR.charCodeAt(i);
}
/** @ignore */
function extension_checkForMagicArrowString(buffer, index = 0) {
    for (let i = -1, n = extension_MAGIC.length; ++i < n;) {
        if (extension_MAGIC[i] !== buffer[index + i]) {
            return false;
        }
    }
    return true;
}
/** @ignore */
const extension_magicLength = extension_MAGIC.length;
/** @ignore */
const extension_magicAndPadding = extension_magicLength + extension_PADDING;
/** @ignore */
const extension_magicX2AndPadding = extension_magicLength * 2 + extension_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 extension_VectorAssembler extends extension_Visitor {
    constructor() {
        super();
        this._byteLength = 0;
        this._nodes = [];
        this._buffers = [];
        this._bufferRegions = [];
    }
    /** @nocollapse */
    static assemble(...args) {
        const assembler = new extension_VectorAssembler();
        const vectorChildren = extension_selectVectorChildrenArgs(extension_recordbatch_RecordBatch, args);
        const [assembleResult = assembler] = assembler.visitMany(vectorChildren);
        return assembleResult;
    }
    visit(vector) {
        if (!extension_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 (!extension_DataType.isNull(vector.type)) {
                extension_addBuffer.call(this, nullCount <= 0
                    ? new Uint8Array(0) // placeholder validity buffer
                    : extension_truncateBitmap(data.offset, length, data.nullBitmap));
            }
            this.nodes.push(new src_extension_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 extension_addBuffer(values) {
    const byteLength = (values.byteLength + 7) & ~7; // Round up to a multiple of 8
    this.buffers.push(values);
    this.bufferRegions.push(new extension_BufferRegion(this._byteLength, byteLength));
    this._byteLength += byteLength;
    return this;
}
/** @ignore */
function extension_assembleUnion(vector) {
    const { type, length, typeIds, valueOffsets } = vector;
    // All Union Vectors have a typeIds buffer
    extension_addBuffer.call(this, typeIds);
    // If this is a Sparse Union, treat it like all other Nested types
    if (type.mode === extension_UnionMode.Sparse) {
        return extension_assembleNestedVector.call(this, vector);
    }
    else if (type.mode === extension_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
            extension_addBuffer.call(this, valueOffsets);
            // We can treat this like all other Nested types
            return extension_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 = extension_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];
            }
            extension_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 extension_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 extension_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 extension_addBuffer.call(this, extension_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 extension_addBuffer.call(this, extension_packBools(vector));
}
/** @ignore */
function extension_assembleFlatVector(vector) {
    return extension_addBuffer.call(this, vector.values.subarray(0, vector.length * vector.stride));
}
/** @ignore */
function extension_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
    extension_addBuffer.call(this, extension_rebaseValueOffsets(-valueOffsets[0], length, valueOffsets)); // valueOffsets buffer first
    extension_addBuffer.call(this, values.subarray(firstOffset, firstOffset + byteLength)); // sliced values buffer second
    return this;
}
/** @ignore */
function extension_assembleListVector(vector) {
    const { length, valueOffsets } = vector;
    // If we have valueOffsets (MapVector, ListVector), push that buffer first
    if (valueOffsets) {
        extension_addBuffer.call(this, extension_rebaseValueOffsets(valueOffsets[0], length, valueOffsets));
    }
    // Then insert the List's values child
    return this.visit(vector.getChildAt(0));
}
/** @ignore */
function extension_assembleNestedVector(vector) {
    return this.visitMany(vector.type.children.map((_, i) => vector.getChildAt(i)).filter(Boolean))[0];
}
extension_VectorAssembler.prototype.visitBool = extension_assembleBoolVector;
extension_VectorAssembler.prototype.visitInt = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitFloat = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitUtf8 = extension_assembleFlatListVector;
extension_VectorAssembler.prototype.visitBinary = extension_assembleFlatListVector;
extension_VectorAssembler.prototype.visitFixedSizeBinary = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitDate = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitTimestamp = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitTime = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitDecimal = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitList = extension_assembleListVector;
extension_VectorAssembler.prototype.visitStruct = extension_assembleNestedVector;
extension_VectorAssembler.prototype.visitUnion = extension_assembleUnion;
extension_VectorAssembler.prototype.visitInterval = extension_assembleFlatVector;
extension_VectorAssembler.prototype.visitFixedSizeList = extension_assembleListVector;
extension_VectorAssembler.prototype.visitMap = extension_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 extension_JSONTypeAssembler extends extension_Visitor {
    visit(node) {
        return node == null ? undefined : super.visit(node);
    }
    visitNull({ typeId }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase() };
    }
    visitInt({ typeId, bitWidth, isSigned }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'bitWidth': bitWidth, 'isSigned': isSigned };
    }
    visitFloat({ typeId, precision }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'precision': extension_Precision[precision] };
    }
    visitBinary({ typeId }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase() };
    }
    visitBool({ typeId }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase() };
    }
    visitUtf8({ typeId }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase() };
    }
    visitDecimal({ typeId, scale, precision }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'scale': scale, 'precision': precision };
    }
    visitDate({ typeId, unit }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'unit': extension_DateUnit[unit] };
    }
    visitTime({ typeId, unit, bitWidth }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'unit': extension_TimeUnit[unit], bitWidth };
    }
    visitTimestamp({ typeId, timezone, unit }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'unit': extension_TimeUnit[unit], timezone };
    }
    visitInterval({ typeId, unit }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'unit': extension_IntervalUnit[unit] };
    }
    visitList({ typeId }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase() };
    }
    visitStruct({ typeId }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase() };
    }
    visitUnion({ typeId, mode, typeIds }) {
        return {
            'name': extension_ArrowType[typeId].toLowerCase(),
            'mode': extension_UnionMode[mode],
            'typeIds': [...typeIds]
        };
    }
    visitDictionary(node) {
        return this.visit(node.dictionary);
    }
    visitFixedSizeBinary({ typeId, byteWidth }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'byteWidth': byteWidth };
    }
    visitFixedSizeList({ typeId, listSize }) {
        return { 'name': extension_ArrowType[typeId].toLowerCase(), 'listSize': listSize };
    }
    visitMap({ typeId, keysSorted }) {
        return { 'name': extension_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 extension_JSONVectorAssembler extends extension_Visitor {
    /** @nocollapse */
    static assemble(...args) {
        return new extension_JSONVectorAssembler().visitMany(extension_selectColumnChildrenArgs(extension_recordbatch_RecordBatch, args));
    }
    visit(column) {
        const { data, name, length } = column;
        const { offset, nullCount, nullBitmap } = data;
        const type = extension_DataType.isDictionary(column.type) ? column.type.indices : column.type;
        const buffers = Object.assign([], data.buffers, { [extension_BufferType.VALIDITY]: undefined });
        return {
            'name': name,
            'count': length,
            'VALIDITY': extension_DataType.isNull(type) ? undefined
                : nullCount <= 0 ? Array.from({ length }, () => 1)
                    : [...extension_iterateBits(nullBitmap, offset, length, null, extension_getBit)],
            ...super.visit(extension_AbstractVector.new(data.clone(type, offset, length, 0, buffers)))
        };
    }
    visitNull() { return {}; }
    visitBool({ values, offset, length }) {
        return { 'DATA': [...extension_iterateBits(values, offset, length, null, extension_getBool)] };
    }
    visitInt(vector) {
        return {
            'DATA': vector.type.bitWidth < 64
                ? [...vector.values]
                : [...extension_bigNumsToStrings(vector.values, 2)]
        };
    }
    visitFloat(vector) {
        return { 'DATA': [...vector.values] };
    }
    visitUtf8(vector) {
        return { 'DATA': [...vector], 'OFFSET': [...vector.valueOffsets] };
    }
    visitBinary(vector) {
        return { 'DATA': [...extension_binaryToString(vector)], OFFSET: [...vector.valueOffsets] };
    }
    visitFixedSizeBinary(vector) {
        return { 'DATA': [...extension_binaryToString(vector)] };
    }
    visitDate(vector) {
        return {
            'DATA': vector.type.unit === extension_DateUnit.DAY
                ? [...vector.values]
                : [...extension_bigNumsToStrings(vector.values, 2)]
        };
    }
    visitTimestamp(vector) {
        return { 'DATA': [...extension_bigNumsToStrings(vector.values, 2)] };
    }
    visitTime(vector) {
        return {
            'DATA': vector.type.unit < extension_TimeUnit.MICROSECOND
                ? [...vector.values]
                : [...extension_bigNumsToStrings(vector.values, 2)]
        };
    }
    visitDecimal(vector) {
        return { 'DATA': [...extension_bigNumsToStrings(vector.values, 4)] };
    }
    visitList(vector) {
        return {
            'OFFSET': [...vector.valueOffsets],
            'children': vector.type.children.map((f, i) => this.visit(new extension_column_Column(f, [vector.getChildAt(i)])))
        };
    }
    visitStruct(vector) {
        return {
            'children': vector.type.children.map((f, i) => this.visit(new extension_column_Column(f, [vector.getChildAt(i)])))
        };
    }
    visitUnion(vector) {
        return {
            'TYPE': [...vector.typeIds],
            'OFFSET': vector.type.mode === extension_UnionMode.Dense ? [...vector.valueOffsets] : undefined,
            'children': vector.type.children.map((f, i) => this.visit(new extension_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 extension_column_Column(f, [vector.getChildAt(i)])))
        };
    }
    visitMap(vector) {
        return {
            'OFFSET': [...vector.valueOffsets],
            'children': vector.type.children.map((f, i) => this.visit(new extension_column_Column(f, [vector.getChildAt(i)])))
        };
    }
}
/** @ignore */
function* extension_binaryToString(vector) {
    for (const octets of vector) {
        yield octets.reduce((str, byte) => {
            return `${str}${('0' + (byte & 0xFF).toString(16)).slice(-2)}`;
        }, '').toUpperCase();
    }
}
/** @ignore */
function* extension_bigNumsToStrings(values, stride) {
    for (let i = -1, n = values.length / stride; ++i < n;) {
        yield `${extension_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 extension_RecordBatchWriter extends extension_ReadableInterop {
    constructor(options) {
        super();
        this._position = 0;
        this._started = false;
        // @ts-ignore
        this._sink = new extension_AsyncByteQueue();
        this._schema = null;
        this._dictionaryBlocks = [];
        this._recordBatchBlocks = [];
        this._dictionaryDeltaOffsets = new Map();
        extension_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 (extension_isPromise(input)) {
            return input.then((x) => this.writeAll(x));
        }
        else if (extension_isAsyncIterable(input)) {
            return extension_writeAllAsync(this, input);
        }
        return extension_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 extension_AsyncByteQueue)) {
            this._sink = sink;
        }
        else {
            this._sink = new extension_AsyncByteQueue();
            if (sink && extension_isWritableDOMStream(sink)) {
                this.toDOMStream({ type: 'bytes' }).pipeTo(sink);
            }
            else if (sink && extension_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 extension_table_Table && !(schema = payload.schema)) {
            return this.finish() && undefined;
        }
        else if (payload instanceof extension_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 extension_recordbatch_RecordBatch) {
            if (!(payload instanceof extension_InternalEmptyPlaceholderRecordBatch)) {
                this._writeRecordBatch(payload);
            }
        }
        else if (payload instanceof extension_table_Table) {
            this.writeAll(payload.chunks);
        }
        else if (extension_isIterable(payload)) {
            this.writeAll(payload);
        }
    }
    _writeMessage(message, alignment = 8) {
        const a = alignment - 1;
        const buffer = src_extension_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 === extension_MessageHeader.RecordBatch) {
            this._recordBatchBlocks.push(new extension_FileBlock(alignedSize, message.bodyLength, this._position));
        }
        else if (message.headerType === extension_MessageHeader.DictionaryBatch) {
            this._dictionaryBlocks.push(new extension_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 = extension_toUint8Array(chunk);
            if (buffer && buffer.byteLength > 0) {
                this._sink.write(buffer);
                this._position += buffer.byteLength;
            }
        }
        return this;
    }
    _writeSchema(schema) {
        return this._writeMessage(src_extension_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(extension_MAGIC);
    }
    _writePadding(nBytes) {
        return nBytes > 0 ? this._write(new Uint8Array(nBytes)) : this;
    }
    _writeRecordBatch(batch) {
        const { byteLength, nodes, bufferRegions, buffers } = extension_VectorAssembler.assemble(batch);
        const recordBatch = new src_extension_RecordBatch(batch.length, nodes, bufferRegions);
        const message = src_extension_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 } = extension_VectorAssembler.assemble(dictionary);
        const recordBatch = new src_extension_RecordBatch(dictionary.length, nodes, bufferRegions);
        const dictionaryBatch = new src_extension_DictionaryBatch(recordBatch, id, isDelta);
        const message = src_extension_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 extension_RecordBatchStreamWriter extends extension_RecordBatchWriter {
    /** @nocollapse */
    static writeAll(input, options) {
        const writer = new extension_RecordBatchStreamWriter(options);
        if (extension_isPromise(input)) {
            return input.then((x) => writer.writeAll(x));
        }
        else if (extension_isAsyncIterable(input)) {
            return extension_writeAllAsync(writer, input);
        }
        return extension_writeAll(writer, input);
    }
}
/** @ignore */
class extension_RecordBatchFileWriter extends extension_RecordBatchWriter {
    /** @nocollapse */
    static writeAll(input) {
        const writer = new extension_RecordBatchFileWriter();
        if (extension_isPromise(input)) {
            return input.then((x) => writer.writeAll(x));
        }
        else if (extension_isAsyncIterable(input)) {
            return extension_writeAllAsync(writer, input);
        }
        return extension_writeAll(writer, input);
    }
    constructor() {
        super();
        this._autoDestroy = true;
    }
    // @ts-ignore
    _writeSchema(schema) {
        return this._writeMagic()._writePadding(2);
    }
    _writeFooter(schema) {
        const buffer = extension_Footer_.encode(new extension_Footer_(schema, extension_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 extension_RecordBatchJSONWriter extends extension_RecordBatchWriter {
    constructor() {
        super();
        this._autoDestroy = true;
        this._recordBatches = [];
        this._dictionaries = [];
    }
    /** @nocollapse */
    static writeAll(input) {
        return new extension_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(extension_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(`${extension_dictionaryBatchToJSON(dictionary, id, isDelta)}`);
        this._dictionaryBlocks.push(new extension_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(`${extension_recordBatchToJSON(this._recordBatches[i])}`);
                this._recordBatchBlocks.push(new extension_FileBlock(0, 0, 0));
            }
            this._write(`\n  ]`);
        }
        if (this._schema) {
            this._write(`\n}`);
        }
        this._dictionaries = [];
        this._recordBatches = [];
        return super.close();
    }
}
/** @ignore */
function extension_writeAll(writer, input) {
    let chunks = input;
    if (input instanceof extension_table_Table) {
        chunks = input.chunks;
        writer.reset(undefined, input.schema);
    }
    for (const batch of chunks) {
        writer.write(batch);
    }
    return writer.finish();
}
/** @ignore */
async function extension_writeAllAsync(writer, batches) {
    for await (const batch of batches) {
        writer.write(batch);
    }
    return writer.finish();
}
/** @ignore */
function extension_fieldToJSON({ name, type, nullable }) {
    const assembler = new extension_JSONTypeAssembler();
    return {
        'name': name, 'nullable': nullable,
        'type': assembler.visit(type),
        'children': (type.children || []).map(extension_fieldToJSON),
        'dictionary': !extension_DataType.isDictionary(type) ? undefined : {
            'id': type.id,
            'isOrdered': type.isOrdered,
            'indexType': assembler.visit(type.indices)
        }
    };
}
/** @ignore */
function extension_dictionaryBatchToJSON(dictionary, id, isDelta = false) {
    const field = new extension_Field(`${id}`, dictionary.type, dictionary.nullCount > 0);
    const columns = extension_JSONVectorAssembler.assemble(new extension_column_Column(field, [dictionary]));
    return JSON.stringify({
        'id': id,
        'isDelta': isDelta,
        'data': {
            'count': dictionary.length,
            'columns': columns
        }
    }, null, 2);
}
/** @ignore */
function extension_recordBatchToJSON(records) {
    return JSON.stringify({
        'count': records.length,
        'columns': extension_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 extension_noopBuf = new Uint8Array(0);
const extension_nullBufs = (bitmapLength) => [
    extension_noopBuf, extension_noopBuf, new Uint8Array(bitmapLength), extension_noopBuf
];
/** @ignore */
function extension_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)
                : extension_Data.new(field.type, 0, batchLength, batchLength, extension_nullBufs(bitmapLength));
        }
    }
    return [new extension_Schema(fields), batchLength, batchData];
}
/** @ignore */
function extension_distributeColumnsIntoRecordBatches(columns) {
    return extension_distributeVectorsIntoRecordBatches(new extension_Schema(columns.map(({ field }) => field)), columns);
}
/** @ignore */
function extension_distributeVectorsIntoRecordBatches(schema, vecs) {
    return extension_uniformlyDistributeChunksAcrossRecordBatches(schema, vecs.map((v) => v instanceof extension_Chunked ? v.chunks.map((c) => c.data) : [v.data]));
}
/** @ignore */
function extension_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 = extension_distributeChildData(fields, batchLength, childData, columns, memo);
            if (batchLength > 0) {
                batchArgs[numBatches++] = [batchLength, childData.slice()];
            }
        }
    }
    return [
        schema = new extension_Schema(fields, schema.metadata),
        batchArgs.map((xs) => new extension_recordbatch_RecordBatch(schema, ...xs))
    ];
}
/** @ignore */
function extension_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)
                : extension_Data.new(field.type, 0, batchLength, batchLength, extension_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 extension_BaseVector extends extension_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 `${extension_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 extension_AbstractVector.new(data, children);
    }
    concat(...others) {
        return extension_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 extension_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] = extension_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
    }
}
extension_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 extension_BinaryVector extends extension_BaseVector {
    asUtf8() {
        return extension_AbstractVector.new(this.data.clone(new extension_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 extension_BoolVector extends extension_BaseVector {
    /** @nocollapse */
    static from(input) {
        return extension_vectorFromValuesWithType(() => new extension_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 extension_DateVector extends extension_BaseVector {
    /** @nocollapse */
    static from(...args) {
        if (args.length === 2) {
            return extension_vectorFromValuesWithType(() => args[1] === extension_DateUnit.DAY ? new extension_DateDay() : new extension_DateMillisecond(), args[0]);
        }
        return extension_vectorFromValuesWithType(() => new extension_DateMillisecond(), args[0]);
    }
}
/** @ignore */
class extension_DateDayVector extends extension_DateVector {
}
/** @ignore */
class extension_DateMillisecondVector extends extension_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 extension_DecimalVector extends extension_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 extension_DictionaryVector extends extension_BaseVector {
    constructor(data) {
        super(data);
        this.indices = extension_AbstractVector.new(data.clone(this.type.indices));
    }
    /** @nocollapse */
    static from(...args) {
        if (args.length === 3) {
            const [values, indices, keys] = args;
            const type = new extension_type_Dictionary(values.type, indices, null, null);
            return extension_AbstractVector.new(extension_Data.Dictionary(type, 0, keys.length, 0, null, keys, values));
        }
        return extension_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); }
}
extension_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 extension_FixedSizeBinaryVector extends extension_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 extension_FixedSizeListVector extends extension_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 extension_FloatVector extends extension_BaseVector {
    /** @nocollapse */
    static from(input) {
        let ArrowType = extension_vectorTypeToDataType(this);
        if ((input instanceof ArrayBuffer) || ArrayBuffer.isView(input)) {
            let InputType = extension_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 (!extension_convertTo16Bit(ArrowType, input.constructor)) {
                    return extension_AbstractVector.new(extension_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 extension_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 extension_Float16Vector extends extension_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 extension_Float32Vector extends extension_FloatVector {
}
/** @ignore */
class extension_Float64Vector extends extension_FloatVector {
}
const extension_convertTo16Bit = (typeCtor, dataCtor) => {
    return (typeCtor === extension_Float16) && (dataCtor !== Uint16Array);
};
/** @ignore */
const extension_arrayTypeToDataType = (ctor) => {
    switch (ctor) {
        case Uint16Array: return extension_Float16;
        case Float32Array: return extension_Float32;
        case Float64Array: return extension_Float64;
        default: return null;
    }
};
/** @ignore */
const extension_vectorTypeToDataType = (ctor) => {
    switch (ctor) {
        case extension_Float16Vector: return extension_Float16;
        case extension_Float32Vector: return extension_Float32;
        case extension_Float64Vector: return extension_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 extension_IntervalVector extends extension_BaseVector {
}
/** @ignore */
class extension_IntervalDayTimeVector extends extension_IntervalVector {
}
/** @ignore */
class extension_IntervalYearMonthVector extends extension_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 extension_IntVector extends extension_BaseVector {
    /** @nocollapse */
    static from(...args) {
        let [input, is64bit = false] = args;
        let ArrowType = extension_int_vectorTypeToDataType(this, is64bit);
        if ((input instanceof ArrayBuffer) || ArrayBuffer.isView(input)) {
            let InputType = extension_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 (extension_convert32To64Bit(ArrowType, input.constructor)) {
                    length *= 0.5;
                }
                return extension_AbstractVector.new(extension_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 extension_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 extension_Int8Vector extends extension_IntVector {
}
/** @ignore */
class extension_Int16Vector extends extension_IntVector {
}
/** @ignore */
class extension_Int32Vector extends extension_IntVector {
}
/** @ignore */
class extension_Int64Vector extends extension_IntVector {
    toBigInt64Array() {
        return extension_toBigInt64Array(this.values);
    }
    get values64() {
        return this._values64 || (this._values64 = this.toBigInt64Array());
    }
}
/** @ignore */
class extension_Uint8Vector extends extension_IntVector {
}
/** @ignore */
class extension_Uint16Vector extends extension_IntVector {
}
/** @ignore */
class extension_Uint32Vector extends extension_IntVector {
}
/** @ignore */
class extension_Uint64Vector extends extension_IntVector {
    toBigUint64Array() {
        return extension_toBigUint64Array(this.values);
    }
    get values64() {
        return this._values64 || (this._values64 = this.toBigUint64Array());
    }
}
const extension_convert32To64Bit = (typeCtor, dataCtor) => {
    return (typeCtor === extension_Int64 || typeCtor === extension_Uint64) &&
        (dataCtor === Int32Array || dataCtor === Uint32Array);
};
/** @ignore */
const extension_int_arrayTypeToDataType = (ctor, is64bit) => {
    switch (ctor) {
        case Int8Array: return extension_Int8;
        case Int16Array: return extension_Int16;
        case Int32Array: return is64bit ? extension_Int64 : extension_Int32;
        case extension_BigInt64ArrayCtor: return extension_Int64;
        case Uint8Array: return extension_Uint8;
        case Uint16Array: return extension_Uint16;
        case Uint32Array: return is64bit ? extension_Uint64 : extension_Uint32;
        case extension_BigUint64ArrayCtor: return extension_Uint64;
        default: return null;
    }
};
/** @ignore */
const extension_int_vectorTypeToDataType = (ctor, is64bit) => {
    switch (ctor) {
        case extension_Int8Vector: return extension_Int8;
        case extension_Int16Vector: return extension_Int16;
        case extension_Int32Vector: return is64bit ? extension_Int64 : extension_Int32;
        case extension_Int64Vector: return extension_Int64;
        case extension_Uint8Vector: return extension_Uint8;
        case extension_Uint16Vector: return extension_Uint16;
        case extension_Uint32Vector: return is64bit ? extension_Uint64 : extension_Uint32;
        case extension_Uint64Vector: return extension_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 extension_ListVector extends extension_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 extension_MapVector extends extension_BaseVector {
    asList() {
        const child = this.type.children[0];
        return extension_AbstractVector.new(this.data.clone(new extension_List(child)));
    }
    bind(index) {
        const child = this.getChildAt(0);
        const { [index]: begin, [index + 1]: end } = this.valueOffsets;
        return new extension_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 extension_NullVector extends extension_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 extension_struct_kRowIndex = Symbol.for('rowIndex');
/** @ignore */
class extension_StructVector extends extension_BaseVector {
    bind(index) {
        const proto = this._row || (this._row = new extension_StructRow(this));
        const bound = Object.create(proto);
        bound[extension_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 extension_TimestampVector extends extension_BaseVector {
}
/** @ignore */
class extension_TimestampSecondVector extends extension_TimestampVector {
}
/** @ignore */
class extension_TimestampMillisecondVector extends extension_TimestampVector {
}
/** @ignore */
class extension_TimestampMicrosecondVector extends extension_TimestampVector {
}
/** @ignore */
class extension_TimestampNanosecondVector extends extension_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 extension_TimeVector extends extension_BaseVector {
}
/** @ignore */
class extension_TimeSecondVector extends extension_TimeVector {
}
/** @ignore */
class extension_TimeMillisecondVector extends extension_TimeVector {
}
/** @ignore */
class extension_TimeMicrosecondVector extends extension_TimeVector {
}
/** @ignore */
class extension_TimeNanosecondVector extends extension_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 extension_UnionVector extends extension_BaseVector {
    get typeIdToChildIndex() { return this.data.type.typeIdToChildIndex; }
}
/** @ignore */
class extension_DenseUnionVector extends extension_UnionVector {
    get valueOffsets() { return this.data.valueOffsets; }
}
/** @ignore */
class extension_SparseUnionVector extends extension_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 extension_Utf8Vector extends extension_BaseVector {
    /** @nocollapse */
    static from(input) {
        return extension_vectorFromValuesWithType(() => new extension_Utf8(), input);
    }
    asBinary() {
        return extension_AbstractVector.new(this.data.clone(new extension_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 extension_partial0(visit) {
    return function () { return visit(this); };
}
/** @ignore */
function extension_partial1(visit) {
    return function (a) { return visit(this, a); };
}
/** @ignore */
function extension_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 extension_GetVisitor extends extension_Visitor {
}
/** @ignore */ const extension_epochDaysToMs = (data, index) => 86400000 * data[index];
/** @ignore */ const extension_epochMillisecondsLongToMs = (data, index) => 4294967296 * (data[index + 1]) + (data[index] >>> 0);
/** @ignore */ const extension_epochMicrosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1000) + ((data[index] >>> 0) / 1000);
/** @ignore */ const extension_epochNanosecondsLongToMs = (data, index) => 4294967296 * (data[index + 1] / 1000000) + ((data[index] >>> 0) / 1000000);
/** @ignore */ const extension_epochMillisecondsToDate = (epochMs) => new Date(epochMs);
/** @ignore */ const extension_epochDaysToDate = (data, index) => extension_epochMillisecondsToDate(extension_epochDaysToMs(data, index));
/** @ignore */ const extension_epochMillisecondsLongToDate = (data, index) => extension_epochMillisecondsToDate(extension_epochMillisecondsLongToMs(data, index));
/** @ignore */
const extension_getNull = (_vector, _index) => null;
/** @ignore */
const extension_getVariableWidthBytes = (values, valueOffsets, index) => {
    const { [index]: x, [index + 1]: y } = valueOffsets;
    return x != null && y != null ? values.subarray(x, y) : null;
};
/** @ignore */
const extension_get_getBool = ({ offset, values }, index) => {
    const idx = offset + index;
    const byte = values[idx >> 3];
    return (byte & 1 << (idx % 8)) !== 0;
};
/** @ignore */
const extension_getDateDay = ({ values }, index) => extension_epochDaysToDate(values, index);
/** @ignore */
const extension_getDateMillisecond = ({ values }, index) => extension_epochMillisecondsLongToDate(values, index * 2);
/** @ignore */
const extension_getNumeric = ({ stride, values }, index) => values[stride * index];
/** @ignore */
const extension_getFloat16 = ({ stride, values }, index) => extension_uint16ToFloat64(values[stride * index]);
/** @ignore */
const extension_getBigInts = ({ stride, values, type }, index) => extension_BN.new(values.subarray(stride * index, stride * (index + 1)), type.isSigned);
/** @ignore */
const extension_getFixedSizeBinary = ({ stride, values }, index) => values.subarray(stride * index, stride * (index + 1));
/** @ignore */
const extension_getBinary = ({ values, valueOffsets }, index) => extension_getVariableWidthBytes(values, valueOffsets, index);
/** @ignore */
const extension_getUtf8 = ({ values, valueOffsets }, index) => {
    const bytes = extension_getVariableWidthBytes(values, valueOffsets, index);
    return bytes !== null ? extension_decodeUtf8(bytes) : null;
};
/* istanbul ignore next */
/** @ignore */
const extension_getInt = (vector, index) => (vector.type.bitWidth < 64
    ? extension_getNumeric(vector, index)
    : extension_getBigInts(vector, index));
/* istanbul ignore next */
/** @ignore */
const extension_getFloat = (vector, index) => (vector.type.precision !== extension_Precision.HALF
    ? extension_getNumeric(vector, index)
    : extension_getFloat16(vector, index));
/* istanbul ignore next */
/** @ignore */
const extension_getDate = (vector, index) => (vector.type.unit === extension_DateUnit.DAY
    ? extension_getDateDay(vector, index)
    : extension_getDateMillisecond(vector, index));
/** @ignore */
const extension_getTimestampSecond = ({ values }, index) => 1000 * extension_epochMillisecondsLongToMs(values, index * 2);
/** @ignore */
const extension_getTimestampMillisecond = ({ values }, index) => extension_epochMillisecondsLongToMs(values, index * 2);
/** @ignore */
const extension_getTimestampMicrosecond = ({ values }, index) => extension_epochMicrosecondsLongToMs(values, index * 2);
/** @ignore */
const extension_getTimestampNanosecond = ({ values }, index) => extension_epochNanosecondsLongToMs(values, index * 2);
/* istanbul ignore next */
/** @ignore */
const extension_getTimestamp = (vector, index) => {
    switch (vector.type.unit) {
        case extension_TimeUnit.SECOND: return extension_getTimestampSecond(vector, index);
        case extension_TimeUnit.MILLISECOND: return extension_getTimestampMillisecond(vector, index);
        case extension_TimeUnit.MICROSECOND: return extension_getTimestampMicrosecond(vector, index);
        case extension_TimeUnit.NANOSECOND: return extension_getTimestampNanosecond(vector, index);
    }
};
/** @ignore */
const extension_getTimeSecond = ({ values, stride }, index) => values[stride * index];
/** @ignore */
const extension_getTimeMillisecond = ({ values, stride }, index) => values[stride * index];
/** @ignore */
const extension_getTimeMicrosecond = ({ values }, index) => extension_BN.signed(values.subarray(2 * index, 2 * (index + 1)));
/** @ignore */
const extension_getTimeNanosecond = ({ values }, index) => extension_BN.signed(values.subarray(2 * index, 2 * (index + 1)));
/* istanbul ignore next */
/** @ignore */
const extension_getTime = (vector, index) => {
    switch (vector.type.unit) {
        case extension_TimeUnit.SECOND: return extension_getTimeSecond(vector, index);
        case extension_TimeUnit.MILLISECOND: return extension_getTimeMillisecond(vector, index);
        case extension_TimeUnit.MICROSECOND: return extension_getTimeMicrosecond(vector, index);
        case extension_TimeUnit.NANOSECOND: return extension_getTimeNanosecond(vector, index);
    }
};
/** @ignore */
const extension_getDecimal = ({ values }, index) => extension_BN.decimal(values.subarray(4 * index, 4 * (index + 1)));
/** @ignore */
const extension_getList = (vector, index) => {
    const child = vector.getChildAt(0), { valueOffsets, stride } = vector;
    return child.slice(valueOffsets[index * stride], valueOffsets[(index * stride) + 1]);
};
/** @ignore */
const extension_getMap = (vector, index) => {
    return vector.bind(index);
};
/** @ignore */
const extension_getStruct = (vector, index) => {
    return vector.bind(index);
};
/* istanbul ignore next */
/** @ignore */
const extension_getUnion = (vector, index) => {
    return vector.type.mode === extension_UnionMode.Dense ?
        extension_getDenseUnion(vector, index) :
        extension_getSparseUnion(vector, index);
};
/** @ignore */
const extension_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 extension_getSparseUnion = (vector, index) => {
    const childIndex = vector.typeIdToChildIndex[vector.typeIds[index]];
    const child = vector.getChildAt(childIndex);
    return child ? child.get(index) : null;
};
/** @ignore */
const extension_getDictionary = (vector, index) => {
    return vector.getValue(vector.getKey(index));
};
/* istanbul ignore next */
/** @ignore */
const extension_getInterval = (vector, index) => (vector.type.unit === extension_IntervalUnit.DAY_TIME)
    ? extension_getIntervalDayTime(vector, index)
    : extension_getIntervalYearMonth(vector, index);
/** @ignore */
const extension_getIntervalDayTime = ({ values }, index) => values.subarray(2 * index, 2 * (index + 1));
/** @ignore */
const extension_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 extension_getFixedSizeList = (vector, index) => {
    const child = vector.getChildAt(0), { stride } = vector;
    return child.slice(index * stride, (index + 1) * stride);
};
extension_GetVisitor.prototype.visitNull = extension_getNull;
extension_GetVisitor.prototype.visitBool = extension_get_getBool;
extension_GetVisitor.prototype.visitInt = extension_getInt;
extension_GetVisitor.prototype.visitInt8 = extension_getNumeric;
extension_GetVisitor.prototype.visitInt16 = extension_getNumeric;
extension_GetVisitor.prototype.visitInt32 = extension_getNumeric;
extension_GetVisitor.prototype.visitInt64 = extension_getBigInts;
extension_GetVisitor.prototype.visitUint8 = extension_getNumeric;
extension_GetVisitor.prototype.visitUint16 = extension_getNumeric;
extension_GetVisitor.prototype.visitUint32 = extension_getNumeric;
extension_GetVisitor.prototype.visitUint64 = extension_getBigInts;
extension_GetVisitor.prototype.visitFloat = extension_getFloat;
extension_GetVisitor.prototype.visitFloat16 = extension_getFloat16;
extension_GetVisitor.prototype.visitFloat32 = extension_getNumeric;
extension_GetVisitor.prototype.visitFloat64 = extension_getNumeric;
extension_GetVisitor.prototype.visitUtf8 = extension_getUtf8;
extension_GetVisitor.prototype.visitBinary = extension_getBinary;
extension_GetVisitor.prototype.visitFixedSizeBinary = extension_getFixedSizeBinary;
extension_GetVisitor.prototype.visitDate = extension_getDate;
extension_GetVisitor.prototype.visitDateDay = extension_getDateDay;
extension_GetVisitor.prototype.visitDateMillisecond = extension_getDateMillisecond;
extension_GetVisitor.prototype.visitTimestamp = extension_getTimestamp;
extension_GetVisitor.prototype.visitTimestampSecond = extension_getTimestampSecond;
extension_GetVisitor.prototype.visitTimestampMillisecond = extension_getTimestampMillisecond;
extension_GetVisitor.prototype.visitTimestampMicrosecond = extension_getTimestampMicrosecond;
extension_GetVisitor.prototype.visitTimestampNanosecond = extension_getTimestampNanosecond;
extension_GetVisitor.prototype.visitTime = extension_getTime;
extension_GetVisitor.prototype.visitTimeSecond = extension_getTimeSecond;
extension_GetVisitor.prototype.visitTimeMillisecond = extension_getTimeMillisecond;
extension_GetVisitor.prototype.visitTimeMicrosecond = extension_getTimeMicrosecond;
extension_GetVisitor.prototype.visitTimeNanosecond = extension_getTimeNanosecond;
extension_GetVisitor.prototype.visitDecimal = extension_getDecimal;
extension_GetVisitor.prototype.visitList = extension_getList;
extension_GetVisitor.prototype.visitStruct = extension_getStruct;
extension_GetVisitor.prototype.visitUnion = extension_getUnion;
extension_GetVisitor.prototype.visitDenseUnion = extension_getDenseUnion;
extension_GetVisitor.prototype.visitSparseUnion = extension_getSparseUnion;
extension_GetVisitor.prototype.visitDictionary = extension_getDictionary;
extension_GetVisitor.prototype.visitInterval = extension_getInterval;
extension_GetVisitor.prototype.visitIntervalDayTime = extension_getIntervalDayTime;
extension_GetVisitor.prototype.visitIntervalYearMonth = extension_getIntervalYearMonth;
extension_GetVisitor.prototype.visitFixedSizeList = extension_getFixedSizeList;
extension_GetVisitor.prototype.visitMap = extension_getMap;
/** @ignore */
const extension_get_instance = new extension_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 extension_IndexOfVisitor extends extension_Visitor {
}
/** @ignore */
function extension_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 extension_indexOfNull(vector, fromIndex) {
    const { nullBitmap } = vector.data;
    if (!nullBitmap || vector.nullCount <= 0) {
        return -1;
    }
    let i = 0;
    for (const isValid of extension_iterateBits(nullBitmap, vector.data.offset + (fromIndex || 0), vector.length, nullBitmap, extension_getBool)) {
        if (!isValid) {
            return i;
        }
        ++i;
    }
    return -1;
}
/** @ignore */
function extension_indexOfValue(vector, searchElement, fromIndex) {
    if (searchElement === undefined) {
        return -1;
    }
    if (searchElement === null) {
        return extension_indexOfNull(vector, fromIndex);
    }
    const compare = extension_createElementComparator(searchElement);
    for (let i = (fromIndex || 0) - 1, n = vector.length; ++i < n;) {
        if (compare(vector.get(i))) {
            return i;
        }
    }
    return -1;
}
/** @ignore */
function extension_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 = extension_createElementComparator(searchElement);
    for (let i = (fromIndex || 0) - 1, n = vector.length; ++i < n;) {
        if (compare(vector.get(i))) {
            return i;
        }
    }
    return -1;
}
extension_IndexOfVisitor.prototype.visitNull = extension_nullIndexOf;
extension_IndexOfVisitor.prototype.visitBool = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitInt = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitInt8 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitInt16 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitInt32 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitInt64 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitUint8 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitUint16 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitUint32 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitUint64 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitFloat = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitFloat16 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitFloat32 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitFloat64 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitUtf8 = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitBinary = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitFixedSizeBinary = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitDate = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitDateDay = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitDateMillisecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimestamp = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimestampSecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimestampMillisecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimestampMicrosecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimestampNanosecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTime = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimeSecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimeMillisecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimeMicrosecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitTimeNanosecond = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitDecimal = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitList = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitStruct = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitUnion = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitDenseUnion = extension_indexOfUnion;
extension_IndexOfVisitor.prototype.visitSparseUnion = extension_indexOfUnion;
extension_IndexOfVisitor.prototype.visitDictionary = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitInterval = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitIntervalDayTime = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitIntervalYearMonth = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitFixedSizeList = extension_indexOfValue;
extension_IndexOfVisitor.prototype.visitMap = extension_indexOfValue;
/** @ignore */
const extension_indexof_instance = new extension_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 extension_IteratorVisitor extends extension_Visitor {
}
/** @ignore */
function extension_nullableIterator(vector) {
    const getFn = extension_get_instance.getVisitFn(vector);
    return extension_iterateBits(vector.data.nullBitmap, vector.data.offset, vector.length, vector, (vec, idx, nullByte, nullBit) => ((nullByte & 1 << nullBit) !== 0) ? getFn(vec, idx) : null);
}
/** @ignore */
function extension_vectorIterator(vector) {
    // If nullable, iterate manually
    if (vector.nullCount > 0) {
        return extension_nullableIterator(vector);
    }
    const { type, typeId, length } = vector;
    // Fast case, defer to native iterators if possible
    if (vector.stride === 1 && ((typeId === extension_Type.Timestamp) ||
        (typeId === extension_Type.Int && type.bitWidth !== 64) ||
        (typeId === extension_Type.Time && type.bitWidth !== 64) ||
        (typeId === extension_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);
        }
    })(extension_get_instance.getVisitFn(vector));
}
extension_IteratorVisitor.prototype.visitNull = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitBool = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitInt = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitInt8 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitInt16 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitInt32 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitInt64 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitUint8 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitUint16 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitUint32 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitUint64 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitFloat = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitFloat16 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitFloat32 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitFloat64 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitUtf8 = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitBinary = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitFixedSizeBinary = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitDate = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitDateDay = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitDateMillisecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimestamp = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimestampSecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimestampMillisecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimestampMicrosecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimestampNanosecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTime = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimeSecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimeMillisecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimeMicrosecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitTimeNanosecond = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitDecimal = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitList = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitStruct = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitUnion = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitDenseUnion = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitSparseUnion = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitDictionary = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitInterval = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitIntervalDayTime = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitIntervalYearMonth = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitFixedSizeList = extension_vectorIterator;
extension_IteratorVisitor.prototype.visitMap = extension_vectorIterator;
/** @ignore */
const extension_iterator_instance = new extension_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 extension_ToArrayVisitor extends extension_Visitor {
}
/** @ignore */
function extension_arrayOfVector(vector) {
    const { type, length, stride } = vector;
    // Fast case, return subarray if possible
    switch (type.typeId) {
        case extension_Type.Int:
        case extension_Type.Float:
        case extension_Type.Decimal:
        case extension_Type.Time:
        case extension_Type.Timestamp:
            return vector.data.values.subarray(0, length * stride);
    }
    // Otherwise if not primitive, slow copy
    return [...extension_iterator_instance.visit(vector)];
}
extension_ToArrayVisitor.prototype.visitNull = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitBool = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitInt = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitInt8 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitInt16 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitInt32 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitInt64 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitUint8 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitUint16 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitUint32 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitUint64 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitFloat = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitFloat16 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitFloat32 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitFloat64 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitUtf8 = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitBinary = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitFixedSizeBinary = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitDate = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitDateDay = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitDateMillisecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimestamp = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimestampSecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimestampMillisecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimestampMicrosecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimestampNanosecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTime = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimeSecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimeMillisecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimeMicrosecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitTimeNanosecond = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitDecimal = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitList = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitStruct = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitUnion = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitDenseUnion = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitSparseUnion = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitDictionary = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitInterval = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitIntervalDayTime = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitIntervalYearMonth = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitFixedSizeList = extension_arrayOfVector;
extension_ToArrayVisitor.prototype.visitMap = extension_arrayOfVector;
/** @ignore */
const extension_toarray_instance = new extension_ToArrayVisitor();

//# sourceMappingURL=toarray.mjs.map

;// ../../node_modules/apache-arrow/visitor/bytewidth.mjs
/* istanbul ignore file */


/** @ignore */ const extension_sum = (x, y) => x + y;
/** @ignore */ const extension_variableWidthColumnErrorMessage = (type) => `Cannot compute the byte width of variable-width column ${type}`;
/** @ignore */
class extension_ByteWidthVisitor extends extension_Visitor {
    visitNull(____) { return 0; }
    visitInt(type) { return type.bitWidth / 8; }
    visitFloat(type) { return type.ArrayType.BYTES_PER_ELEMENT; }
    visitBinary(type) { throw new Error(extension_variableWidthColumnErrorMessage(type)); }
    visitUtf8(type) { throw new Error(extension_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 === extension_TimeUnit.SECOND ? 4 : 8; }
    visitInterval(type) { return (type.unit + 1) * 4; }
    visitList(type) { throw new Error(extension_variableWidthColumnErrorMessage(type)); }
    visitStruct(type) { return this.visitFields(type.children).reduce(extension_sum, 0); }
    visitUnion(type) { return this.visitFields(type.children).reduce(extension_sum, 0); }
    visitFixedSizeBinary(type) { return type.byteWidth; }
    visitFixedSizeList(type) { return type.listSize * this.visitFields(type.children).reduce(extension_sum, 0); }
    visitMap(type) { return this.visitFields(type.children).reduce(extension_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(extension_sum, 0); }
}
/** @ignore */
const extension_bytewidth_instance = new extension_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 extension_GetVectorConstructor extends extension_Visitor {
    visitNull() { return extension_NullVector; }
    visitBool() { return extension_BoolVector; }
    visitInt() { return extension_IntVector; }
    visitInt8() { return extension_Int8Vector; }
    visitInt16() { return extension_Int16Vector; }
    visitInt32() { return extension_Int32Vector; }
    visitInt64() { return extension_Int64Vector; }
    visitUint8() { return extension_Uint8Vector; }
    visitUint16() { return extension_Uint16Vector; }
    visitUint32() { return extension_Uint32Vector; }
    visitUint64() { return extension_Uint64Vector; }
    visitFloat() { return extension_FloatVector; }
    visitFloat16() { return extension_Float16Vector; }
    visitFloat32() { return extension_Float32Vector; }
    visitFloat64() { return extension_Float64Vector; }
    visitUtf8() { return extension_Utf8Vector; }
    visitBinary() { return extension_BinaryVector; }
    visitFixedSizeBinary() { return extension_FixedSizeBinaryVector; }
    visitDate() { return extension_DateVector; }
    visitDateDay() { return extension_DateDayVector; }
    visitDateMillisecond() { return extension_DateMillisecondVector; }
    visitTimestamp() { return extension_TimestampVector; }
    visitTimestampSecond() { return extension_TimestampSecondVector; }
    visitTimestampMillisecond() { return extension_TimestampMillisecondVector; }
    visitTimestampMicrosecond() { return extension_TimestampMicrosecondVector; }
    visitTimestampNanosecond() { return extension_TimestampNanosecondVector; }
    visitTime() { return extension_TimeVector; }
    visitTimeSecond() { return extension_TimeSecondVector; }
    visitTimeMillisecond() { return extension_TimeMillisecondVector; }
    visitTimeMicrosecond() { return extension_TimeMicrosecondVector; }
    visitTimeNanosecond() { return extension_TimeNanosecondVector; }
    visitDecimal() { return extension_DecimalVector; }
    visitList() { return extension_ListVector; }
    visitStruct() { return extension_StructVector; }
    visitUnion() { return extension_UnionVector; }
    visitDenseUnion() { return extension_DenseUnionVector; }
    visitSparseUnion() { return extension_SparseUnionVector; }
    visitDictionary() { return extension_DictionaryVector; }
    visitInterval() { return extension_IntervalVector; }
    visitIntervalDayTime() { return extension_IntervalDayTimeVector; }
    visitIntervalYearMonth() { return extension_IntervalYearMonthVector; }
    visitFixedSizeList() { return extension_FixedSizeListVector; }
    visitMap() { return extension_MapVector; }
}
/** @ignore */
const extension_vectorctor_instance = new extension_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 */
extension_AbstractVector.new = extension_newVector;
/** @nocollapse */
extension_AbstractVector.from = extension_vectorFrom;
/** @ignore */
function extension_newVector(data, ...args) {
    return new (extension_vectorctor_instance.getVisitFn(data)())(data, ...args);
}
/** @ignore */
function extension_vectorFromValuesWithType(newDataType, input) {
    if (extension_isIterable(input)) {
        return extension_AbstractVector.from({ 'nullValues': [null, undefined], type: newDataType(), 'values': input });
    }
    else if (extension_isAsyncIterable(input)) {
        return extension_AbstractVector.from({ 'nullValues': [null, undefined], type: newDataType(), 'values': input });
    }
    const { 'values': values = [], 'type': type = newDataType(), 'nullValues': nullValues = [null, undefined], } = { ...input };
    return extension_isIterable(values)
        ? extension_AbstractVector.from({ nullValues, ...input, type })
        : extension_AbstractVector.from({ nullValues, ...input, type });
}
function extension_vectorFrom(input) {
    const { 'values': values = [], ...options } = { 'nullValues': [null, undefined], ...input };
    if (extension_isIterable(values)) {
        const chunks = [...extension_Builder.throughIterable(options)(values)];
        return (chunks.length === 1 ? chunks[0] : extension_Chunked.concat(chunks));
    }
    return (async (chunks) => {
        const transform = extension_Builder.throughAsyncIterable(options);
        for await (const chunk of transform(values)) {
            chunks.push(chunk);
        }
        return (chunks.length === 1 ? chunks[0] : extension_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!
//
extension_BaseVector.prototype.get = function baseVectorGet(index) {
    return extension_get_instance.visit(this, index);
};
extension_BaseVector.prototype.set = function baseVectorSet(index, value) {
    return extension_set_instance.visit(this, index, value);
};
extension_BaseVector.prototype.indexOf = function baseVectorIndexOf(value, fromIndex) {
    return extension_indexof_instance.visit(this, value, fromIndex);
};
extension_BaseVector.prototype.toArray = function baseVectorToArray() {
    return extension_toarray_instance.visit(this);
};
extension_BaseVector.prototype.getByteWidth = function baseVectorGetByteWidth() {
    return extension_bytewidth_instance.visit(this.type);
};
extension_BaseVector.prototype[Symbol.iterator] = function baseVectorSymbolIterator() {
    return extension_iterator_instance.visit(this);
};
extension_BaseVector.prototype._bindDataAccessors = extension_bindBaseVectorDataAccessors;
// Perf: bind and assign the operator Visitor methods to each of the Vector subclasses for each Type
Object.keys(extension_Type)
    .map((T) => extension_Type[T])
    .filter((T) => typeof T === 'number')
    .filter((typeId) => typeId !== extension_Type.NONE)
    .forEach((typeId) => {
    const VectorCtor = extension_vectorctor_instance.visit(typeId);
    VectorCtor.prototype['get'] = extension_partial1(extension_get_instance.getVisitFn(typeId));
    VectorCtor.prototype['set'] = extension_partial2(extension_set_instance.getVisitFn(typeId));
    VectorCtor.prototype['indexOf'] = extension_partial2(extension_indexof_instance.getVisitFn(typeId));
    VectorCtor.prototype['toArray'] = extension_partial0(extension_toarray_instance.getVisitFn(typeId));
    VectorCtor.prototype['getByteWidth'] = extension_partialType0(extension_bytewidth_instance.getVisitFn(typeId));
    VectorCtor.prototype[Symbol.iterator] = extension_partial0(extension_iterator_instance.getVisitFn(typeId));
});
/** @ignore */
function extension_partialType0(visit) {
    return function () { return visit(this.type); };
}
/** @ignore */
function extension_wrapNullableGet(fn) {
    return function (i) { return this.isValid(i) ? fn.call(this, i) : null; };
}
/** @ignore */
function extension_wrapNullableSet(fn) {
    return function (i, a) {
        if (extension_setBool(this.nullBitmap, this.offset + i, !(a === null || a === undefined))) {
            fn.call(this, i, a);
        }
    };
}
/** @ignore */
function extension_bindBaseVectorDataAccessors() {
    const nullBitmap = this.nullBitmap;
    if (nullBitmap && nullBitmap.byteLength > 0) {
        this.get = extension_wrapNullableGet(this.get);
        this.set = extension_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 extension_table_Table extends extension_Chunked {
    constructor(...args) {
        let schema = null;
        if (args[0] instanceof extension_Schema) {
            schema = args.shift();
        }
        let chunks = extension_selectArgs(extension_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 extension_InternalEmptyPlaceholderRecordBatch(schema));
        super(new extension_Struct(schema.fields), chunks);
        this._schema = schema;
        this._chunks = chunks;
    }
    /** @nocollapse */
    static empty(schema = new extension_Schema([])) { return new extension_table_Table(schema, []); }
    /** @nocollapse */
    static from(input) {
        if (!input) {
            return extension_table_Table.empty();
        }
        if (typeof input === 'object') {
            let table = extension_isIterable(input['values']) ? extension_tableFromIterable(input)
                : extension_isAsyncIterable(input['values']) ? extension_tableFromAsyncIterable(input)
                    : null;
            if (table !== null) {
                return table;
            }
        }
        let reader = extension_RecordBatchReader.from(input);
        if (extension_isPromise(reader)) {
            return (async () => await extension_table_Table.from(await reader))();
        }
        if (reader.isSync() && (reader = reader.open())) {
            return !reader.schema ? extension_table_Table.empty() : new extension_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 extension_table_Table(schema, batches);
            }
            return extension_table_Table.empty();
        })(reader.open());
    }
    /** @nocollapse */
    static async fromAsync(source) {
        return await extension_table_Table.from(source);
    }
    /** @nocollapse */
    static fromStruct(vector) {
        return extension_table_Table.new(vector.data.childData, vector.type.children);
    }
    /** @nocollapse */
    static new(...cols) {
        return new extension_table_Table(...extension_distributeColumnsIntoRecordBatches(extension_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 extension_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 extension_column_Column(field, chunks));
            }
        }
        return null;
    }
    // @ts-ignore
    serialize(encoding = 'binary', stream = true) {
        const Writer = !stream
            ? extension_RecordBatchFileWriter
            : extension_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 extension_table_Table(schema, this._chunks.map(({ length, data: { childData } }) => {
            return new extension_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 extension_table_Table(...extension_distributeVectorsIntoRecordBatches(schema, columns));
    }
}
function extension_tableFromIterable(input) {
    const { type } = input;
    if (type instanceof extension_Struct) {
        return extension_table_Table.fromStruct(extension_StructVector.from(input));
    }
    return null;
}
function extension_tableFromAsyncIterable(input) {
    const { type } = input;
    if (type instanceof extension_Struct) {
        return extension_StructVector.from(input).then((vector) => extension_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 extension_recordbatch_RecordBatch extends extension_StructVector {
    constructor(...args) {
        let data;
        let schema = args[0];
        let children;
        if (args[1] instanceof extension_Data) {
            [, data, children] = args;
        }
        else {
            const fields = schema.fields;
            const [, length, childData] = args;
            data = extension_Data.Struct(new extension_Struct(fields), 0, length, 0, null, childData);
        }
        super(data, children);
        this._schema = schema;
    }
    /** @nocollapse */
    static from(options) {
        if (extension_isIterable(options['values'])) {
            return extension_table_Table.from(options);
        }
        return extension_table_Table.from(options);
    }
    /** @nocollapse */
    static new(...args) {
        const [fs, xs] = extension_selectFieldArgs(args);
        const vs = xs.filter((x) => x instanceof extension_AbstractVector);
        return new extension_recordbatch_RecordBatch(...extension_ensureSameLengthData(new extension_Schema(fs), vs.map((x) => x.data)));
    }
    clone(data, children = this._children) {
        return new extension_recordbatch_RecordBatch(this._schema, data, children);
    }
    concat(...others) {
        const schema = this._schema, chunks = extension_Chunked.flatten(this, ...others);
        return new extension_table_Table(schema, chunks.map(({ data }) => new extension_recordbatch_RecordBatch(schema, data)));
    }
    get schema() { return this._schema; }
    get numCols() { return this._schema.fields.length; }
    get dictionaries() {
        return this._dictionaries || (this._dictionaries = extension_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 extension_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 extension_InternalEmptyPlaceholderRecordBatch extends extension_recordbatch_RecordBatch {
    constructor(schema) {
        super(schema, 0, schema.fields.map((f) => extension_Data.new(f.type, 0, 0, 0)));
    }
}
/** @ignore */
class extension_DictionaryCollector extends extension_Visitor {
    constructor() {
        super(...arguments);
        this.dictionaries = new Map();
    }
    static collect(batch) {
        return new extension_DictionaryCollector().visit(batch.data, new extension_Struct(batch.schema.fields)).dictionaries;
    }
    visit(data, type) {
        if (extension_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 extension_RecordBatchReader extends extension_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 extension_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 extension_adapters.toDOMStream((this.isSync()
            ? { [Symbol.iterator]: () => this }
            : { [Symbol.asyncIterator]: () => this }));
    }
    toNodeStream() {
        return extension_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 extension_RecordBatchReader) {
            return source;
        }
        else if (extension_isArrowJSON(source)) {
            return extension_fromArrowJSON(source);
        }
        else if (extension_isFileHandle(source)) {
            return extension_fromFileHandle(source);
        }
        else if (extension_isPromise(source)) {
            return (async () => await extension_RecordBatchReader.from(await source))();
        }
        else if (extension_isFetchResponse(source) || extension_isReadableDOMStream(source) || extension_isReadableNodeStream(source) || extension_isAsyncIterable(source)) {
            return extension_fromAsyncByteStream(new extension_AsyncByteStream(source));
        }
        return extension_fromByteStream(new extension_ByteStream(source));
    }
    /** @nocollapse */
    static readAll(source) {
        if (source instanceof extension_RecordBatchReader) {
            return source.isSync() ? extension_readAllSync(source) : extension_readAllAsync(source);
        }
        else if (extension_isArrowJSON(source) || ArrayBuffer.isView(source) || extension_isIterable(source) || extension_isIteratorResult(source)) {
            return extension_readAllSync(source);
        }
        return extension_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 extension_RecordBatchStreamReader extends extension_RecordBatchReader {
    constructor(_impl) {
        super(_impl);
        this._impl = _impl;
    }
    [Symbol.iterator]() { return this._impl[Symbol.iterator](); }
    async *[Symbol.asyncIterator]() { yield* this[Symbol.iterator](); }
}
/** @ignore */
class extension_AsyncRecordBatchStreamReader extends extension_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 extension_RecordBatchFileReader extends extension_RecordBatchStreamReader {
    constructor(_impl) {
        super(_impl);
        this._impl = _impl;
    }
}
/** @ignore */
class extension_AsyncRecordBatchFileReader extends extension_AsyncRecordBatchStreamReader {
    constructor(_impl) {
        super(_impl);
        this._impl = _impl;
    }
}
/** @ignore */
class extension_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 extension_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(extension_AbstractVector.new(this._loadVectors(data, body, [type])[0])) :
                extension_AbstractVector.new(this._loadVectors(data, body, [type])[0]));
        }
        return dictionary;
    }
    _loadVectors(header, body, types) {
        return new extension_VectorLoader(body, header.nodes, header.buffers, this.dictionaries).visitMany(types);
    }
}
/** @ignore */
class extension_RecordBatchStreamReaderImpl extends extension_RecordBatchReaderImpl {
    constructor(source, dictionaries) {
        super(dictionaries);
        this._reader = !extension_isArrowJSON(source)
            ? new extension_MessageReader(this._handle = source)
            : new extension_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 = extension_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 extension_ITERATOR_DONE;
    }
    return(value) {
        if (!this.closed && this.autoDestroy && (this.closed = true)) {
            return this.reset()._reader.return(value);
        }
        return extension_ITERATOR_DONE;
    }
    next() {
        if (this.closed) {
            return extension_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 extension_InternalEmptyPlaceholderRecordBatch(this.schema) };
        }
        return this.return();
    }
    _readNextMessageAndValidate(type) {
        return this._reader.readMessage(type);
    }
}
/** @ignore */
class extension_AsyncRecordBatchStreamReaderImpl extends extension_RecordBatchReaderImpl {
    constructor(source, dictionaries) {
        super(dictionaries);
        this._reader = new extension_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 = extension_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 extension_ITERATOR_DONE;
    }
    async return(value) {
        if (!this.closed && this.autoDestroy && (this.closed = true)) {
            return await this.reset()._reader.return(value);
        }
        return extension_ITERATOR_DONE;
    }
    async next() {
        if (this.closed) {
            return extension_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 extension_InternalEmptyPlaceholderRecordBatch(this.schema) };
        }
        return await this.return();
    }
    async _readNextMessageAndValidate(type) {
        return await this._reader.readMessage(type);
    }
}
/** @ignore */
class extension_RecordBatchFileReaderImpl extends extension_RecordBatchStreamReaderImpl {
    constructor(source, dictionaries) {
        super(source instanceof extension_RandomAccessFile ? source : new extension_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(extension_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(extension_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 - extension_magicAndPadding;
        const length = _handle.readInt32(offset);
        const buffer = _handle.readAt(offset - length, length);
        return extension_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 extension_AsyncRecordBatchFileReaderImpl extends extension_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 extension_AsyncRandomAccessFile ? source : new extension_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(extension_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(extension_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 - extension_magicAndPadding;
        const length = await _handle.readInt32(offset);
        const buffer = await _handle.readAt(offset - length, length);
        return extension_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 extension_RecordBatchJSONReaderImpl extends extension_RecordBatchStreamReaderImpl {
    constructor(source, dictionaries) {
        super(source, dictionaries);
    }
    _loadVectors(header, body, types) {
        return new extension_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 extension_shouldAutoDestroy(self, options) {
    return options && (typeof options['autoDestroy'] === 'boolean') ? options['autoDestroy'] : self['autoDestroy'];
}
/** @ignore */
function* extension_readAllSync(source) {
    const reader = extension_RecordBatchReader.from(source);
    try {
        if (!reader.open({ autoDestroy: false }).closed) {
            do {
                yield reader;
            } while (!(reader.reset().open()).closed);
        }
    }
    finally {
        reader.cancel();
    }
}
/** @ignore */
async function* extension_readAllAsync(source) {
    const reader = await extension_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 extension_fromArrowJSON(source) {
    return new extension_RecordBatchStreamReader(new extension_RecordBatchJSONReaderImpl(source));
}
/** @ignore */
function extension_fromByteStream(source) {
    const bytes = source.peek((extension_magicLength + 7) & ~7);
    return bytes && bytes.byteLength >= 4 ? !extension_checkForMagicArrowString(bytes)
        ? new extension_RecordBatchStreamReader(new extension_RecordBatchStreamReaderImpl(source))
        : new extension_RecordBatchFileReader(new extension_RecordBatchFileReaderImpl(source.read()))
        : new extension_RecordBatchStreamReader(new extension_RecordBatchStreamReaderImpl(function* () { }()));
}
/** @ignore */
async function extension_fromAsyncByteStream(source) {
    const bytes = await source.peek((extension_magicLength + 7) & ~7);
    return bytes && bytes.byteLength >= 4 ? !extension_checkForMagicArrowString(bytes)
        ? new extension_AsyncRecordBatchStreamReader(new extension_AsyncRecordBatchStreamReaderImpl(source))
        : new extension_RecordBatchFileReader(new extension_RecordBatchFileReaderImpl(await source.read()))
        : new extension_AsyncRecordBatchStreamReader(new extension_AsyncRecordBatchStreamReaderImpl(async function* () { }()));
}
/** @ignore */
async function extension_fromFileHandle(source) {
    const { size } = await source.stat();
    const file = new extension_AsyncRandomAccessFile(source, size);
    if (size >= extension_magicX2AndPadding) {
        if (extension_checkForMagicArrowString(await file.readAt(0, (extension_magicLength + 7) & ~7))) {
            return new extension_AsyncRecordBatchFileReader(new extension_AsyncRecordBatchFileReaderImpl(file));
        }
    }
    return new extension_AsyncRecordBatchStreamReader(new extension_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 extension_toDOMStream(source, options) {
    if (extension_isAsyncIterable(source)) {
        return extension_asyncIterableAsReadableDOMStream(source, options);
    }
    if (extension_isIterable(source)) {
        return extension_iterableAsReadableDOMStream(source, options);
    }
    /* istanbul ignore next */
    throw new Error(`toDOMStream() must be called with an Iterable or AsyncIterable`);
}
/** @ignore */
function extension_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 = extension_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 extension_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 = extension_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 extension_builderThroughDOMStream(options) {
    return new extension_BuilderTransform(options);
}
/** @ignore */
class extension_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 = extension_Builder.new(builderOptions);
        this._getSize = queueingStrategy !== 'bytes' ? extension_chunkLength : extension_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' ? extension_chunkLength : extension_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 extension_chunkLength = (chunk) => chunk.length;
/** @ignore */ const extension_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 extension_recordBatchReaderThroughDOMStream(writableStrategy, readableStrategy) {
    const queue = new extension_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 extension_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 extension_recordBatchWriterThroughDOMStream(writableStrategy, readableStrategy) {
    const writer = new this(writableStrategy);
    const reader = new extension_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 extension_Value {
    eq(other) {
        if (!(other instanceof extension_Value)) {
            other = new extension_predicate_Literal(other);
        }
        return new extension_Equals(this, other);
    }
    le(other) {
        if (!(other instanceof extension_Value)) {
            other = new extension_predicate_Literal(other);
        }
        return new extension_LTeq(this, other);
    }
    ge(other) {
        if (!(other instanceof extension_Value)) {
            other = new extension_predicate_Literal(other);
        }
        return new extension_GTeq(this, other);
    }
    lt(other) {
        return new extension_Not(this.ge(other));
    }
    gt(other) {
        return new extension_Not(this.le(other));
    }
    ne(other) {
        return new extension_Not(this.eq(other));
    }
}
/** @ignore */
class extension_predicate_Literal extends extension_Value {
    constructor(v) {
        super();
        this.v = v;
    }
}
/** @ignore */
class extension_Col extends extension_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 extension_Predicate {
    and(...expr) { return new extension_And(this, ...expr); }
    or(...expr) { return new extension_Or(this, ...expr); }
    not() { return new extension_Not(this); }
}
/** @ignore */
class extension_ComparisonPredicate extends extension_Predicate {
    constructor(left, right) {
        super();
        this.left = left;
        this.right = right;
    }
    bind(batch) {
        if (this.left instanceof extension_predicate_Literal) {
            if (this.right instanceof extension_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 extension_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 extension_CombinationPredicate extends extension_Predicate {
    constructor(...children) {
        super();
        this.children = children;
    }
}
// add children to prototype so it doesn't get mangled in es2015/umd
extension_CombinationPredicate.prototype.children = Object.freeze([]); // freeze for safety
/** @ignore */
class extension_And extends extension_CombinationPredicate {
    constructor(...children) {
        // Flatten any Ands
        children = children.reduce((accum, p) => {
            return accum.concat(p instanceof extension_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 extension_Or extends extension_CombinationPredicate {
    constructor(...children) {
        // Flatten any Ors
        children = children.reduce((accum, p) => {
            return accum.concat(p instanceof extension_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 extension_Equals extends extension_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 extension_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 extension_LTeq extends extension_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 extension_GTeq extends extension_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 extension_Not extends extension_Predicate {
    constructor(child) {
        super();
        this.child = child;
    }
    bind(batch) {
        const func = this.child.bind(batch);
        return (idx, batch) => !func(idx, batch);
    }
}
/** @ignore */
class extension_CustomPredicate extends extension_Predicate {
    constructor(next, bind_) {
        super();
        this.next = next;
        this.bind_ = bind_;
    }
    bind(batch) {
        this.bind_(batch);
        return this.next;
    }
}
function extension_lit(v) { return new extension_predicate_Literal(v); }
function extension_col(n) { return new extension_Col(n); }
function extension_and(...p) { return new extension_And(...p); }
function extension_or(...p) { return new extension_Or(...p); }
function extension_custom(next, bind) {
    return new extension_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.






extension_table_Table.prototype.countBy = function (name) { return new extension_DataFrame(this.chunks).countBy(name); };
extension_table_Table.prototype.scan = function (next, bind) { return new extension_DataFrame(this.chunks).scan(next, bind); };
extension_table_Table.prototype.scanReverse = function (next, bind) { return new extension_DataFrame(this.chunks).scanReverse(next, bind); };
extension_table_Table.prototype.filter = function (predicate) { return new extension_DataFrame(this.chunks).filter(predicate); };
class extension_DataFrame extends extension_table_Table {
    filter(predicate) {
        return new extension_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 extension_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 (!extension_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 extension_CountByResult(vector.dictionary, extension_IntVector.from(counts));
    }
}
/** @ignore */
class extension_CountByResult extends extension_table_Table {
    constructor(values, counts) {
        const schema = new extension_Schema([
            new extension_Field('values', values.type),
            new extension_Field('counts', counts.type)
        ]);
        super(new extension_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 extension_FilteredDataFrame extends extension_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 extension_FilteredDataFrame(this._chunks, this._predicate.and(predicate));
    }
    countBy(name) {
        const batches = this._chunks, numBatches = batches.length;
        const count_by = typeof name === 'string' ? new extension_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 (!extension_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 extension_CountByResult(vector.dictionary, extension_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 extension_util = {
    ...extension_bn_namespaceObject,
    ...extension_util_int_namespaceObject,
    ...extension_bit_namespaceObject,
    ...extension_util_math_namespaceObject,
    ...extension_buffer_namespaceObject,
    ...extension_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.








extension_adapters.toDOMStream = extension_toDOMStream;
extension_Builder['throughDOM'] = extension_builderThroughDOMStream;
extension_RecordBatchReader['throughDOM'] = extension_recordBatchReaderThroughDOMStream;
extension_RecordBatchWriter['throughDOM'] = extension_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 extension_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 extension_ceil64Bytes(length, bpe = 1) {
  return ((((length * bpe) + 63) & ~63) || 64) / bpe;
}

function extension_util_array(Type, length, bpe = Type.BYTES_PER_ELEMENT) {
  return new Type(extension_ceil64Bytes(length, bpe));
}

function extension_arrowData(d) {
  return d instanceof extension_Data
    ? d
    : extension_Data.new(d.type, 0, d.length, d.nulls, d.buffers, null, d.dict);
}

function extension_arrowVector(data) {
  return extension_AbstractVector.new(extension_arrowData(data));
}

const extension_encoder = new TextEncoder();

function extension_encode(data, idx, str) {
  const bytes = extension_encoder.encode(str);
  data.set(bytes, idx);
  return bytes.length;
}

function extension_encodeInto(data, idx, str) {
  return extension_encoder.encodeInto(str, data.subarray(idx)).written;
}

const extension_writeUtf8 = extension_encoder.encodeInto ? extension_encodeInto : extension_encode;
;// ../../node_modules/arquero/src/arrow/builder/array-builder.js


/* harmony default export */ function extension_array_builder(type, length) {
  const data = extension_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 extension_bool_builder(type, length) {
  const data = extension_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 extension_date_day_builder(type, length) {
  const data = extension_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 extension_date_millis_builder(type, length) {
  const data = extension_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 extension_default_builder(type) {
  const b = extension_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 extension_utf8_builder(type, length, strlen) {
  const offset = extension_util_array(Int32Array, length + 1);
  const buf = extension_util_array(Uint8Array, 3 * strlen);

  let idx = 0;

  return {
    set(value, index) {
      idx += extension_writeUtf8(buf, idx, value);
      offset[index + 1] = idx;
    },
    data: () => {
      // slice utf buffer if over-allocated
      const dlen = extension_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 extension_dictionary_builder(type, length) {
  const values = [];
  const data = extension_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: extension_dictionary(type.dictionary, values, strlen)
    })
  };
}

function extension_dictionary(type, values, strlen) {
  const b = extension_utf8_builder(type, values.length, strlen);
  values.forEach(b.set);
  return extension_arrowVector(b.data());
}
;// ../../node_modules/arquero/src/arrow/builder/valid-builder.js


/* harmony default export */ function extension_valid_builder(builder, length) {
  const valid = extension_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 extension_builder(type, nrows, nullable = true) {
  let method;

  switch (type.typeId) {
    case extension_arrow_types.Int:
      method = type.bitWidth < 64 ? extension_array_builder : null;
      break;
    case extension_arrow_types.Float:
      method = type.precision > 0 ? extension_array_builder : null;
      break;
    case extension_arrow_types.Dictionary:
      // check sub-types against builder assumptions
      // if check fails, fallback to default builder
      method = (
        type.dictionary.typeId === extension_arrow_types.Utf8 &&
        type.indices.typeId === extension_arrow_types.Int &&
        type.indices.bitWidth < 64
      ) ? extension_dictionary_builder : null;
      break;
    case extension_arrow_types.Bool:
      method = extension_bool_builder;
      break;
    case extension_arrow_types.Date:
      method = type.unit ? extension_date_millis_builder : extension_date_day_builder;
      break;
  }

  return method == null ? extension_default_builder(type)
    : nullable ? extension_valid_builder(method(type, nrows), nrows)
    : method(type, nrows);
}
;// ../../node_modules/arquero/src/arrow/encode/data-from.js



function extension_dataFromArray(array, type) {
  const length = array.length;
  const size = extension_ceil64Bytes(length, array.BYTES_PER_ELEMENT);

  let data = array;
  if (length !== size) {
    data = new array.constructor(size);
    data.set(array);
  }

  return extension_arrowData({ type, length, buffers: [null, data] });
}

function extension_dataFromScan(nrows, scan, column, type, nullable = true) {
  const b = extension_builder(type, nrows, nullable);
  scan(column, b.set);
  return extension_arrowData(b.data());
}
;// ../../node_modules/arquero/src/arrow/builder/resolve-type.js





/* harmony default export */ function extension_resolve_type(type) {
  if (type instanceof extension_DataType || type == null) {
    return type;
  }

  switch (type) {
    case extension_arrow_types.Binary:
      return new extension_Binary();
    case extension_arrow_types.Bool:
      return new extension_Bool();
    case extension_arrow_types.DateDay:
      return new extension_DateDay();
    case extension_arrow_types.DateMillisecond:
    case extension_arrow_types.Date:
      return new extension_DateMillisecond();
    case extension_arrow_types.Dictionary:
      return new extension_type_Dictionary(new extension_Utf8(), new extension_Int32());
    case extension_arrow_types.Float16:
      return new extension_Float16();
    case extension_arrow_types.Float32:
      return new extension_Float32();
    case extension_arrow_types.Float64:
    case extension_arrow_types.Float:
      return new extension_Float64();
    case extension_arrow_types.Int8:
      return new extension_Int8();
    case extension_arrow_types.Int16:
      return new extension_Int16();
    case extension_arrow_types.Int32:
    case extension_arrow_types.Int:
      return new extension_Int32();
    case extension_arrow_types.Int64:
      return new extension_Int64();
    case extension_arrow_types.IntervalDayTime:
      return new extension_IntervalDayTime();
    case extension_arrow_types.Interval:
    case extension_arrow_types.IntervalYearMonth:
      return new extension_IntervalYearMonth();
    case extension_arrow_types.Null:
      return new extension_Null();
    case extension_arrow_types.TimeMicrosecond:
      return new extension_TimeMicrosecond();
    case extension_arrow_types.TimeMillisecond:
    case extension_arrow_types.Time:
      return new extension_TimeMillisecond();
    case extension_arrow_types.TimeNanosecond:
      return new extension_TimeNanosecond();
    case extension_arrow_types.TimeSecond:
      return new extension_TimeSecond();
    case extension_arrow_types.Uint8:
      return new extension_Uint8();
    case extension_arrow_types.Uint16:
      return new extension_Uint16();
    case extension_arrow_types.Uint32:
      return new extension_Uint32();
    case extension_arrow_types.Uint64:
      return new extension_Uint64();
    case extension_arrow_types.Utf8:
      return new extension_Utf8();
    default:
      extension_util_error(
        `Unsupported type code: ${extension_to_string(type)}. ` +
        'Use a data type constructor instead?'
      );
  }
}
;// ../../node_modules/arquero/src/util/is-exact-utc-date.js
/* harmony default export */ function extension_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 extension_profile(scan, column) {
  const p = extension_profiler();
  scan(column, p.add);
  return p;
}

function extension_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 (extension_is_date(value)) {
          ++p.dates;
          if (extension_is_exact_utc_date(value)) {
            ++p.utcdays;
          }
        } else if (extension_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 = extension_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] = extension_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 extension_resolve_type(extension_infer(p));
    }
  };

  return p;
}

function extension_infer(p) {
  const valid = p.count - p.nulls;

  if (valid === 0) {
    return extension_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 ? extension_arrow_types.Float64
        : v < (1 << 7) ? extension_arrow_types.Int8 : v < (1 << 15) ? extension_arrow_types.Int16 : extension_arrow_types.Int32
      : v >= 2 ** 32 ? extension_arrow_types.Float64
        : v < (1 << 8) ? extension_arrow_types.Uint8 : v < (1 << 16) ? extension_arrow_types.Uint16 : extension_arrow_types.Uint32;
  }
  else if (p.nums === valid) {
    return extension_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 ? extension_arrow_types.Int64
        : extension_util_error(`BigInt exceeds 64 bits: ${v}`)
      : p.max < 2 ** 64 ? extension_arrow_types.Uint64
        : extension_util_error(`BigInt exceeds 64 bits: ${p.max}`);
  }
  else if (p.bools === valid) {
    return extension_arrow_types.Bool;
  }
  else if (p.utcdays === valid) {
    return extension_arrow_types.DateDay;
  }
  else if (p.dates === valid) {
    return extension_arrow_types.DateMillisecond;
  }
  else if (p.arrays === valid) {
    const type = extension_Field.new('value', p.array_prof.type(), true);
    return p.minlen === p.maxlen
      ? new extension_FixedSizeList(p.minlen, type)
      : new extension_List(type);
  }
  else if (p.structs === valid) {
    const sp = p.struct_prof;
    return new extension_Struct(
      Object.keys(sp).map(name => extension_Field.new(name, sp[name].type(), true))
    );
  }
  else if (p.strings > 0) {
    return extension_arrow_types.Dictionary;
  }
  else {
    extension_util_error('Type inference failure');
  }
}
;// ../../node_modules/arquero/src/arrow/encode/data-from-objects.js




/* harmony default export */ function extension_data_from_objects(data, name, nrows, scan, type, nullable = true) {
  type = extension_resolve_type(type);

  // perform type inference if needed
  if (!type) {
    const p = extension_profile(scan, name);
    nullable = p.nulls > 0;
    type = p.type();
  }

  return extension_dataFromScan(nrows, scan, name, type, nullable);
}
;// ../../node_modules/arquero/src/arrow/encode/data-from-table.js






/* harmony default export */ function extension_data_from_table(table, name, nrows, scan, type, nullable = true) {
  type = extension_resolve_type(type);
  const column = table.column(name);
  const reified = !(table.isFiltered() || table.isOrdered());

  // use existing arrow data if types match
  const vec = extension_data_from_table_arrowVector(column);
  if (vec && reified && extension_typeCompatible(vec.type, type)) {
    return vec;
  }

  // if backing data is a typed array, leverage that
  const data = column.data;
  if (extension_is_typed_array(data)) {
    const dtype = extension_typeFromArray(data);
    if (reified && dtype && extension_typeCompatible(dtype, type)) {
      return extension_dataFromArray(data, dtype);
    } else {
      type = type || dtype;
      nullable = false;
    }
  }

  // perform type inference if needed
  if (!type) {
    const p = extension_profile(scan, column);
    nullable = p.nulls > 0;
    type = p.type();
  }

  return extension_dataFromScan(nrows, scan, column, type, nullable);
}

function extension_data_from_table_arrowVector(value) {
  return value instanceof extension_AbstractVector ? value
    : value.vector instanceof extension_AbstractVector ? value.vector
    : null;
}

function extension_typeFromArray(data) {
  const types = {
    Float32Array:    extension_Float32,
    Float64Array:    extension_Float64,
    Int8Array:       extension_Int8,
    Int16Array:      extension_Int16,
    Int32Array:      extension_Int32,
    Uint8Array:      extension_Uint8,
    Uint16Array:     extension_Uint16,
    Uint32Array:     extension_Uint32,
    BigInt64Array:   extension_Int64,
    BigUint64Array:  extension_Uint64
  };
  const Type = types[data.constructor.name];
  return Type ? new Type() : null;
}

function extension_typeCompatible(a, b) {
  return !a || !b ? true : a.compareTo(b);
}
;// ../../node_modules/arquero/src/arrow/encode/scan.js


function extension_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 extension_scanTable(table, limit, offset) {
  const scanAll = offset === 0 && table.numRows() <= limit
               && !table.isFiltered() && !table.isOrdered();

  return (column, visit) => {
    let i = -1;
    scanAll && extension_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 extension_table() {
  // trap Table access to provide a helpful message
  // when Apache Arrow has not been imported
  try {
    return extension_table_Table;
  } catch (err) {
    extension_util_error(
      'Apache Arrow not imported, ' +
      'see https://github.com/uwdata/arquero#usage'
    );
  }
}

function extension_arrow_table_from(arrow) {
  return arrow && arrow.chunks ? arrow : extension_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 extension_arrow_encode(data, options = {}) {
  const { types = {} } = options;
  const { dataFrom, names, nrows, scan } = extension_encode_init(data, options);
  return extension_table().new(
    names.map(name => {
      const col = dataFrom(data, name, nrows, scan, types[name]);
      return col.length === nrows
        ? col
        : extension_util_error('Column length mismatch');
    }),
    names
  );
}

function extension_encode_init(data, options) {
  const { columns, limit = Infinity, offset = 0 } = options;
  const names = extension_util_is_function(columns) ? columns(data)
    : extension_is_array(columns) ? columns
    : null;
  if (extension_is_array(data)) {
    return {
      dataFrom: extension_data_from_objects,
      names: names || Object.keys(data[0]),
      nrows: Math.min(limit, data.length - offset),
      scan: extension_scanArray(data, limit, offset)
    };
  } else if (extension_isTable(data)) {
    return {
      dataFrom: extension_data_from_table,
      names: names || data.columnNames(),
      nrows: Math.min(limit, data.numRows() - offset),
      scan: extension_scanTable(data, limit, offset)
    };
  } else {
    extension_util_error('Unsupported input data type');
  }
}

function extension_isTable(data) {
  return data && extension_util_is_function(data.reify);
}
;// ../../node_modules/arquero/src/format/to-arrow.js

/* harmony default export */ const extension_to_arrow = (extension_arrow_encode);
;// ../../node_modules/arquero/src/format/infer.js


function extension_isExactDateUTC(d) {
  return d.getUTCHours() === 0
    && d.getUTCMinutes() === 0
    && d.getUTCSeconds() === 0
    && d.getUTCMilliseconds() === 0;
}

/* harmony default export */ function extension_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' && extension_is_date(value)) {
      ++dates;
      if (extension_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 extension_columns(table, names) {
  return extension_util_is_function(names)
    ? names(table)
    : names || table.columnNames();
}

function extension_formats(table, names, options) {
  const formatOpt = options.format || {};
  const alignOpt = options.align || {};
  const format = {};
  const align = {};

  names.forEach(name => {
    const auto = extension_format_infer(extension_values(table, name), options);
    align[name] = alignOpt[name] || auto.align;
    format[name] = formatOpt[name] || auto.format;
  });

  return { align, format };
}

function extension_values(table, columnName) {
  const column = table.column(columnName);
  return fn => table.scan(row => fn(column.get(row)));
}

function extension_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 extension_to_csv(table, options = {}) {
  const names = extension_columns(table, options.columns);
  const format = options.format || {};
  const delim = options.delimiter || ',';
  const reFormat = new RegExp(`["${delim}\n\r]`);

  const formatValue = value => value == null ? ''
    : extension_is_date(value) ? extension_formatUTCDate(value, true)
    : reFormat.test(value += '') ? '"' + value.replace(/"/g, '""') + '"'
    : value;

  const vals = names.map(formatValue);
  let text = '';

  extension_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 extension_format_value(v, options = {}) {
  if (extension_util_is_function(options)) {
    return options(v) + '';
  }

  const type = typeof v;

  if (type === 'object') {
    if (extension_is_date(v)) {
      return options.utc ? extension_formatUTCDate(v) : extension_formatDate(v);
    } else {
      const s = JSON.stringify(
        v,
        (k, v) => extension_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 extension_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 extension_to_html(table, options = {}) {
  const names = extension_columns(table, options.columns);
  const { align, format } = extension_formats(table, names, options);
  const style = extension_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(extension_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');

  extension_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 extension_styles(options) {
  return extension_map_object(
    options.style,
    value => extension_util_is_function(value) ? value : () => value
  );
}
;// ../../node_modules/arquero/src/util/default-true.js
/* harmony default export */ function extension_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 extension_defaultFormatter = value => extension_is_date(value)
  ? extension_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 extension_to_json(table, options = {}) {
  const schema = extension_default_true(options.schema);
  const format = options.format || {};
  const names = extension_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] || extension_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 extension_to_markdown(table, options = {}) {
  const names = extension_columns(table, options.columns);
  const { align, format } = extension_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('|')
    + '|';

  extension_scan(table, names, options.limit, options.offset, {
    row() {
      text += '\n|';
    },
    cell(value, name) {
      text += escape(extension_format_value(value, format[name])) + '|';
    }
  });

  return text + '\n';
}
;// ../../node_modules/arquero/src/util/assign.js


/* harmony default export */ function extension_util_assign(map, pairs) {
  for (const [key, value] of extension_entries(pairs)) {
    map.set(key, value);
  }
  return map;
}
;// ../../node_modules/arquero/src/util/escape-regexp.js
/* harmony default export */ function extension_escape_regexp(str) {
  return str.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
}
;// ../../node_modules/arquero/src/helpers/selection.js










function extension_resolve(table, sel, map = new Map()) {
  sel = extension_is_number(sel) ? table.columnName(sel) : sel;

  if (extension_is_string(sel)) {
    map.set(sel, sel);
  } else if (extension_is_array(sel)) {
    sel.forEach(r => extension_resolve(table, r, map));
  } else if (extension_util_is_function(sel)) {
    extension_resolve(table, sel(table), map);
  } else if (extension_is_object(sel)) {
    extension_util_assign(map, sel);
  } else {
    extension_util_error(`Invalid column selection: ${extension_to_string(sel)}`);
  }

  return map;
}

function extension_decorate(value, toObject) {
  value.toObject = toObject;
  return value;
}

function extension_toObject(value) {
  return extension_is_array(value) ? value.map(extension_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 extension_selection_all() {
  return extension_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 extension_not(...selection) {
  selection = selection.flat();
  return extension_decorate(
    table => {
      const drop = extension_resolve(table, selection);
      return table.columnNames(name => !drop.has(name));
    },
    () => ({ not: extension_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 extension_range(start, end) {
  return extension_decorate(
    table => {
      let i = extension_is_number(start) ? start : table.columnIndex(start);
      let j = extension_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 extension_matches(pattern) {
  if (extension_is_string(pattern)) pattern = RegExp(extension_escape_regexp(pattern));
  return extension_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 extension_startswith(string) {
  return extension_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 extension_endswith(string) {
  return extension_matches(RegExp(escapeRegExp(string) + '$'));
}
;// ../../node_modules/arquero/src/util/array-type.js


/* harmony default export */ function extension_array_type(column) {
  return extension_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 extension_column_table_ColumnTable extends extension_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 extension_column_table_ColumnTable(extension_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 extension_column_table_ColumnTable) return columns;
    const data = {};
    const keys = [];
    for (const [key, value] of extension_entries(columns)) {
      data[key] = value;
      keys.push(key);
    }
    return new extension_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) {
    extension_map_object(columns, extension_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 extension_column_table_ColumnTable(
      data || this._data,
      names || (!data ? this._names : null),
      f,
      groups !== undefined ? groups : extension_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 = extension_column_set(base).groupby(base.groups());
    tables.forEach(input => {
      input = extension_column_table_ColumnTable.new(input);
      if (input.numRows() !== nrows) extension_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)
      : extension_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 extension_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 = extension_resolve(this, options.columns || extension_selection_all());
    const create = extension_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 extension_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 = extension_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 (extension_array_type(prev))(nrows);
        let r = -1;
        scan(row => curr[++r] = prev.get(row));
      }

      if (this.isGrouped()) {
        groups = extension_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 extension_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 extension_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 extension_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 extension_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 extension_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 extension_to_markdown(this, options);
  }
}

function extension_objectBuilder(table) {
  let b = table._builder;

  if (!b) {
    const create = extension_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 extension_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 extension_walk(node, ctx, visitors, parent) {
  const visit = visitors[node.type] || visitors['Default'];
  if (visit && visit(node, ctx, parent) === false) return;

  const walker = extension_walkers[node.type];
  if (walker) walker(node, ctx, visitors);
}

const extension_unary = (node, ctx, visitors) => {
  extension_walk(node.argument, ctx, visitors, node);
};

const extension_walk_binary = (node, ctx, visitors) => {
  extension_walk(node.left, ctx, visitors, node);
  extension_walk(node.right, ctx, visitors, node);
};

const extension_ternary = (node, ctx, visitors) => {
  extension_walk(node.test, ctx, visitors, node);
  extension_walk(node.consequent, ctx, visitors, node);
  if (node.alternate) extension_walk(node.alternate, ctx, visitors, node);
};

const extension_walk_func = (node, ctx, visitors) => {
  extension_walk_list(node.params, ctx, visitors, node);
  extension_walk(node.body, ctx, visitors, node);
};

const extension_walk_call = (node, ctx, visitors) => {
  extension_walk(node.callee, ctx, visitors, node);
  extension_walk_list(node.arguments, ctx, visitors, node);
};

const extension_walk_list = (nodes, ctx, visitors, node) => {
  nodes.forEach(item => extension_walk(item, ctx, visitors, node));
};

const extension_walkers = {
  TemplateLiteral: (node, ctx, visitors) => {
    extension_walk_list(node.expressions, ctx, visitors, node);
    extension_walk_list(node.quasis, ctx, visitors, node);
  },
  MemberExpression: (node, ctx, visitors) => {
    extension_walk(node.object, ctx, visitors, node);
    extension_walk(node.property, ctx, visitors, node);
  },
  CallExpression: extension_walk_call,
  NewExpression: extension_walk_call,
  ArrayExpression: (node, ctx, visitors) => {
    extension_walk_list(node.elements, ctx, visitors, node);
  },
  AssignmentExpression: extension_walk_binary,
  AwaitExpression: extension_unary,
  BinaryExpression: extension_walk_binary,
  LogicalExpression: extension_walk_binary,
  UnaryExpression: extension_unary,
  UpdateExpression: extension_unary,
  ConditionalExpression: extension_ternary,
  ObjectExpression: (node, ctx, visitors) => {
    extension_walk_list(node.properties, ctx, visitors, node);
  },
  Property: (node, ctx, visitors) => {
    extension_walk(node.key, ctx, visitors, node);
    extension_walk(node.value, ctx, visitors, node);
  },

  ArrowFunctionExpression: extension_walk_func,
  FunctionExpression: extension_walk_func,
  FunctionDeclaration: extension_walk_func,

  VariableDeclaration: (node, ctx, visitors) => {
    extension_walk_list(node.declarations, ctx, visitors, node);
  },
  VariableDeclarator: (node, ctx, visitors) => {
    extension_walk(node.id, ctx, visitors, node);
    extension_walk(node.init, ctx, visitors, node);
  },
  SpreadElement: (node, ctx, visitors) => {
    extension_walk(node.argument, ctx, visitors, node);
  },

  BlockStatement: (node, ctx, visitors) => {
    extension_walk_list(node.body, ctx, visitors, node);
  },
  ExpressionStatement: (node, ctx, visitors) => {
    extension_walk(node.expression, ctx, visitors, node);
  },
  IfStatement: extension_ternary,
  ForStatement: (node, ctx, visitors) => {
    extension_walk(node.init, ctx, visitors, node);
    extension_walk(node.test, ctx, visitors, node);
    extension_walk(node.update, ctx, visitors, node);
    extension_walk(node.body, ctx, visitors, node);
  },
  WhileStatement: (node, ctx, visitors) => {
    extension_walk(node.test, ctx, visitors, node);
    extension_walk(node.body, ctx, visitors, node);
  },
  DoWhileStatement: (node, ctx, visitors) => {
    extension_walk(node.body, ctx, visitors, node);
    extension_walk(node.test, ctx, visitors, node);
  },
  SwitchStatement: (node, ctx, visitors) => {
    extension_walk(node.discriminant, ctx, visitors, node);
    extension_walk_list(node.cases, ctx, visitors, node);
  },
  SwitchCase: (node, ctx, visitors) => {
    if (node.test) extension_walk(node.test, ctx, visitors, node);
    extension_walk_list(node.consequent, ctx, visitors, node);
  },
  ReturnStatement: extension_unary,

  Program: (node, ctx, visitors) => {
    extension_walk(node.body[0], ctx, visitors, node);
  }
};
;// ../../node_modules/arquero/src/expression/ast/clean.js


function extension_strip(node) {
  delete node.start;
  delete node.end;
  delete node.optional;
}

function extension_stripMember(node) {
  extension_strip(node);
  delete node.object;
  delete node.property;
  delete node.computed;
  if (!node.table) delete node.table;
}

/* harmony default export */ function extension_clean(ast) {
  extension_walk(ast, null, {
    Column: extension_stripMember,
    Constant: extension_stripMember,
    Default: extension_strip
  });
  return ast;
}
;// ../../node_modules/arquero/src/expression/ast/util.js


function extension_is(type, node) {
  return node && node.type === type;
}

function extension_isFunctionExpression(node) {
  return extension_is(extension_FunctionExpression, node)
    || extension_is(extension_ArrowFunctionExpression, node);
}
;// ../../node_modules/arquero/src/util/to-function.js


/* harmony default export */ function extension_to_function(value) {
  return extension_util_is_function(value) ? value : () => value;
}
;// ../../node_modules/arquero/src/expression/parse-escape.js





const extension_ERROR_ESC_AGGRONLY = 'Escaped functions are not valid as rollup or pivot values.';

/* harmony default export */ function extension_parse_escape(ctx, spec, params) {
  if (ctx.aggronly) extension_util_error(extension_ERROR_ESC_AGGRONLY);

  // generate escaped function invocation code
  const code = '(row,data)=>fn('
    + extension_rowObjectCode(ctx.table.columnNames())
    + ',$)';

  return { escape: extension_expression_compile.escape(code, extension_to_function(spec.expr), params) };
}
;// ../../node_modules/acorn/dist/acorn.mjs
// This file was generated. Do not modify manually!
var extension_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 extension_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 extension_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 extension_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 extension_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 extension_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 extension_keywords$1 = {
  5: extension_ecma5AndLessKeywords,
  "5module": extension_ecma5AndLessKeywords + " export import",
  6: extension_ecma5AndLessKeywords + " const class extends export import super"
};

var extension_keywordRelationalOperator = /^in(stanceof)?$/;

// ## Character categories

var extension_nonASCIIidentifierStart = new RegExp("[" + extension_nonASCIIidentifierStartChars + "]");
var extension_nonASCIIidentifier = new RegExp("[" + extension_nonASCIIidentifierStartChars + extension_nonASCIIidentifierChars + "]");

// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function extension_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 extension_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 && extension_nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  if (astral === false) { return false }
  return extension_isInAstralSet(code, extension_astralIdentifierStartCodes)
}

// Test whether a given character is part of an identifier.

function extension_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 && extension_nonASCIIidentifier.test(String.fromCharCode(code)) }
  if (astral === false) { return false }
  return extension_isInAstralSet(code, extension_astralIdentifierStartCodes) || extension_isInAstralSet(code, extension_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 extension_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 extension_binop(name, prec) {
  return new extension_TokenType(name, {beforeExpr: true, binop: prec})
}
var extension_beforeExpr = {beforeExpr: true}, extension_startsExpr = {startsExpr: true};

// Map keyword names to token types.

var extension_keywords = {};

// Succinct definitions of keyword token types
function extension_kw(name, options) {
  if ( options === void 0 ) options = {};

  options.keyword = name;
  return extension_keywords[name] = new extension_TokenType(name, options)
}

var extension_types$1 = {
  num: new extension_TokenType("num", extension_startsExpr),
  regexp: new extension_TokenType("regexp", extension_startsExpr),
  string: new extension_TokenType("string", extension_startsExpr),
  name: new extension_TokenType("name", extension_startsExpr),
  privateId: new extension_TokenType("privateId", extension_startsExpr),
  eof: new extension_TokenType("eof"),

  // Punctuation token types.
  bracketL: new extension_TokenType("[", {beforeExpr: true, startsExpr: true}),
  bracketR: new extension_TokenType("]"),
  braceL: new extension_TokenType("{", {beforeExpr: true, startsExpr: true}),
  braceR: new extension_TokenType("}"),
  parenL: new extension_TokenType("(", {beforeExpr: true, startsExpr: true}),
  parenR: new extension_TokenType(")"),
  comma: new extension_TokenType(",", extension_beforeExpr),
  semi: new extension_TokenType(";", extension_beforeExpr),
  colon: new extension_TokenType(":", extension_beforeExpr),
  dot: new extension_TokenType("."),
  question: new extension_TokenType("?", extension_beforeExpr),
  questionDot: new extension_TokenType("?."),
  arrow: new extension_TokenType("=>", extension_beforeExpr),
  template: new extension_TokenType("template"),
  invalidTemplate: new extension_TokenType("invalidTemplate"),
  ellipsis: new extension_TokenType("...", extension_beforeExpr),
  backQuote: new extension_TokenType("`", extension_startsExpr),
  dollarBraceL: new extension_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 extension_TokenType("=", {beforeExpr: true, isAssign: true}),
  assign: new extension_TokenType("_=", {beforeExpr: true, isAssign: true}),
  incDec: new extension_TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  prefix: new extension_TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  logicalOR: extension_binop("||", 1),
  logicalAND: extension_binop("&&", 2),
  bitwiseOR: extension_binop("|", 3),
  bitwiseXOR: extension_binop("^", 4),
  bitwiseAND: extension_binop("&", 5),
  equality: extension_binop("==/!=/===/!==", 6),
  relational: extension_binop("</>/<=/>=", 7),
  bitShift: extension_binop("<</>>/>>>", 8),
  plusMin: new extension_TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  modulo: extension_binop("%", 10),
  star: extension_binop("*", 10),
  slash: extension_binop("/", 10),
  starstar: new extension_TokenType("**", {beforeExpr: true}),
  coalesce: extension_binop("??", 1),

  // Keyword token types.
  _break: extension_kw("break"),
  _case: extension_kw("case", extension_beforeExpr),
  _catch: extension_kw("catch"),
  _continue: extension_kw("continue"),
  _debugger: extension_kw("debugger"),
  _default: extension_kw("default", extension_beforeExpr),
  _do: extension_kw("do", {isLoop: true, beforeExpr: true}),
  _else: extension_kw("else", extension_beforeExpr),
  _finally: extension_kw("finally"),
  _for: extension_kw("for", {isLoop: true}),
  _function: extension_kw("function", extension_startsExpr),
  _if: extension_kw("if"),
  _return: extension_kw("return", extension_beforeExpr),
  _switch: extension_kw("switch"),
  _throw: extension_kw("throw", extension_beforeExpr),
  _try: extension_kw("try"),
  _var: extension_kw("var"),
  _const: extension_kw("const"),
  _while: extension_kw("while", {isLoop: true}),
  _with: extension_kw("with"),
  _new: extension_kw("new", {beforeExpr: true, startsExpr: true}),
  _this: extension_kw("this", extension_startsExpr),
  _super: extension_kw("super", extension_startsExpr),
  _class: extension_kw("class", extension_startsExpr),
  _extends: extension_kw("extends", extension_beforeExpr),
  _export: extension_kw("export"),
  _import: extension_kw("import", extension_startsExpr),
  _null: extension_kw("null", extension_startsExpr),
  _true: extension_kw("true", extension_startsExpr),
  _false: extension_kw("false", extension_startsExpr),
  _in: extension_kw("in", {beforeExpr: true, binop: 7}),
  _instanceof: extension_kw("instanceof", {beforeExpr: true, binop: 7}),
  _typeof: extension_kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  _void: extension_kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  _delete: extension_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 extension_lineBreak = /\r\n?|\n|\u2028|\u2029/;
var extension_lineBreakG = new RegExp(extension_lineBreak.source, "g");

function extension_isNewLine(code) {
  return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}

function extension_nextLineBreak(code, from, end) {
  if ( end === void 0 ) end = code.length;

  for (var i = from; i < end; i++) {
    var next = code.charCodeAt(i);
    if (extension_isNewLine(next))
      { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  }
  return -1
}

var extension_nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;

var extension_skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;

var extension_acorn_ref = Object.prototype;
var extension_acorn_hasOwnProperty = extension_acorn_ref.hasOwnProperty;
var extension_acorn_toString = extension_acorn_ref.toString;

var extension_hasOwn = Object.hasOwn || (function (obj, propName) { return (
  extension_acorn_hasOwnProperty.call(obj, propName)
); });

var extension_acorn_isArray = Array.isArray || (function (obj) { return (
  extension_acorn_toString.call(obj) === "[object Array]"
); });

var extension_regexpCache = Object.create(null);

function extension_wordsRegexp(words) {
  return extension_regexpCache[words] || (extension_regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"))
}

function extension_codePointToString(code) {
  // UTF-16 Decoding
  if (code <= 0xFFFF) { return String.fromCharCode(code) }
  code -= 0x10000;
  return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}

var extension_loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;

// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.

var extension_Position = function Position(line, col) {
  this.line = line;
  this.column = col;
};

extension_Position.prototype.offset = function offset (n) {
  return new extension_Position(this.line, this.column + n)
};

var extension_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 extension_getLineInfo(input, offset) {
  for (var line = 1, cur = 0;;) {
    var nextBreak = extension_nextLineBreak(input, cur, offset);
    if (nextBreak < 0) { return new extension_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 extension_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 extension_warnedAboutEcmaVersion = false;

function extension_getOptions(opts) {
  var options = {};

  for (var opt in extension_defaultOptions)
    { options[opt] = opts && extension_hasOwn(opts, opt) ? opts[opt] : extension_defaultOptions[opt]; }

  if (options.ecmaVersion === "latest") {
    options.ecmaVersion = 1e8;
  } else if (options.ecmaVersion == null) {
    if (!extension_warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
      extension_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 (extension_acorn_isArray(options.onToken)) {
    var tokens = options.onToken;
    options.onToken = function (token) { return tokens.push(token); };
  }
  if (extension_acorn_isArray(options.onComment))
    { options.onComment = extension_pushComment(options, options.onComment); }

  return options
}

function extension_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 extension_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
    extension_SCOPE_TOP = 1,
    extension_SCOPE_FUNCTION = 2,
    extension_SCOPE_ASYNC = 4,
    extension_SCOPE_GENERATOR = 8,
    extension_SCOPE_ARROW = 16,
    extension_SCOPE_SIMPLE_CATCH = 32,
    extension_SCOPE_SUPER = 64,
    extension_SCOPE_DIRECT_SUPER = 128,
    extension_SCOPE_CLASS_STATIC_BLOCK = 256,
    extension_SCOPE_VAR = extension_SCOPE_TOP | extension_SCOPE_FUNCTION | extension_SCOPE_CLASS_STATIC_BLOCK;

function extension_functionFlags(async, generator) {
  return extension_SCOPE_FUNCTION | (async ? extension_SCOPE_ASYNC : 0) | (generator ? extension_SCOPE_GENERATOR : 0)
}

// Used in checkLVal* and declareName to determine the type of a binding
var
    extension_BIND_NONE = 0, // Not a binding
    extension_BIND_VAR = 1, // Var-style binding
    extension_BIND_LEXICAL = 2, // Let- or const-style binding
    extension_BIND_FUNCTION = 3, // Function declaration
    extension_BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
    extension_BIND_OUTSIDE = 5; // Special case for function names as bound inside the function

var extension_Parser = function Parser(options, input, startPos) {
  this.options = options = extension_getOptions(options);
  this.sourceFile = options.sourceFile;
  this.keywords = extension_wordsRegexp(extension_keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  var reserved = "";
  if (options.allowReserved !== true) {
    reserved = extension_reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
    if (options.sourceType === "module") { reserved += " await"; }
  }
  this.reservedWords = extension_wordsRegexp(reserved);
  var reservedStrict = (reserved ? reserved + " " : "") + extension_reservedWords.strict;
  this.reservedWordsStrict = extension_wordsRegexp(reservedStrict);
  this.reservedWordsStrictBind = extension_wordsRegexp(reservedStrict + " " + extension_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(extension_lineBreak).length;
  } else {
    this.pos = this.lineStart = 0;
    this.curLine = 1;
  }

  // Properties of the current token:
  // Its type
  this.type = extension_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(extension_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 extension_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 } };

extension_Parser.prototype.parse = function parse () {
  var node = this.options.program || this.startNode();
  this.nextToken();
  return this.parseTopLevel(node)
};

extension_prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & extension_SCOPE_FUNCTION) > 0 };

extension_prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & extension_SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };

extension_prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & extension_SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };

extension_prototypeAccessors.canAwait.get = function () {
  for (var i = this.scopeStack.length - 1; i >= 0; i--) {
    var scope = this.scopeStack[i];
    if (scope.inClassFieldInit || scope.flags & extension_SCOPE_CLASS_STATIC_BLOCK) { return false }
    if (scope.flags & extension_SCOPE_FUNCTION) { return (scope.flags & extension_SCOPE_ASYNC) > 0 }
  }
  return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
};

extension_prototypeAccessors.allowSuper.get = function () {
  var ref = this.currentThisScope();
    var flags = ref.flags;
    var inClassFieldInit = ref.inClassFieldInit;
  return (flags & extension_SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
};

extension_prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & extension_SCOPE_DIRECT_SUPER) > 0 };

extension_prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };

extension_prototypeAccessors.allowNewDotTarget.get = function () {
  var ref = this.currentThisScope();
    var flags = ref.flags;
    var inClassFieldInit = ref.inClassFieldInit;
  return (flags & (extension_SCOPE_FUNCTION | extension_SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
};

extension_prototypeAccessors.inClassStaticBlock.get = function () {
  return (this.currentVarScope().flags & extension_SCOPE_CLASS_STATIC_BLOCK) > 0
};

extension_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
};

extension_Parser.parse = function parse (input, options) {
  return new this(options, input).parse()
};

extension_Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  var parser = new this(options, input, pos);
  parser.nextToken();
  return parser.parseExpression()
};

extension_Parser.tokenizer = function tokenizer (input, options) {
  return new this(options, input)
};

Object.defineProperties( extension_Parser.prototype, extension_prototypeAccessors );

var extension_pp$9 = extension_Parser.prototype;

// ## Parser utilities

var extension_literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
extension_pp$9.strictDirective = function(start) {
  if (this.options.ecmaVersion < 5) { return false }
  for (;;) {
    // Try to find string literal.
    extension_skipWhiteSpace.lastIndex = start;
    start += extension_skipWhiteSpace.exec(this.input)[0].length;
    var match = extension_literal.exec(this.input.slice(start));
    if (!match) { return false }
    if ((match[1] || match[2]) === "use strict") {
      extension_skipWhiteSpace.lastIndex = start + match[0].length;
      var spaceAfter = extension_skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
      var next = this.input.charAt(end);
      return next === ";" || next === "}" ||
        (extension_lineBreak.test(spaceAfter[0]) &&
         !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
    }
    start += match[0].length;

    // Skip semicolon, if any.
    extension_skipWhiteSpace.lastIndex = start;
    start += extension_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.

extension_pp$9.eat = function(type) {
  if (this.type === type) {
    this.next();
    return true
  } else {
    return false
  }
};

// Tests whether parsed token is a contextual keyword.

extension_pp$9.isContextual = function(name) {
  return this.type === extension_types$1.name && this.value === name && !this.containsEsc
};

// Consumes contextual keyword if possible.

extension_pp$9.eatContextual = function(name) {
  if (!this.isContextual(name)) { return false }
  this.next();
  return true
};

// Asserts that following token is given contextual keyword.

extension_pp$9.expectContextual = function(name) {
  if (!this.eatContextual(name)) { this.unexpected(); }
};

// Test whether a semicolon can be inserted at the current position.

extension_pp$9.canInsertSemicolon = function() {
  return this.type === extension_types$1.eof ||
    this.type === extension_types$1.braceR ||
    extension_lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};

extension_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.

extension_pp$9.semicolon = function() {
  if (!this.eat(extension_types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
};

extension_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.

extension_pp$9.expect = function(type) {
  this.eat(type) || this.unexpected();
};

// Raise an unexpected token error.

extension_pp$9.unexpected = function(pos) {
  this.raise(pos != null ? pos : this.start, "Unexpected token");
};

var extension_DestructuringErrors = function DestructuringErrors() {
  this.shorthandAssign =
  this.trailingComma =
  this.parenthesizedAssign =
  this.parenthesizedBind =
  this.doubleProto =
    -1;
};

extension_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"); }
};

extension_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"); }
};

extension_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"); }
};

extension_pp$9.isSimpleAssignTarget = function(expr) {
  if (expr.type === "ParenthesizedExpression")
    { return this.isSimpleAssignTarget(expr.expression) }
  return expr.type === "Identifier" || expr.type === "MemberExpression"
};

var extension_pp$8 = extension_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.

extension_pp$8.parseTopLevel = function(node) {
  var exports = Object.create(null);
  if (!node.body) { node.body = []; }
  while (this.type !== extension_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 extension_loopLabel = {kind: "loop"}, extension_switchLabel = {kind: "switch"};

extension_pp$8.isLet = function(context) {
  if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  extension_skipWhiteSpace.lastIndex = this.pos;
  var skip = extension_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 (extension_isIdentifierStart(nextCh, true)) {
    var pos = next + 1;
    while (extension_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 (!extension_keywordRelationalOperator.test(ident)) { return true }
  }
  return false
};

// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
extension_pp$8.isAsyncFunction = function() {
  if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
    { return false }

  extension_skipWhiteSpace.lastIndex = this.pos;
  var skip = extension_skipWhiteSpace.exec(this.input);
  var next = this.pos + skip[0].length, after;
  return !extension_lineBreak.test(this.input.slice(this.pos, next)) &&
    this.input.slice(next, next + 8) === "function" &&
    (next + 8 === this.input.length ||
     !(extension_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.

extension_pp$8.parseStatement = function(context, topLevel, exports) {
  var starttype = this.type, node = this.startNode(), kind;

  if (this.isLet(context)) {
    starttype = extension_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 extension_types$1._break: case extension_types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  case extension_types$1._debugger: return this.parseDebuggerStatement(node)
  case extension_types$1._do: return this.parseDoStatement(node)
  case extension_types$1._for: return this.parseForStatement(node)
  case extension_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 extension_types$1._class:
    if (context) { this.unexpected(); }
    return this.parseClass(node, true)
  case extension_types$1._if: return this.parseIfStatement(node)
  case extension_types$1._return: return this.parseReturnStatement(node)
  case extension_types$1._switch: return this.parseSwitchStatement(node)
  case extension_types$1._throw: return this.parseThrowStatement(node)
  case extension_types$1._try: return this.parseTryStatement(node)
  case extension_types$1._const: case extension_types$1._var:
    kind = kind || this.value;
    if (context && kind !== "var") { this.unexpected(); }
    return this.parseVarStatement(node, kind)
  case extension_types$1._while: return this.parseWhileStatement(node)
  case extension_types$1._with: return this.parseWithStatement(node)
  case extension_types$1.braceL: return this.parseBlock(true, node)
  case extension_types$1.semi: return this.parseEmptyStatement(node)
  case extension_types$1._export:
  case extension_types$1._import:
    if (this.options.ecmaVersion > 10 && starttype === extension_types$1._import) {
      extension_skipWhiteSpace.lastIndex = this.pos;
      var skip = extension_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 === extension_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 === extension_types$1.name && expr.type === "Identifier" && this.eat(extension_types$1.colon))
      { return this.parseLabeledStatement(node, maybeName, expr, context) }
    else { return this.parseExpressionStatement(node, expr) }
  }
};

extension_pp$8.parseBreakContinueStatement = function(node, keyword) {
  var isBreak = keyword === "break";
  this.next();
  if (this.eat(extension_types$1.semi) || this.insertSemicolon()) { node.label = null; }
  else if (this.type !== extension_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")
};

extension_pp$8.parseDebuggerStatement = function(node) {
  this.next();
  this.semicolon();
  return this.finishNode(node, "DebuggerStatement")
};

extension_pp$8.parseDoStatement = function(node) {
  this.next();
  this.labels.push(extension_loopLabel);
  node.body = this.parseStatement("do");
  this.labels.pop();
  this.expect(extension_types$1._while);
  node.test = this.parseParenExpression();
  if (this.options.ecmaVersion >= 6)
    { this.eat(extension_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.

extension_pp$8.parseForStatement = function(node) {
  this.next();
  var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  this.labels.push(extension_loopLabel);
  this.enterScope(0);
  this.expect(extension_types$1.parenL);
  if (this.type === extension_types$1.semi) {
    if (awaitAt > -1) { this.unexpected(awaitAt); }
    return this.parseFor(node, null)
  }
  var isLet = this.isLet();
  if (this.type === extension_types$1._var || this.type === extension_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 === extension_types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
      if (this.options.ecmaVersion >= 9) {
        if (this.type === extension_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 extension_DestructuringErrors;
  var initPos = this.start;
  var init = awaitAt > -1
    ? this.parseExprSubscripts(refDestructuringErrors, "await")
    : this.parseExpression(true, refDestructuringErrors);
  if (this.type === extension_types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
    if (awaitAt > -1) { // implies `ecmaVersion >= 9` (see declaration of awaitAt)
      if (this.type === extension_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)
};

extension_pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  this.next();
  return this.parseFunction(node, extension_FUNC_STATEMENT | (declarationPosition ? 0 : extension_FUNC_HANGING_STATEMENT), false, isAsync)
};

extension_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(extension_types$1._else) ? this.parseStatement("if") : null;
  return this.finishNode(node, "IfStatement")
};

extension_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(extension_types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  else { node.argument = this.parseExpression(); this.semicolon(); }
  return this.finishNode(node, "ReturnStatement")
};

extension_pp$8.parseSwitchStatement = function(node) {
  this.next();
  node.discriminant = this.parseParenExpression();
  node.cases = [];
  this.expect(extension_types$1.braceL);
  this.labels.push(extension_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 !== extension_types$1.braceR;) {
    if (this.type === extension_types$1._case || this.type === extension_types$1._default) {
      var isCase = this.type === extension_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(extension_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")
};

extension_pp$8.parseThrowStatement = function(node) {
  this.next();
  if (extension_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 extension_empty$1 = [];

extension_pp$8.parseCatchClauseParam = function() {
  var param = this.parseBindingAtom();
  var simple = param.type === "Identifier";
  this.enterScope(simple ? extension_SCOPE_SIMPLE_CATCH : 0);
  this.checkLValPattern(param, simple ? extension_BIND_SIMPLE_CATCH : extension_BIND_LEXICAL);
  this.expect(extension_types$1.parenR);

  return param
};

extension_pp$8.parseTryStatement = function(node) {
  this.next();
  node.block = this.parseBlock();
  node.handler = null;
  if (this.type === extension_types$1._catch) {
    var clause = this.startNode();
    this.next();
    if (this.eat(extension_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(extension_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")
};

extension_pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  this.next();
  this.parseVar(node, false, kind, allowMissingInitializer);
  this.semicolon();
  return this.finishNode(node, "VariableDeclaration")
};

extension_pp$8.parseWhileStatement = function(node) {
  this.next();
  node.test = this.parseParenExpression();
  this.labels.push(extension_loopLabel);
  node.body = this.parseStatement("while");
  this.labels.pop();
  return this.finishNode(node, "WhileStatement")
};

extension_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")
};

extension_pp$8.parseEmptyStatement = function(node) {
  this.next();
  return this.finishNode(node, "EmptyStatement")
};

extension_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 === extension_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")
};

extension_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).

extension_pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  if ( node === void 0 ) node = this.startNode();

  node.body = [];
  this.expect(extension_types$1.braceL);
  if (createNewLexicalScope) { this.enterScope(0); }
  while (this.type !== extension_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.

extension_pp$8.parseFor = function(node, init) {
  node.init = init;
  this.expect(extension_types$1.semi);
  node.test = this.type === extension_types$1.semi ? null : this.parseExpression();
  this.expect(extension_types$1.semi);
  node.update = this.type === extension_types$1.parenR ? null : this.parseExpression();
  this.expect(extension_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.

extension_pp$8.parseForIn = function(node, init) {
  var isForIn = this.type === extension_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(extension_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.

extension_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(extension_types$1.eq)) {
      decl.init = this.parseMaybeAssign(isFor);
    } else if (!allowMissingInitializer && kind === "const" && !(this.type === extension_types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
      this.unexpected();
    } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === extension_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(extension_types$1.comma)) { break }
  }
  return node
};

extension_pp$8.parseVarId = function(decl, kind) {
  decl.id = this.parseBindingAtom();
  this.checkLValPattern(decl.id, kind === "var" ? extension_BIND_VAR : extension_BIND_LEXICAL, false);
};

var extension_FUNC_STATEMENT = 1, extension_FUNC_HANGING_STATEMENT = 2, extension_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
extension_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 === extension_types$1.star && (statement & extension_FUNC_HANGING_STATEMENT))
      { this.unexpected(); }
    node.generator = this.eat(extension_types$1.star);
  }
  if (this.options.ecmaVersion >= 8)
    { node.async = !!isAsync; }

  if (statement & extension_FUNC_STATEMENT) {
    node.id = (statement & extension_FUNC_NULLABLE_ID) && this.type !== extension_types$1.name ? null : this.parseIdent();
    if (node.id && !(statement & extension_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 ? extension_BIND_VAR : extension_BIND_LEXICAL : extension_BIND_FUNCTION); }
  }

  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  this.yieldPos = 0;
  this.awaitPos = 0;
  this.awaitIdentPos = 0;
  this.enterScope(extension_functionFlags(node.async, node.generator));

  if (!(statement & extension_FUNC_STATEMENT))
    { node.id = this.type === extension_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 & extension_FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
};

extension_pp$8.parseFunctionParams = function(node) {
  this.expect(extension_types$1.parenL);
  node.params = this.parseBindingList(extension_types$1.parenR, false, this.options.ecmaVersion >= 8);
  this.checkYieldAwaitInDefaultParams();
};

// Parse a class declaration or literal (depending on the
// `isStatement` parameter).

extension_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(extension_types$1.braceL);
  while (this.type !== extension_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" && extension_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")
};

extension_pp$8.parseClassElement = function(constructorAllowsSuper) {
  if (this.eat(extension_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(extension_types$1.braceL)) {
      this.parseClassStaticBlock(node);
      return node
    }
    if (this.isClassElementNameStart() || this.type === extension_types$1.star) {
      isStatic = true;
    } else {
      keyName = "static";
    }
  }
  node.static = isStatic;
  if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
    if ((this.isClassElementNameStart() || this.type === extension_types$1.star) && !this.canInsertSemicolon()) {
      isAsync = true;
    } else {
      keyName = "async";
    }
  }
  if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(extension_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 === extension_types$1.parenL || kind !== "method" || isGenerator || isAsync) {
    var isConstructor = !node.static && extension_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
};

extension_pp$8.isClassElementNameStart = function() {
  return (
    this.type === extension_types$1.name ||
    this.type === extension_types$1.privateId ||
    this.type === extension_types$1.num ||
    this.type === extension_types$1.string ||
    this.type === extension_types$1.bracketL ||
    this.type.keyword
  )
};

extension_pp$8.parseClassElementName = function(element) {
  if (this.type === extension_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);
  }
};

extension_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 && extension_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")
};

extension_pp$8.parseClassField = function(field) {
  if (extension_checkKeyName(field, "constructor")) {
    this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  } else if (field.static && extension_checkKeyName(field, "prototype")) {
    this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  }

  if (this.eat(extension_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")
};

extension_pp$8.parseClassStaticBlock = function(node) {
  node.body = [];

  var oldLabels = this.labels;
  this.labels = [];
  this.enterScope(extension_SCOPE_CLASS_STATIC_BLOCK | extension_SCOPE_SUPER);
  while (this.type !== extension_types$1.braceR) {
    var stmt = this.parseStatement(null);
    node.body.push(stmt);
  }
  this.next();
  this.exitScope();
  this.labels = oldLabels;

  return this.finishNode(node, "StaticBlock")
};

extension_pp$8.parseClassId = function(node, isStatement) {
  if (this.type === extension_types$1.name) {
    node.id = this.parseIdent();
    if (isStatement)
      { this.checkLValSimple(node.id, extension_BIND_LEXICAL, false); }
  } else {
    if (isStatement === true)
      { this.unexpected(); }
    node.id = null;
  }
};

extension_pp$8.parseClassSuper = function(node) {
  node.superClass = this.eat(extension_types$1._extends) ? this.parseExprSubscripts(null, false) : null;
};

extension_pp$8.enterClassBody = function() {
  var element = {declared: Object.create(null), used: []};
  this.privateNameStack.push(element);
  return element.declared
};

extension_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 (!extension_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 extension_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 extension_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.

extension_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 !== extension_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")
};

extension_pp$8.parseExport = function(node, exports) {
  this.next();
  // export * from '...'
  if (this.eat(extension_types$1.star)) {
    return this.parseExportAllDeclaration(node, exports)
  }
  if (this.eat(extension_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 !== extension_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")
};

extension_pp$8.parseExportDeclaration = function(node) {
  return this.parseStatement(null)
};

extension_pp$8.parseExportDefaultDeclaration = function() {
  var isAsync;
  if (this.type === extension_types$1._function || (isAsync = this.isAsyncFunction())) {
    var fNode = this.startNode();
    this.next();
    if (isAsync) { this.next(); }
    return this.parseFunction(fNode, extension_FUNC_STATEMENT | extension_FUNC_NULLABLE_ID, false, isAsync)
  } else if (this.type === extension_types$1._class) {
    var cNode = this.startNode();
    return this.parseClass(cNode, "nullableID")
  } else {
    var declaration = this.parseMaybeAssign();
    this.semicolon();
    return declaration
  }
};

extension_pp$8.checkExport = function(exports, name, pos) {
  if (!exports) { return }
  if (typeof name !== "string")
    { name = name.type === "Identifier" ? name.name : name.value; }
  if (extension_hasOwn(exports, name))
    { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  exports[name] = true;
};

extension_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); }
};

extension_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);
  }
};

extension_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.

extension_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")
};

extension_pp$8.parseExportSpecifiers = function(exports) {
  var nodes = [], first = true;
  // export { x, y as z } [from '...']
  this.expect(extension_types$1.braceL);
  while (!this.eat(extension_types$1.braceR)) {
    if (!first) {
      this.expect(extension_types$1.comma);
      if (this.afterTrailingComma(extension_types$1.braceR)) { break }
    } else { first = false; }

    nodes.push(this.parseExportSpecifier(exports));
  }
  return nodes
};

// Parses import declaration.

extension_pp$8.parseImport = function(node) {
  this.next();

  // import '...'
  if (this.type === extension_types$1.string) {
    node.specifiers = extension_empty$1;
    node.source = this.parseExprAtom();
  } else {
    node.specifiers = this.parseImportSpecifiers();
    this.expectContextual("from");
    node.source = this.type === extension_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.

extension_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, extension_BIND_LEXICAL);

  return this.finishNode(node, "ImportSpecifier")
};

extension_pp$8.parseImportDefaultSpecifier = function() {
  // import defaultObj, { x, y as z } from '...'
  var node = this.startNode();
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, extension_BIND_LEXICAL);
  return this.finishNode(node, "ImportDefaultSpecifier")
};

extension_pp$8.parseImportNamespaceSpecifier = function() {
  var node = this.startNode();
  this.next();
  this.expectContextual("as");
  node.local = this.parseIdent();
  this.checkLValSimple(node.local, extension_BIND_LEXICAL);
  return this.finishNode(node, "ImportNamespaceSpecifier")
};

extension_pp$8.parseImportSpecifiers = function() {
  var nodes = [], first = true;
  if (this.type === extension_types$1.name) {
    nodes.push(this.parseImportDefaultSpecifier());
    if (!this.eat(extension_types$1.comma)) { return nodes }
  }
  if (this.type === extension_types$1.star) {
    nodes.push(this.parseImportNamespaceSpecifier());
    return nodes
  }
  this.expect(extension_types$1.braceL);
  while (!this.eat(extension_types$1.braceR)) {
    if (!first) {
      this.expect(extension_types$1.comma);
      if (this.afterTrailingComma(extension_types$1.braceR)) { break }
    } else { first = false; }

    nodes.push(this.parseImportSpecifier());
  }
  return nodes
};

extension_pp$8.parseWithClause = function() {
  var nodes = [];
  if (!this.eat(extension_types$1._with)) {
    return nodes
  }
  this.expect(extension_types$1.braceL);
  var attributeKeys = {};
  var first = true;
  while (!this.eat(extension_types$1.braceR)) {
    if (!first) {
      this.expect(extension_types$1.comma);
      if (this.afterTrailingComma(extension_types$1.braceR)) { break }
    } else { first = false; }

    var attr = this.parseImportAttribute();
    var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
    if (extension_hasOwn(attributeKeys, keyName))
      { this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'"); }
    attributeKeys[keyName] = true;
    nodes.push(attr);
  }
  return nodes
};

extension_pp$8.parseImportAttribute = function() {
  var node = this.startNode();
  node.key = this.type === extension_types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
  this.expect(extension_types$1.colon);
  if (this.type !== extension_types$1.string) {
    this.unexpected();
  }
  node.value = this.parseExprAtom();
  return this.finishNode(node, "ImportAttribute")
};

extension_pp$8.parseModuleExportName = function() {
  if (this.options.ecmaVersion >= 13 && this.type === extension_types$1.string) {
    var stringLiteral = this.parseLiteral(this.value);
    if (extension_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.
extension_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);
  }
};
extension_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 extension_pp$7 = extension_Parser.prototype;

// Convert existing expression atom to assignable pattern
// if possible.

extension_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.

extension_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.

extension_pp$7.parseSpread = function(refDestructuringErrors) {
  var node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  return this.finishNode(node, "SpreadElement")
};

extension_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 !== extension_types$1.name)
    { this.unexpected(); }

  node.argument = this.parseBindingAtom();

  return this.finishNode(node, "RestElement")
};

// Parses lvalue (assignable) atom.

extension_pp$7.parseBindingAtom = function() {
  if (this.options.ecmaVersion >= 6) {
    switch (this.type) {
    case extension_types$1.bracketL:
      var node = this.startNode();
      this.next();
      node.elements = this.parseBindingList(extension_types$1.bracketR, true, true);
      return this.finishNode(node, "ArrayPattern")

    case extension_types$1.braceL:
      return this.parseObj(true)
    }
  }
  return this.parseIdent()
};

extension_pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) { first = false; }
    else { this.expect(extension_types$1.comma); }
    if (allowEmpty && this.type === extension_types$1.comma) {
      elts.push(null);
    } else if (allowTrailingComma && this.afterTrailingComma(close)) {
      break
    } else if (this.type === extension_types$1.ellipsis) {
      var rest = this.parseRestBinding();
      this.parseBindingListItem(rest);
      elts.push(rest);
      if (this.type === extension_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
};

extension_pp$7.parseAssignableListItem = function(allowModifiers) {
  var elem = this.parseMaybeDefault(this.start, this.startLoc);
  this.parseBindingListItem(elem);
  return elem
};

extension_pp$7.parseBindingListItem = function(param) {
  return param
};

// Parses assignment pattern around given atom if possible.

extension_pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  left = left || this.parseBindingAtom();
  if (this.options.ecmaVersion < 6 || !this.eat(extension_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).

extension_pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = extension_BIND_NONE;

  var isBind = bindingType !== extension_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 === extension_BIND_LEXICAL && expr.name === "let")
        { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
      if (checkClashes) {
        if (extension_hasOwn(checkClashes, expr.name))
          { this.raiseRecoverable(expr.start, "Argument name clash"); }
        checkClashes[expr.name] = true;
      }
      if (bindingType !== extension_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");
  }
};

extension_pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = extension_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);
  }
};

extension_pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  if ( bindingType === void 0 ) bindingType = extension_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 extension_TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  this.token = token;
  this.isExpr = !!isExpr;
  this.preserveSpace = !!preserveSpace;
  this.override = override;
  this.generator = !!generator;
};

var extension_types = {
  b_stat: new extension_TokContext("{", false),
  b_expr: new extension_TokContext("{", true),
  b_tmpl: new extension_TokContext("${", false),
  p_stat: new extension_TokContext("(", false),
  p_expr: new extension_TokContext("(", true),
  q_tmpl: new extension_TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  f_stat: new extension_TokContext("function", false),
  f_expr: new extension_TokContext("function", true),
  f_expr_gen: new extension_TokContext("function", true, false, null, true),
  f_gen: new extension_TokContext("function", false, false, null, true)
};

var extension_pp$6 = extension_Parser.prototype;

extension_pp$6.initialContext = function() {
  return [extension_types.b_stat]
};

extension_pp$6.curContext = function() {
  return this.context[this.context.length - 1]
};

extension_pp$6.braceIsBlock = function(prevType) {
  var parent = this.curContext();
  if (parent === extension_types.f_expr || parent === extension_types.f_stat)
    { return true }
  if (prevType === extension_types$1.colon && (parent === extension_types.b_stat || parent === extension_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 === extension_types$1._return || prevType === extension_types$1.name && this.exprAllowed)
    { return extension_lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  if (prevType === extension_types$1._else || prevType === extension_types$1.semi || prevType === extension_types$1.eof || prevType === extension_types$1.parenR || prevType === extension_types$1.arrow)
    { return true }
  if (prevType === extension_types$1.braceL)
    { return parent === extension_types.b_stat }
  if (prevType === extension_types$1._var || prevType === extension_types$1._const || prevType === extension_types$1.name)
    { return false }
  return !this.exprAllowed
};

extension_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
};

extension_pp$6.updateContext = function(prevType) {
  var update, type = this.type;
  if (type.keyword && prevType === extension_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

extension_pp$6.overrideContext = function(tokenCtx) {
  if (this.curContext() !== tokenCtx) {
    this.context[this.context.length - 1] = tokenCtx;
  }
};

// Token-specific context update code

extension_types$1.parenR.updateContext = extension_types$1.braceR.updateContext = function() {
  if (this.context.length === 1) {
    this.exprAllowed = true;
    return
  }
  var out = this.context.pop();
  if (out === extension_types.b_stat && this.curContext().token === "function") {
    out = this.context.pop();
  }
  this.exprAllowed = !out.isExpr;
};

extension_types$1.braceL.updateContext = function(prevType) {
  this.context.push(this.braceIsBlock(prevType) ? extension_types.b_stat : extension_types.b_expr);
  this.exprAllowed = true;
};

extension_types$1.dollarBraceL.updateContext = function() {
  this.context.push(extension_types.b_tmpl);
  this.exprAllowed = true;
};

extension_types$1.parenL.updateContext = function(prevType) {
  var statementParens = prevType === extension_types$1._if || prevType === extension_types$1._for || prevType === extension_types$1._with || prevType === extension_types$1._while;
  this.context.push(statementParens ? extension_types.p_stat : extension_types.p_expr);
  this.exprAllowed = true;
};

extension_types$1.incDec.updateContext = function() {
  // tokExprAllowed stays unchanged
};

extension_types$1._function.updateContext = extension_types$1._class.updateContext = function(prevType) {
  if (prevType.beforeExpr && prevType !== extension_types$1._else &&
      !(prevType === extension_types$1.semi && this.curContext() !== extension_types.p_stat) &&
      !(prevType === extension_types$1._return && extension_lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
      !((prevType === extension_types$1.colon || prevType === extension_types$1.braceL) && this.curContext() === extension_types.b_stat))
    { this.context.push(extension_types.f_expr); }
  else
    { this.context.push(extension_types.f_stat); }
  this.exprAllowed = false;
};

extension_types$1.colon.updateContext = function() {
  if (this.curContext().token === "function") { this.context.pop(); }
  this.exprAllowed = true;
};

extension_types$1.backQuote.updateContext = function() {
  if (this.curContext() === extension_types.q_tmpl)
    { this.context.pop(); }
  else
    { this.context.push(extension_types.q_tmpl); }
  this.exprAllowed = false;
};

extension_types$1.star.updateContext = function(prevType) {
  if (prevType === extension_types$1._function) {
    var index = this.context.length - 1;
    if (this.context[index] === extension_types.f_expr)
      { this.context[index] = extension_types.f_expr_gen; }
    else
      { this.context[index] = extension_types.f_gen; }
  }
  this.exprAllowed = true;
};

extension_types$1.name.updateContext = function(prevType) {
  var allowed = false;
  if (this.options.ecmaVersion >= 6 && prevType !== extension_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 extension_pp$5 = extension_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.

extension_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).

extension_pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  var startPos = this.start, startLoc = this.startLoc;
  var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  if (this.type === extension_types$1.comma) {
    var node = this.startNodeAt(startPos, startLoc);
    node.expressions = [expr];
    while (this.eat(extension_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 `+=`.

extension_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 extension_DestructuringErrors;
    ownDestructuringErrors = true;
  }

  var startPos = this.start, startLoc = this.startLoc;
  if (this.type === extension_types$1.parenL || this.type === extension_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 === extension_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 === extension_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.

extension_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(extension_types$1.question)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.test = expr;
    node.consequent = this.parseMaybeAssign();
    this.expect(extension_types$1.colon);
    node.alternate = this.parseMaybeAssign(forInit);
    return this.finishNode(node, "ConditionalExpression")
  }
  return expr
};

// Start the precedence parser.

extension_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.

extension_pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  var prec = this.type.binop;
  if (prec != null && (!forInit || this.type !== extension_types$1._in)) {
    if (prec > minPrec) {
      var logical = this.type === extension_types$1.logicalOR || this.type === extension_types$1.logicalAND;
      var coalesce = this.type === extension_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 = extension_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 === extension_types$1.coalesce) || (coalesce && (this.type === extension_types$1.logicalOR || this.type === extension_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
};

extension_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.

extension_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 === extension_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" && extension_isLocalVariableAccess(node.argument))
      { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
    else if (node.operator === "delete" && extension_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 === extension_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 !== extension_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(extension_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 extension_isLocalVariableAccess(node) {
  return (
    node.type === "Identifier" ||
    node.type === "ParenthesizedExpression" && extension_isLocalVariableAccess(node.expression)
  )
}

function extension_isPrivateFieldAccess(node) {
  return (
    node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
    node.type === "ChainExpression" && extension_isPrivateFieldAccess(node.expression) ||
    node.type === "ParenthesizedExpression" && extension_isPrivateFieldAccess(node.expression)
  )
}

// Parse call, dot, and `[]`-subscript expressions.

extension_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
};

extension_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;
  }
};

extension_pp$5.shouldParseAsyncArrow = function() {
  return !this.canInsertSemicolon() && this.eat(extension_types$1.arrow)
};

extension_pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
};

extension_pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  var optionalSupported = this.options.ecmaVersion >= 11;
  var optional = optionalSupported && this.eat(extension_types$1.questionDot);
  if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }

  var computed = this.eat(extension_types$1.bracketL);
  if (computed || (optional && this.type !== extension_types$1.parenL && this.type !== extension_types$1.backQuote) || this.eat(extension_types$1.dot)) {
    var node = this.startNodeAt(startPos, startLoc);
    node.object = base;
    if (computed) {
      node.property = this.parseExpression();
      this.expect(extension_types$1.bracketR);
    } else if (this.type === extension_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(extension_types$1.parenL)) {
    var refDestructuringErrors = new extension_DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    var exprList = this.parseExprList(extension_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 === extension_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 `{}`.

extension_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 === extension_types$1.slash) { this.readRegexp(); }

  var node, canBeArrow = this.potentialArrowAt === this.start;
  switch (this.type) {
  case extension_types$1._super:
    if (!this.allowSuper)
      { this.raise(this.start, "'super' keyword outside a method"); }
    node = this.startNode();
    this.next();
    if (this.type === extension_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 !== extension_types$1.dot && this.type !== extension_types$1.bracketL && this.type !== extension_types$1.parenL)
      { this.unexpected(); }
    return this.finishNode(node, "Super")

  case extension_types$1._this:
    node = this.startNode();
    this.next();
    return this.finishNode(node, "ThisExpression")

  case extension_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(extension_types$1._function)) {
      this.overrideContext(extension_types.f_expr);
      return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
    }
    if (canBeArrow && !this.canInsertSemicolon()) {
      if (this.eat(extension_types$1.arrow))
        { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
      if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === extension_types$1.name && !containsEsc &&
          (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
        id = this.parseIdent(false);
        if (this.canInsertSemicolon() || !this.eat(extension_types$1.arrow))
          { this.unexpected(); }
        return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
      }
    }
    return id

  case extension_types$1.regexp:
    var value = this.value;
    node = this.parseLiteral(value.value);
    node.regex = {pattern: value.pattern, flags: value.flags};
    return node

  case extension_types$1.num: case extension_types$1.string:
    return this.parseLiteral(this.value)

  case extension_types$1._null: case extension_types$1._true: case extension_types$1._false:
    node = this.startNode();
    node.value = this.type === extension_types$1._null ? null : this.type === extension_types$1._true;
    node.raw = this.type.keyword;
    this.next();
    return this.finishNode(node, "Literal")

  case extension_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 extension_types$1.bracketL:
    node = this.startNode();
    this.next();
    node.elements = this.parseExprList(extension_types$1.bracketR, true, true, refDestructuringErrors);
    return this.finishNode(node, "ArrayExpression")

  case extension_types$1.braceL:
    this.overrideContext(extension_types.b_expr);
    return this.parseObj(false, refDestructuringErrors)

  case extension_types$1._function:
    node = this.startNode();
    this.next();
    return this.parseFunction(node, 0)

  case extension_types$1._class:
    return this.parseClass(this.startNode(), false)

  case extension_types$1._new:
    return this.parseNew()

  case extension_types$1.backQuote:
    return this.parseTemplate()

  case extension_types$1._import:
    if (this.options.ecmaVersion >= 11) {
      return this.parseExprImport(forNew)
    } else {
      return this.unexpected()
    }

  default:
    return this.parseExprAtomDefault()
  }
};

extension_pp$5.parseExprAtomDefault = function() {
  this.unexpected();
};

extension_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 === extension_types$1.parenL && !forNew) {
    return this.parseDynamicImport(node)
  } else if (this.type === extension_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();
  }
};

extension_pp$5.parseDynamicImport = function(node) {
  this.next(); // skip `(`

  // Parse node.source.
  node.source = this.parseMaybeAssign();

  if (this.options.ecmaVersion >= 16) {
    if (!this.eat(extension_types$1.parenR)) {
      this.expect(extension_types$1.comma);
      if (!this.afterTrailingComma(extension_types$1.parenR)) {
        node.options = this.parseMaybeAssign();
        if (!this.eat(extension_types$1.parenR)) {
          this.expect(extension_types$1.comma);
          if (!this.afterTrailingComma(extension_types$1.parenR)) {
            this.unexpected();
          }
        }
      } else {
        node.options = null;
      }
    } else {
      node.options = null;
    }
  } else {
    // Verify ending.
    if (!this.eat(extension_types$1.parenR)) {
      var errorPos = this.start;
      if (this.eat(extension_types$1.comma) && this.eat(extension_types$1.parenR)) {
        this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
      } else {
        this.unexpected(errorPos);
      }
    }
  }

  return this.finishNode(node, "ImportExpression")
};

extension_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")
};

extension_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")
};

extension_pp$5.parseParenExpression = function() {
  this.expect(extension_types$1.parenL);
  var val = this.parseExpression();
  this.expect(extension_types$1.parenR);
  return val
};

extension_pp$5.shouldParseArrow = function(exprList) {
  return !this.canInsertSemicolon()
};

extension_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 extension_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 !== extension_types$1.parenR) {
      first ? first = false : this.expect(extension_types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(extension_types$1.parenR, true)) {
        lastIsComma = true;
        break
      } else if (this.type === extension_types$1.ellipsis) {
        spreadStart = this.start;
        exprList.push(this.parseParenItem(this.parseRestBinding()));
        if (this.type === extension_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(extension_types$1.parenR);

    if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(extension_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
  }
};

extension_pp$5.parseParenItem = function(item) {
  return item
};

extension_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 extension_acorn_empty = [];

extension_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 === extension_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(extension_types$1.parenL)) { node.arguments = this.parseExprList(extension_types$1.parenR, this.options.ecmaVersion >= 8, false); }
  else { node.arguments = extension_acorn_empty; }
  return this.finishNode(node, "NewExpression")
};

// Parse template expression.

extension_pp$5.parseTemplateElement = function(ref) {
  var isTagged = ref.isTagged;

  var elem = this.startNode();
  if (this.type === extension_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 === extension_types$1.backQuote;
  return this.finishNode(elem, "TemplateElement")
};

extension_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 === extension_types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
    this.expect(extension_types$1.dollarBraceL);
    node.expressions.push(this.parseExpression());
    this.expect(extension_types$1.braceR);
    node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  }
  this.next();
  return this.finishNode(node, "TemplateLiteral")
};

extension_pp$5.isAsyncProp = function(prop) {
  return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
    (this.type === extension_types$1.name || this.type === extension_types$1.num || this.type === extension_types$1.string || this.type === extension_types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === extension_types$1.star)) &&
    !extension_lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};

// Parse an object literal or binding pattern.

extension_pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  var node = this.startNode(), first = true, propHash = {};
  node.properties = [];
  this.next();
  while (!this.eat(extension_types$1.braceR)) {
    if (!first) {
      this.expect(extension_types$1.comma);
      if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(extension_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")
};

extension_pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  if (this.options.ecmaVersion >= 9 && this.eat(extension_types$1.ellipsis)) {
    if (isPattern) {
      prop.argument = this.parseIdent(false);
      if (this.type === extension_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 === extension_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(extension_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(extension_types$1.star);
    this.parsePropertyName(prop);
  } else {
    isAsync = false;
  }
  this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  return this.finishNode(prop, "Property")
};

extension_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"); }
  }
};

extension_pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  if ((isGenerator || isAsync) && this.type === extension_types$1.colon)
    { this.unexpected(); }

  if (this.eat(extension_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 === extension_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 !== extension_types$1.comma && this.type !== extension_types$1.braceR && this.type !== extension_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 === extension_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(); }
};

extension_pp$5.parsePropertyName = function(prop) {
  if (this.options.ecmaVersion >= 6) {
    if (this.eat(extension_types$1.bracketL)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssign();
      this.expect(extension_types$1.bracketR);
      return prop.key
    } else {
      prop.computed = false;
    }
  }
  return prop.key = this.type === extension_types$1.num || this.type === extension_types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
};

// Initialize empty function node.

extension_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.

extension_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(extension_functionFlags(isAsync, node.generator) | extension_SCOPE_SUPER | (allowDirectSuper ? extension_SCOPE_DIRECT_SUPER : 0));

  this.expect(extension_types$1.parenL);
  node.params = this.parseBindingList(extension_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.

extension_pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;

  this.enterScope(extension_functionFlags(isAsync, false) | extension_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.

extension_pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  var isExpression = isArrowFunction && this.type !== extension_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, extension_BIND_OUTSIDE); }
    node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
    node.expression = false;
    this.adaptDirectivePrologue(node.body.body);
    this.labels = oldLabels;
  }
  this.exitScope();
};

extension_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.

extension_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, extension_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).

extension_pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (!first) {
      this.expect(extension_types$1.comma);
      if (allowTrailingComma && this.afterTrailingComma(close)) { break }
    } else { first = false; }

    var elt = (void 0);
    if (allowEmpty && this.type === extension_types$1.comma)
      { elt = null; }
    else if (this.type === extension_types$1.ellipsis) {
      elt = this.parseSpread(refDestructuringErrors);
      if (refDestructuringErrors && this.type === extension_types$1.comma && refDestructuringErrors.trailingComma < 0)
        { refDestructuringErrors.trailingComma = this.start; }
    } else {
      elt = this.parseMaybeAssign(false, refDestructuringErrors);
    }
    elts.push(elt);
  }
  return elts
};

extension_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.

extension_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
};

extension_pp$5.parseIdentNode = function() {
  var node = this.startNode();
  if (this.type === extension_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 = extension_types$1.name;
  } else {
    this.unexpected();
  }
  return node
};

extension_pp$5.parsePrivateIdent = function() {
  var node = this.startNode();
  if (this.type === extension_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.

extension_pp$5.parseYield = function(forInit) {
  if (!this.yieldPos) { this.yieldPos = this.start; }

  var node = this.startNode();
  this.next();
  if (this.type === extension_types$1.semi || this.canInsertSemicolon() || (this.type !== extension_types$1.star && !this.type.startsExpr)) {
    node.delegate = false;
    node.argument = null;
  } else {
    node.delegate = this.eat(extension_types$1.star);
    node.argument = this.parseMaybeAssign(forInit);
  }
  return this.finishNode(node, "YieldExpression")
};

extension_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 extension_pp$4 = extension_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.

extension_pp$4.raise = function(pos, message) {
  var loc = extension_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
};

extension_pp$4.raiseRecoverable = extension_pp$4.raise;

extension_pp$4.curPosition = function() {
  if (this.options.locations) {
    return new extension_Position(this.curLine, this.pos - this.lineStart)
  }
};

var extension_pp$3 = extension_Parser.prototype;

var extension_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.

extension_pp$3.enterScope = function(flags) {
  this.scopeStack.push(new extension_Scope(flags));
};

extension_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.
extension_pp$3.treatFunctionsAsVarInScope = function(scope) {
  return (scope.flags & extension_SCOPE_FUNCTION) || !this.inModule && (scope.flags & extension_SCOPE_TOP)
};

extension_pp$3.declareName = function(name, bindingType, pos) {
  var redeclared = false;
  if (bindingType === extension_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 & extension_SCOPE_TOP))
      { delete this.undefinedExports[name]; }
  } else if (bindingType === extension_BIND_SIMPLE_CATCH) {
    var scope$1 = this.currentScope();
    scope$1.lexical.push(name);
  } else if (bindingType === extension_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 & extension_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 & extension_SCOPE_TOP))
        { delete this.undefinedExports[name]; }
      if (scope$3.flags & extension_SCOPE_VAR) { break }
    }
  }
  if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
};

extension_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;
  }
};

extension_pp$3.currentScope = function() {
  return this.scopeStack[this.scopeStack.length - 1]
};

extension_pp$3.currentVarScope = function() {
  for (var i = this.scopeStack.length - 1;; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & extension_SCOPE_VAR) { return scope }
  }
};

// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
extension_pp$3.currentThisScope = function() {
  for (var i = this.scopeStack.length - 1;; i--) {
    var scope = this.scopeStack[i];
    if (scope.flags & extension_SCOPE_VAR && !(scope.flags & extension_SCOPE_ARROW)) { return scope }
  }
};

var extension_Node = function Node(parser, pos, loc) {
  this.type = "";
  this.start = pos;
  this.end = 0;
  if (parser.options.locations)
    { this.loc = new extension_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 extension_pp$2 = extension_Parser.prototype;

extension_pp$2.startNode = function() {
  return new extension_Node(this, this.start, this.startLoc)
};

extension_pp$2.startNodeAt = function(pos, loc) {
  return new extension_Node(this, pos, loc)
};

// Finish an AST node, adding `type` and `end` properties.

function extension_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
}

extension_pp$2.finishNode = function(node, type) {
  return extension_finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
};

// Finish node at given position

extension_pp$2.finishNodeAt = function(node, type, pos, loc) {
  return extension_finishNodeAt.call(this, node, type, pos, loc)
};

extension_pp$2.copyNode = function(node) {
  var newNode = new extension_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 extension_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 extension_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 extension_ecma10BinaryProperties = extension_ecma9BinaryProperties + " Extended_Pictographic";
var extension_ecma11BinaryProperties = extension_ecma10BinaryProperties;
var extension_ecma12BinaryProperties = extension_ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
var extension_ecma13BinaryProperties = extension_ecma12BinaryProperties;
var extension_ecma14BinaryProperties = extension_ecma13BinaryProperties;

var extension_unicodeBinaryProperties = {
  9: extension_ecma9BinaryProperties,
  10: extension_ecma10BinaryProperties,
  11: extension_ecma11BinaryProperties,
  12: extension_ecma12BinaryProperties,
  13: extension_ecma13BinaryProperties,
  14: extension_ecma14BinaryProperties
};

// #table-binary-unicode-properties-of-strings
var extension_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 extension_unicodeBinaryPropertiesOfStrings = {
  9: "",
  10: "",
  11: "",
  12: "",
  13: "",
  14: extension_ecma14BinaryPropertiesOfStrings
};

// #table-unicode-general-category-values
var extension_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 extension_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 extension_ecma10ScriptValues = extension_ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var extension_ecma11ScriptValues = extension_ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var extension_ecma12ScriptValues = extension_ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var extension_ecma13ScriptValues = extension_ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
var extension_ecma14ScriptValues = extension_ecma13ScriptValues + " " + extension_scriptValuesAddedInUnicode;

var extension_unicodeScriptValues = {
  9: extension_ecma9ScriptValues,
  10: extension_ecma10ScriptValues,
  11: extension_ecma11ScriptValues,
  12: extension_ecma12ScriptValues,
  13: extension_ecma13ScriptValues,
  14: extension_ecma14ScriptValues
};

var extension_acorn_data = {};
function extension_buildUnicodeData(ecmaVersion) {
  var d = extension_acorn_data[ecmaVersion] = {
    binary: extension_wordsRegexp(extension_unicodeBinaryProperties[ecmaVersion] + " " + extension_unicodeGeneralCategoryValues),
    binaryOfStrings: extension_wordsRegexp(extension_unicodeBinaryPropertiesOfStrings[ecmaVersion]),
    nonBinary: {
      General_Category: extension_wordsRegexp(extension_unicodeGeneralCategoryValues),
      Script: extension_wordsRegexp(extension_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 extension_i = 0, extension_acorn_list = [9, 10, 11, 12, 13, 14]; extension_i < extension_acorn_list.length; extension_i += 1) {
  var extension_ecmaVersion = extension_acorn_list[extension_i];

  extension_buildUnicodeData(extension_ecmaVersion);
}

var extension_pp$1 = extension_Parser.prototype;

// Track disjunction structure to determine whether a duplicate
// capture group name is allowed because it is in a separate branch.
var extension_BranchID = function BranchID(parent, base) {
  // Parent disjunction branch
  this.parent = parent;
  // Identifies this set of sibling branches
  this.base = base || this;
};

extension_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
};

extension_BranchID.prototype.sibling = function sibling () {
  return new extension_BranchID(this.parent, this.base)
};

var extension_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 = extension_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;
};

extension_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;
  }
};

extension_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).
extension_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
};

extension_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
};

extension_RegExpValidationState.prototype.current = function current (forceU) {
    if ( forceU === void 0 ) forceU = false;

  return this.at(this.pos, forceU)
};

extension_RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
    if ( forceU === void 0 ) forceU = false;

  return this.at(this.nextIndex(this.pos, forceU), forceU)
};

extension_RegExpValidationState.prototype.advance = function advance (forceU) {
    if ( forceU === void 0 ) forceU = false;

  this.pos = this.nextIndex(this.pos, forceU);
};

extension_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
};

extension_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}
 */
extension_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 extension_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}
 */
extension_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 && extension_hasProp(state.groupNames)) {
    state.switchN = true;
    this.regexp_pattern(state);
  }
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
extension_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
extension_pp$1.regexp_disjunction = function(state) {
  var trackDisjunction = this.options.ecmaVersion >= 16;
  if (trackDisjunction) { state.branchID = new extension_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
extension_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
extension_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
extension_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
extension_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
extension_pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  return (
    state.eat(0x2A /* * */) ||
    state.eat(0x2B /* + */) ||
    state.eat(0x3F /* ? */) ||
    this.regexp_eatBracedQuantifier(state, noError)
  )
};
extension_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
extension_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)
  )
};
extension_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
};
extension_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
};
extension_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
extension_pp$1.regexp_eatModifiers = function(state) {
  var modifiers = "";
  var ch = 0;
  while ((ch = state.current()) !== -1 && extension_isRegularExpressionModifier(ch)) {
    modifiers += extension_codePointToString(ch);
    state.advance();
  }
  return modifiers
};
// RegularExpressionModifier :: one of
//   `i` `m` `s`
function extension_isRegularExpressionModifier(ch) {
  return ch === 0x69 /* i */ || ch === 0x6d /* m */ || ch === 0x73 /* s */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
extension_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
extension_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
extension_pp$1.regexp_eatSyntaxCharacter = function(state) {
  var ch = state.current();
  if (extension_isSyntaxCharacter(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }
  return false
};
function extension_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.
extension_pp$1.regexp_eatPatternCharacters = function(state) {
  var start = state.pos;
  var ch = 0;
  while ((ch = state.current()) !== -1 && !extension_isSyntaxCharacter(ch)) {
    state.advance();
  }
  return state.pos !== start
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
extension_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
extension_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.
extension_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.
extension_pp$1.regexp_eatRegExpIdentifierName = function(state) {
  state.lastStringValue = "";
  if (this.regexp_eatRegExpIdentifierStart(state)) {
    state.lastStringValue += extension_codePointToString(state.lastIntValue);
    while (this.regexp_eatRegExpIdentifierPart(state)) {
      state.lastStringValue += extension_codePointToString(state.lastIntValue);
    }
    return true
  }
  return false
};

// RegExpIdentifierStart ::
//   UnicodeIDStart
//   `$`
//   `_`
//   `\` RegExpUnicodeEscapeSequence[+U]
extension_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 (extension_isRegExpIdentifierStart(ch)) {
    state.lastIntValue = ch;
    return true
  }

  state.pos = start;
  return false
};
function extension_isRegExpIdentifierStart(ch) {
  return extension_isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
}

// RegExpIdentifierPart ::
//   UnicodeIDContinue
//   `$`
//   `_`
//   `\` RegExpUnicodeEscapeSequence[+U]
//   <ZWNJ>
//   <ZWJ>
extension_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 (extension_isRegExpIdentifierPart(ch)) {
    state.lastIntValue = ch;
    return true
  }

  state.pos = start;
  return false
};
function extension_isRegExpIdentifierPart(ch) {
  return extension_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
extension_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
};
extension_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
};
extension_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
extension_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)
  )
};
extension_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
};
extension_pp$1.regexp_eatZero = function(state) {
  if (state.current() === 0x30 /* 0 */ && !extension_isDecimalDigit(state.lookahead())) {
    state.lastIntValue = 0;
    state.advance();
    return true
  }
  return false
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
extension_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
extension_pp$1.regexp_eatControlLetter = function(state) {
  var ch = state.current();
  if (extension_isControlLetter(ch)) {
    state.lastIntValue = ch % 0x20;
    state.advance();
    return true
  }
  return false
};
function extension_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
extension_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 /* } */) &&
      extension_isValidUnicode(state.lastIntValue)
    ) {
      return true
    }
    if (switchU) {
      state.raise("Invalid unicode escape");
    }
    state.pos = start;
  }

  return false
};
function extension_isValidUnicode(ch) {
  return ch >= 0 && ch <= 0x10FFFF
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
extension_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
extension_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 extension_CharSetNone = 0; // Nothing parsed
var extension_CharSetOk = 1; // Construct parsed, cannot contain strings
var extension_CharSetString = 2; // Construct parsed, can contain strings

// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
extension_pp$1.regexp_eatCharacterClassEscape = function(state) {
  var ch = state.current();

  if (extension_isCharacterClassEscape(ch)) {
    state.lastIntValue = -1;
    state.advance();
    return extension_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 === extension_CharSetString) { state.raise("Invalid property name"); }
      return result
    }
    state.raise("Invalid property name");
  }

  return extension_CharSetNone
};

function extension_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
extension_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 extension_CharSetOk
    }
  }
  state.pos = start;

  // LoneUnicodePropertyNameOrValue
  if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
    var nameOrValue = state.lastStringValue;
    return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
  }
  return extension_CharSetNone
};

extension_pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  if (!extension_hasOwn(state.unicodeProperties.nonBinary, name))
    { state.raise("Invalid property name"); }
  if (!state.unicodeProperties.nonBinary[name].test(value))
    { state.raise("Invalid property value"); }
};

extension_pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  if (state.unicodeProperties.binary.test(nameOrValue)) { return extension_CharSetOk }
  if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return extension_CharSetString }
  state.raise("Invalid property name");
};

// UnicodePropertyName ::
//   UnicodePropertyNameCharacters
extension_pp$1.regexp_eatUnicodePropertyName = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (extension_isUnicodePropertyNameCharacter(ch = state.current())) {
    state.lastStringValue += extension_codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== ""
};

function extension_isUnicodePropertyNameCharacter(ch) {
  return extension_isControlLetter(ch) || ch === 0x5F /* _ */
}

// UnicodePropertyValue ::
//   UnicodePropertyValueCharacters
extension_pp$1.regexp_eatUnicodePropertyValue = function(state) {
  var ch = 0;
  state.lastStringValue = "";
  while (extension_isUnicodePropertyValueCharacter(ch = state.current())) {
    state.lastStringValue += extension_codePointToString(ch);
    state.advance();
  }
  return state.lastStringValue !== ""
};
function extension_isUnicodePropertyValueCharacter(ch) {
  return extension_isUnicodePropertyNameCharacter(ch) || extension_isDecimalDigit(ch)
}

// LoneUnicodePropertyNameOrValue ::
//   UnicodePropertyValueCharacters
extension_pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  return this.regexp_eatUnicodePropertyValue(state)
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
extension_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 === extension_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
extension_pp$1.regexp_classContents = function(state) {
  if (state.current() === 0x5D /* ] */) { return extension_CharSetOk }
  if (state.switchV) { return this.regexp_classSetExpression(state) }
  this.regexp_nonEmptyClassRanges(state);
  return extension_CharSetOk
};

// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
extension_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
extension_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 */ || extension_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
extension_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
extension_pp$1.regexp_classSetExpression = function(state) {
  var result = extension_CharSetOk, subResult;
  if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
    if (subResult === extension_CharSetString) { result = extension_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 !== extension_CharSetString) { result = extension_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 === extension_CharSetString) { result = extension_CharSetString; }
  }
};

// https://tc39.es/ecma262/#prod-ClassSetRange
extension_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
extension_pp$1.regexp_eatClassSetOperand = function(state) {
  if (this.regexp_eatClassSetCharacter(state)) { return extension_CharSetOk }
  return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
};

// https://tc39.es/ecma262/#prod-NestedClass
extension_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 === extension_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
extension_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
extension_pp$1.regexp_classStringDisjunctionContents = function(state) {
  var result = this.regexp_classString(state);
  while (state.eat(0x7C /* | */)) {
    if (this.regexp_classString(state) === extension_CharSetString) { result = extension_CharSetString; }
  }
  return result
};

// https://tc39.es/ecma262/#prod-ClassString
// https://tc39.es/ecma262/#prod-NonEmptyClassString
extension_pp$1.regexp_classString = function(state) {
  var count = 0;
  while (this.regexp_eatClassSetCharacter(state)) { count++; }
  return count === 1 ? extension_CharSetOk : extension_CharSetString
};

// https://tc39.es/ecma262/#prod-ClassSetCharacter
extension_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() && extension_isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
  if (extension_isClassSetSyntaxCharacter(ch)) { return false }
  state.advance();
  state.lastIntValue = ch;
  return true
};

// https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
function extension_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 extension_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
extension_pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  var ch = state.current();
  if (extension_isClassSetReservedPunctuator(ch)) {
    state.lastIntValue = ch;
    state.advance();
    return true
  }
  return false
};

// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
function extension_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
extension_pp$1.regexp_eatClassControlLetter = function(state) {
  var ch = state.current();
  if (extension_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
extension_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
extension_pp$1.regexp_eatDecimalDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (extension_isDecimalDigit(ch = state.current())) {
    state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
    state.advance();
  }
  return state.pos !== start
};
function extension_isDecimalDigit(ch) {
  return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
}

// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
extension_pp$1.regexp_eatHexDigits = function(state) {
  var start = state.pos;
  var ch = 0;
  state.lastIntValue = 0;
  while (extension_isHexDigit(ch = state.current())) {
    state.lastIntValue = 16 * state.lastIntValue + extension_hexToInt(ch);
    state.advance();
  }
  return state.pos !== start
};
function extension_isHexDigit(ch) {
  return (
    (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
    (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
    (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  )
}
function extension_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).
extension_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
extension_pp$1.regexp_eatOctalDigit = function(state) {
  var ch = state.current();
  if (extension_isOctalDigit(ch)) {
    state.lastIntValue = ch - 0x30; /* 0 */
    state.advance();
    return true
  }
  state.lastIntValue = 0;
  return false
};
function extension_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
extension_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 (!extension_isHexDigit(ch)) {
      state.pos = start;
      return false
    }
    state.lastIntValue = 16 * state.lastIntValue + extension_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 extension_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 extension_SourceLocation(p, p.startLoc, p.endLoc); }
  if (p.options.ranges)
    { this.range = [p.start, p.end]; }
};

// ## Tokenizer

var extension_pp = extension_Parser.prototype;

// Move to the next token

extension_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 extension_Token(this)); }

  this.lastTokEnd = this.end;
  this.lastTokStart = this.start;
  this.lastTokEndLoc = this.endLoc;
  this.lastTokStartLoc = this.startLoc;
  this.nextToken();
};

extension_pp.getToken = function() {
  this.next();
  return new extension_Token(this)
};

// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
  { extension_pp[Symbol.iterator] = function() {
    var this$1$1 = this;

    return {
      next: function () {
        var token = this$1$1.getToken();
        return {
          done: token.type === extension_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.

extension_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(extension_types$1.eof) }

  if (curContext.override) { return curContext.override(this) }
  else { this.readToken(this.fullCharCodeAtPos()); }
};

extension_pp.readToken = function(code) {
  // Identifier or keyword. '\uXXXX' sequences are allowed in
  // identifiers, so '\' also dispatches to that.
  if (extension_isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
    { return this.readWord() }

  return this.getTokenFromCode(code)
};

extension_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
};

extension_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 = extension_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()); }
};

extension_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 && !extension_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.

extension_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 && extension_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.

extension_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.
//
extension_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(extension_types$1.ellipsis)
  } else {
    ++this.pos;
    return this.finishToken(extension_types$1.dot)
  }
};

extension_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(extension_types$1.assign, 2) }
  return this.finishOp(extension_types$1.slash, 1)
};

extension_pp.readToken_mult_modulo_exp = function(code) { // '%*'
  var next = this.input.charCodeAt(this.pos + 1);
  var size = 1;
  var tokentype = code === 42 ? extension_types$1.star : extension_types$1.modulo;

  // exponentiation operator ** and **=
  if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
    ++size;
    tokentype = extension_types$1.starstar;
    next = this.input.charCodeAt(this.pos + 2);
  }

  if (next === 61) { return this.finishOp(extension_types$1.assign, size + 1) }
  return this.finishOp(tokentype, size)
};

extension_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(extension_types$1.assign, 3) }
    }
    return this.finishOp(code === 124 ? extension_types$1.logicalOR : extension_types$1.logicalAND, 2)
  }
  if (next === 61) { return this.finishOp(extension_types$1.assign, 2) }
  return this.finishOp(code === 124 ? extension_types$1.bitwiseOR : extension_types$1.bitwiseAND, 1)
};

extension_pp.readToken_caret = function() { // '^'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) { return this.finishOp(extension_types$1.assign, 2) }
  return this.finishOp(extension_types$1.bitwiseXOR, 1)
};

extension_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 || extension_lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
      // A `-->` line comment
      this.skipLineComment(3);
      this.skipSpace();
      return this.nextToken()
    }
    return this.finishOp(extension_types$1.incDec, 2)
  }
  if (next === 61) { return this.finishOp(extension_types$1.assign, 2) }
  return this.finishOp(extension_types$1.plusMin, 1)
};

extension_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(extension_types$1.assign, size + 1) }
    return this.finishOp(extension_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(extension_types$1.relational, size)
};

extension_pp.readToken_eq_excl = function(code) { // '=!'
  var next = this.input.charCodeAt(this.pos + 1);
  if (next === 61) { return this.finishOp(extension_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(extension_types$1.arrow)
  }
  return this.finishOp(code === 61 ? extension_types$1.eq : extension_types$1.prefix, 1)
};

extension_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(extension_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(extension_types$1.assign, 3) }
      }
      return this.finishOp(extension_types$1.coalesce, 2)
    }
  }
  return this.finishOp(extension_types$1.question, 1)
};

extension_pp.readToken_numberSign = function() { // '#'
  var ecmaVersion = this.options.ecmaVersion;
  var code = 35; // '#'
  if (ecmaVersion >= 13) {
    ++this.pos;
    code = this.fullCharCodeAtPos();
    if (extension_isIdentifierStart(code, true) || code === 92 /* '\' */) {
      return this.finishToken(extension_types$1.privateId, this.readWord1())
    }
  }

  this.raise(this.pos, "Unexpected character '" + extension_codePointToString(code) + "'");
};

extension_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(extension_types$1.parenL)
  case 41: ++this.pos; return this.finishToken(extension_types$1.parenR)
  case 59: ++this.pos; return this.finishToken(extension_types$1.semi)
  case 44: ++this.pos; return this.finishToken(extension_types$1.comma)
  case 91: ++this.pos; return this.finishToken(extension_types$1.bracketL)
  case 93: ++this.pos; return this.finishToken(extension_types$1.bracketR)
  case 123: ++this.pos; return this.finishToken(extension_types$1.braceL)
  case 125: ++this.pos; return this.finishToken(extension_types$1.braceR)
  case 58: ++this.pos; return this.finishToken(extension_types$1.colon)

  case 96: // '`'
    if (this.options.ecmaVersion < 6) { break }
    ++this.pos;
    return this.finishToken(extension_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(extension_types$1.prefix, 1)

  case 35: // '#'
    return this.readToken_numberSign()
  }

  this.raise(this.pos, "Unexpected character '" + extension_codePointToString(code) + "'");
};

extension_pp.finishOp = function(type, size) {
  var str = this.input.slice(this.pos, this.pos + size);
  this.pos += size;
  return this.finishToken(type, str)
};

extension_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 (extension_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 extension_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(extension_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.

extension_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 extension_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 extension_stringToBigInt(str) {
  if (typeof BigInt !== "function") {
    return null
  }

  // `BigInt(value)` throws syntax error if the string contains numeric separators.
  return BigInt(str.replace(/_/g, ""))
}

extension_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 = extension_stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
  } else if (extension_isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  return this.finishToken(extension_types$1.num, val)
};

// Read an integer, octal integer, or floating-point number.

extension_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 = extension_stringToBigInt(this.input.slice(start, this.pos));
    ++this.pos;
    if (extension_isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
    return this.finishToken(extension_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 (extension_isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }

  var val = extension_stringToNumber(this.input.slice(start, this.pos), octal);
  return this.finishToken(extension_types$1.num, val)
};

// Read a string value, interpreting backslash-escapes.

extension_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
};

extension_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 (extension_isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
      ++this.pos;
    }
  }
  out += this.input.slice(chunkStart, this.pos++);
  return this.finishToken(extension_types$1.string, out)
};

// Reads template string tokens.

var extension_INVALID_TEMPLATE_ESCAPE_ERROR = {};

extension_pp.tryReadTemplateToken = function() {
  this.inTemplateElement = true;
  try {
    this.readTmplToken();
  } catch (err) {
    if (err === extension_INVALID_TEMPLATE_ESCAPE_ERROR) {
      this.readInvalidTemplateToken();
    } else {
      throw err
    }
  }

  this.inTemplateElement = false;
};

extension_pp.invalidStringToken = function(position, message) {
  if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
    throw extension_INVALID_TEMPLATE_ESCAPE_ERROR
  } else {
    this.raise(position, message);
  }
};

extension_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 === extension_types$1.template || this.type === extension_types$1.invalidTemplate)) {
        if (ch === 36) {
          this.pos += 2;
          return this.finishToken(extension_types$1.dollarBraceL)
        } else {
          ++this.pos;
          return this.finishToken(extension_types$1.backQuote)
        }
      }
      out += this.input.slice(chunkStart, this.pos);
      return this.finishToken(extension_types$1.template, out)
    }
    if (ch === 92) { // '\'
      out += this.input.slice(chunkStart, this.pos);
      out += this.readEscapedChar(true);
      chunkStart = this.pos;
    } else if (extension_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
extension_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(extension_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

extension_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 extension_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 (extension_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').

extension_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.

extension_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 (extension_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 ? extension_isIdentifierStart : extension_isIdentifierChar)(esc, astral))
        { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
      word += extension_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.

extension_pp.readWord = function() {
  var word = this.readWord1();
  var type = extension_types$1.name;
  if (this.keywords.test(word)) {
    type = extension_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 extension_version = "8.14.0";

extension_Parser.acorn = {
  Parser: extension_Parser,
  version: extension_version,
  defaultOptions: extension_defaultOptions,
  Position: extension_Position,
  SourceLocation: extension_SourceLocation,
  getLineInfo: extension_getLineInfo,
  Node: extension_Node,
  TokenType: extension_TokenType,
  tokTypes: extension_types$1,
  keywordTypes: extension_keywords,
  TokContext: extension_TokContext,
  tokContexts: extension_types,
  isIdentifierChar: extension_isIdentifierChar,
  isIdentifierStart: extension_isIdentifierStart,
  Token: extension_Token,
  isNewLine: extension_isNewLine,
  lineBreak: extension_lineBreak,
  lineBreakG: extension_lineBreakG,
  nonASCIIwhitespace: extension_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 extension_parse(input, options) {
  return extension_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 extension_parseExpressionAt(input, pos, options) {
  return extension_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 extension_tokenizer(input, options) {
  return extension_Parser.tokenizer(input, options)
}



;// ../../node_modules/arquero/src/expression/constants.js
/* harmony default export */ const extension_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 extension_PARSER_OPT = { ecmaVersion: 11 };
const extension_DEFAULT_PARAM_ID = '$';
const extension_DEFAULT_TUPLE_ID = 'd';
const extension_DEFAULT_TUPLE_ID1 = 'd1';
const extension_DEFAULT_TUPLE_ID2 = 'd2';

const extension_NO = msg => (node, ctx) => ctx.error(node, msg + ' not allowed');
const extension_ERROR_AGGREGATE = extension_NO('Aggregate function');
const extension_ERROR_WINDOW = extension_NO('Window function');
const extension_ERROR_ARGUMENT = 'Invalid argument';
const extension_ERROR_COLUMN = 'Invalid column reference';
const extension_ERROR_AGGRONLY = extension_ERROR_COLUMN + ' (must be input to an aggregate function)';
const extension_ERROR_FUNCTION = 'Invalid function call';
const extension_ERROR_MEMBER = 'Invalid member expression';
const extension_ERROR_OP_PARAMETER = 'Invalid operator parameter';
const extension_ERROR_PARAM = 'Invalid param reference';
const extension_ERROR_VARIABLE = 'Invalid variable reference';
const extension_ERROR_VARIABLE_OP = 'Variable not accessible in operator call';
const extension_ERROR_DECLARATION = 'Unsupported variable declaration';
const extension_ERROR_DESTRUCTURE = 'Unsupported destructuring pattern';
const extension_ERROR_CLOSURE = 'Table expressions do not support closures';
const extension_ERROR_ESCAPE = 'Use aq.escape(fn) to use a function as-is (including closures)';
const extension_ERROR_USE_PARAMS = 'use table.params({ name: value }) to define dynamic parameters';
const extension_ERROR_ADD_FUNCTION = 'use aq.addFunction(name, fn) to add new op functions';
const extension_ERROR_VARIABLE_NOTE = `\nNote: ${extension_ERROR_CLOSURE}. ${extension_ERROR_ESCAPE}, or ${extension_ERROR_USE_PARAMS}.`;
const extension_ERROR_FUNCTION_NOTE = `\nNote: ${extension_ERROR_CLOSURE}. ${extension_ERROR_ESCAPE}, or ${extension_ERROR_ADD_FUNCTION}.`;
const extension_ERROR_ROW_OBJECT = `The ${extension_row_object_ROW_OBJECT} method is not valid in multi-table expressions.`;

function extension_parseExpression(ctx, spec) {
  const ast = extension_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 (extension_isFunctionExpression(node)) {
    extension_parseFunction(node, ctx);
    node = node.body;
  } else if (ctx.join) {
    ctx.scope.add(ctx.tuple1 = extension_DEFAULT_TUPLE_ID1);
    ctx.scope.add(ctx.tuple2 = extension_DEFAULT_TUPLE_ID2);
    ctx.scope.add(ctx.$param = extension_DEFAULT_PARAM_ID);
  } else {
    ctx.scope.add(ctx.tuple = extension_DEFAULT_TUPLE_ID);
    ctx.scope.add(ctx.$param = extension_DEFAULT_PARAM_ID);
  }

  // rewrite column references & function calls
  extension_walk(node, ctx, extension_parse_expression_visitors);

  return ctx.root;
}

function extension_parseAST(expr) {
  try {
    const code = expr.field ? extension_fieldRef(expr)
      : extension_is_array(expr) ? extension_to_string(expr)
      : expr;
    return extension_parse(`expr=(${code})`, extension_PARSER_OPT).body[0].expression.right;
  } catch (err) {
    extension_util_error(`Expression parse error: ${expr+''}`, err);
  }
}

function extension_fieldRef(expr) {
  const col = JSON.stringify(expr+'');
  return !(expr.table || 0) ? `d=>d[${col}]` : `(a,b)=>b[${col}]`;
}

const extension_parse_expression_visitors = {
  FunctionDeclaration: extension_NO('Function definitions'),
  ForStatement: extension_NO('For loops'),
  ForOfStatement: extension_NO('For-of loops'),
  ForInStatement: extension_NO('For-in loops'),
  WhileStatement: extension_NO('While loops'),
  DoWhileStatement: extension_NO('Do-while loops'),
  AwaitExpression: extension_NO('Await expressions'),
  ArrowFunctionExpression: extension_NO('Function definitions'),
  AssignmentExpression: extension_NO('Assignments'),
  FunctionExpression: extension_NO('Function definitions'),
  NewExpression: extension_NO('Use of "new"'),
  UpdateExpression: extension_NO('Update expressions'),

  VariableDeclarator(node, ctx) {
    extension_handleDeclaration(node.id, ctx);
  },
  Identifier(node, ctx, parent) {
    if (extension_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, extension_ERROR_VARIABLE, extension_ERROR_VARIABLE_NOTE);
    }
  },
  CallExpression(node, ctx) {
    const name = extension_functionName(node.callee);
    const def = extension_getAggregate(name) || extension_getWindow(name);

    // parse operator and rewrite invocation
    if (def) {
      if ((ctx.join || ctx.aggregate === false) && extension_hasAggregate(def)) {
        extension_ERROR_AGGREGATE(node, ctx);
      }
      if ((ctx.join || ctx.window === false) && extension_hasWindow(def)) {
        extension_ERROR_WINDOW(node, ctx);
      }

      ctx.$op = 1;
      if (ctx.ast) {
        extension_updateFunctionNode(node, name, ctx);
        node.arguments.forEach(arg => extension_walk(arg, ctx, extension_opVisitors));
      } else {
        const op = ctx.op(extension_parseOperator(ctx, def, name, node.arguments));
        Object.assign(node, { type: extension_constants_Op, name: op.id });
      }
      ctx.$op = 0;
      return false;
    } else if (extension_hasFunction(name)) {
      extension_updateFunctionNode(node, name, ctx);
    } else {
      ctx.error(node, extension_ERROR_FUNCTION, extension_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 (!extension_is(extension_Identifier, object)) return;
    const { name } = object;

    // allow use of Math prefix to access constant values
    if (extension_isMath(node) && extension_is(extension_Identifier, property)
        && extension_util_has(extension_constants, property.name)) {
      extension_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 extension_spliceMember(node, index, ctx, extension_checkColumn, parent);
    } else if (name === ctx.$param) {
      // replace member expression with param ref
      return extension_spliceMember(node, index, ctx, extension_checkParam);
    } else if (ctx.paramsRef.has(name)) {
      extension_updateParameterNode(node, ctx.paramsRef.get(name));
    } else if (ctx.columnRef.has(name)) {
      extension_updateColumnNode(object, name, ctx, node);
    } else if (extension_util_has(ctx.params, name)) {
      extension_updateParameterNode(object, name);
    }
  }
};

function extension_spliceMember(node, index, ctx, check, parent) {
  const { property, computed } = node;
  let name;

  if (!computed) {
    name = property.name;
  } else if (extension_is(extension_Literal, property)) {
    name = property.value;
  } else try {
    name = ctx.param(property);
  } catch (e) {
    ctx.error(node, extension_ERROR_MEMBER);
  }

  check(node, name, index, ctx, parent);
  return false;
}

const extension_opVisitors = {
  ...extension_parse_expression_visitors,
  VariableDeclarator: extension_NO('Variable declaration in operator call'),
  Identifier(node, ctx, parent) {
    if (extension_handleIdentifier(node, ctx, parent)) {
      ctx.error(node, extension_ERROR_VARIABLE_OP);
    }
  },
  CallExpression(node, ctx) {
    const name = extension_functionName(node.callee);

    // rewrite if built-in function
    if (extension_hasFunction(name)) {
      extension_updateFunctionNode(node, name, ctx);
    } else {
      ctx.error(node, extension_ERROR_FUNCTION, extension_ERROR_FUNCTION_NOTE);
    }
  }
};

function extension_parseFunction(node, ctx) {
  if (node.generator) extension_NO('Generator functions')(node, ctx);
  if (node.async) extension_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) {
    extension_parseRef(ctx, params[0], 'tuple1', setc(1));
    if (len > 1) extension_parseRef(ctx, params[1], 'tuple2', setc(2));
    if (len > 2) extension_parseRef(ctx, params[2], '$param', setp);
  } else {
    extension_parseRef(ctx, params[0], 'tuple', setc(0));
    if (len > 1) extension_parseRef(ctx, params[1], '$param', setp);
  }

  ctx.root = node.body;
}

function extension_parseRef(ctx, node, refName, alias) {
  if (extension_is(extension_Identifier, node)) {
    ctx.scope.add(node.name);
    ctx[refName] = node.name;
  } else if (extension_is(extension_ObjectPattern, node)) {
    node.properties.forEach(p => {
      const key = extension_is(extension_Identifier, p.key) ? p.key.name
        : extension_is(extension_Literal, p.key) ? p.key.value
        : ctx.error(p, extension_ERROR_ARGUMENT);
      if (!extension_is(extension_Identifier, p.value)) {
        ctx.error(p.value, extension_ERROR_DESTRUCTURE);
      }
      alias(p.value.name, key);
    });
  }
}

function extension_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) {
      extension_walk(arg, ctx, extension_opVisitors);
      fields.push(ctx.field(arg));
    } else if (index < idxParams) {
      extension_walk(arg, ctx, extension_opVisitors);
      params.push(ctx.param(arg));
    } else {
      ctx.error(arg, extension_ERROR_OP_PARAMETER);
    }
  });

  return { name, fields, params, ...(ctx.spec.window || {}) };
}

function extension_functionName(node) {
  return extension_is(extension_Identifier, node) ? node.name
    : !extension_is(extension_MemberExpression, node) ? null
    : extension_isMath(node) ? extension_rewriteMath(node.property.name)
    : node.property.name;
}

function extension_isMath(node) {
  return extension_is(extension_Identifier, node.object) && node.object.name === 'Math';
}

function extension_rewriteMath(name) {
  return name === 'max' ? 'greatest'
    : name === 'min' ? 'least'
    : name;
}

function extension_handleIdentifier(node, ctx, parent) {
  const { name } = node;

  if (extension_is(extension_MemberExpression, parent) && parent.property === node) {
    // do nothing: check head node, not nested properties
  } else if (extension_is(extension_Property, parent) && parent.key === node) {
    // do nothing: identifiers allowed in object expressions
  } else if (ctx.paramsRef.has(name)) {
    extension_updateParameterNode(node, ctx.paramsRef.get(name));
  } else if (ctx.columnRef.has(name)) {
    extension_updateColumnNode(node, name, ctx, parent);
  } else if (extension_util_has(ctx.params, name)) {
    extension_updateParameterNode(node, name);
  } else if (extension_util_has(extension_constants, name)) {
    extension_updateConstantNode(node, name);
  } else {
    return true;
  }
}

function extension_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, extension_ERROR_COLUMN);
  }

  // check if column reference is valid in current context
  if (ctx.aggronly && !ctx.$op) {
    ctx.error(node, extension_ERROR_AGGRONLY);
  }

  // rewrite ast node as a column access
  extension_rewrite(node, name, index, col, parent);
}

function extension_updateColumnNode(node, key, ctx, parent) {
  const [name, index] = ctx.columnRef.get(key);
  extension_checkColumn(node, name, index, ctx, parent);
}

function extension_checkParam(node, name, index, ctx) {
  if (ctx.params && !extension_util_has(ctx.params, name)) {
    ctx.error(node, extension_ERROR_PARAM);
  }
  extension_updateParameterNode(node, name);
}

function extension_updateParameterNode(node, name) {
  node.type = extension_Parameter;
  node.name = name;
}

function extension_updateConstantNode(node, name) {
  node.type = extension_Constant;
  node.name = name;
  node.raw = extension_constants[name];
}

function extension_updateFunctionNode(node, name, ctx) {
  if (name === extension_row_object_ROW_OBJECT) {
    const t = ctx.table;
    if (!t) ctx.error(node, extension_ERROR_ROW_OBJECT);
    extension_rowObjectExpression(node,
      node.arguments.length
        ? node.arguments.map(node => {
            const col = ctx.param(node);
            const name = extension_is_number(col) ? t.columnName(col) : col;
            if (!t.column(name)) ctx.error(node, extension_ERROR_COLUMN);
            return name;
          })
        : t.columnNames()
    );
  } else {
    node.callee = { type: extension_constants_Function, name };
  }
}

function extension_handleDeclaration(node, ctx) {
  if (extension_is(extension_Identifier, node)) {
    ctx.scope.add(node.name);
  } else if (extension_is(extension_ArrayPattern, node)) {
    node.elements.forEach(elm => extension_handleDeclaration(elm, ctx));
  } else if (extension_is(extension_ObjectPattern, node)) {
    node.properties.forEach(prop => extension_handleDeclaration(prop.value, ctx));
  } else {
    ctx.error(node.id, extension_ERROR_DECLARATION);
  }
}
;// ../../node_modules/arquero/src/expression/parse.js












const extension_ANNOTATE = { [extension_constants_Column]: 1, [extension_constants_Op]: 1 };

/* harmony default export */ function extension_expression_parse(input, opt = {}) {
  const generate = opt.generate || extension_codegen;
  const compiler = opt.compiler || extension_expression_compile;
  const params = extension_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 = extension_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 extension_is(extension_Literal, node)
        ? node.value
        : compiler.param(generate(node), params);
    },
    value(name, node) {
      names.push(name);
      const e = node.escape || (opt.ast
        ? extension_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 (extension_ANNOTATE[node.type] && e !== node && extension_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);
      extension_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 extension_entries(input)) {
    ctx.value(
      name + '',
      value.escape
        ? extension_parse_escape(ctx, value, params)
        : extension_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 extension_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 extension_getParams(opt) {
  return (opt.table ? extension_getTableParams(opt.table)
    : opt.join ? {
        ...extension_getTableParams(opt.join[1]),
        ...extension_getTableParams(opt.join[0])
      }
    : {}) || {};
}

function extension_getTableParams(table) {
  return table && extension_util_is_function(table.params) ? table.params() : {};
}
;// ../../node_modules/arquero/src/query/constants.js
const extension_Expr = 'Expr';
const extension_ExprList = 'ExprList';
const extension_ExprNumber = 'ExprNumber';
const extension_ExprObject = 'ExprObject';
const extension_JoinKeys = 'JoinKeys';
const extension_JoinValues = 'JoinValues';
const extension_Options = 'Options';
const extension_OrderbyKeys = 'OrderKeys';
const extension_SelectionList = 'SelectionList';
const extension_TableRef = 'TableRef';
const extension_TableRefList = 'TableRefList';

const extension_Descending = 'Descending';
const extension_constants_Query = 'Query';
const extension_Selection = 'Selection';
const extension_constants_Verb = 'Verb';
const extension_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 extension_wrap(expr, properties) {
  return expr && expr.expr
    ? new extension_Wrapper({ ...expr, ...properties })
    : new extension_Wrapper(properties, expr);
}

class extension_Wrapper {
  constructor(properties, expr) {
    this.expr = expr;
    Object.assign(this, properties);
  }
  toString() {
    return String(this.expr);
  }
  toObject() {
    return {
      ...this,
      expr: this.toString(),
      ...(extension_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 extension_desc(expr) {
  return extension_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 extension_field(expr, name, table = 0) {
  const props = table ? { field: true, table } : { field: true };
  return extension_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 extension_rolling(expr, frame, includePeers) {
  return extension_wrap(expr, {
    window: {
      frame: frame || [-Infinity, 0],
      peers: !!includePeers
    }
  });
}
;// ../../node_modules/arquero/src/query/util.js














function extension_util_func(expr) {
  const f = d => d;
  f.toString = () => expr;
  return f;
}

function extension_getTable(catalog, ref) {
  ref = ref && extension_util_is_function(ref.query) ? ref.query() : ref;
  return ref && extension_util_is_function(ref.evaluate)
    ? ref.evaluate(null, catalog)
    : catalog(ref);
}

function extension_isSelection(value) {
  return extension_is_object(value) && (
    extension_is_array(value.all) ||
    extension_is_array(value.matches) ||
    extension_is_array(value.not) ||
    extension_is_array(value.range)
  );
}

function extension_util_toObject(value) {
  return value && extension_util_is_function(value.toObject) ? value.toObject()
    : extension_util_is_function(value) ? { expr: String(value), func: true }
    : extension_is_array(value) ? value.map(extension_util_toObject)
    : extension_is_object(value) ? extension_map_object(value, _ => extension_util_toObject(_))
    : value;
}

function extension_fromObject(value) {
  return extension_is_array(value) ? value.map(extension_fromObject)
    : !extension_is_object(value) ? value
    : extension_is_array(value.verbs) ? extension_query_Query.from(value)
    : extension_is_array(value.all) ? extension_selection_all()
    : extension_is_array(value.range) ? extension_range(...value.range)
    : extension_is_array(value.match) ? extension_matches(RegExp(...value.match))
    : extension_is_array(value.not) ? extension_not(value.not.map(extension_util_toObject))
    : extension_fromExprObject(value);
}

function extension_fromExprObject(value) {
  let output = value;
  let expr = value.expr;

  if (expr != null) {
    if (value.field === true) {
      output = expr = extension_field(expr);
    } else if (value.func === true) {
      output = expr = extension_util_func(expr);
    }

    if (extension_is_object(value.window)) {
      const { frame, peers } = value.window;
      output = expr = extension_rolling(expr, frame, peers);
    }

    if (value.desc === true) {
      output = extension_desc(expr);
    }
  }

  return value === output
    ? extension_map_object(value, _ => extension_fromObject(_))
    : output;
}

function extension_joinKeys(keys) {
  return extension_is_array(keys) ? keys.map(extension_parseJoinKeys)
    : keys;
}

function extension_parseJoinKeys(keys) {
  const list = [];

  extension_to_array(keys).forEach(param => {
    extension_is_number(param) ? list.push(param)
      : extension_is_string(param) ? list.push(extension_field(param, null))
      : extension_is_object(param) && param.expr ? list.push(param)
      : extension_util_is_function(param) ? list.push(param)
      : extension_util_error(`Invalid key value: ${param+''}`);
  });

  return list;
}

function extension_joinValues(values) {
  return extension_is_array(values)
    ? values.map(extension_parseJoinValues)
    : values;
}

function extension_parseJoinValues(values, index) {
  return index < 2 ? extension_to_array(values) : values;
}

function extension_orderbyKeys(keys) {
  const list = [];

  keys.forEach(param => {
    const expr = param.expr != null ? param.expr : param;
    if (extension_is_object(expr) && !extension_util_is_function(expr)) {
      for (const key in expr) {
        list.push(expr[key]);
      }
    } else {
      param = extension_is_number(expr) ? expr
        : extension_is_string(expr) ? extension_field(param)
        : extension_util_is_function(expr) ? param
        : extension_util_error(`Invalid orderby field: ${param+''}`);
      list.push(param);
    }
  });

  return list;
}
;// ../../node_modules/arquero/src/query/to-ast.js













const extension_Methods = {
  [extension_Expr]: extension_astExpr,
  [extension_ExprList]: extension_astExprList,
  [extension_ExprNumber]: extension_astExprNumber,
  [extension_ExprObject]: extension_astExprObject,
  [extension_JoinKeys]: extension_astJoinKeys,
  [extension_JoinValues]: extension_astJoinValues,
  [extension_OrderbyKeys]: extension_astExprList,
  [extension_SelectionList]: extension_astSelectionList
};

/* harmony default export */ function extension_to_ast(value, type, propTypes) {
  return type === extension_TableRef ? extension_astTableRef(value)
    : type === extension_TableRefList ? value.map(extension_astTableRef)
    : extension_ast(extension_util_toObject(value), type, propTypes);
}

function extension_ast(value, type, propTypes) {
  return type === extension_Options
    ? (value ? extension_astOptions(value, propTypes) : value)
    : extension_Methods[type](value);
}

function extension_astOptions(value, types = {}) {
  const output = {};
  for (const key in value) {
    const prop = value[key];
    output[key] = types[key] ? extension_ast(prop, types[key]) : prop;
  }
  return output;
}

function extension_astParse(expr, opt) {
  return extension_expression_parse({ expr }, { ...opt, ast: true }).exprs[0];
}

function extension_astColumn(name) {
  return { type: extension_constants_Column, name };
}

function extension_astColumnIndex(index) {
  return { type: extension_constants_Column, index };
}

function extension_astExprObject(obj, opt) {
  if (extension_is_string(obj)) {
    return extension_astParse(obj, opt);
  }

  if (obj.expr) {
    let ast;
    if (obj.field === true) {
      ast = extension_astColumn(obj.expr);
    } else if (obj.func === true) {
      ast = extension_astExprObject(obj.expr, opt);
    }
    if (ast) {
      if (obj.desc) {
        ast = { type: extension_Descending, expr: ast };
      }
      if (obj.window) {
        ast = { type: extension_Window, expr: ast, ...obj.window };
      }
      return ast;
    }
  }

  return Object.keys(obj)
    .map(key => ({
      ...extension_astExprObject(obj[key], opt),
      as: key
    }));
}

function extension_astSelection(sel) {
  const type = extension_Selection;
  return sel.all ? { type, operator: 'all' }
    : sel.not ? { type, operator: 'not', arguments: extension_astExprList(sel.not) }
    : sel.range ? { type, operator: 'range', arguments: extension_astExprList(sel.range) }
    : sel.matches ? { type, operator: 'matches', arguments: sel.matches }
    : extension_util_error('Invalid input');
}

function extension_astSelectionList(arr) {
  return extension_to_array(arr).map(extension_astSelectionItem).flat();
}

function extension_astSelectionItem(val) {
  return extension_isSelection(val) ? extension_astSelection(val)
    : extension_is_number(val) ? extension_astColumnIndex(val)
    : extension_is_string(val) ? extension_astColumn(val)
    : extension_is_object(val) ? Object.keys(val)
      .map(name => ({ type: extension_constants_Column, name, as: val[name] }))
    : extension_util_error('Invalid input');
}

function extension_astExpr(val) {
  return extension_isSelection(val) ? extension_astSelection(val)
    : extension_is_number(val) ? extension_astColumnIndex(val)
    : extension_is_string(val) ? extension_astColumn(val)
    : extension_is_object(val) ? extension_astExprObject(val)
    : extension_util_error('Invalid input');
}

function extension_astExprList(arr) {
  return extension_to_array(arr).map(extension_astExpr).flat();
}

function extension_astExprNumber(val) {
  return extension_is_number(val) ? val : extension_astExprObject(val);
}

function extension_astJoinKeys(val) {
  return extension_is_array(val)
    ? val.map(extension_astExprList)
    : extension_astExprObject(val, { join: true });
}

function extension_astJoinValues(val) {
  return extension_is_array(val)
    ? val.map((v, i) => i < 2
        ? extension_astExprList(v)
        : extension_astExprObject(v, { join: true })
      )
    : extension_astExprObject(val, { join: true });
}

function extension_astTableRef(value) {
  return value && extension_util_is_function(value.toAST)
    ? value.toAST()
    : value;
}
;// ../../node_modules/arquero/src/query/verb.js








/**
 * Model an Arquero verb as a serializable object.
 */
class extension_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 === extension_JoinKeys ? extension_joinKeys(param)
        : type === extension_JoinValues ? extension_joinValues(param)
        : type === extension_OrderbyKeys ? extension_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 = extension_verb_Verbs[object.verb];
    const params = (verb.schema || [])
      .map(({ name }) => extension_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 === extension_TableRef ? extension_getTable(catalog, value)
        : type === extension_TableRefList ? value.map(t => extension_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] = extension_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: extension_constants_Verb, verb: this.verb };
    this.schema.forEach(({ name, type, props }) => {
      obj[name] = extension_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 extension_verb_createVerb(name, schema) {
  return Object.assign(
    (...params) => new extension_Verb(name, schema, params),
    { schema }
  );
}

/**
 * A lookup table of verb classes.
 */
const extension_verb_Verbs = {
  count:      extension_verb_createVerb('count', [
                { name: 'options', type: extension_Options }
              ]),
  derive:     extension_verb_createVerb('derive', [
                { name: 'values', type: extension_ExprObject },
                { name: 'options', type: extension_Options,
                  props: { before: extension_SelectionList, after: extension_SelectionList }
                }
              ]),
  filter:     extension_verb_createVerb('filter', [
                { name: 'criteria', type: extension_ExprObject }
              ]),
  groupby:    extension_verb_createVerb('groupby', [
                { name: 'keys', type: extension_ExprList }
              ]),
  orderby:    extension_verb_createVerb('orderby', [
                { name: 'keys', type: extension_OrderbyKeys }
              ]),
  relocate:   extension_verb_createVerb('relocate', [
                { name: 'columns', type: extension_SelectionList },
                { name: 'options', type: extension_Options,
                  props: { before: extension_SelectionList, after: extension_SelectionList }
                }
              ]),
  rename:     extension_verb_createVerb('rename', [
                { name: 'columns', type: extension_SelectionList }
              ]),
  rollup:     extension_verb_createVerb('rollup', [
                { name: 'values', type: extension_ExprObject }
              ]),
  sample:     extension_verb_createVerb('sample', [
                { name: 'size', type: extension_ExprNumber },
                { name: 'options', type: extension_Options, props: { weight: extension_Expr } }
              ]),
  select:     extension_verb_createVerb('select', [
                { name: 'columns', type: extension_SelectionList }
              ]),
  ungroup:    extension_verb_createVerb('ungroup'),
  unorder:    extension_verb_createVerb('unorder'),
  reify:      extension_verb_createVerb('reify'),
  dedupe:     extension_verb_createVerb('dedupe', [
                { name: 'keys', type: extension_ExprList, default: [] }
              ]),
  impute:     extension_verb_createVerb('impute', [
                { name: 'values', type: extension_ExprObject },
                { name: 'options', type: extension_Options, props: { expand: extension_ExprList } }
              ]),
  fold:       extension_verb_createVerb('fold', [
                { name: 'values', type: extension_ExprList },
                { name: 'options', type: extension_Options }
              ]),
  pivot:      extension_verb_createVerb('pivot', [
                { name: 'keys', type: extension_ExprList },
                { name: 'values', type: extension_ExprList },
                { name: 'options', type: extension_Options }
              ]),
  spread:     extension_verb_createVerb('spread', [
                { name: 'values', type: extension_ExprList },
                { name: 'options', type: extension_Options }
              ]),
  unroll:     extension_verb_createVerb('unroll', [
                { name: 'values', type: extension_ExprList },
                { name: 'options', type: extension_Options, props: { drop: extension_ExprList } }
              ]),
  lookup:     extension_verb_createVerb('lookup', [
                { name: 'table', type: extension_TableRef },
                { name: 'on', type: extension_JoinKeys },
                { name: 'values', type: extension_ExprList }
              ]),
  join:       extension_verb_createVerb('join', [
                { name: 'table', type: extension_TableRef },
                { name: 'on', type: extension_JoinKeys },
                { name: 'values', type: extension_JoinValues },
                { name: 'options', type: extension_Options }
              ]),
  cross:      extension_verb_createVerb('cross', [
                { name: 'table', type: extension_TableRef },
                { name: 'values', type: extension_JoinValues },
                { name: 'options', type: extension_Options }
              ]),
  semijoin:   extension_verb_createVerb('semijoin', [
                { name: 'table', type: extension_TableRef },
                { name: 'on', type: extension_JoinKeys }
              ]),
  antijoin:   extension_verb_createVerb('antijoin', [
                { name: 'table', type: extension_TableRef },
                { name: 'on', type: extension_JoinKeys }
              ]),
  concat:     extension_verb_createVerb('concat', [
                { name: 'tables', type: extension_TableRefList }
              ]),
  union:      extension_verb_createVerb('union', [
                { name: 'tables', type: extension_TableRefList }
              ]),
  intersect:  extension_verb_createVerb('intersect', [
                { name: 'tables', type: extension_TableRefList }
              ]),
  except:     extension_verb_createVerb('except', [
                { name: 'tables', type: extension_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 extension_query(tableName) {
  return new extension_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 extension_queryFrom(object) {
  return extension_query_Query.from(object);
}

/**
 * Model a query as a collection of serializble verbs.
 * Provides a table-like interface for constructing queries.
 */
class extension_query_Query extends extension_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 extension_query_Query(verbs.map(extension_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 extension_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 extension_serialize(this, 'toAST', { type: extension_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 extension_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 extension_query_append(qb, verb) {
  return new extension_query_Query(
    qb._verbs.concat(verb),
    qb._params,
    qb._table
  );
}

function extension_query_addQueryVerb(name, verb) {
  extension_query_Query.prototype[name] = function(...args) {
    return extension_query_append(this, verb(...args));
  };
}

// Internal verb handlers
for (const name in extension_verb_Verbs) {
  const verb = extension_verb_Verbs[name];
  extension_query_Query.prototype['__' + name] = function(qb, ...args) {
    return extension_query_append(qb, verb(...args));
  };
}
;// ../../node_modules/arquero/package.json
const extension_package_namespaceObject = {"rE":"4.8.8"};
;// ../../node_modules/arquero/src/arrow/arrow-dictionary.js


/**
 * Create a new Arquero column that proxies access to an
 * Apache Arrow dictionary column.
 * @param {object} vector An Apache Arrow dictionary column.
 */
/* harmony default export */ function extension_arrow_dictionary(vector) {
  const { chunks, dictionary, length, nullCount } = vector;
  const size = dictionary.length;
  const keys = extension_dictKeys(chunks || [vector], length, nullCount, size);
  const values = Array(size);

  const value = k => k == null || k < 0 || k >= size ? null
    : values[k] !== undefined ? values[k]
    : (values[k] = dictionary.get(k));

  return {
    vector,
    length,

    get: row => value(keys[row]),

    key: row => keys[row],

    keyFor(value) {
      if (value === null) return nullCount ? size : -1;
      for (let i = 0; i < size; ++i) {
        if (values[i] === undefined) values[i] = dictionary.get(i);
        if (values[i] === value) return i;
      }
      return -1;
    },

    groups(names) {
      const s = size + (nullCount ? 1 : 0);
      return { keys, get: [value], names, rows: extension_sequence(0, s), size: s };
    },

    [Symbol.iterator]() {
      return vector[Symbol.iterator]();
    }
  };
}

/**
 * Generate a dictionary key array
 * @param {object[]} chunks Arrow column chunks
 * @param {number} length The length of the Arrow column
 * @param {number} nulls The count of column null values
 * @param {number} size The backing dictionary size
 */
function extension_dictKeys(chunks, length, nulls, size) {
  const v = chunks.length > 1 || nulls
    ? extension_flatten(chunks, length, chunks[0].type.indices)
    : chunks[0].values;
  return nulls ? extension_nullKeys(chunks, v, size) : v;
}

/**
 * Flatten Arrow column chunks into a single array.
 */
function extension_flatten(chunks, length, type) {
  const array = new type.ArrayType(length);
  const n = chunks.length;
  for (let i = 0, idx = 0, len; i < n; ++i) {
    len = chunks[i].length;
    array.set(chunks[i].values.subarray(0, len), idx);
    idx += len;
  }
  return array;
}

/**
 * Encode null values as an additional dictionary key.
 * Returns a new key array with null values added.
 * TODO: safeguard against integer overflow?
 */
function extension_nullKeys(chunks, keys, key) {
  // iterate over null bitmaps, encode null values as key
  const n = chunks.length;
  for (let i = 0, idx = 0, m, base, bits, byte; i < n; ++i) {
    bits = chunks[i].nullBitmap;
    m = chunks[i].length >> 3;
    if (bits && bits.length) {
      for (let j = 0; j <= m; ++j) {
        if ((byte = bits[j]) !== 255) {
          base = idx + (j << 3);
          if ((byte & (1 << 0)) === 0) keys[base + 0] = key;
          if ((byte & (1 << 1)) === 0) keys[base + 1] = key;
          if ((byte & (1 << 2)) === 0) keys[base + 2] = key;
          if ((byte & (1 << 3)) === 0) keys[base + 3] = key;
          if ((byte & (1 << 4)) === 0) keys[base + 4] = key;
          if ((byte & (1 << 5)) === 0) keys[base + 5] = key;
          if ((byte & (1 << 6)) === 0) keys[base + 6] = key;
          if ((byte & (1 << 7)) === 0) keys[base + 7] = key;
        }
      }
    }
    idx += chunks[i].length;
  }
  return keys;
}
;// ../../node_modules/arquero/src/util/unroll.js
/* harmony default export */ function extension_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/arrow/arrow-column.js







const extension_isList = id => id === extension_arrow_types.List || id === extension_arrow_types.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 extension_arrowColumn(arrow, nested) {
  if (arrow.dictionary) return extension_arrow_dictionary(arrow);
  const { typeId, chunks, length, numChildren } = arrow;
  const vector = chunks && chunks.length === 1 ? chunks[0] : arrow;
  const get = numChildren && nested ? extension_getNested(vector)
    : numChildren ? extension_memoize(extension_getNested(vector))
    : typeId === extension_arrow_types.Utf8 ? extension_memoize(row => vector.get(row))
    : null;

  return get
    ? { vector, length, get, [Symbol.iterator]: () => extension_iterator(length, get) }
    : vector;
}

function extension_memoize(get) {
  const values = [];
  return row => {
    const v = values[row];
    return v !== undefined ? v : (values[row] = get(row));
  };
}

function* extension_iterator(n, get) {
  for (let i = 0; i < n; ++i) {
    yield get(i);
  }
}

const extension_arrayFrom = vector => vector.numChildren
  ? extension_util_repeat(vector.length, extension_getNested(vector))
  : vector.nullCount ? [...vector]
  : vector.toArray();

const extension_getNested = vector => extension_isList(vector.typeId) ? extension_arrow_column_getList(vector)
  : vector.typeId === extension_arrow_types.Struct ? extension_arrow_column_getStruct(vector)
  : extension_util_error(`Unsupported Arrow type: ${extension_to_string(vector.VectorName)}`);

const extension_arrow_column_getList = vector => vector.nullCount
  ? row => vector.isValid(row) ? extension_arrayFrom(vector.get(row)) : null
  : row => extension_arrayFrom(vector.get(row));

function extension_arrow_column_getStruct(vector) {
  const props = [];
  const code = [];
  vector.type.children.forEach((field, i) => {
    props.push(extension_arrowColumn(vector.getChildAt(i), true));
    code.push(`${extension_to_string(field.name)}:_${i}.get(row)`);
  });
  const get = extension_unroll('row', '({' + code + '})', props);

  return vector.nullCount
    ? row => vector.isValid(row) ? get(row) : null
    : get;
}
;// ../../node_modules/arquero/src/table/bit-set.js
const extension_ONE = 0x80000000;
const extension_ALL = 0xFFFFFFFF;

/**
 * Represent an indexable set of bits.
 */
class extension_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] & (extension_ONE >>> i);
  }

  /**
   * Set the bit at a given index to one.
   * @param {number} i The bit index.
   */
  set(i) {
    this._bits[i >> 5] |= (extension_ONE >>> i);
  }

  /**
   * Clear the bit at a given index to zero.
   * @param {number} i The bit index.
   */
  clear(i) {
    this._bits[i >> 5] &= ~(extension_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] & (extension_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] &= extension_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/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 extension_from_arrow(arrow, options = {}) {
  arrow = extension_arrow_table_from(arrow);
  const { chunks, length, schema } = arrow;

  // resolve column selection
  const fields = schema.fields.map(f => f.name);
  const sel = extension_resolve({
    columnNames: test => test ? fields.filter(test) : fields.slice(),
    columnIndex: name => fields.indexOf(name)
  }, options.columns || extension_selection_all());

  // build Arquero columns for backing Arrow columns
  const cols = extension_column_set();
  sel.forEach((name, key) => {
    cols.add(name, extension_arrowColumn(arrow.getColumn(key)));
  });

  // build row filter bit mask as needed
  const bits = arrow.count() !== length ? new extension_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 extension_column_table_ColumnTable(cols.data, cols.names, bits);
}
;// ../../node_modules/arquero/src/util/parse-values.js



const extension_parseBoolean = [ // boolean
  v => (v === 'true') || (v === 'false'),
  v => v === 'false' ? false : true
];

const extension_parseNumber = [ // number
  v => v === 'NaN' || (v = +v) === v,
  v => +v
];

const extension_parseDate = [ // iso date
  extension_is_iso_date_string,
  v => new Date(Date.parse(v))
];

function extension_numberParser(options) {
  const { decimal } = options;
  return decimal && decimal !== '.'
    ? extension_parseNumber.map(f => s => f(s && s.replace(decimal, '.')))
    : extension_parseNumber;
}

/* harmony default export */ function extension_parse_values(values, options) {
  const types = [extension_parseBoolean, extension_numberParser(options), extension_parseDate];
  const n = types.length;
  for (let i = 0; i < n; ++i) {
    const [test, parser] = types[i];
    if (extension_check(values, test)) {
      return parser;
    }
  }
  return identity;
}

function extension_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 extension_defaultNames(n, off = 0) {
  return repeat(n - off, i => `col${i + off + 1}`);
}

/* harmony default export */ function extension_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, extension_defaultNames(n, names.length)] : names
    : extension_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 = extension_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 extension_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 extension_constants_EOL = {};
const extension_constants_EOF = {};
const extension_constants_QUOTE = 34;
const extension_constants_NEWLINE = 10;
const extension_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 extension_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 extension_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 extension_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 extension_from_fixed(text, options = {}) {
  const read = parseLines(text, options);
  const p = extension_positions(options);
  return fromTextRows(
    () => {
      const line = read();
      if (line) {
        return p.map(([i, j]) => line.slice(i, j).trim());
      }
    },
    options.names,
    options
  );
}

function extension_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 extension_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 extension_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 extension_engine_select(table, columns) {
  const cols = extension_column_set();

  columns.forEach((value, curr) => {
    const next = extension_is_string(value) ? value : curr;
    if (next) {
      const col = table.column(curr) || extension_util_error(`Unrecognized column: ${curr}`);
      cols.add(next, col);
    }
  });

  return table.create(cols);
}
;// ../../node_modules/arquero/src/verbs/relocate.js




/* harmony default export */ function extension_relocate(table, columns, { before, after } = {}) {
  const bef = before != null;
  const aft = after != null;

  if (!(bef || aft)) {
    extension_util_error('relocate requires a before or after option.');
  }
  if (bef && aft) {
    extension_util_error('relocate accepts only one of the before or after options.');
  }

  columns = extension_resolve(table, columns);
  const anchors = [...extension_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 extension_engine_select(table, select);
}
;// ../../node_modules/arquero/src/util/concat.js
/* harmony default export */ function extension_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/ascending.js
/* harmony default export */ function extension_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 extension_min(values, start = 0, stop = values.length) {
  let min = stop ? values[start++] : extension_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 extension_max(values, start = 0, stop = values.length) {
  let max = stop ? values[start++] : extension_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 extension_to_numeric(value) {
  return extension_is_bigint(value) ? value : +value;
}
;// ../../node_modules/arquero/src/util/quantile.js




function extension_quantile(values, p) {
  const n = values.length;

  if (!n) return extension_util_null;
  if ((p = +p) <= 0 || n < 2) return extension_to_numeric(values[0]);
  if (p >= 1) return extension_to_numeric(values[n - 1]);

  const i = (n - 1) * p;
  const i0 = Math.floor(i);
  const v0 = extension_to_numeric(values[i0]);
  return extension_is_bigint(v0)
    ? v0
    : v0 + (extension_to_numeric(values[i0 + 1]) - v0) * (i - i0);
}
;// ../../node_modules/arquero/src/util/value-list.js





class extension_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]
      : extension_min(this._values, this._start);
  }

  max() {
    return this._sorted && this._sorted.length
      ? this._sorted[this._sorted.length - 1]
      : extension_max(this._values, this._start);
  }

  quantile(p) {
    if (!this._sorted) {
      this._sorted = this.values(true);
      this._sorted.sort(extension_ascending);
    }
    return extension_quantile(this._sorted, p);
  }
}
;// ../../node_modules/arquero/src/engine/reduce/field-reducer.js








const extension_field_reducer_update = (ops, args, fn) => extension_unroll(
  args,
  '{' + extension_concat(ops, (_, i) => `_${i}.${fn}(${args});`) + '}',
  ops
);

/* harmony default export */ function extension_field_reducer(oplist, stream) {
  const { ops, output } = extension_expand(oplist, stream);
  const fields = oplist[0].fields;
  const n = fields.length;
  const cls = n === 0 ? extension_FieldReducer
    : n === 1 ? extension_Field1Reducer
    : n === 2 ? extension_Field2Reducer
    : extension_util_error('Unsupported field count: ' + n);
  return new cls(fields, ops, output, stream);
}

function extension_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 = extension_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 extension_FieldReducer extends extension_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 extension_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 extension_Field1Reducer extends extension_FieldReducer {
  constructor(fields, ops, outputs, stream) {
    super(fields, ops, outputs, stream);

    // unroll op invocations for performance
    const args = ['state', 'v1', 'v2'];
    this._add = extension_field_reducer_update(ops, args, 'add');
    this._rem = extension_field_reducer_update(ops, args, 'rem');
  }

  add(state, row, data) {
    const value = this._fields[0](row, data);
    ++state.count;
    if (extension_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 (extension_is_valid(value)) {
      --state.valid;
      if (state.list) state.list.rem();
      this._rem(state, value);
    }
  }
}

class extension_Field2Reducer extends extension_FieldReducer {
  constructor(fields, ops, outputs, stream) {
    super(fields, ops, outputs, stream);

    // unroll op invocations for performance
    const args = ['state', 'v1', 'v2'];
    this._add = extension_field_reducer_update(ops, args, 'add');
    this._rem = extension_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 (extension_is_valid(value1) && extension_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 (extension_is_valid(value1) && extension_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 extension_aggregateGet(table, ops, get) {
  if (ops.length) {
    const data = table.data();
    const { keys } = table.groups() || {};
    const result = extension_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 extension_aggregate(table, ops, result) {
  if (!ops.length) return result; // early exit

  // instantiate aggregators and result store
  const aggrs = extension_reducers(ops);
  const groups = table.groups();
  const size = groups ? groups.size : 1;
  result = result || extension_util_repeat(ops.length, () => Array(size));

  // compute aggregates, extract results
  if (size > 1) {
    aggrs.forEach(aggr => {
      const cells = extension_reduceGroups(table, aggr, groups);
      for (let i = 0; i < size; ++i) {
        aggr.write(cells[i], result, i);
      }
    });
  } else {
    aggrs.forEach(aggr => {
      const cell = extension_reduceFlat(table, aggr);
      aggr.write(cell, result, 0);
    });
  }

  return result;
}

function extension_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(extension_field_reducer(fields[key], stream));
  }

  return aggrs;
}

function extension_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 extension_reduceGroups(table, reducer, groups) {
  const { keys, size } = groups;

  // initialize aggregation cells
  const cells = extension_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 extension_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 extension_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 extension_bisect = extension_bisector(extension_ascending);

/* harmony default export */ function extension_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
    ? extension_unroll(
        ['w', 'r', 'k'],
        '{' + extension_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 = extension_bisect.left(peer, peer[w.i0]);
        }
        if (w.i1 < n && isPeer(w.i1)) {
          w.i1 = extension_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 extension_frameValue = op =>
  (op.frame || [null, null]).map(v => Number.isFinite(v) ? Math.abs(v) : null);

const extension_peersValue = op => !!op.peers;

function extension_windowOp(spec) {
  const { id, name, fields = [], params = [] } = spec;
  const op = extension_getWindow(name).create(...params);
  if (fields.length) op.get = fields[0];
  op.id = id;
  return op;
}

function extension_window_window(table, cols, exprs, result = {}, ops) {
  // instantiate window states
  const data = table.data();
  const states = extension_windowStates(ops, data);
  const nstate = states.length;

  const write = extension_unroll(
    ['r', 'd', 'op'],
    '{' + extension_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 = extension_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 extension_windowStates(ops, data) {
  const map = {};

  // group operations by window frame parameters
  ops.forEach(op => {
    const frame = extension_frameValue(op);
    const peers = extension_peersValue(op);
    const key = `${frame},${peers}`;
    const { aggOps, winOps } = map[key] || (map[key] = {
      frame,
      peers,
      aggOps: [],
      winOps: []
    });
    extension_hasAggregate(op.name)
      ? aggOps.push(op)
      : winOps.push(extension_windowOp(op));
  });

  return Object.values(map).map(_ => extension_window_state(
    data, _.frame, _.peers, _.winOps,
    extension_reducers(_.aggOps, _.frame[0] != null ? -1 : 1)
  ));
}

function extension_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 extension_isWindowed(op) {
  return extension_hasWindow(op.name) ||
    op.frame && (
      Number.isFinite(op.frame[0]) ||
      Number.isFinite(op.frame[1])
    );
}

/* harmony default export */ function extension_derive(table, { names, exprs, ops }, options = {}) {
  // instantiate output data
  const total = table.totalRows();
  const cols = extension_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 ] = extension_segmentOps(ops);

  const size = table.isGrouped() ? table.groups().size : 1;
  const result = extension_aggregate(
    table, aggOps,
    extension_util_repeat(ops.length, () => Array(size))
  );

  // perform table scans to generate output values
  winOps.length
    ? extension_window_window(table, data, exprs, result, winOps)
    : extension_output(table, data, exprs, result);

  return table.create(cols);
}

function extension_segmentOps(ops) {
  const aggOps = [];
  const winOps = [];
  const n = ops.length;

  for (let i = 0; i < n; ++i) {
    const op = ops[i];
    op.id = i;
    (extension_isWindowed(op) ? winOps : aggOps).push(op);
  }

  return [aggOps, winOps];
}

function extension_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 extension_verbs_derive(table, values, options = {}) {
  const dt = extension_derive(table, extension_expression_parse(values, { table }), options);

  return options.drop || (options.before == null && options.after == null)
    ? dt
    : extension_relocate(dt,
        Object.keys(values).filter(name => !table.column(name)),
        options
      );
}
;// ../../node_modules/arquero/src/verbs/except.js
/* harmony default export */ function extension_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/engine/filter.js


/* harmony default export */ function extension_engine_filter(table, predicate) {
  const n = table.totalRows();
  const bits = table.mask();
  const data = table.data();
  const filter = new extension_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 extension_verbs_filter(table, criteria) {
  const test = extension_expression_parse({ p: criteria }, { table });
  let predicate = test.exprs[0];
  if (test.ops.length) {
    const { data } = extension_derive(table, test, { drop: true }).column('p');
    predicate = row => data[row];
  }
  return extension_engine_filter(table, predicate);
}
;// ../../node_modules/arquero/src/engine/unroll.js




/* harmony default export */ function extension_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 = extension_aggregateGet(table, ops, exprs);

  // initialize output columns
  const cols = extension_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 = extension_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 = extension_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 extension_fold(table, { names = [], exprs = [], ops = [] }, options = {}) {
  if (names.length === 0) return table;

  const [k = 'key', v = 'value'] = options.as || [];
  const vals = extension_aggregateGet(table, ops, exprs);

  return extension_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 extension_util_parse(name, table, params, options = { window: false }) {
  const exprs = new Map();

  const marshal = param => {
    param = extension_is_number(param) ? table.columnName(param) : param;
    extension_is_string(param) ? exprs.set(param, extension_field(param))
      : extension_util_is_function(param) ? extension_resolve(table, param).forEach(marshal)
      : extension_is_object(param) ? extension_util_assign(exprs, param)
      : extension_util_error(`Invalid ${name} value: ${param+''}`);
  };

  extension_to_array(params).forEach(marshal);

  if (options.preparse) {
    options.preparse(exprs);
  }

  return extension_expression_parse(exprs, { table, ...options });
}
;// ../../node_modules/arquero/src/verbs/fold.js



/* harmony default export */ function extension_verbs_fold(table, values, options) {
  return extension_fold(table, extension_util_parse('fold', table, values), options);
}
;// ../../node_modules/arquero/src/engine/impute.js






/* harmony default export */ function extension_impute(table, values, keys, arrays) {
  const write = keys && keys.length;
  return extension_impute_impute(
    write ? extension_impute_expand(table, keys, arrays) : table,
    values,
    write
  );
}

function extension_impute_impute(table, { names, exprs, ops }, write) {
  const gets = extension_aggregateGet(table, ops, exprs);
  const cols = write ? null : extension_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] = !extension_is_valid(v) ? get(idx) : v;
    });
  });

  return write ? table : table.create(cols);
}

function extension_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 = extension_key_function(keyGet);
  table.scan((idx, data) => hash.add(keyTable(idx, data)));

  // initialize output table data
  const names = table.columnNames();
  const cols = extension_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 = extension_key_function(keyGet.map((k, i) => a => a[i]));
  const set = extension_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);
    extension_enumerate(groups, values, (vec, idx) => {
      if (!hash.has(keyEnum(vec))) {
        set(vec);
        keys[row++] = idx[0];
      }
    });
    cols.groupby({ ...groups, keys });
  } else {
    extension_enumerate(groups, values, vec => {
      if (!hash.has(keyEnum(vec))) set(vec);
    });
  }

  return table.create(cols.new());
}

function extension_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 extension_rollup(table, { names, exprs, ops }) {
  // output data
  const cols = extension_column_set();
  const groups = table.groups();

  // write groupby fields to output
  if (groups) extension_groupOutput(cols, groups);

  // compute and write aggregate output
  extension_rollup_output(names, exprs, groups, extension_aggregate(table, ops), cols);

  // return output table
  return table.create(cols.new());
}

function extension_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 extension_verbs_impute(table, values, options = {}) {
  values = extension_expression_parse(values, { table });

  values.names.forEach(name =>
    table.column(name) ? 0 : extension_util_error(`Invalid impute column ${extension_to_string(name)}`)
  );

  if (options.expand) {
    const opt = { preparse: extension_preparse, aggronly: true };
    const params = extension_util_parse('impute', table, options.expand, opt);
    const result = extension_rollup(table.ungroup(), params);
    return extension_impute(
      table, values, params.names,
      params.names.map(name => result.get(name, 0))
    );
  } else {
    return extension_impute(table, values);
  }
}

// map direct field reference to "unique" aggregate
function extension_preparse(map) {
  map.forEach((value, key) =>
    value.field ? map.set(key, extension_array_agg_distinct(value + '')) : 0
  );
}
;// ../../node_modules/arquero/src/verbs/intersect.js
/* harmony default export */ function extension_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 extension_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 extension_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 extension_emitter(columns, getters) {
  const args = ['i', 'a', 'j', 'b'];
  return extension_unroll(
    args,
    '{' + extension_concat(columns, (_, i) => `_${i}.push($${i}(${args}));`) + '}',
    columns, getters
  );
}

/* harmony default export */ function extension_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 = extension_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 = extension_emitter(columns, getters);

  // perform join
  const join = extension_is_array(predicate) ? extension_hashJoin : extension_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 extension_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 extension_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 = extension_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 extension_parse_key(name, table, params) {
  const exprs = new Map();

  extension_to_array(params).forEach((param, i) => {
    param = extension_is_number(param) ? table.columnName(param) : param;
    extension_is_string(param) ? exprs.set(i, extension_field(param))
      : extension_util_is_function(param) || extension_is_object(param) && param.expr ? exprs.set(i, param)
      : extension_util_error(`Invalid ${name} key value: ${param+''}`);
  });

  const fn = extension_expression_parse(exprs, { table, aggregate: false, window: false });
  return extension_key_function(fn.exprs, true);
}
;// ../../node_modules/arquero/src/util/intersect.js
function extension_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 extension_inferKeys(tableL, tableR, on) {
  if (!on) {
    // perform natural join if join condition not provided
    const isect = extension_intersect_intersect(tableL.columnNames(), tableR.columnNames());
    if (!isect.length) extension_util_error('Natural join requires shared column names.');
    on = [isect, isect];
  } else if (extension_is_string(on)) {
    on = [on, on];
  } else if (extension_is_array(on) && on.length === 1) {
    on = [on[0], on[0]];
  }

  return on;
}

function extension_keyPredicate(tableL, tableR, onL, onR) {
  if (onL.length !== onR.length) {
    extension_util_error('Mismatched number of join keys');
  }
  return [
    extension_parse_key('join', tableL, onL),
    extension_parse_key('join', tableR, onR)
  ];
}
;// ../../node_modules/arquero/src/verbs/join.js










const extension_OPT_L = { aggregate: false, window: false };
const extension_OPT_R = { ...extension_OPT_L, index: 1 };

/* harmony default export */ function extension_verbs_join(tableL, tableR, on, values, options = {}) {
  on = extension_inferKeys(tableL, tableR, on);
  const optParse = { join: [tableL, tableR] };
  let predicate;

  if (extension_is_array(on)) {
    const [onL, onR] = on.map(extension_to_array);
    predicate = extension_keyPredicate(tableL, tableR, onL, onR);

    if (!values) {
      // infer output columns, suppress duplicated key columns
      values = extension_inferValues(tableL, onL, onR, options);
    }
  } else {
    predicate = extension_expression_parse({ on }, optParse).exprs[0];

    if (!values) {
      // include all table columns if values not provided
      values = [extension_selection_all(), extension_selection_all()];
    }
  }

  return extension_join(
    tableL, tableR, predicate,
    extension_parseValues(tableL, tableR, values, optParse, options && options.suffix),
    options
  );
}

function extension_inferValues(tableL, onL, onR, options) {
  const isect = [];
  onL.forEach((s, i) => extension_is_string(s) && s === onR[i] ? isect.push(s) : 0);
  const vR = extension_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 = `[${extension_to_string(s)}]`;
        return shared.has(s)
          ? { [s]: `(a, b) => a${c} == null ? b${c} : a${c}` }
          : s;
      }),
      vR
    ];
  }

  return options.right ? [vR, extension_selection_all()] : [extension_selection_all(), vR];
}

function extension_parseValues(tableL, tableR, values, optParse, suffix = []) {
  if (extension_is_array(values)) {
    let vL, vR, vJ, n = values.length;
    vL = vR = vJ = { names: [], exprs: [] };

    if (n--) {
      vL = extension_util_parse('join', tableL, values[0], optParse);
    }
    if (n--) {
      vR = extension_util_parse('join', tableR, values[1], extension_OPT_R);
    }
    if (n--) {
      vJ = extension_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) {
      extension_rekey(vL.names, rename, suffix[0] || '_1');
      extension_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 extension_expression_parse(values, optParse);
  }
}

function extension_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 extension_join_filter(tableL, tableR, predicate, options = {}) {
  // calculate semi-join filter mask
  const filter = new extension_BitSet(tableL.totalRows());
  const join = extension_is_array(predicate) ? extension_hashSemiJoin : extension_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 extension_hashSemiJoin(filter, tableL, tableR, [keyL, keyR]) {
  // build lookup table
  const lut = extension_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 extension_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 extension_verbs_join_filter(tableL, tableR, on, options) {
  on = extension_inferKeys(tableL, tableR, on);

  const predicate = extension_is_array(on)
    ? extension_keyPredicate(tableL, tableR, ...on.map(extension_to_array))
    : extension_expression_parse({ on }, { join: [tableL, tableR] }).exprs[0];

  return extension_join_filter(tableL, tableR, predicate, options);
}
;// ../../node_modules/arquero/src/engine/lookup.js







/* harmony default export */ function extension_lookup(tableL, tableR, [keyL, keyR], { names, exprs, ops }) {
  // instantiate output data
  const cols = extension_column_set(tableL);
  const total = tableL.totalRows();
  names.forEach(name => cols.add(name, Array(total).fill(extension_util_null)));

  // build lookup table
  const lut = extension_rowLookup(tableR, keyR);

  // generate setter function for lookup match
  const set = extension_unroll(
    ['lr', 'rr', 'data'],
    '{' + extension_concat(names, (_, i) => `_[${i}][lr] = $[${i}](rr, data);`) + '}',
    names.map(name => cols.data[name]),
    extension_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 extension_verbs_lookup(tableL, tableR, on, values) {
  on = extension_inferKeys(tableL, tableR, on);
  return extension_lookup(
    tableL,
    tableR,
    [ extension_parse_key('lookup', tableL, on[0]), extension_parse_key('lookup', tableR, on[1]) ],
    extension_util_parse('lookup', tableR, values)
  );
}
;// ../../node_modules/arquero/src/engine/pivot.js



const extension_opt = (value, defaultValue) => value != null ? value : defaultValue;

/* harmony default export */ function extension_pivot(table, on, values, options = {}) {
  const { keys, keyColumn } = extension_pivotKeys(table, on, options);
  const vsep = extension_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 => extension_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(extension_pivot_output(values, namefn, table.groups(), results));
}

function extension_pivotKeys(table, on, options) {
  const limit = options.limit > 0 ? +options.limit : Infinity;
  const sort = extension_opt(options.sort, true);
  const ksep = extension_opt(options.keySeparator, '_');

  // construct key accessor function
  const get = extension_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 = extension_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 extension_pivot_output({ names, exprs }, namefn, groups, results) {
  const size = groups ? groups.size : 1;
  const cols = extension_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) extension_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 extension_verbs_pivot(table, on, values, options) {
  return extension_pivot(
    table,
    extension_util_parse('fold', table, on),
    extension_util_parse('fold', table, values, { preparse: extension_pivot_preparse, aggronly: true }),
    options
  );
}

// map direct field reference to "any" aggregate
function extension_pivot_preparse(map) {
  map.forEach((value, key) =>
    value.field ? map.set(key, extension_any(value + '')) : 0
  );
}
;// ../../node_modules/arquero/src/verbs/rename.js



/* harmony default export */ function extension_rename(table, columns) {
  const map = new Map();
  table.columnNames(x => (map.set(x, x), 0));
  return extension_engine_select(table, extension_resolve(table, columns, map));
}
;// ../../node_modules/arquero/src/verbs/rollup.js



/* harmony default export */ function extension_verbs_rollup(table, values) {
  return extension_rollup(table, extension_expression_parse(values, { table, aggronly: true }));
}
;// ../../node_modules/arquero/src/util/sample.js




/* harmony default export */ function extension_sample(buffer, replace, index, weight) {
  return (
    replace
      ? (weight ? extension_sampleRW : extension_sampleRU)
      : (weight ? extension_sampleNW : extension_sampleNU)
  )(buffer.length, buffer, index, weight);
}

// uniform sampling with replacement
// uses straightforward uniform sampling
function extension_sampleRU(size, buffer, index) {
  const n = index.length;
  for (let i = 0; i < size; ++i) {
    buffer[i] = index[(n * extension_random()) | 0];
  }
  return buffer;
}

// weighted sampling with replacement
// uses binary search lookup against cumulative weight
function extension_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 = extension_bisector(extension_ascending).right;
  for (let i = 0; i < size; ++i) {
    buffer[i] = index[bisect(w, sum * extension_random())];
  }
  return buffer;
}

// uniform sampling without replacement
// uses reservoir sampling to build out the sample
// https://en.wikipedia.org/wiki/Reservoir_sampling
function extension_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 * extension_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 extension_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(extension_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 extension_util_shuffle(array, lo = 0, hi = array.length) {
  let n = hi - (lo = +lo);

  while (n) {
    const i = extension_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 extension_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 {
      extension_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
    extension_util_shuffle(samples);
  }

  return table.reify(samples);
}
;// ../../node_modules/arquero/src/verbs/sample.js







/* harmony default export */ function extension_verbs_sample(table, size, options = {}) {
  return extension_engine_sample(
    table,
    extension_parseSize(table, size),
    extension_parseWeight(table, options.weight),
    options
  );
}

const extension_get = col => row => col.get(row) || 0;

function extension_parseSize(table, size) {
  return extension_is_number(size)
    ? () => size
    : extension_get(extension_rollup(table, extension_expression_parse({ size }, { table })).column('size'));
}

function extension_parseWeight(table, w) {
  if (w == null) return null;
  w = extension_is_number(w) ? table.columnName(w) : w;
  return extension_get(
    extension_is_string(w)
      ? table.column(w)
      : extension_derive(table, extension_expression_parse({ w }, { table }), { drop: true }).column('w')
  );
}
;// ../../node_modules/arquero/src/verbs/select.js



/* harmony default export */ function extension_verbs_select(table, columns) {
  return extension_engine_select(table, extension_resolve(table, columns));
}
;// ../../node_modules/arquero/src/engine/spread.js





/* harmony default export */ function extension_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 = extension_aggregateGet(table, ops, exprs);
  const cols = extension_column_set();
  const map = names.reduce((map, name, i) => map.set(name, i), new Map());

  const add = (index, name) => {
    const columns = extension_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 extension_spread_spread(table, get, limit) {
  const nrows = table.totalRows();
  const columns = [];

  table.scan((row, data) => {
    const values = extension_to_array(get(row, data));
    const n = Math.min(values.length, limit);
    while (columns.length < n) {
      columns.push(Array(nrows).fill(extension_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 extension_verbs_spread(table, values, options) {
  return extension_engine_spread(table, extension_util_parse('spread', table, values), options);
}
;// ../../node_modules/arquero/src/verbs/union.js
/* harmony default export */ function extension_union(table, others) {
  return table.concat(others).dedupe();
}
;// ../../node_modules/arquero/src/verbs/unroll.js



/* harmony default export */ function extension_verbs_unroll(table, values, options) {
  return extension_engine_unroll(
    table,
    extension_util_parse('unroll', table, values),
    options && options.drop
      ? { ...options, drop: extension_util_parse('unroll', table, options.drop).names }
      : options
  );
}
;// ../../node_modules/arquero/src/engine/groupby.js



/* harmony default export */ function extension_groupby(table, exprs) {
  return table.create({
    groups: extension_createGroups(table, exprs)
  });
}

function extension_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 = extension_aggregateGet(table, ops, exprs);
  const getKey = extension_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 extension_verbs_groupby(table, values) {
  return extension_groupby(table, extension_util_parse('groupby', table, values));
}
;// ../../node_modules/arquero/src/engine/orderby.js
/* harmony default export */ function extension_orderby(table, comparator) {
  return table.create({ order: comparator });
}

;// ../../node_modules/arquero/src/expression/compare.js




// generate code to compare a single field
const extension_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 src_extension_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 } = extension_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([
          extension_codegen(node, { index: 'a', op: opA }),
          extension_codegen(node, { index: 'b', op: opB })
        ]);
      }
    },
    window: false
  });

  // calculate aggregate values if needed
  const result = extension_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 += extension_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 extension_verbs_orderby(table, values) {
  return extension_orderby(table, extension_orderby_parseValues(table, values));
}

function extension_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 (extension_is_object(expr) && !extension_util_is_function(expr)) {
      for (const key in expr) add(expr[key]);
    } else {
      add(
        extension_is_number(expr) ? extension_field(param, table.columnName(expr))
          : extension_is_string(expr) ? extension_field(param)
          : extension_util_is_function(expr) ? param
          : extension_util_error(`Invalid orderby field: ${param+''}`)
      );
    }
  });

  return src_extension_compare(table, exprs);
}
;// ../../node_modules/arquero/src/engine/concat.js



/* harmony default export */ function extension_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 = extension_column_set();

  table.columnNames().forEach(name => {
    const arr = Array(nrows);
    let row = 0;
    tables.forEach(table => {
      const col = table.column(name) || { get: () => extension_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 extension_reduce(table, reducer) {
  const cols = extension_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
    ? extension_reduceGroups(table, reducer, groups)
    : [ extension_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 extension_ungroup(table) {
  return table.isGrouped()
    ? table.create({ groups: null })
    : table;
}
;// ../../node_modules/arquero/src/engine/unorder.js
/* harmony default export */ function extension_unorder(table) {
  return table.isOrdered()
    ? table.create({ order: null })
    : table;
}
;// ../../node_modules/arquero/src/verbs/index.js





























/* harmony default export */ const extension_verbs = ({
  __antijoin: (table, other, on) =>
    extension_verbs_join_filter(table, other, on, { anti: true }),
  __count: (table, options = {}) =>
    extension_verbs_rollup(table, { [options.as || 'count']: extension_count() }),
  __cross: (table, other, values, options) =>
    extension_verbs_join(table, other, () => true, values, {
      ...options, left: true, right: true
    }),
  __concat: extension_engine_concat,
  __dedupe: extension_dedupe,
  __derive: extension_verbs_derive,
  __except: extension_except,
  __filter: extension_verbs_filter,
  __fold: extension_verbs_fold,
  __impute: extension_verbs_impute,
  __intersect: extension_intersect,
  __join: extension_verbs_join,
  __lookup: extension_verbs_lookup,
  __pivot: extension_verbs_pivot,
  __relocate: extension_relocate,
  __rename: extension_rename,
  __rollup: extension_verbs_rollup,
  __sample: extension_verbs_sample,
  __select: extension_verbs_select,
  __semijoin: extension_verbs_join_filter,
  __spread: extension_verbs_spread,
  __union: extension_union,
  __unroll: extension_verbs_unroll,
  __groupby: extension_verbs_groupby,
  __orderby: extension_verbs_orderby,
  __ungroup: extension_ungroup,
  __unorder: extension_unorder,
  __reduce: extension_reduce
});
;// ../../node_modules/arquero/src/table/index.js



// Add verb implementations to ColumnTable prototype
Object.assign(extension_column_table_ColumnTable.prototype, extension_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 extension_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 extension_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 extension_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 extension_loadArrow(url, options) {
  return extension_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 extension_loadCSV(url, options) {
  return extension_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 extension_loadFixed(url, options) {
  return extension_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 extension_loadJSON(url, options) {
  return extension_load(url, { ...options, as: 'json', using: extension_parseJSON });
}

function extension_parseJSON(data, options) {
  return isArray(data) ? from(data) : fromJSON(data, options);
}
;// ../../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 extension_agg(table, expr) {
  return table.ungroup().rollup({ _: expr }).get('_');
}
;// ../../node_modules/arquero/src/register.js













const extension_onIllegal = (name, type) =>
  error(`Illegal ${type} name: ${toString(name)}`);

const extension_onDefined = (name, type) =>
  error(`The ${type} ${toString(name)} is already defined. Use override option?`);

const extension_onReserve = (name, type) =>
  error(`The ${type} name ${toString(name)} is reserved and can not be overridden.`);

function extension_register_check(name, options, obj = ops, type = 'function') {
  if (!name) extension_onIllegal(name, type);
  if (!options.override && has(obj, name)) extension_onDefined(name, type);
}

// -- Op Functions --------------------------------------------------

function extension_verifyFunction(name, def, object, options) {
  return object[name] === def || extension_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 extension_addOp(name, def, object, options = {}) {
  if (extension_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 extension_addAggregateFunction(name, def, options) {
  extension_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 extension_addWindowFunction(name, def, options) {
  extension_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 extension_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) {
      extension_onReserve(ROW_OBJECT, 'function');
    }
  }
  if (extension_verifyFunction(name, fn, functions, options)) return;
  functions[name] = fn;
  ops[name] = fn;
}

// -- Table Methods and Verbs ---------------------------------------

const extension_proto = extension_column_table_ColumnTable.prototype;

/**
 * Reserved table/query methods that must not be overwritten.
 */
let extension_RESERVED;

function extension_addReserved(obj) {
  for (; obj; obj = Object.getPrototypeOf(obj)) {
    Object.getOwnPropertyNames(obj).forEach(name => extension_RESERVED[name] = 1);
  }
}

function extension_verifyTableMethod(name, fn, options) {
  const type = 'method';

  // exit early if duplicate re-assignment
  if (extension_proto[name] && extension_proto[name].fn === fn) return true;

  // initialize reserved properties to avoid overriding internals
  if (!extension_RESERVED) {
    extension_RESERVED = {};
    extension_addReserved(extension_proto);
    extension_addReserved(Query.prototype);
  }

  // perform name checks
  if (extension_RESERVED[name]) extension_onReserve(name, type);
  if ((name + '')[0] === '_') extension_onIllegal(name, type);
  extension_register_check(name, options, extension_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 extension_addTableMethod(name, method, options = {}) {
  if (extension_verifyTableMethod(name, method, options)) return;
  extension_proto[name] = function(...args) { return method(this, ...args); };
  extension_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 extension_addVerb(name, method, params, options = {}) {
  // register table method first
  // if that doesn't throw, add serializable verb entry
  extension_addTableMethod(name, method, options);
  addQueryVerb(name, Verbs[name] = createVerb(name, params));
}

// -- Package Bundles -----------------------------------------------

const extension_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 extension_addPackage(bundle, options = {}) {
  const pkg = bundle && bundle[extension_PACKAGE] || bundle;
  const parts = {
    functions: [
      (name, def, opt) => extension_verifyFunction(name, def, functions, opt),
      extension_addFunction
    ],
    aggregateFunctions: [
      (name, def, opt) => extension_verifyFunction(name, def, aggregateFunctions, opt),
      extension_addAggregateFunction
    ],
    windowFunctions: [
      (name, def, opt) => extension_verifyFunction(name, def, windowFunctions, opt),
      extension_addWindowFunction
    ],
    tableMethods: [
      extension_verifyTableMethod,
      extension_addTableMethod
    ],
    verbs: [
      (name, obj, opt) => extension_verifyTableMethod(name, obj.method, opt),
      (name, obj, opt) => extension_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 extension_internal = {
  Table: extension_Table,
  ColumnTable: extension_column_table_ColumnTable,
  Transformable: extension_Transformable,
  Query: extension_query_Query,
  Reducer: extension_Reducer,
  Verb: extension_Verb,
  Verbs: extension_verb_Verbs,
  columnFactory: extension_columnFactory,
  parse: extension_expression_parse,
  walk_ast: extension_walk
};

// export public API

const extension_src_version = extension_package_namespaceObject.rE;






















;// ../../node_modules/svelte/store/index.mjs



const extension_subscriber_queue = [];
/**
 * Creates a `Readable` store that allows reading by subscription.
 * @param value initial value
 * @param {StartStopNotifier} [start]
 */
function extension_readable(value, start) {
    return {
        subscribe: extension_writable(value, start).subscribe
    };
}
/**
 * Create a `Writable` store that allows both updating and reading by subscription.
 * @param {*=}value initial value
 * @param {StartStopNotifier=} start
 */
function extension_writable(value, start = extension_noop) {
    let stop;
    const subscribers = new Set();
    function set(new_value) {
        if (extension_safe_not_equal(value, new_value)) {
            value = new_value;
            if (stop) { // store is ready
                const run_queue = !extension_subscriber_queue.length;
                for (const subscriber of subscribers) {
                    subscriber[1]();
                    extension_subscriber_queue.push(subscriber, value);
                }
                if (run_queue) {
                    for (let i = 0; i < extension_subscriber_queue.length; i += 2) {
                        extension_subscriber_queue[i][0](extension_subscriber_queue[i + 1]);
                    }
                    extension_subscriber_queue.length = 0;
                }
            }
        }
    }
    function update(fn) {
        set(fn(value));
    }
    function subscribe(run, invalidate = extension_noop) {
        const subscriber = [run, invalidate];
        subscribers.add(subscriber);
        if (subscribers.size === 1) {
            stop = start(set) || extension_noop;
        }
        run(value);
        return () => {
            subscribers.delete(subscriber);
            if (subscribers.size === 0 && stop) {
                stop();
                stop = null;
            }
        };
    }
    return { set, update, subscribe };
}
function extension_derived(stores, fn, initial_value) {
    const single = !Array.isArray(stores);
    const stores_array = single
        ? [stores]
        : stores;
    const auto = fn.length < 2;
    return extension_readable(initial_value, (set) => {
        let started = false;
        const values = [];
        let pending = 0;
        let cleanup = extension_noop;
        const sync = () => {
            if (pending) {
                return;
            }
            cleanup();
            const result = fn(single ? values[0] : values, set);
            if (auto) {
                set(result);
            }
            else {
                cleanup = extension_internal_is_function(result) ? result : extension_noop;
            }
        };
        const unsubscribers = stores_array.map((store, i) => extension_subscribe(store, (value) => {
            values[i] = value;
            pending &= ~(1 << i);
            if (started) {
                sync();
            }
        }, () => {
            pending |= (1 << i);
        }));
        started = true;
        sync();
        return function stop() {
            extension_run_all(unsubscribers);
            cleanup();
            // We need to set this to false because callbacks can still happen despite having unsubscribed:
            // Callbacks might already be placed in the queue which doesn't know it should no longer
            // invoke this derived store.
            started = false;
        };
    });
}
/**
 * Takes a store and returns a new one derived from the old one that is readable.
 *
 * @param store - store to make readonly
 */
function extension_readonly(store) {
    return {
        subscribe: store.subscribe.bind(store)
    };
}



;// ../../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 extension_UNIQUE_COLS_PCTG = 0.1;
function extension_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 extension_getBinnableStringColumns(table) {
    const colNames = table.columnNames();
    const binnnableStringColumns = [];
    for (const colName of colNames) {
        const columnType = extension_getColumnType(table, colName);
        if (columnType === "string") {
            if (extension_isStringColumnBinnable(colName, table)) {
                binnnableStringColumns.push(colName);
            }
        }
    }
    return binnnableStringColumns;
}
function extension_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 < extension_UNIQUE_COLS_PCTG * table.numRows()) {
        return true;
    }
    return false;
}
const extension_cartesian = (...a) => a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e].reduce((acc, val) => acc.concat(val), []))));

;// ../../canvas_viz/dist/stores.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 extension_widgetWritable(name_, value_) {
    const name = name_;
    const curVal = extension_writable(value_);
    let model;
    return {
        set: (v) => {
            curVal.set(v);
            if (model) {
                model.set(name, v);
                model.save_changes();
            }
        },
        setModel: (m) => {
            model = m;
            curVal.set(model.get(name));
            model.on("change:" + name, () => curVal.set(model.get(name)), null);
        },
        subscribe: curVal.subscribe,
        update: (func) => {
            curVal.update((v) => {
                const out = func(v);
                // TODO: figure out why spread operator isn't enough to update model.
                if (model) {
                    model.set(name, "");
                    model.set(name, out);
                    model.save_changes();
                }
                return out;
            });
        },
    };
}
const extension_canvasSpec = extension_widgetWritable("canvas_spec", {});
const extension_widgetSpecs = extension_widgetWritable("widgetSpecs", {});
const extension_dataTable = extension_widgetWritable("table", new DataView(new ArrayBuffer(0)));
const extension_selected = extension_widgetWritable("selected", []);
const extension_groupColumns = extension_widgetWritable("group_columns", []);
const extension_stores_filter = extension_widgetWritable("filter", "");
const extension_filterError = extension_widgetWritable("filter_error", "");
const extension_tooltip = extension_widgetWritable("tooltip", {
    hover: false,
    mousePos: { x: 0, y: 0 },
    fetchPrefix: "",
    instance: undefined,
    number: 0,
});
const extension_stores_table = extension_derived(extension_dataTable, (d) => extension_from_arrow(d));
const extension_filteredTable = extension_derived([extension_stores_table, extension_stores_filter], ([table, filter]) => {
    extension_filterError.set("");
    let filteredTable = table;
    if (filter) {
        try {
            filteredTable = filteredTable.filter(filter);
        }
        catch (err) {
            extension_filterError.set(err);
        }
    }
    return filteredTable;
});
const extension_groupNames = extension_derived([extension_filteredTable, extension_groupColumns], ([filteredTable, groupColumns]) => {
    if (groupColumns.length > 0) {
        const uniqueColumnValues = groupColumns.map((col) => filteredTable
            .rollup({ col: extension_op_api.array_agg_distinct(col) })
            .object().col);
        // If just one column, don't do cartesian product and make it a 2D array.
        if (uniqueColumnValues.length === 1) {
            return uniqueColumnValues[0].map((group) => [group]);
        }
        return extension_cartesian(...uniqueColumnValues);
    }
    else
        return [];
});
const extension_groupedTables = extension_derived([extension_filteredTable, extension_groupColumns, extension_groupNames, extension_canvasSpec], ([filteredTable, groupColumns, groupNames, canvasSpec]) => {
    if (groupColumns !== undefined &&
        filteredTable !== undefined &&
        groupNames !== undefined &&
        groupColumns.length > 0 &&
        groupNames.length > 0) {
        let groupedTable = filteredTable.groupby(...groupColumns);
        let partitions = groupedTable.partitions();
        let groupedTables = partitions.map((partition) => filteredTable.reify(partition));
        return groupedTables;
    }
    else {
        return [];
    }
});
function extension_initializeStores(model) {
    extension_selected.setModel(model);
    extension_stores_filter.setModel(model);
    extension_groupColumns.setModel(model);
    extension_canvasSpec.setModel(model);
    extension_dataTable.setModel(model);
}

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

function extension_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 extension_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 extension_joinCss([
    extension_joinCss({
      float,
      width,
      height,
      'line-height': lineHeight,
      'font-size': fontSize,
      'text-align': textAlign,
      'vertical-align': verticalAlign,
      'transform-origin': 'center',
      overflow,
    }),
    style,
  ]);
}

function extension_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 extension_joinCss(
    [
      `translate(${extension_utils_parseNumber(translateX) * translateTimes}${translateUnit},${extension_utils_parseNumber(translateY) * translateTimes}${translateUnit})`,
      `scale(${flipX * extension_utils_parseNumber(scale)},${flipY * extension_utils_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 extension_add_css(target) {
	extension_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 extension_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 extension_create_if_block_1;
		return extension_create_else_block;
	}

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

	return {
		c() {
			svg = extension_svg_element("svg");
			g1 = extension_svg_element("g");
			g0 = extension_svg_element("g");
			if_block.c();
			extension_attr(g0, "transform", /*transform*/ ctx[10]);
			extension_attr(g1, "transform", g1_transform_value = `translate(${/*i*/ ctx[7][0] / 2} ${/*i*/ ctx[7][1] / 2})`);
			extension_attr(g1, "transform-origin", g1_transform_origin_value = `${/*i*/ ctx[7][0] / 4} 0`);
			extension_attr(svg, "id", /*id*/ ctx[0]);
			extension_attr(svg, "class", svg_class_value = "" + (extension_null_to_empty(/*c*/ ctx[8]) + " svelte-q6amlk"));
			extension_attr(svg, "style", /*s*/ ctx[9]);
			extension_attr(svg, "viewBox", svg_viewBox_value = `0 0 ${/*i*/ ctx[7][0]} ${/*i*/ ctx[7][1]}`);
			extension_attr(svg, "aria-hidden", "true");
			extension_attr(svg, "role", "img");
			extension_attr(svg, "xmlns", "http://www.w3.org/2000/svg");
		},
		m(target, anchor) {
			extension_insert(target, svg, anchor);
			extension_append(svg, g1);
			extension_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) {
				extension_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})`)) {
				extension_attr(g1, "transform", g1_transform_value);
			}

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

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

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

			if (dirty & /*s*/ 512) {
				extension_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]}`)) {
				extension_attr(svg, "viewBox", svg_viewBox_value);
			}
		},
		d(detaching) {
			if (detaching) extension_detach(svg);
			if_block.d();
		}
	};
}

// (114:8) {:else}
function extension_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 = extension_svg_element("path");
			path1 = extension_svg_element("path");
			extension_attr(path0, "d", path0_d_value = /*i*/ ctx[7][4][0]);
			extension_attr(path0, "fill", path0_fill_value = /*secondaryColor*/ ctx[3] || /*color*/ ctx[1] || 'currentColor');

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

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

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

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

			if (dirty & /*secondaryColor, color*/ 10 && path0_fill_value !== (path0_fill_value = /*secondaryColor*/ ctx[3] || /*color*/ ctx[1] || 'currentColor')) {
				extension_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])) {
				extension_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})`)) {
				extension_attr(path0, "transform", path0_transform_value);
			}

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

			if (dirty & /*primaryColor, color*/ 6 && path1_fill_value !== (path1_fill_value = /*primaryColor*/ ctx[2] || /*color*/ ctx[1] || 'currentColor')) {
				extension_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])) {
				extension_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})`)) {
				extension_attr(path1, "transform", path1_transform_value);
			}
		},
		d(detaching) {
			if (detaching) extension_detach(path0);
			if (detaching) extension_detach(path1);
		}
	};
}

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

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

			if (dirty & /*color, primaryColor*/ 6 && path_fill_value !== (path_fill_value = /*color*/ ctx[1] || /*primaryColor*/ ctx[2] || 'currentColor')) {
				extension_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})`)) {
				extension_attr(path, "transform", path_transform_value);
			}
		},
		d(detaching) {
			if (detaching) extension_detach(path);
		}
	};
}

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

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = extension_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			extension_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 = extension_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: extension_noop,
		o: extension_noop,
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) extension_detach(if_block_anchor);
		}
	};
}

function extension_fa_svelte_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 = extension_joinCss([clazz, 'svelte-fa', spin && 'spin', pulse && 'pulse'], ' '));
		}

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

		if ($$self.$$.dirty & /*scale, translateX, translateY, rotate, flip*/ 4063232) {
			$: $$invalidate(10, transform = extension_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 extension_Fa extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(
			this,
			options,
			extension_fa_svelte_instance,
			extension_create_fragment,
			extension_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
			},
			extension_add_css
		);
	}
}

/* harmony default export */ const extension_fa_svelte = (extension_Fa);
;// ../../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 extension_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 extension_backIn(t) {
    const s = 1.70158;
    return t * t * ((s + 1) * t - s);
}
function extension_backOut(t) {
    const s = 1.70158;
    return --t * t * ((s + 1) * t + s) + 1;
}
function extension_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 extension_bounceInOut(t) {
    return t < 0.5
        ? 0.5 * (1.0 - extension_bounceOut(1.0 - t * 2.0))
        : 0.5 * extension_bounceOut(t * 2.0 - 1.0) + 0.5;
}
function extension_bounceIn(t) {
    return 1.0 - extension_bounceOut(1.0 - t);
}
function extension_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 extension_circIn(t) {
    return 1.0 - Math.sqrt(1.0 - t * t);
}
function extension_circOut(t) {
    return Math.sqrt(1 - --t * t);
}
function extension_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 extension_cubicIn(t) {
    return t * t * t;
}
function extension_easing_cubicOut(t) {
    const f = t - 1.0;
    return f * f * f + 1.0;
}
function extension_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 extension_elasticIn(t) {
    return Math.sin((13.0 * t * Math.PI) / 2) * Math.pow(2.0, 10.0 * (t - 1.0));
}
function extension_elasticOut(t) {
    return (Math.sin((-13.0 * (t + 1.0) * Math.PI) / 2) * Math.pow(2.0, -10.0 * t) + 1.0);
}
function extension_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 extension_expoIn(t) {
    return t === 0.0 ? t : Math.pow(2.0, 10.0 * (t - 1.0));
}
function extension_expoOut(t) {
    return t === 1.0 ? t : 1.0 - Math.pow(2.0, -10.0 * t);
}
function extension_quadInOut(t) {
    t /= 0.5;
    if (t < 1)
        return 0.5 * t * t;
    t--;
    return -0.5 * (t * (t - 2) - 1);
}
function extension_quadIn(t) {
    return t * t;
}
function extension_quadOut(t) {
    return -t * (t - 2.0);
}
function extension_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 extension_quartIn(t) {
    return Math.pow(t, 4.0);
}
function extension_quartOut(t) {
    return Math.pow(t - 1.0, 3.0) * (1.0 - t) + 1.0;
}
function extension_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 extension_quintIn(t) {
    return t * t * t * t * t;
}
function extension_quintOut(t) {
    return --t * t * t * t * t + 1;
}
function extension_sineInOut(t) {
    return -0.5 * (Math.cos(Math.PI * t) - 1);
}
function extension_sineIn(t) {
    const v = Math.cos(t * Math.PI * 0.5);
    if (Math.abs(v) < 1e-14)
        return 1;
    else
        return 1 - v;
}
function extension_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 extension_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 extension_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 extension_fade(node, { delay = 0, duration = 400, easing = extension_internal_identity } = {}) {
    const o = +getComputedStyle(node).opacity;
    return {
        delay,
        duration,
        easing,
        css: t => `opacity: ${t * o}`
    };
}
function extension_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 extension_slide(node, { delay = 0, duration = 400, 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 extension_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 extension_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 extension_crossfade(_a) {
    var { fallback } = _a, defaults = extension_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)
    ];
}



// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faChartBar.js
var extension_faChartBar = __webpack_require__(4383);
;// ../../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 extension_CanvasDataType;
(function (CanvasDataType) {
    CanvasDataType[CanvasDataType["TABULAR"] = 1] = "TABULAR";
    CanvasDataType[CanvasDataType["IMAGE"] = 2] = "IMAGE";
    CanvasDataType[CanvasDataType["AUDIO"] = 3] = "AUDIO";
})(extension_CanvasDataType || (extension_CanvasDataType = {}));
var extension_ResolverType;
(function (ResolverType) {
    ResolverType[ResolverType["BINNED_STRING"] = 0] = "BINNED_STRING";
    ResolverType[ResolverType["NUMBER"] = 1] = "NUMBER";
})(extension_ResolverType || (extension_ResolverType = {}));

;// ../../node_modules/@fireflysemantics/join/fesm2015/fireflysemantics-join.js
/**
MIT License

Copyright (c) Firefly Semantics Corporation
Copyright (c) 2020 Ole K. Ersoy
Copyright (c) 2015 José F. Romaniello

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. */
/**
 * @param args The components of the URL
 * @throws TypeError if the args URL components are not all of type string
 * @return The URL string
 */
function extension_fireflysemantics_join_join(...args) {
    let components = [];
    /**
     * If an empty array is received then
     * the URL is just ''.
     */
    if (args.length === 0) {
        return '';
    }
    /** The args values must be of type string */
    args.forEach(component => {
        if (typeof component !== 'string') {
            throw new TypeError(`Url components must be of type string. 
                    The ${component} component is of type ${typeof component}`);
        }
    });
    /**
     * If the protocol is specified by itself,
     * then the protocol is combined with the
     * subsequent array value.
     */
    const protocol = args[0];
    if (protocol.match(/^[^/:]+:\/*$/) && args.length > 1) {
        var first = args.shift();
        args[0] = first + args[0];
    }
    /**
     * The file protocol should have two or three slashes.
     * Other protocols should have 2.
     */
    if (args[0].match(/^file:\/\/\//)) {
        args[0] = args[0].replace(/^([^/:]+):\/*/, '$1:///');
    }
    else {
        args[0] = args[0].replace(/^([^/:]+):\/*/, '$1://');
    }
    /** The args values must be of type string */
    args.forEach((component, i) => {
        if (component === '') {
            return;
        }
        /**
         * Remove starting slashes for all but the first component
         */
        if (i > 0) {
            component = component.replace(/^[\/]+/, '');
        }
        /**
         * Remove the ending slashes for each component but the last.
         */
        if (i < args.length - 1) {
            component = component.replace(/[\/]+$/, '');
        }
        else {
            // For the last combine multiple slashes into one.
            component = component.replace(/[\/]+$/, '/');
        }
        components.push(component);
    });
    /**
     * Separate all the components by a single /
     */
    let url = components.join('/');
    // remove trailing slash before parameters or hash
    url = url.replace(/\/(\?|&|#[^!])/g, '$1');
    // replace ? in parameters with &
    var parts = url.split('?');
    url = parts.shift() + (parts.length > 0 ? '?' : '') + parts.join('&');
    return url;
}

/*
 * Public API Surface of join
 */

/**
 * Generated bundle index. Do not edit.
 */


//# sourceMappingURL=fireflysemantics-join.js.map

// EXTERNAL MODULE: ../../node_modules/@jupyterlab/services/lib/index.js
var extension_lib = __webpack_require__(7883);
;// ../../canvas_viz/dist/helpers/contentservice.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.
 */

/**
 * Singleton contentsService class for managing file operations
 */
class extension_ContentsService {
    constructor() {
        var _a;
        const contentsManager = new extension_lib.ContentsManager();
        this.contentsManager = contentsManager;
        // Get the server root from the contents manager settings
        this.baseServerPath = ((_a = contentsManager.serverSettings) === null || _a === void 0 ? void 0 : _a.baseUrl) || process.env.JUPYTER_SERVER_ROOT || '';
    }
    static getInstance() {
        if (!this.instance) {
            this.instance = new extension_ContentsService();
        }
        return this.instance;
    }
    /**
     * Create a file/directory if it does not exist. Otherwise, save the change in a file/directory in the given path
     * @param path path to a file/directory
     * @param options options that specify if it's a file or directory and additial information
     * Usage: save('snippets', { type: 'directory' }) to create/save a directory
     *        save('snippets/test.json', {type: 'file', format: 'text', content: 'Lorem ipsum dolor sit amet'})
     */
    async save(path, options) {
        try {
            const changedModel = await this.contentsManager.save(path, options);
            return changedModel;
        }
        catch (error) {
            console.error('Error saving file/directory:', error);
            throw error; // Re-throw the error instead of returning it
        }
    }
    async readContent(path) {
        try {
            const getFileResult = await this.contentsManager.get(path);
            if (typeof getFileResult.content !== 'string') {
                throw new Error('Unable to read the image');
            }
            return `data:${getFileResult.mimetype};${getFileResult.format},${getFileResult.content}`;
        }
        catch (error) {
            console.error('Error reading file/directory:', error);
            throw error; // Re-throw the error instead of returning it
        }
    }
    async readAudioContent(path) {
        try {
            const getFileResult = await this.contentsManager.get(path);
            if (typeof getFileResult.content !== 'string') {
                throw new Error('Unable to read the Audio data');
            }
            return `${getFileResult.content}`;
        }
        catch (error) {
            console.error('Error reading file/directory:', error);
            throw error; // Re-throw the error instead of returning it
        }
    }
    /**
     * Convert a server path to a local filesystem path
     * @param path - Server path (e.g., '/notebooks/example.ipynb')
     * @returns Local filesystem path (e.g., '/home/user/notebooks/example.ipynb')
     *
     * Usage:
     * ```typescript
     * const serverPath = '/notebooks/example.ipynb';
     * const localPath = contentsService.getLocalPath(serverPath);
     * console.log(localPath); // '/home/user/notebooks/example.ipynb'
     * ```
     */
    getLocalPath(path) {
        const relativePath = this.contentsManager.localPath(path);
        if (!this.baseServerPath) {
            console.warn('Base server path not available, returning relative path');
            return relativePath;
        }
        return `${this.baseServerPath}/${relativePath}`.replace(/\/+/g, '/'); // Clean up any double slashes
    }
    /**
     * Convert a local filesystem path to a server path
     * @param localPath - Local filesystem path (e.g., '/home/user/notebooks/example.ipynb')
     * @returns Server path (e.g., '/notebooks/example.ipynb')
     *
     * Usage:
     * ```typescript
     * const localPath = '/home/user/notebooks/example.ipynb';
     * const serverPath = contentsService.getServerPath(localPath);
     * console.log(serverPath); // '/notebooks/example.ipynb'
     * ```
     */
    getServerPath(localPath) {
        return this.contentsManager.normalize(localPath);
    }
    /**
     * Resolve a relative path against a parent directory
     * @param relativePath - Relative path to resolve (e.g., '../data/file.csv')
     * @param parent - Parent directory to resolve against (e.g., '/notebooks/project')
     * @returns Resolved absolute server path
     *
     * Usage:
     * ```typescript
     * // When in /notebooks/project/analysis
     * const relativePath = '../data/file.csv';
     * const parent = '/notebooks/project/analysis';
     * const resolved = contentsService.resolvePath(relativePath, parent);
     * console.log(resolved); // '/notebooks/project/data/file.csv'
     *
     * // Handle special cases
     * contentsService.resolvePath('.', '/home');        // Returns '/home'
     * contentsService.resolvePath('..', '/home/user');  // Returns '/home'
     * contentsService.resolvePath('file.txt', '/dir');  // Returns '/dir/file.txt'
     * ```
     */
    resolvePath(relativePath, parent) {
        return this.contentsManager.resolvePath(relativePath, parent);
    }
}

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





function extension_create_catch_block(ctx) {
	let p;
	let t_value = /*error*/ ctx[9].message + "";
	let t;

	return {
		c() {
			p = extension_internal_element("p");
			t = extension_internal_text(t_value);
			extension_attr(p, "class", "error");
		},
		m(target, anchor) {
			extension_insert(target, p, anchor);
			extension_append(p, t);
		},
		p(ctx, dirty) {
			if (dirty & /*imagePromise*/ 8 && t_value !== (t_value = /*error*/ ctx[9].message + "")) extension_set_data(t, t_value);
		},
		d(detaching) {
			if (detaching) extension_detach(p);
		}
	};
}

// (55:2) {:then src}
function extension_create_then_block(ctx) {
	let img;
	let img_src_value;
	let img_alt_value;
	let img_class_value;
	let img_style_value;
	let mounted;
	let dispose;

	return {
		c() {
			img = extension_internal_element("img");
			extension_attr(img, "id", "imageSample");
			if (!extension_src_url_equal(img.src, img_src_value = /*src*/ ctx[8])) extension_attr(img, "src", img_src_value);
			extension_attr(img, "alt", img_alt_value = "Image with title: " + /*id*/ ctx[0]);
			extension_attr(img, "class", img_class_value = /*large*/ ctx[2] ? "mx-1" : "w-12 m-1");
			extension_attr(img, "style", img_style_value = `background: black; max-width: ${/*large*/ ctx[2] ? '256px' : '128px'}`);
		},
		m(target, anchor) {
			extension_insert(target, img, anchor);

			if (!mounted) {
				dispose = extension_listen(img, "error", extension_handleImageError);
				mounted = true;
			}
		},
		p(ctx, dirty) {
			if (dirty & /*imagePromise*/ 8 && !extension_src_url_equal(img.src, img_src_value = /*src*/ ctx[8])) {
				extension_attr(img, "src", img_src_value);
			}

			if (dirty & /*id*/ 1 && img_alt_value !== (img_alt_value = "Image with title: " + /*id*/ ctx[0])) {
				extension_attr(img, "alt", img_alt_value);
			}

			if (dirty & /*large*/ 4 && img_class_value !== (img_class_value = /*large*/ ctx[2] ? "mx-1" : "w-12 m-1")) {
				extension_attr(img, "class", img_class_value);
			}

			if (dirty & /*large*/ 4 && img_style_value !== (img_style_value = `background: black; max-width: ${/*large*/ ctx[2] ? '256px' : '128px'}`)) {
				extension_attr(img, "style", img_style_value);
			}
		},
		d(detaching) {
			if (detaching) extension_detach(img);
			mounted = false;
			dispose();
		}
	};
}

// (53:23)      <p class="loading">Loading...</p>   {:then src}
function extension_create_pending_block(ctx) {
	let p;

	return {
		c() {
			p = extension_internal_element("p");
			p.textContent = "Loading...";
			extension_attr(p, "class", "loading");
		},
		m(target, anchor) {
			extension_insert(target, p, anchor);
		},
		p: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(p);
		}
	};
}

function extension_ImageSample_svelte_create_fragment(ctx) {
	let div;
	let promise;

	let info = {
		ctx,
		current: null,
		token: null,
		hasCatch: true,
		pending: extension_create_pending_block,
		then: extension_create_then_block,
		catch: extension_create_catch_block,
		value: 8,
		error: 9
	};

	extension_handle_promise(promise = /*imagePromise*/ ctx[3], info);

	return {
		c() {
			div = extension_internal_element("div");
			info.block.c();
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			info.block.m(div, info.anchor = null);
			info.mount = () => div;
			info.anchor = null;
		},
		p(new_ctx, [dirty]) {
			ctx = new_ctx;
			info.ctx = ctx;

			if (dirty & /*imagePromise*/ 8 && promise !== (promise = /*imagePromise*/ ctx[3]) && extension_handle_promise(promise, info)) {
				
			} else {
				extension_update_await_block_branch(info, ctx, dirty);
			}
		},
		i: extension_noop,
		o: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(div);
			info.block.d();
			info.token = null;
			info = null;
		}
	};
}

function extension_handleImageError(event) {
	console.error("Error loading image:", event);
	const target = event.target;
	target.alt = 'Image failed to load';
}

function extension_ImageSample_svelte_instance($$self, $$props, $$invalidate) {
	let $canvasSpec,
		$$unsubscribe_canvasSpec = extension_noop,
		$$subscribe_canvasSpec = () => ($$unsubscribe_canvasSpec(), $$unsubscribe_canvasSpec = extension_subscribe(canvasSpec, $$value => $$invalidate(5, $canvasSpec = $$value)), canvasSpec);

	$$self.$$.on_destroy.push(() => $$unsubscribe_canvasSpec());
	let { id } = $$props;
	let { canvasSpec } = $$props;
	$$subscribe_canvasSpec();
	let { large = false } = $$props;
	let { storybook = false } = $$props;
	let imagePromise;
	const contentsManager = extension_ContentsService.getInstance();

	async function loadImage(filesPath, imageId) {
		// console.log("Loading image:", imageId);
		if (storybook) {
			// console.log("Loading image from storybook:", join(filesPath, imageId));
			return extension_fireflysemantics_join_join(filesPath, imageId);
		} else {
			try {
				const filePath = extension_fireflysemantics_join_join(filesPath, imageId);
				const result = await contentsManager.readContent(filePath);

				if (typeof result !== 'string') {
					throw new Error('Unexpected content type');
				}

				return result;
			} catch(error) {
				console.error('Error reading image file:', error);
				throw new Error(`Failed to load image: ${imageId}`);
			}
		}
	}

	$$self.$$set = $$props => {
		if ('id' in $$props) $$invalidate(0, id = $$props.id);
		if ('canvasSpec' in $$props) $$subscribe_canvasSpec($$invalidate(1, canvasSpec = $$props.canvasSpec));
		if ('large' in $$props) $$invalidate(2, large = $$props.large);
		if ('storybook' in $$props) $$invalidate(4, storybook = $$props.storybook);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*$canvasSpec, id*/ 33) {
			$: $$invalidate(3, imagePromise = loadImage($canvasSpec.filesPath, id));
		}
	};

	return [id, canvasSpec, large, imagePromise, storybook, $canvasSpec];
}

class extension_ImageSample extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(this, options, extension_ImageSample_svelte_instance, extension_ImageSample_svelte_create_fragment, extension_safe_not_equal, {
			id: 0,
			canvasSpec: 1,
			large: 2,
			storybook: 4
		});
	}
}

/* harmony default export */ const extension_ImageSample_svelte = (extension_ImageSample);
;// ../../node_modules/svelte/index.mjs


// EXTERNAL MODULE: ../../node_modules/wavesurfer.js/dist/wavesurfer.js
var extension_dist_wavesurfer = __webpack_require__(7290);
var extension_wavesurfer_default = /*#__PURE__*/__webpack_require__.n(extension_dist_wavesurfer);
;// ../../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 extension_get_text_slot_changes = dirty => ({});
const extension_get_text_slot_context = ctx => ({});
const extension_get_icon_slot_changes = dirty => ({});
const extension_get_icon_slot_context = ctx => ({});

// (26:4) {#if $$slots.icon}
function extension_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 = extension_create_slot(icon_slot_template, ctx, /*$$scope*/ ctx[2], extension_get_icon_slot_context);

	return {
		c() {
			div = extension_internal_element("div");
			if (icon_slot) icon_slot.c();
			extension_attr(div, "class", div_class_value = /*$$slots*/ ctx[1].text ? "pr-2 flex" : "flex");
		},
		m(target, anchor) {
			extension_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)) {
					extension_update_slot_base(
						icon_slot,
						icon_slot_template,
						ctx,
						/*$$scope*/ ctx[2],
						!current
						? extension_get_all_dirty_from_scope(/*$$scope*/ ctx[2])
						: extension_get_slot_changes(icon_slot_template, /*$$scope*/ ctx[2], dirty, extension_get_icon_slot_changes),
						extension_get_icon_slot_context
					);
				}
			}

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

function extension_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 && extension_IconButton_svelte_create_if_block(ctx);
	const text_slot_template = /*#slots*/ ctx[3].text;
	const text_slot = extension_create_slot(text_slot_template, ctx, /*$$scope*/ ctx[2], extension_get_text_slot_context);

	return {
		c() {
			button = extension_internal_element("button");
			div = extension_internal_element("div");
			if (if_block) if_block.c();
			t = extension_space();
			if (text_slot) text_slot.c();
			extension_attr(div, "class", "flex items-center");

			extension_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) {
			extension_insert(target, button, anchor);
			extension_append(button, div);
			if (if_block) if_block.m(div, null);
			extension_append(div, t);

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

			current = true;

			if (!mounted) {
				dispose = [
					extension_listen(button, "click", /*click_handler*/ ctx[4]),
					extension_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) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_IconButton_svelte_create_if_block(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(div, t);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}

			if (text_slot) {
				if (text_slot.p && (!current || dirty & /*$$scope*/ 4)) {
					extension_update_slot_base(
						text_slot,
						text_slot_template,
						ctx,
						/*$$scope*/ ctx[2],
						!current
						? extension_get_all_dirty_from_scope(/*$$scope*/ ctx[2])
						: extension_get_slot_changes(text_slot_template, /*$$scope*/ ctx[2], dirty, extension_get_text_slot_changes),
						extension_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"))) {
				extension_attr(button, "class", button_class_value);
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			extension_transition_in(text_slot, local);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			extension_transition_out(text_slot, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(button);
			if (if_block) if_block.d();
			if (text_slot) text_slot.d(detaching);
			mounted = false;
			extension_run_all(dispose);
		}
	};
}

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

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

	function mouseleave_handler(event) {
		extension_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 extension_IconButton extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_IconButton_svelte_instance, extension_IconButton_svelte_create_fragment, extension_safe_not_equal, { filled: 0 });
	}
}

/* harmony default export */ const extension_IconButton_svelte = (extension_IconButton);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faPlay.js
var extension_faPlay = __webpack_require__(3852);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faPause.js
var extension_faPause = __webpack_require__(2162);
;// ../../canvas_viz/dist/elements/AudioSample.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/AudioSample.svelte generated by Svelte v3.59.2 */











function extension_create_icon_slot(ctx) {
	let fa;
	let current;

	fa = new extension_fa_svelte({
			props: {
				icon: /*playing*/ ctx[3] ? extension_faPause/* faPause */.G1 : extension_faPlay/* faPlay */.ij,
				slot: "icon"
			}
		});

	return {
		c() {
			extension_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(fa, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const fa_changes = {};
			if (dirty & /*playing*/ 8) fa_changes.icon = /*playing*/ ctx[3] ? extension_faPause/* faPause */.G1 : extension_faPlay/* faPlay */.ij;
			fa.$set(fa_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(fa, detaching);
		}
	};
}

function extension_AudioSample_svelte_create_fragment(ctx) {
	let div2;
	let div0;
	let t;
	let div1;
	let iconbutton;
	let div2_class_value;
	let current;
	let mounted;
	let dispose;

	iconbutton = new extension_IconButton_svelte({
			props: {
				$$slots: { icon: [extension_create_icon_slot] },
				$$scope: { ctx }
			}
		});

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

	return {
		c() {
			div2 = extension_internal_element("div");
			div0 = extension_internal_element("div");
			t = extension_space();
			div1 = extension_internal_element("div");
			extension_create_component(iconbutton.$$.fragment);
			extension_attr(div2, "class", div2_class_value = "flex flex-col " + (/*large*/ ctx[1] ? 'w-48 mx-1' : 'w-24 m-1'));
		},
		m(target, anchor) {
			extension_insert(target, div2, anchor);
			extension_append(div2, div0);
			/*div0_binding*/ ctx[11](div0);
			extension_append(div2, t);
			extension_append(div2, div1);
			extension_mount_component(iconbutton, div1, null);
			current = true;

			if (!mounted) {
				dispose = extension_listen(div0, "click", /*click_handler*/ ctx[10]);
				mounted = true;
			}
		},
		p(ctx, [dirty]) {
			const iconbutton_changes = {};

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

			iconbutton.$set(iconbutton_changes);

			if (!current || dirty & /*large*/ 2 && div2_class_value !== (div2_class_value = "flex flex-col " + (/*large*/ ctx[1] ? 'w-48 mx-1' : 'w-24 m-1'))) {
				extension_attr(div2, "class", div2_class_value);
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div2);
			/*div0_binding*/ ctx[11](null);
			extension_destroy_component(iconbutton);
			mounted = false;
			dispose();
		}
	};
}

function extension_base64ToArrayBuffer(base64) {
	try {
		const trimmedBase64 = base64.trim();
		const binaryString = atob(trimmedBase64);
		const bytes = new Uint8Array(binaryString.length);

		for (let i = 0; i < binaryString.length; i++) {
			bytes[i] = binaryString.charCodeAt(i);
		}

		return bytes.buffer;
	} catch(error) {
		console.error("Failed to decode base64 string:", error);
		console.log("Problematic base64 string:", base64);
		throw error;
	}
}

function extension_AudioSample_svelte_instance($$self, $$props, $$invalidate) {
	let $canvasSpec,
		$$unsubscribe_canvasSpec = extension_noop,
		$$subscribe_canvasSpec = () => ($$unsubscribe_canvasSpec(), $$unsubscribe_canvasSpec = extension_subscribe(canvasSpec, $$value => $$invalidate(9, $canvasSpec = $$value)), canvasSpec);

	$$self.$$.on_destroy.push(() => $$unsubscribe_canvasSpec());
	let { id } = $$props;
	let { canvasSpec } = $$props;
	$$subscribe_canvasSpec();
	let { large = false } = $$props;
	let { storybook = false } = $$props;
	const contentsManager = extension_ContentsService.getInstance();
	let container;
	let wavesurfer;
	let playing = false;
	let oldId = "";

	function changePlayStatus() {
		if (playing) {
			wavesurfer.pause();
			$$invalidate(3, playing = false);
		} else {
			wavesurfer.play();
			$$invalidate(3, playing = true);
		}
	}

	extension_onDestroy(() => {
		if (wavesurfer) {
			wavesurfer.destroy();
		}
	});

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

	function div0_binding($$value) {
		extension_binding_callbacks[$$value ? 'unshift' : 'push'](() => {
			container = $$value;
			((((($$invalidate(2, container), $$invalidate(5, id)), $$invalidate(8, oldId)), $$invalidate(7, wavesurfer)), $$invalidate(9, $canvasSpec)), $$invalidate(6, storybook));
		});
	}

	$$self.$$set = $$props => {
		if ('id' in $$props) $$invalidate(5, id = $$props.id);
		if ('canvasSpec' in $$props) $$subscribe_canvasSpec($$invalidate(0, canvasSpec = $$props.canvasSpec));
		if ('large' in $$props) $$invalidate(1, large = $$props.large);
		if ('storybook' in $$props) $$invalidate(6, storybook = $$props.storybook);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*container, id, oldId, wavesurfer, $canvasSpec, storybook*/ 996) {
			$: if (container !== undefined && id !== oldId) {
				if (wavesurfer !== undefined) wavesurfer.destroy();
				$$invalidate(2, container.innerHTML = "", container);

				$$invalidate(7, wavesurfer = extension_wavesurfer_default().create({
					container,
					waveColor: "#cfcfcf",
					progressColor: "#0071e3"
				}));

				const filePath = extension_fireflysemantics_join_join($canvasSpec.filesPath, id);

				if (storybook) {
					wavesurfer.load(filePath);
				} else {
					contentsManager.readAudioContent(filePath).then(result => {
						const arrayBuffer = extension_base64ToArrayBuffer(result);
						wavesurfer.loadArrayBuffer(arrayBuffer);
					}).catch(error => {
						console.error("Unable to load the audio data", error);
					});
				}

				$$invalidate(3, playing = false);
				$$invalidate(8, oldId = id);
			}
		}
	};

	return [
		canvasSpec,
		large,
		container,
		playing,
		changePlayStatus,
		id,
		storybook,
		wavesurfer,
		oldId,
		$canvasSpec,
		click_handler,
		div0_binding
	];
}

class extension_AudioSample extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(this, options, extension_AudioSample_svelte_instance, extension_AudioSample_svelte_create_fragment, extension_safe_not_equal, {
			id: 5,
			canvasSpec: 0,
			large: 1,
			storybook: 6
		});
	}
}

/* harmony default export */ const extension_AudioSample_svelte = (extension_AudioSample);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faTable.js
var extension_faTable = __webpack_require__(7184);
;// ../../canvas_viz/dist/elements/TabularSample.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/TabularSample.svelte generated by Svelte v3.59.2 */





function extension_TabularSample_svelte_create_fragment(ctx) {
	let div;
	let fa;
	let current;
	let mounted;
	let dispose;
	fa = new extension_fa_svelte({ props: { icon: extension_faTable/* faTable */.w9 } });

	return {
		c() {
			div = extension_internal_element("div");
			extension_create_component(fa.$$.fragment);
			extension_attr(div, "class", "p-2");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_mount_component(fa, div, null);
			current = true;

			if (!mounted) {
				dispose = extension_listen(div, "click", /*click_handler*/ ctx[1]);
				mounted = true;
			}
		},
		p: extension_noop,
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(fa);
			mounted = false;
			dispose();
		}
	};
}

function extension_TabularSample_svelte_instance($$self, $$props, $$invalidate) {
	let { storybook = false } = $$props;

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

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

	return [storybook, click_handler];
}

class extension_TabularSample extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_TabularSample_svelte_instance, extension_TabularSample_svelte_create_fragment, extension_safe_not_equal, { storybook: 0 });
	}
}

/* harmony default export */ const extension_TabularSample_svelte = (extension_TabularSample);
;// ../../canvas_viz/dist/helpers/filetype.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 extension_getComponentForType(type) {
    switch (type) {
        case extension_CanvasDataType.AUDIO:
            return extension_AudioSample_svelte;
        case extension_CanvasDataType.IMAGE:
            return extension_ImageSample_svelte;
        default:
            return extension_TabularSample_svelte;
    }
}

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







function extension_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[15] = list[i][0];
	child_ctx[16] = list[i][1];
	return child_ctx;
}

// (46:0) {#if $tooltip.hover && $tooltip.instance !== undefined}
function extension_DataSampleDetail_svelte_create_if_block(ctx) {
	let div3;
	let div0;
	let switch_instance;
	let t0;
	let div2;
	let div1;
	let t1_value = /*$tooltip*/ ctx[7].instance[/*$canvasSpec*/ ctx[9].idColumn] + "";
	let t1;
	let t2;
	let t3;
	let div3_resize_listener;
	let div3_transition;
	let current;
	var switch_value = extension_getComponentForType(/*$canvasSpec*/ ctx[9].dataType);

	function switch_props(ctx) {
		return {
			props: {
				id: /*$tooltip*/ ctx[7].instance[/*$canvasSpec*/ ctx[9].idColumn],
				canvasSpec: /*canvasSpec*/ ctx[0],
				storybook: /*storybook*/ ctx[2],
				large: true
			}
		};
	}

	if (switch_value) {
		switch_instance = extension_construct_svelte_component(switch_value, switch_props(ctx));
	}

	let if_block = /*$tooltip*/ ctx[7].number !== undefined && extension_create_if_block_2(ctx);
	let each_value = Object.entries(/*$tooltip*/ ctx[7].instance);
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = extension_create_each_block(extension_get_each_context(ctx, each_value, i));
	}

	return {
		c() {
			div3 = extension_internal_element("div");
			div0 = extension_internal_element("div");
			if (switch_instance) extension_create_component(switch_instance.$$.fragment);
			t0 = extension_space();
			div2 = extension_internal_element("div");
			div1 = extension_internal_element("div");
			t1 = extension_internal_text(t1_value);
			t2 = extension_space();
			if (if_block) if_block.c();
			t3 = extension_space();

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			extension_attr(div0, "class", "flex flex-shrink-0");
			extension_attr(div1, "class", "flex font-bold");
			extension_attr(div2, "class", "flex flex-col pl-2 pr-4 m-2 mt-0 break-all");
			extension_attr(div3, "class", "text-sm fixed p-1 rounded text-text-dark shadow z-10 flex mt-4 mb-4");
			extension_attr(div3, "style", /*style*/ ctx[8]);
			extension_add_render_callback(() => /*div3_elementresize_handler*/ ctx[14].call(div3));
		},
		m(target, anchor) {
			extension_insert(target, div3, anchor);
			extension_append(div3, div0);
			if (switch_instance) extension_mount_component(switch_instance, div0, null);
			extension_append(div3, t0);
			extension_append(div3, div2);
			extension_append(div2, div1);
			extension_append(div1, t1);
			extension_append(div2, t2);
			if (if_block) if_block.m(div2, null);
			extension_append(div2, t3);

			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(div2, null);
				}
			}

			div3_resize_listener = extension_add_iframe_resize_listener(div3, /*div3_elementresize_handler*/ ctx[14].bind(div3));
			current = true;
		},
		p(ctx, dirty) {
			const switch_instance_changes = {};
			if (dirty & /*$tooltip, $canvasSpec*/ 640) switch_instance_changes.id = /*$tooltip*/ ctx[7].instance[/*$canvasSpec*/ ctx[9].idColumn];
			if (dirty & /*canvasSpec*/ 1) switch_instance_changes.canvasSpec = /*canvasSpec*/ ctx[0];
			if (dirty & /*storybook*/ 4) switch_instance_changes.storybook = /*storybook*/ ctx[2];

			if (dirty & /*$canvasSpec*/ 512 && switch_value !== (switch_value = extension_getComponentForType(/*$canvasSpec*/ ctx[9].dataType))) {
				if (switch_instance) {
					extension_group_outros();
					const old_component = switch_instance;

					extension_transition_out(old_component.$$.fragment, 1, 0, () => {
						extension_destroy_component(old_component, 1);
					});

					extension_check_outros();
				}

				if (switch_value) {
					switch_instance = extension_construct_svelte_component(switch_value, switch_props(ctx));
					extension_create_component(switch_instance.$$.fragment);
					extension_transition_in(switch_instance.$$.fragment, 1);
					extension_mount_component(switch_instance, div0, null);
				} else {
					switch_instance = null;
				}
			} else if (switch_value) {
				switch_instance.$set(switch_instance_changes);
			}

			if ((!current || dirty & /*$tooltip, $canvasSpec*/ 640) && t1_value !== (t1_value = /*$tooltip*/ ctx[7].instance[/*$canvasSpec*/ ctx[9].idColumn] + "")) extension_set_data(t1, t1_value);

			if (/*$tooltip*/ ctx[7].number !== undefined) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*$tooltip*/ 128) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_create_if_block_2(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(div2, t3);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}

			if (dirty & /*formatValue, Object, $tooltip, $canvasSpec*/ 1664) {
				each_value = Object.entries(/*$tooltip*/ ctx[7].instance);
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = extension_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
					} else {
						each_blocks[i] = extension_create_each_block(child_ctx);
						each_blocks[i].c();
						each_blocks[i].m(div2, null);
					}
				}

				for (; i < each_blocks.length; i += 1) {
					each_blocks[i].d(1);
				}

				each_blocks.length = each_value.length;
			}

			if (!current || dirty & /*style*/ 256) {
				extension_attr(div3, "style", /*style*/ ctx[8]);
			}
		},
		i(local) {
			if (current) return;
			if (switch_instance) extension_transition_in(switch_instance.$$.fragment, local);
			extension_transition_in(if_block);

			extension_add_render_callback(() => {
				if (!current) return;
				if (!div3_transition) div3_transition = extension_create_bidirectional_transition(div3, extension_fade, {}, true);
				div3_transition.run(1);
			});

			current = true;
		},
		o(local) {
			if (switch_instance) extension_transition_out(switch_instance.$$.fragment, local);
			extension_transition_out(if_block);
			if (!div3_transition) div3_transition = extension_create_bidirectional_transition(div3, extension_fade, {}, false);
			div3_transition.run(0);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div3);
			if (switch_instance) extension_destroy_component(switch_instance);
			if (if_block) if_block.d();
			extension_destroy_each(each_blocks, detaching);
			div3_resize_listener();
			if (detaching && div3_transition) div3_transition.end();
		}
	};
}

// (67:6) {#if $tooltip.number !== undefined}
function extension_create_if_block_2(ctx) {
	let div;
	let fa;
	let t0;
	let span;
	let t1_value = /*$tooltip*/ ctx[7].number + "";
	let t1;
	let current;
	fa = new extension_fa_svelte({ props: { icon: extension_faChartBar/* faChartBar */.$F } });

	return {
		c() {
			div = extension_internal_element("div");
			extension_create_component(fa.$$.fragment);
			t0 = extension_space();
			span = extension_internal_element("span");
			t1 = extension_internal_text(t1_value);
			extension_attr(span, "class", "ml-2");
			extension_attr(div, "class", "flex flex-nowrap");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_mount_component(fa, div, null);
			extension_append(div, t0);
			extension_append(div, span);
			extension_append(span, t1);
			current = true;
		},
		p(ctx, dirty) {
			if ((!current || dirty & /*$tooltip*/ 128) && t1_value !== (t1_value = /*$tooltip*/ ctx[7].number + "")) extension_set_data(t1, t1_value);
		},
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(fa);
		}
	};
}

// (74:8) {#if key !== $canvasSpec.idColumn && !key.startsWith("familiarity_") && !key.startsWith("duplicates_") && !key.startsWith("projection_") && !key.startsWith("splitFamiliarity")}
function extension_DataSampleDetail_svelte_create_if_block_1(ctx) {
	let div;
	let span0;
	let t0_value = /*key*/ ctx[15] + "";
	let t0;
	let t1;
	let t2;
	let span1;
	let t3_value = /*formatValue*/ ctx[10](/*val*/ ctx[16]) + "";
	let t3;
	let t4;

	return {
		c() {
			div = extension_internal_element("div");
			span0 = extension_internal_element("span");
			t0 = extension_internal_text(t0_value);
			t1 = extension_internal_text(":");
			t2 = extension_space();
			span1 = extension_internal_element("span");
			t3 = extension_internal_text(t3_value);
			t4 = extension_space();
			extension_attr(span0, "class", "font-bold");
			extension_attr(span1, "class", "ml-2");
			extension_attr(div, "class", "flex flex-nowrap");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_append(div, span0);
			extension_append(span0, t0);
			extension_append(span0, t1);
			extension_append(div, t2);
			extension_append(div, span1);
			extension_append(span1, t3);
			extension_append(div, t4);
		},
		p(ctx, dirty) {
			if (dirty & /*$tooltip*/ 128 && t0_value !== (t0_value = /*key*/ ctx[15] + "")) extension_set_data(t0, t0_value);
			if (dirty & /*$tooltip*/ 128 && t3_value !== (t3_value = /*formatValue*/ ctx[10](/*val*/ ctx[16]) + "")) extension_set_data(t3, t3_value);
		},
		d(detaching) {
			if (detaching) extension_detach(div);
		}
	};
}

// (73:6) {#each Object.entries($tooltip.instance) as [key, val]}
function extension_create_each_block(ctx) {
	let show_if = /*key*/ ctx[15] !== /*$canvasSpec*/ ctx[9].idColumn && !/*key*/ ctx[15].startsWith("familiarity_") && !/*key*/ ctx[15].startsWith("duplicates_") && !/*key*/ ctx[15].startsWith("projection_") && !/*key*/ ctx[15].startsWith("splitFamiliarity");
	let if_block_anchor;
	let if_block = show_if && extension_DataSampleDetail_svelte_create_if_block_1(ctx);

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = extension_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			extension_insert(target, if_block_anchor, anchor);
		},
		p(ctx, dirty) {
			if (dirty & /*$tooltip, $canvasSpec*/ 640) show_if = /*key*/ ctx[15] !== /*$canvasSpec*/ ctx[9].idColumn && !/*key*/ ctx[15].startsWith("familiarity_") && !/*key*/ ctx[15].startsWith("duplicates_") && !/*key*/ ctx[15].startsWith("projection_") && !/*key*/ ctx[15].startsWith("splitFamiliarity");

			if (show_if) {
				if (if_block) {
					if_block.p(ctx, dirty);
				} else {
					if_block = extension_DataSampleDetail_svelte_create_if_block_1(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;
			}
		},
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) extension_detach(if_block_anchor);
		}
	};
}

function extension_DataSampleDetail_svelte_create_fragment(ctx) {
	let if_block_anchor;
	let current;
	let mounted;
	let dispose;
	extension_add_render_callback(/*onwindowresize*/ ctx[13]);
	let if_block = /*$tooltip*/ ctx[7].hover && /*$tooltip*/ ctx[7].instance !== undefined && extension_DataSampleDetail_svelte_create_if_block(ctx);

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = extension_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			extension_insert(target, if_block_anchor, anchor);
			current = true;

			if (!mounted) {
				dispose = extension_listen(window, "resize", /*onwindowresize*/ ctx[13]);
				mounted = true;
			}
		},
		p(ctx, [dirty]) {
			if (/*$tooltip*/ ctx[7].hover && /*$tooltip*/ ctx[7].instance !== undefined) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*$tooltip*/ 128) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_DataSampleDetail_svelte_create_if_block(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(if_block_anchor.parentNode, if_block_anchor);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) extension_detach(if_block_anchor);
			mounted = false;
			dispose();
		}
	};
}

function extension_DataSampleDetail_svelte_instance($$self, $$props, $$invalidate) {
	let yPos;
	let xStyle;
	let style;

	let $tooltip,
		$$unsubscribe_tooltip = extension_noop,
		$$subscribe_tooltip = () => ($$unsubscribe_tooltip(), $$unsubscribe_tooltip = extension_subscribe(tooltip, $$value => $$invalidate(7, $tooltip = $$value)), tooltip);

	let $canvasSpec,
		$$unsubscribe_canvasSpec = extension_noop,
		$$subscribe_canvasSpec = () => ($$unsubscribe_canvasSpec(), $$unsubscribe_canvasSpec = extension_subscribe(canvasSpec, $$value => $$invalidate(9, $canvasSpec = $$value)), canvasSpec);

	$$self.$$.on_destroy.push(() => $$unsubscribe_tooltip());
	$$self.$$.on_destroy.push(() => $$unsubscribe_canvasSpec());

	const formatValue = val => {
		if (Array.isArray(val)) return val.toString();
		if (typeof val === 'number') return val.toFixed(2);
		return val;
	};

	let { canvasSpec } = $$props;
	$$subscribe_canvasSpec();
	let { tooltip } = $$props;
	$$subscribe_tooltip();
	let { storybook = false } = $$props;
	let windowWidth = 0;
	let windowHeight = 0;
	let tooltipWidth = 0;
	let tooltipHeight = 0;

	function onwindowresize() {
		$$invalidate(3, windowWidth = window.innerWidth)
		$$invalidate(4, windowHeight = window.innerHeight)
	}

	function div3_elementresize_handler() {
		tooltipWidth = this.offsetWidth;
		tooltipHeight = this.offsetHeight;
		$$invalidate(5, tooltipWidth);
		$$invalidate(6, tooltipHeight);
	}

	$$self.$$set = $$props => {
		if ('canvasSpec' in $$props) $$subscribe_canvasSpec($$invalidate(0, canvasSpec = $$props.canvasSpec));
		if ('tooltip' in $$props) $$subscribe_tooltip($$invalidate(1, tooltip = $$props.tooltip));
		if ('storybook' in $$props) $$invalidate(2, storybook = $$props.storybook);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*windowHeight, $tooltip, tooltipHeight*/ 208) {
			$: $$invalidate(12, yPos = windowHeight > $tooltip.mousePos.y + tooltipHeight
			? $tooltip.mousePos.y
			: $tooltip.mousePos.y - tooltipHeight - 20);
		}

		if ($$self.$$.dirty & /*windowWidth, $tooltip, tooltipWidth*/ 168) {
			$: $$invalidate(11, xStyle = windowWidth > $tooltip.mousePos.x + tooltipWidth + 10
			? `left: ${$tooltip.mousePos.x}px;`
			: `right: 10px;`);
		}

		if ($$self.$$.dirty & /*yPos, xStyle*/ 6144) {
			$: $$invalidate(8, style = `top: ${yPos}px; ${xStyle}; background: black`);
		}
	};

	return [
		canvasSpec,
		tooltip,
		storybook,
		windowWidth,
		windowHeight,
		tooltipWidth,
		tooltipHeight,
		$tooltip,
		style,
		$canvasSpec,
		formatValue,
		xStyle,
		yPos,
		onwindowresize,
		div3_elementresize_handler
	];
}

class extension_DataSampleDetail extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_DataSampleDetail_svelte_instance, extension_DataSampleDetail_svelte_create_fragment, extension_safe_not_equal, { canvasSpec: 0, tooltip: 1, storybook: 2 });
	}
}

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






function extension_JupyterWidget_svelte_create_else_block(ctx) {
	let t;

	return {
		c() {
			t = extension_internal_text("No data to show.");
		},
		m(target, anchor) {
			extension_insert(target, t, anchor);
		},
		p: extension_noop,
		i: extension_noop,
		o: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(t);
		}
	};
}

// (28:0) {#if $table && $widgetSpec}
function extension_JupyterWidget_svelte_create_if_block(ctx) {
	let div;
	let switch_instance;
	let div_class_value;
	let current;
	var switch_value = /*widget*/ ctx[0];

	function switch_props(ctx) {
		return {
			props: {
				widgetSpec: /*$widgetSpec*/ ctx[2],
				selected: extension_selected,
				filter: extension_stores_filter,
				groupColumns: extension_groupColumns,
				groupNames: extension_groupNames,
				canvasSpec: extension_canvasSpec,
				dataTable: extension_dataTable,
				filterError: extension_filterError,
				tooltip: extension_tooltip,
				table: extension_stores_table,
				filteredTable: extension_filteredTable,
				groupedTables: extension_groupedTables,
				notebook: true
			}
		};
	}

	if (switch_value) {
		switch_instance = extension_construct_svelte_component(switch_value, switch_props(ctx));
		switch_instance.$on("specChanged", /*handleSpecChanged*/ ctx[4]);
	}

	return {
		c() {
			div = extension_internal_element("div");
			if (switch_instance) extension_create_component(switch_instance.$$.fragment);

			extension_attr(div, "class", div_class_value = "" + ((/*$widgetSpec*/ ctx[2].name === 'toolbar'
			? 'border-midgrey border-2'
			: '') + " mt-2 h-full"));

			extension_set_style(div, "min-height", "350px");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			if (switch_instance) extension_mount_component(switch_instance, div, null);
			current = true;
		},
		p(ctx, dirty) {
			const switch_instance_changes = {};
			if (dirty & /*$widgetSpec*/ 4) switch_instance_changes.widgetSpec = /*$widgetSpec*/ ctx[2];

			if (dirty & /*widget*/ 1 && switch_value !== (switch_value = /*widget*/ ctx[0])) {
				if (switch_instance) {
					extension_group_outros();
					const old_component = switch_instance;

					extension_transition_out(old_component.$$.fragment, 1, 0, () => {
						extension_destroy_component(old_component, 1);
					});

					extension_check_outros();
				}

				if (switch_value) {
					switch_instance = extension_construct_svelte_component(switch_value, switch_props(ctx));
					switch_instance.$on("specChanged", /*handleSpecChanged*/ ctx[4]);
					extension_create_component(switch_instance.$$.fragment);
					extension_transition_in(switch_instance.$$.fragment, 1);
					extension_mount_component(switch_instance, div, null);
				} else {
					switch_instance = null;
				}
			} else if (switch_value) {
				switch_instance.$set(switch_instance_changes);
			}

			if (!current || dirty & /*$widgetSpec*/ 4 && div_class_value !== (div_class_value = "" + ((/*$widgetSpec*/ ctx[2].name === 'toolbar'
			? 'border-midgrey border-2'
			: '') + " mt-2 h-full"))) {
				extension_attr(div, "class", div_class_value);
			}
		},
		i(local) {
			if (current) return;
			if (switch_instance) extension_transition_in(switch_instance.$$.fragment, local);
			current = true;
		},
		o(local) {
			if (switch_instance) extension_transition_out(switch_instance.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			if (switch_instance) extension_destroy_component(switch_instance);
		}
	};
}

function extension_JupyterWidget_svelte_create_fragment(ctx) {
	let current_block_type_index;
	let if_block;
	let t;
	let datasampledetail;
	let current;
	const if_block_creators = [extension_JupyterWidget_svelte_create_if_block, extension_JupyterWidget_svelte_create_else_block];
	const if_blocks = [];

	function select_block_type(ctx, dirty) {
		if (/*$table*/ ctx[1] && /*$widgetSpec*/ ctx[2]) return 0;
		return 1;
	}

	current_block_type_index = select_block_type(ctx, -1);
	if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
	datasampledetail = new extension_DataSampleDetail_svelte({ props: { tooltip: extension_tooltip, canvasSpec: extension_canvasSpec } });

	return {
		c() {
			if_block.c();
			t = extension_space();
			extension_create_component(datasampledetail.$$.fragment);
		},
		m(target, anchor) {
			if_blocks[current_block_type_index].m(target, anchor);
			extension_insert(target, t, anchor);
			extension_mount_component(datasampledetail, target, anchor);
			current = true;
		},
		p(ctx, [dirty]) {
			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 {
				extension_group_outros();

				extension_transition_out(if_blocks[previous_block_index], 1, 1, () => {
					if_blocks[previous_block_index] = null;
				});

				extension_check_outros();
				if_block = if_blocks[current_block_type_index];

				if (!if_block) {
					if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
					if_block.c();
				} else {
					if_block.p(ctx, dirty);
				}

				extension_transition_in(if_block, 1);
				if_block.m(t.parentNode, t);
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			extension_transition_in(datasampledetail.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			extension_transition_out(datasampledetail.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if_blocks[current_block_type_index].d(detaching);
			if (detaching) extension_detach(t);
			extension_destroy_component(datasampledetail, detaching);
		}
	};
}

function extension_JupyterWidget_svelte_instance($$self, $$props, $$invalidate) {
	let $table;
	let $widgetSpec;
	extension_component_subscribe($$self, extension_stores_table, $$value => $$invalidate(1, $table = $$value));
	let { model } = $$props;
	let { widget } = $$props;
	extension_initializeStores(model);
	let widgetSpec = extension_widgetWritable("widget_spec", model.attributes.widget_spec);
	extension_component_subscribe($$self, widgetSpec, value => $$invalidate(2, $widgetSpec = value));
	widgetSpec.setModel(model);

	function handleSpecChanged(event) {
		widgetSpec.set(event.detail.spec);
	}

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

	return [widget, $table, $widgetSpec, widgetSpec, handleSpecChanged, model];
}

class extension_JupyterWidget extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_JupyterWidget_svelte_instance, extension_JupyterWidget_svelte_create_fragment, extension_safe_not_equal, { model: 5, widget: 0 });
	}
}

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


function extension_PaginationControls_svelte_create_fragment(ctx) {
	let div3;
	let div2;
	let div0;
	let p0;
	let t0;
	let span0;
	let t1_value = /*page*/ ctx[0] * /*instancesPerPage*/ ctx[1] + 1 + "";
	let t1;
	let t2;
	let span1;
	let t3_value = Math.min(/*page*/ ctx[0] * /*instancesPerPage*/ ctx[1] + /*instancesPerPage*/ ctx[1], /*size*/ ctx[2]) + "";
	let t3;
	let t4;
	let span2;
	let t5;
	let t6;
	let t7;
	let div1;
	let nav;
	let p1;
	let t10;
	let p2;
	let t11;
	let t12_value = /*page*/ ctx[0] + 1 + "";
	let t12;
	let t13;
	let t14;
	let t15;
	let p3;
	let mounted;
	let dispose;

	return {
		c() {
			div3 = extension_internal_element("div");
			div2 = extension_internal_element("div");
			div0 = extension_internal_element("div");
			p0 = extension_internal_element("p");
			t0 = extension_internal_text("Showing\n        ");
			span0 = extension_internal_element("span");
			t1 = extension_internal_text(t1_value);
			t2 = extension_internal_text("\n        to\n        ");
			span1 = extension_internal_element("span");
			t3 = extension_internal_text(t3_value);
			t4 = extension_internal_text("\n        of\n        ");
			span2 = extension_internal_element("span");
			t5 = extension_internal_text(/*size*/ ctx[2]);
			t6 = extension_internal_text("\n        results");
			t7 = extension_space();
			div1 = extension_internal_element("div");
			nav = extension_internal_element("nav");
			p1 = extension_internal_element("p");

			p1.innerHTML = `<span class="sr-only">Previous</span> 
          
          <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd"></path></svg>`;

			t10 = extension_space();
			p2 = extension_internal_element("p");
			t11 = extension_internal_text("Page ");
			t12 = extension_internal_text(t12_value);
			t13 = extension_internal_text(" of ");
			t14 = extension_internal_text(/*maxPage*/ ctx[3]);
			t15 = extension_space();
			p3 = extension_internal_element("p");

			p3.innerHTML = `<span class="sr-only">Next</span> 
          
          <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg>`;

			extension_attr(span0, "class", "font-medium");
			extension_attr(span1, "class", "font-medium");
			extension_attr(span2, "class", "font-medium");
			extension_attr(p0, "class", "text-sm text-gray-700");
			extension_attr(p1, "class", "bg-white relative cursor-pointer inline-flex items-center px-2 py-2 rounded-l-md border border-lightgrey text-sm font-medium text-gray-500 hover:bg-lightgrey");
			extension_attr(p2, "aria-current", "page");
			extension_attr(p2, "class", "z-10 bg-indigo-50 border-lightgrey text-indigo-600 relative inline-flex items-center px-4 py-2 border text-sm font-medium bg-white");
			extension_attr(p3, "class", "bg-white relative cursor-pointer inline-flex items-center px-2 py-2 rounded-r-md border border-lightgrey text-sm font-medium text-gray-500 hover:bg-lightgrey");
			extension_attr(nav, "class", "relative z-0 inline-flex rounded-md shadow-sm -space-x-px");
			extension_attr(nav, "aria-label", "Pagination");
			extension_attr(div2, "class", "sm:flex-1 sm:flex sm:items-center sm:justify-between");
			extension_attr(div3, "class", "pt-2 flex items-center justify-between");
		},
		m(target, anchor) {
			extension_insert(target, div3, anchor);
			extension_append(div3, div2);
			extension_append(div2, div0);
			extension_append(div0, p0);
			extension_append(p0, t0);
			extension_append(p0, span0);
			extension_append(span0, t1);
			extension_append(p0, t2);
			extension_append(p0, span1);
			extension_append(span1, t3);
			extension_append(p0, t4);
			extension_append(p0, span2);
			extension_append(span2, t5);
			extension_append(p0, t6);
			extension_append(div2, t7);
			extension_append(div2, div1);
			extension_append(div1, nav);
			extension_append(nav, p1);
			extension_append(nav, t10);
			extension_append(nav, p2);
			extension_append(p2, t11);
			extension_append(p2, t12);
			extension_append(p2, t13);
			extension_append(p2, t14);
			extension_append(nav, t15);
			extension_append(nav, p3);

			if (!mounted) {
				dispose = [
					extension_listen(p1, "click", /*click_handler*/ ctx[4]),
					extension_listen(p3, "click", /*click_handler_1*/ ctx[5])
				];

				mounted = true;
			}
		},
		p(ctx, [dirty]) {
			if (dirty & /*page, instancesPerPage*/ 3 && t1_value !== (t1_value = /*page*/ ctx[0] * /*instancesPerPage*/ ctx[1] + 1 + "")) extension_set_data(t1, t1_value);
			if (dirty & /*page, instancesPerPage, size*/ 7 && t3_value !== (t3_value = Math.min(/*page*/ ctx[0] * /*instancesPerPage*/ ctx[1] + /*instancesPerPage*/ ctx[1], /*size*/ ctx[2]) + "")) extension_set_data(t3, t3_value);
			if (dirty & /*size*/ 4) extension_set_data(t5, /*size*/ ctx[2]);
			if (dirty & /*page*/ 1 && t12_value !== (t12_value = /*page*/ ctx[0] + 1 + "")) extension_set_data(t12, t12_value);
			if (dirty & /*maxPage*/ 8) extension_set_data(t14, /*maxPage*/ ctx[3]);
		},
		i: extension_noop,
		o: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(div3);
			mounted = false;
			extension_run_all(dispose);
		}
	};
}

function extension_PaginationControls_svelte_instance($$self, $$props, $$invalidate) {
	let maxPage;
	let { instancesPerPage } = $$props;
	let { size } = $$props;
	let { page = 0 } = $$props;
	const click_handler = () => page !== 0 ? $$invalidate(0, page--, page) : "";
	const click_handler_1 = () => page < maxPage - 1 ? $$invalidate(0, page++, page) : "";

	$$self.$$set = $$props => {
		if ('instancesPerPage' in $$props) $$invalidate(1, instancesPerPage = $$props.instancesPerPage);
		if ('size' in $$props) $$invalidate(2, size = $$props.size);
		if ('page' in $$props) $$invalidate(0, page = $$props.page);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*size, instancesPerPage*/ 6) {
			$: $$invalidate(3, maxPage = Math.ceil(size / instancesPerPage));
		}
	};

	return [page, instancesPerPage, size, maxPage, click_handler, click_handler_1];
}

class extension_PaginationControls extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_PaginationControls_svelte_instance, extension_PaginationControls_svelte_create_fragment, extension_safe_not_equal, { instancesPerPage: 1, size: 2, page: 0 });
	}
}

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


const extension_get_content_slot_changes = dirty => ({});
const extension_get_content_slot_context = ctx => ({});

function extension_Container_svelte_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[4] = list[i];
	return child_ctx;
}

const extension_Container_svelte_get_icon_slot_changes = dirty => ({});
const extension_Container_svelte_get_icon_slot_context = ctx => ({});
const extension_get_header_slot_changes = dirty => ({});
const extension_get_header_slot_context = ctx => ({});

// (25:4) {#if title !== undefined}
function extension_Container_svelte_create_if_block_1(ctx) {
	let span;
	let t;

	return {
		c() {
			span = extension_internal_element("span");
			t = extension_internal_text(/*title*/ ctx[0]);
			extension_attr(span, "class", "pr-2 text-lg");
		},
		m(target, anchor) {
			extension_insert(target, span, anchor);
			extension_append(span, t);
		},
		p(ctx, dirty) {
			if (dirty & /*title*/ 1) extension_set_data(t, /*title*/ ctx[0]);
		},
		d(detaching) {
			if (detaching) extension_detach(span);
		}
	};
}

// (28:4) {#if categories !== undefined}
function extension_Container_svelte_create_if_block(ctx) {
	let each_1_anchor;
	let each_value = /*categories*/ ctx[1];
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = extension_Container_svelte_create_each_block(extension_Container_svelte_get_each_context(ctx, each_value, i));
	}

	return {
		c() {
			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			each_1_anchor = extension_empty();
		},
		m(target, anchor) {
			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(target, anchor);
				}
			}

			extension_insert(target, each_1_anchor, anchor);
		},
		p(ctx, dirty) {
			if (dirty & /*categories*/ 2) {
				each_value = /*categories*/ ctx[1];
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = extension_Container_svelte_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
					} else {
						each_blocks[i] = extension_Container_svelte_create_each_block(child_ctx);
						each_blocks[i].c();
						each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
					}
				}

				for (; i < each_blocks.length; i += 1) {
					each_blocks[i].d(1);
				}

				each_blocks.length = each_value.length;
			}
		},
		d(detaching) {
			extension_destroy_each(each_blocks, detaching);
			if (detaching) extension_detach(each_1_anchor);
		}
	};
}

// (29:6) {#each categories as category}
function extension_Container_svelte_create_each_block(ctx) {
	let span;
	let t_value = /*category*/ ctx[4] + "";
	let t;

	return {
		c() {
			span = extension_internal_element("span");
			t = extension_internal_text(t_value);
			extension_attr(span, "class", "pr-1 text-sm");
		},
		m(target, anchor) {
			extension_insert(target, span, anchor);
			extension_append(span, t);
		},
		p(ctx, dirty) {
			if (dirty & /*categories*/ 2 && t_value !== (t_value = /*category*/ ctx[4] + "")) extension_set_data(t, t_value);
		},
		d(detaching) {
			if (detaching) extension_detach(span);
		}
	};
}

function extension_Container_svelte_create_fragment(ctx) {
	let div2;
	let div0;
	let t0;
	let div1;
	let t1;
	let t2;
	let t3;
	let current;
	const header_slot_template = /*#slots*/ ctx[3].header;
	const header_slot = extension_create_slot(header_slot_template, ctx, /*$$scope*/ ctx[2], extension_get_header_slot_context);
	const icon_slot_template = /*#slots*/ ctx[3].icon;
	const icon_slot = extension_create_slot(icon_slot_template, ctx, /*$$scope*/ ctx[2], extension_Container_svelte_get_icon_slot_context);
	let if_block0 = /*title*/ ctx[0] !== undefined && extension_Container_svelte_create_if_block_1(ctx);
	let if_block1 = /*categories*/ ctx[1] !== undefined && extension_Container_svelte_create_if_block(ctx);
	const content_slot_template = /*#slots*/ ctx[3].content;
	const content_slot = extension_create_slot(content_slot_template, ctx, /*$$scope*/ ctx[2], extension_get_content_slot_context);

	return {
		c() {
			div2 = extension_internal_element("div");
			div0 = extension_internal_element("div");
			if (header_slot) header_slot.c();
			t0 = extension_space();
			div1 = extension_internal_element("div");
			if (icon_slot) icon_slot.c();
			t1 = extension_space();
			if (if_block0) if_block0.c();
			t2 = extension_space();
			if (if_block1) if_block1.c();
			t3 = extension_space();
			if (content_slot) content_slot.c();
			extension_attr(div0, "class", "flex items-top mb-2 justify-between border-b pb-1 border-midgrey");
			extension_attr(div1, "class", "flex items-center");
			extension_attr(div2, "class", "flex flex-col border-midgrey border rounded-md p-2 w-full");
		},
		m(target, anchor) {
			extension_insert(target, div2, anchor);
			extension_append(div2, div0);

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

			extension_append(div2, t0);
			extension_append(div2, div1);

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

			extension_append(div1, t1);
			if (if_block0) if_block0.m(div1, null);
			extension_append(div1, t2);
			if (if_block1) if_block1.m(div1, null);
			extension_append(div2, t3);

			if (content_slot) {
				content_slot.m(div2, null);
			}

			current = true;
		},
		p(ctx, [dirty]) {
			if (header_slot) {
				if (header_slot.p && (!current || dirty & /*$$scope*/ 4)) {
					extension_update_slot_base(
						header_slot,
						header_slot_template,
						ctx,
						/*$$scope*/ ctx[2],
						!current
						? extension_get_all_dirty_from_scope(/*$$scope*/ ctx[2])
						: extension_get_slot_changes(header_slot_template, /*$$scope*/ ctx[2], dirty, extension_get_header_slot_changes),
						extension_get_header_slot_context
					);
				}
			}

			if (icon_slot) {
				if (icon_slot.p && (!current || dirty & /*$$scope*/ 4)) {
					extension_update_slot_base(
						icon_slot,
						icon_slot_template,
						ctx,
						/*$$scope*/ ctx[2],
						!current
						? extension_get_all_dirty_from_scope(/*$$scope*/ ctx[2])
						: extension_get_slot_changes(icon_slot_template, /*$$scope*/ ctx[2], dirty, extension_Container_svelte_get_icon_slot_changes),
						extension_Container_svelte_get_icon_slot_context
					);
				}
			}

			if (/*title*/ ctx[0] !== undefined) {
				if (if_block0) {
					if_block0.p(ctx, dirty);
				} else {
					if_block0 = extension_Container_svelte_create_if_block_1(ctx);
					if_block0.c();
					if_block0.m(div1, t2);
				}
			} else if (if_block0) {
				if_block0.d(1);
				if_block0 = null;
			}

			if (/*categories*/ ctx[1] !== undefined) {
				if (if_block1) {
					if_block1.p(ctx, dirty);
				} else {
					if_block1 = extension_Container_svelte_create_if_block(ctx);
					if_block1.c();
					if_block1.m(div1, null);
				}
			} else if (if_block1) {
				if_block1.d(1);
				if_block1 = null;
			}

			if (content_slot) {
				if (content_slot.p && (!current || dirty & /*$$scope*/ 4)) {
					extension_update_slot_base(
						content_slot,
						content_slot_template,
						ctx,
						/*$$scope*/ ctx[2],
						!current
						? extension_get_all_dirty_from_scope(/*$$scope*/ ctx[2])
						: extension_get_slot_changes(content_slot_template, /*$$scope*/ ctx[2], dirty, extension_get_content_slot_changes),
						extension_get_content_slot_context
					);
				}
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(header_slot, local);
			extension_transition_in(icon_slot, local);
			extension_transition_in(content_slot, local);
			current = true;
		},
		o(local) {
			extension_transition_out(header_slot, local);
			extension_transition_out(icon_slot, local);
			extension_transition_out(content_slot, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div2);
			if (header_slot) header_slot.d(detaching);
			if (icon_slot) icon_slot.d(detaching);
			if (if_block0) if_block0.d();
			if (if_block1) if_block1.d();
			if (content_slot) content_slot.d(detaching);
		}
	};
}

function extension_Container_svelte_instance($$self, $$props, $$invalidate) {
	let { $$slots: slots = {}, $$scope } = $$props;
	let { title = undefined } = $$props;
	let { categories = undefined } = $$props;

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

	return [title, categories, $$scope, slots];
}

class extension_Container extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_Container_svelte_instance, extension_Container_svelte_create_fragment, extension_safe_not_equal, { title: 0, categories: 1 });
	}
}

/* harmony default export */ const extension_Container_svelte = (extension_Container);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faCheckSquare.js
var extension_faCheckSquare = __webpack_require__(8547);
;// ../../canvas_viz/dist/elements/DataSample.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/DataSample.svelte generated by Svelte v3.59.2 */






function extension_DataSample_svelte_create_if_block(ctx) {
	let icon;
	let current;

	icon = new extension_fa_svelte({
			props: {
				class: "absolute top-0 right-0 bg-white border-2 border-white",
				icon: extension_faCheckSquare/* faCheckSquare */.rQ
			}
		});

	return {
		c() {
			extension_create_component(icon.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(icon, target, anchor);
			current = true;
		},
		p: extension_noop,
		i(local) {
			if (current) return;
			extension_transition_in(icon.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(icon.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(icon, detaching);
		}
	};
}

function extension_DataSample_svelte_create_fragment(ctx) {
	let div;
	let switch_instance;
	let t;
	let show_if = /*$selected*/ ctx[6].includes(/*id*/ ctx[5]);
	let current;
	let mounted;
	let dispose;
	var switch_value = extension_getComponentForType(/*$canvasSpec*/ ctx[3].dataType);

	function switch_props(ctx) {
		return {
			props: {
				id: /*id*/ ctx[5],
				canvasSpec: /*canvasSpec*/ ctx[0],
				storybook: /*storybook*/ ctx[2]
			}
		};
	}

	if (switch_value) {
		switch_instance = extension_construct_svelte_component(switch_value, switch_props(ctx));
		switch_instance.$on("click", /*click_handler*/ ctx[13]);
	}

	let if_block = show_if && extension_DataSample_svelte_create_if_block(ctx);

	return {
		c() {
			div = extension_internal_element("div");
			if (switch_instance) extension_create_component(switch_instance.$$.fragment);
			t = extension_space();
			if (if_block) if_block.c();
			extension_attr(div, "class", "relative");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			if (switch_instance) extension_mount_component(switch_instance, div, null);
			extension_append(div, t);
			if (if_block) if_block.m(div, null);
			current = true;

			if (!mounted) {
				dispose = [
					extension_listen(div, "mouseenter", /*mouseenter_handler*/ ctx[14]),
					extension_listen(div, "mouseleave", /*mouseleave_handler*/ ctx[15]),
					extension_listen(div, "mousemove", /*handleMousemove*/ ctx[8])
				];

				mounted = true;
			}
		},
		p(ctx, [dirty]) {
			const switch_instance_changes = {};
			if (dirty & /*id*/ 32) switch_instance_changes.id = /*id*/ ctx[5];
			if (dirty & /*canvasSpec*/ 1) switch_instance_changes.canvasSpec = /*canvasSpec*/ ctx[0];
			if (dirty & /*storybook*/ 4) switch_instance_changes.storybook = /*storybook*/ ctx[2];

			if (dirty & /*$canvasSpec*/ 8 && switch_value !== (switch_value = extension_getComponentForType(/*$canvasSpec*/ ctx[3].dataType))) {
				if (switch_instance) {
					extension_group_outros();
					const old_component = switch_instance;

					extension_transition_out(old_component.$$.fragment, 1, 0, () => {
						extension_destroy_component(old_component, 1);
					});

					extension_check_outros();
				}

				if (switch_value) {
					switch_instance = extension_construct_svelte_component(switch_value, switch_props(ctx));
					switch_instance.$on("click", /*click_handler*/ ctx[13]);
					extension_create_component(switch_instance.$$.fragment);
					extension_transition_in(switch_instance.$$.fragment, 1);
					extension_mount_component(switch_instance, div, t);
				} else {
					switch_instance = null;
				}
			} else if (switch_value) {
				switch_instance.$set(switch_instance_changes);
			}

			if (dirty & /*$selected, id*/ 96) show_if = /*$selected*/ ctx[6].includes(/*id*/ ctx[5]);

			if (show_if) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*$selected, id*/ 96) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_DataSample_svelte_create_if_block(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(div, null);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;
			if (switch_instance) extension_transition_in(switch_instance.$$.fragment, local);
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			if (switch_instance) extension_transition_out(switch_instance.$$.fragment, local);
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			if (switch_instance) extension_destroy_component(switch_instance);
			if (if_block) if_block.d();
			mounted = false;
			extension_run_all(dispose);
		}
	};
}

function extension_DataSample_svelte_instance($$self, $$props, $$invalidate) {
	let id;

	let $canvasSpec,
		$$unsubscribe_canvasSpec = extension_noop,
		$$subscribe_canvasSpec = () => ($$unsubscribe_canvasSpec(), $$unsubscribe_canvasSpec = extension_subscribe(canvasSpec, $$value => $$invalidate(3, $canvasSpec = $$value)), canvasSpec);

	let $selected,
		$$unsubscribe_selected = extension_noop,
		$$subscribe_selected = () => ($$unsubscribe_selected(), $$unsubscribe_selected = extension_subscribe(selected, $$value => $$invalidate(6, $selected = $$value)), selected);

	$$self.$$.on_destroy.push(() => $$unsubscribe_canvasSpec());
	$$self.$$.on_destroy.push(() => $$unsubscribe_selected());
	let { dataPoint } = $$props;
	let { canvasSpec } = $$props;
	$$subscribe_canvasSpec();
	let { selected } = $$props;
	$$subscribe_selected();
	let { tooltip } = $$props;
	let { number = undefined } = $$props;
	let { storybook = false } = $$props;
	let hover = false;
	let m = { x: 0, y: 0 };

	function select() {
		const index = $selected.indexOf(id);

		if (index > -1) {
			selected.update(d => {
				d.splice(index, 1);
				return [...d];
			});
		} else {
			selected.set([...$selected, id]);
		}
	}

	function handleMousemove(event) {
		m.x = event.clientX;
		m.y = event.clientY;
		updateSampleTooltip();
	}

	function updateSampleTooltip() {
		tooltip.set({
			hover,
			mousePos: m,
			fetchPrefix: $canvasSpec.filesPath,
			instance: dataPoint,
			number
		});
	}

	const click_handler = () => select();

	const mouseenter_handler = () => {
		$$invalidate(4, hover = true);
		updateSampleTooltip();
	};

	const mouseleave_handler = () => {
		$$invalidate(4, hover = false);
		updateSampleTooltip();
	};

	$$self.$$set = $$props => {
		if ('dataPoint' in $$props) $$invalidate(10, dataPoint = $$props.dataPoint);
		if ('canvasSpec' in $$props) $$subscribe_canvasSpec($$invalidate(0, canvasSpec = $$props.canvasSpec));
		if ('selected' in $$props) $$subscribe_selected($$invalidate(1, selected = $$props.selected));
		if ('tooltip' in $$props) $$invalidate(11, tooltip = $$props.tooltip);
		if ('number' in $$props) $$invalidate(12, number = $$props.number);
		if ('storybook' in $$props) $$invalidate(2, storybook = $$props.storybook);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*dataPoint, $canvasSpec*/ 1032) {
			$: $$invalidate(5, id = dataPoint[$canvasSpec.idColumn]);
		}
	};

	return [
		canvasSpec,
		selected,
		storybook,
		$canvasSpec,
		hover,
		id,
		$selected,
		select,
		handleMousemove,
		updateSampleTooltip,
		dataPoint,
		tooltip,
		number,
		click_handler,
		mouseenter_handler,
		mouseleave_handler
	];
}

class extension_DataSample extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(this, options, extension_DataSample_svelte_instance, extension_DataSample_svelte_create_fragment, extension_safe_not_equal, {
			dataPoint: 10,
			canvasSpec: 0,
			selected: 1,
			tooltip: 11,
			number: 12,
			storybook: 2
		});
	}
}

/* harmony default export */ const extension_DataSample_svelte = (extension_DataSample);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faEyeSlash.js
var extension_faEyeSlash = __webpack_require__(5408);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faEye.js
var extension_faEye = __webpack_require__(849);
;// ../../canvas_viz/dist/elements/SampleRowContainer.svelte
/* media/satish/Development/workspace/projects/exploratory_data_analysis/deepview/src/deepview_canvas/canvas_viz/dist/elements/SampleRowContainer.svelte generated by Svelte v3.59.2 */








function extension_SampleRowContainer_svelte_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[9] = list[i];
	return child_ctx;
}

// (32:4) {#each dataPoints.slice(0, numberShown) as dataPoint}
function extension_SampleRowContainer_svelte_create_each_block(ctx) {
	let datasample;
	let current;

	datasample = new extension_DataSample_svelte({
			props: {
				dataPoint: /*dataPoint*/ ctx[9],
				canvasSpec: /*canvasSpec*/ ctx[3],
				selected: /*selected*/ ctx[2],
				tooltip: /*tooltip*/ ctx[4],
				storybook: /*storybook*/ ctx[5]
			}
		});

	return {
		c() {
			extension_create_component(datasample.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(datasample, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const datasample_changes = {};
			if (dirty & /*dataPoints, numberShown*/ 66) datasample_changes.dataPoint = /*dataPoint*/ ctx[9];
			if (dirty & /*canvasSpec*/ 8) datasample_changes.canvasSpec = /*canvasSpec*/ ctx[3];
			if (dirty & /*selected*/ 4) datasample_changes.selected = /*selected*/ ctx[2];
			if (dirty & /*tooltip*/ 16) datasample_changes.tooltip = /*tooltip*/ ctx[4];
			if (dirty & /*storybook*/ 32) datasample_changes.storybook = /*storybook*/ ctx[5];
			datasample.$set(datasample_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(datasample.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(datasample.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(datasample, detaching);
		}
	};
}

// (36:2) {#if dataPoints.length > numberShown}
function extension_SampleRowContainer_svelte_create_if_block_1(ctx) {
	let iconbutton;
	let current;

	iconbutton = new extension_IconButton_svelte({
			props: {
				$$slots: {
					text: [extension_create_text_slot_1],
					icon: [extension_create_icon_slot_1]
				},
				$$scope: { ctx }
			}
		});

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

	return {
		c() {
			extension_create_component(iconbutton.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(iconbutton, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const iconbutton_changes = {};

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

			iconbutton.$set(iconbutton_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(iconbutton, detaching);
		}
	};
}

// (38:6) 
function extension_create_icon_slot_1(ctx) {
	let fa;
	let current;
	fa = new extension_fa_svelte({ props: { icon: extension_faEye/* faEye */.pS, slot: "icon" } });

	return {
		c() {
			extension_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(fa, target, anchor);
			current = true;
		},
		p: extension_noop,
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(fa, detaching);
		}
	};
}

// (39:6) 
function extension_create_text_slot_1(ctx) {
	let p;
	let t0;
	let t1_value = /*dataPoints*/ ctx[1].length - /*defaultNumberShown*/ ctx[0] + "";
	let t1;
	let t2;

	return {
		c() {
			p = extension_internal_element("p");
			t0 = extension_internal_text("Show ");
			t1 = extension_internal_text(t1_value);
			t2 = extension_internal_text(" more");
			extension_attr(p, "slot", "text");
		},
		m(target, anchor) {
			extension_insert(target, p, anchor);
			extension_append(p, t0);
			extension_append(p, t1);
			extension_append(p, t2);
		},
		p(ctx, dirty) {
			if (dirty & /*dataPoints, defaultNumberShown*/ 3 && t1_value !== (t1_value = /*dataPoints*/ ctx[1].length - /*defaultNumberShown*/ ctx[0] + "")) extension_set_data(t1, t1_value);
		},
		d(detaching) {
			if (detaching) extension_detach(p);
		}
	};
}

// (42:2) {#if dataPoints.length === numberShown && dataPoints.length > defaultNumberShown}
function extension_SampleRowContainer_svelte_create_if_block(ctx) {
	let iconbutton;
	let current;

	iconbutton = new extension_IconButton_svelte({
			props: {
				$$slots: {
					text: [extension_create_text_slot],
					icon: [extension_SampleRowContainer_svelte_create_icon_slot]
				},
				$$scope: { ctx }
			}
		});

	iconbutton.$on("click", /*click_handler_1*/ ctx[8]);

	return {
		c() {
			extension_create_component(iconbutton.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(iconbutton, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const iconbutton_changes = {};

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

			iconbutton.$set(iconbutton_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(iconbutton, detaching);
		}
	};
}

// (44:6) 
function extension_SampleRowContainer_svelte_create_icon_slot(ctx) {
	let fa;
	let current;

	fa = new extension_fa_svelte({
			props: { icon: extension_faEyeSlash/* faEyeSlash */.k6, slot: "icon" }
		});

	return {
		c() {
			extension_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(fa, target, anchor);
			current = true;
		},
		p: extension_noop,
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(fa, detaching);
		}
	};
}

// (45:6) 
function extension_create_text_slot(ctx) {
	let p;

	return {
		c() {
			p = extension_internal_element("p");
			p.textContent = "Collapse";
			extension_attr(p, "slot", "text");
		},
		m(target, anchor) {
			extension_insert(target, p, anchor);
		},
		p: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(p);
		}
	};
}

function extension_SampleRowContainer_svelte_create_fragment(ctx) {
	let div1;
	let div0;
	let t0;
	let t1;
	let current;
	let each_value = /*dataPoints*/ ctx[1].slice(0, /*numberShown*/ ctx[6]);
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = extension_SampleRowContainer_svelte_create_each_block(extension_SampleRowContainer_svelte_get_each_context(ctx, each_value, i));
	}

	const out = i => extension_transition_out(each_blocks[i], 1, 1, () => {
		each_blocks[i] = null;
	});

	let if_block0 = /*dataPoints*/ ctx[1].length > /*numberShown*/ ctx[6] && extension_SampleRowContainer_svelte_create_if_block_1(ctx);
	let if_block1 = /*dataPoints*/ ctx[1].length === /*numberShown*/ ctx[6] && /*dataPoints*/ ctx[1].length > /*defaultNumberShown*/ ctx[0] && extension_SampleRowContainer_svelte_create_if_block(ctx);

	return {
		c() {
			div1 = extension_internal_element("div");
			div0 = extension_internal_element("div");

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			t0 = extension_space();
			if (if_block0) if_block0.c();
			t1 = extension_space();
			if (if_block1) if_block1.c();
			extension_attr(div0, "class", "flex flex-wrap");
			extension_attr(div1, "class", "flex flex-wrap items-center justify-between flex-1");
		},
		m(target, anchor) {
			extension_insert(target, div1, anchor);
			extension_append(div1, div0);

			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(div0, null);
				}
			}

			extension_append(div1, t0);
			if (if_block0) if_block0.m(div1, null);
			extension_append(div1, t1);
			if (if_block1) if_block1.m(div1, null);
			current = true;
		},
		p(ctx, [dirty]) {
			if (dirty & /*dataPoints, numberShown, canvasSpec, selected, tooltip, storybook*/ 126) {
				each_value = /*dataPoints*/ ctx[1].slice(0, /*numberShown*/ ctx[6]);
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = extension_SampleRowContainer_svelte_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
						extension_transition_in(each_blocks[i], 1);
					} else {
						each_blocks[i] = extension_SampleRowContainer_svelte_create_each_block(child_ctx);
						each_blocks[i].c();
						extension_transition_in(each_blocks[i], 1);
						each_blocks[i].m(div0, null);
					}
				}

				extension_group_outros();

				for (i = each_value.length; i < each_blocks.length; i += 1) {
					out(i);
				}

				extension_check_outros();
			}

			if (/*dataPoints*/ ctx[1].length > /*numberShown*/ ctx[6]) {
				if (if_block0) {
					if_block0.p(ctx, dirty);

					if (dirty & /*dataPoints, numberShown*/ 66) {
						extension_transition_in(if_block0, 1);
					}
				} else {
					if_block0 = extension_SampleRowContainer_svelte_create_if_block_1(ctx);
					if_block0.c();
					extension_transition_in(if_block0, 1);
					if_block0.m(div1, t1);
				}
			} else if (if_block0) {
				extension_group_outros();

				extension_transition_out(if_block0, 1, 1, () => {
					if_block0 = null;
				});

				extension_check_outros();
			}

			if (/*dataPoints*/ ctx[1].length === /*numberShown*/ ctx[6] && /*dataPoints*/ ctx[1].length > /*defaultNumberShown*/ ctx[0]) {
				if (if_block1) {
					if_block1.p(ctx, dirty);

					if (dirty & /*dataPoints, numberShown, defaultNumberShown*/ 67) {
						extension_transition_in(if_block1, 1);
					}
				} else {
					if_block1 = extension_SampleRowContainer_svelte_create_if_block(ctx);
					if_block1.c();
					extension_transition_in(if_block1, 1);
					if_block1.m(div1, null);
				}
			} else if (if_block1) {
				extension_group_outros();

				extension_transition_out(if_block1, 1, 1, () => {
					if_block1 = null;
				});

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;

			for (let i = 0; i < each_value.length; i += 1) {
				extension_transition_in(each_blocks[i]);
			}

			extension_transition_in(if_block0);
			extension_transition_in(if_block1);
			current = true;
		},
		o(local) {
			each_blocks = each_blocks.filter(Boolean);

			for (let i = 0; i < each_blocks.length; i += 1) {
				extension_transition_out(each_blocks[i]);
			}

			extension_transition_out(if_block0);
			extension_transition_out(if_block1);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div1);
			extension_destroy_each(each_blocks, detaching);
			if (if_block0) if_block0.d();
			if (if_block1) if_block1.d();
		}
	};
}

function extension_SampleRowContainer_svelte_instance($$self, $$props, $$invalidate) {
	let { defaultNumberShown = 20 } = $$props;
	let { dataPoints } = $$props;
	let { selected } = $$props;
	let { canvasSpec } = $$props;
	let { tooltip } = $$props;
	let { storybook = false } = $$props;
	let numberShown = defaultNumberShown;
	const click_handler = () => $$invalidate(6, numberShown = dataPoints.length);
	const click_handler_1 = () => $$invalidate(6, numberShown = defaultNumberShown);

	$$self.$$set = $$props => {
		if ('defaultNumberShown' in $$props) $$invalidate(0, defaultNumberShown = $$props.defaultNumberShown);
		if ('dataPoints' in $$props) $$invalidate(1, dataPoints = $$props.dataPoints);
		if ('selected' in $$props) $$invalidate(2, selected = $$props.selected);
		if ('canvasSpec' in $$props) $$invalidate(3, canvasSpec = $$props.canvasSpec);
		if ('tooltip' in $$props) $$invalidate(4, tooltip = $$props.tooltip);
		if ('storybook' in $$props) $$invalidate(5, storybook = $$props.storybook);
	};

	return [
		defaultNumberShown,
		dataPoints,
		selected,
		canvasSpec,
		tooltip,
		storybook,
		numberShown,
		click_handler,
		click_handler_1
	];
}

class extension_SampleRowContainer extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(this, options, extension_SampleRowContainer_svelte_instance, extension_SampleRowContainer_svelte_create_fragment, extension_safe_not_equal, {
			defaultNumberShown: 0,
			dataPoints: 1,
			selected: 2,
			canvasSpec: 3,
			tooltip: 4,
			storybook: 5
		});
	}
}

/* harmony default export */ const extension_SampleRowContainer_svelte = (extension_SampleRowContainer);
;// ../../canvas_viz/dist/helpers/selection.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 extension_selectAll(selectedStore, newSelected) {
    let existingSelectedSet = new Set(extension_get_store_value(selectedStore));
    let newSelectedSet = new Set(newSelected);
    if (extension_setHasAll(newSelectedSet, existingSelectedSet)) {
        for (var toRemove of newSelectedSet)
            existingSelectedSet.delete(toRemove);
        selectedStore.update(() => [...existingSelectedSet]);
        return;
    }
    let combinedSelected = new Set([...existingSelectedSet, ...newSelectedSet]);
    selectedStore.set(Array.from(combinedSelected));
}
function extension_setHasAll(set, setHas) {
    for (var a of set)
        if (!setHas.has(a))
            return false;
    return true;
}

;// ./src/DatasetDuplicatesList.svelte
/* src/DatasetDuplicatesList.svelte generated by Svelte v3.59.2 */







function extension_DatasetDuplicatesList_svelte_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[15] = list[i];
	child_ctx[17] = i;
	return child_ctx;
}

// (66:2) {:else}
function extension_DatasetDuplicatesList_svelte_create_else_block(ctx) {
	let container;
	let current;

	container = new extension_Container_svelte({
			props: {
				$$slots: {
					content: [extension_create_content_slot_1],
					header: [extension_create_header_slot_1]
				},
				$$scope: { ctx }
			}
		});

	return {
		c() {
			extension_create_component(container.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(container, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const container_changes = {};

			if (dirty & /*$$scope, filteredPoints, defaultNumberShown, canvasSpec, selected, tooltip, storybook, dataPoints, $canvasSpec, candidatesGroupNumber*/ 265721) {
				container_changes.$$scope = { dirty, ctx };
			}

			container.$set(container_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(container.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(container.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(container, detaching);
		}
	};
}

// (45:2) {#if $groupNames.length === 0}
function extension_DatasetDuplicatesList_svelte_create_if_block(ctx) {
	let container;
	let current;

	container = new extension_Container_svelte({
			props: {
				$$slots: {
					content: [extension_create_content_slot],
					header: [extension_create_header_slot]
				},
				$$scope: { ctx }
			}
		});

	return {
		c() {
			extension_create_component(container.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(container, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const container_changes = {};

			if (dirty & /*$$scope, dataPoints, selected, canvasSpec, tooltip, storybook, $canvasSpec, candidatesGroupNumber*/ 264633) {
				container_changes.$$scope = { dirty, ctx };
			}

			container.$set(container_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(container.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(container.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(container, detaching);
		}
	};
}

// (80:10) 
function extension_DatasetDuplicatesList_svelte_create_icon_slot_1(ctx) {
	let fa;
	let current;

	fa = new extension_fa_svelte({
			props: { icon: extension_faCheckSquare/* faCheckSquare */.rQ, slot: "icon" }
		});

	return {
		c() {
			extension_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(fa, target, anchor);
			current = true;
		},
		p: extension_noop,
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(fa, detaching);
		}
	};
}

// (68:6) 
function extension_create_header_slot_1(ctx) {
	let div;
	let h3;
	let t0_value = `Candidate Group ${/*candidatesGroupNumber*/ ctx[8]}` + "";
	let t0;
	let t1;
	let iconbutton;
	let current;

	iconbutton = new extension_IconButton_svelte({
			props: {
				$$slots: { icon: [extension_DatasetDuplicatesList_svelte_create_icon_slot_1] },
				$$scope: { ctx }
			}
		});

	iconbutton.$on("click", /*click_handler_1*/ ctx[14]);

	return {
		c() {
			div = extension_internal_element("div");
			h3 = extension_internal_element("h3");
			t0 = extension_internal_text(t0_value);
			t1 = extension_space();
			extension_create_component(iconbutton.$$.fragment);
			extension_attr(h3, "class", "font-bold whitespace-nowrap mr-3");
			extension_attr(div, "class", "flex items-top justify-between w-full");
			extension_attr(div, "slot", "header");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_append(div, h3);
			extension_append(h3, t0);
			extension_append(div, t1);
			extension_mount_component(iconbutton, div, null);
			current = true;
		},
		p(ctx, dirty) {
			if ((!current || dirty & /*candidatesGroupNumber*/ 256) && t0_value !== (t0_value = `Candidate Group ${/*candidatesGroupNumber*/ ctx[8]}` + "")) extension_set_data(t0, t0_value);
			const iconbutton_changes = {};

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

			iconbutton.$set(iconbutton_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(iconbutton);
		}
	};
}

// (85:10) {#if group.points.length !== 0}
function extension_DatasetDuplicatesList_svelte_create_if_block_1(ctx) {
	let div;
	let h3;
	let t0_value = /*group*/ ctx[15].attrs.join(' | ') + "";
	let t0;
	let t1;
	let samplerowcontainer;
	let current;

	samplerowcontainer = new extension_SampleRowContainer_svelte({
			props: {
				defaultNumberShown: /*defaultNumberShown*/ ctx[6],
				dataPoints: /*group*/ ctx[15].points,
				canvasSpec: /*canvasSpec*/ ctx[4],
				selected: /*selected*/ ctx[3],
				tooltip: /*tooltip*/ ctx[5],
				storybook: /*storybook*/ ctx[7]
			}
		});

	return {
		c() {
			div = extension_internal_element("div");
			h3 = extension_internal_element("h3");
			t0 = extension_internal_text(t0_value);
			t1 = extension_space();
			extension_create_component(samplerowcontainer.$$.fragment);
			extension_attr(h3, "class", "whitespace-nowrap italic");
			extension_attr(div, "class", "flex items-center");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_append(div, h3);
			extension_append(h3, t0);
			extension_insert(target, t1, anchor);
			extension_mount_component(samplerowcontainer, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			if ((!current || dirty & /*filteredPoints*/ 1024) && t0_value !== (t0_value = /*group*/ ctx[15].attrs.join(' | ') + "")) extension_set_data(t0, t0_value);
			const samplerowcontainer_changes = {};
			if (dirty & /*defaultNumberShown*/ 64) samplerowcontainer_changes.defaultNumberShown = /*defaultNumberShown*/ ctx[6];
			if (dirty & /*filteredPoints*/ 1024) samplerowcontainer_changes.dataPoints = /*group*/ ctx[15].points;
			if (dirty & /*canvasSpec*/ 16) samplerowcontainer_changes.canvasSpec = /*canvasSpec*/ ctx[4];
			if (dirty & /*selected*/ 8) samplerowcontainer_changes.selected = /*selected*/ ctx[3];
			if (dirty & /*tooltip*/ 32) samplerowcontainer_changes.tooltip = /*tooltip*/ ctx[5];
			if (dirty & /*storybook*/ 128) samplerowcontainer_changes.storybook = /*storybook*/ ctx[7];
			samplerowcontainer.$set(samplerowcontainer_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(samplerowcontainer.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(samplerowcontainer.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			if (detaching) extension_detach(t1);
			extension_destroy_component(samplerowcontainer, detaching);
		}
	};
}

// (84:8) {#each filteredPoints as group, i}
function extension_DatasetDuplicatesList_svelte_create_each_block(ctx) {
	let if_block_anchor;
	let current;
	let if_block = /*group*/ ctx[15].points.length !== 0 && extension_DatasetDuplicatesList_svelte_create_if_block_1(ctx);

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = extension_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			extension_insert(target, if_block_anchor, anchor);
			current = true;
		},
		p(ctx, dirty) {
			if (/*group*/ ctx[15].points.length !== 0) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*filteredPoints*/ 1024) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_DatasetDuplicatesList_svelte_create_if_block_1(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(if_block_anchor.parentNode, if_block_anchor);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) extension_detach(if_block_anchor);
		}
	};
}

// (83:6) 
function extension_create_content_slot_1(ctx) {
	let div;
	let current;
	let each_value = /*filteredPoints*/ ctx[10];
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = extension_DatasetDuplicatesList_svelte_create_each_block(extension_DatasetDuplicatesList_svelte_get_each_context(ctx, each_value, i));
	}

	const out = i => extension_transition_out(each_blocks[i], 1, 1, () => {
		each_blocks[i] = null;
	});

	return {
		c() {
			div = extension_internal_element("div");

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			extension_attr(div, "slot", "content");
		},
		m(target, anchor) {
			extension_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 & /*defaultNumberShown, filteredPoints, canvasSpec, selected, tooltip, storybook*/ 1272) {
				each_value = /*filteredPoints*/ ctx[10];
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = extension_DatasetDuplicatesList_svelte_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
						extension_transition_in(each_blocks[i], 1);
					} else {
						each_blocks[i] = extension_DatasetDuplicatesList_svelte_create_each_block(child_ctx);
						each_blocks[i].c();
						extension_transition_in(each_blocks[i], 1);
						each_blocks[i].m(div, null);
					}
				}

				extension_group_outros();

				for (i = each_value.length; i < each_blocks.length; i += 1) {
					out(i);
				}

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;

			for (let i = 0; i < each_value.length; i += 1) {
				extension_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) {
				extension_transition_out(each_blocks[i]);
			}

			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_each(each_blocks, detaching);
		}
	};
}

// (59:10) 
function extension_DatasetDuplicatesList_svelte_create_icon_slot(ctx) {
	let fa;
	let current;

	fa = new extension_fa_svelte({
			props: { icon: extension_faCheckSquare/* faCheckSquare */.rQ, slot: "icon" }
		});

	return {
		c() {
			extension_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(fa, target, anchor);
			current = true;
		},
		p: extension_noop,
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(fa, detaching);
		}
	};
}

// (47:6) 
function extension_create_header_slot(ctx) {
	let div;
	let h3;
	let t0_value = `Candidate Group ${/*candidatesGroupNumber*/ ctx[8]}` + "";
	let t0;
	let t1;
	let iconbutton;
	let current;

	iconbutton = new extension_IconButton_svelte({
			props: {
				$$slots: { icon: [extension_DatasetDuplicatesList_svelte_create_icon_slot] },
				$$scope: { ctx }
			}
		});

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

	return {
		c() {
			div = extension_internal_element("div");
			h3 = extension_internal_element("h3");
			t0 = extension_internal_text(t0_value);
			t1 = extension_space();
			extension_create_component(iconbutton.$$.fragment);
			extension_attr(h3, "class", "font-bold whitespace-nowrap mr-3");
			extension_attr(div, "class", "flex items-top justify-between w-full");
			extension_attr(div, "slot", "header");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_append(div, h3);
			extension_append(h3, t0);
			extension_append(div, t1);
			extension_mount_component(iconbutton, div, null);
			current = true;
		},
		p(ctx, dirty) {
			if ((!current || dirty & /*candidatesGroupNumber*/ 256) && t0_value !== (t0_value = `Candidate Group ${/*candidatesGroupNumber*/ ctx[8]}` + "")) extension_set_data(t0, t0_value);
			const iconbutton_changes = {};

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

			iconbutton.$set(iconbutton_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(iconbutton);
		}
	};
}

// (62:6) 
function extension_create_content_slot(ctx) {
	let div;
	let samplerowcontainer;
	let current;

	samplerowcontainer = new extension_SampleRowContainer_svelte({
			props: {
				dataPoints: /*dataPoints*/ ctx[0],
				selected: /*selected*/ ctx[3],
				canvasSpec: /*canvasSpec*/ ctx[4],
				tooltip: /*tooltip*/ ctx[5],
				storybook: /*storybook*/ ctx[7]
			}
		});

	return {
		c() {
			div = extension_internal_element("div");
			extension_create_component(samplerowcontainer.$$.fragment);
			extension_attr(div, "class", "flex");
			extension_attr(div, "slot", "content");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_mount_component(samplerowcontainer, div, null);
			current = true;
		},
		p(ctx, dirty) {
			const samplerowcontainer_changes = {};
			if (dirty & /*dataPoints*/ 1) samplerowcontainer_changes.dataPoints = /*dataPoints*/ ctx[0];
			if (dirty & /*selected*/ 8) samplerowcontainer_changes.selected = /*selected*/ ctx[3];
			if (dirty & /*canvasSpec*/ 16) samplerowcontainer_changes.canvasSpec = /*canvasSpec*/ ctx[4];
			if (dirty & /*tooltip*/ 32) samplerowcontainer_changes.tooltip = /*tooltip*/ ctx[5];
			if (dirty & /*storybook*/ 128) samplerowcontainer_changes.storybook = /*storybook*/ ctx[7];
			samplerowcontainer.$set(samplerowcontainer_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(samplerowcontainer.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(samplerowcontainer.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(samplerowcontainer);
		}
	};
}

function extension_DatasetDuplicatesList_svelte_create_fragment(ctx) {
	let div;
	let current_block_type_index;
	let if_block;
	let current;
	const if_block_creators = [extension_DatasetDuplicatesList_svelte_create_if_block, extension_DatasetDuplicatesList_svelte_create_else_block];
	const if_blocks = [];

	function select_block_type(ctx, dirty) {
		if (/*$groupNames*/ ctx[9].length === 0) return 0;
		return 1;
	}

	current_block_type_index = select_block_type(ctx, -1);
	if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);

	return {
		c() {
			div = extension_internal_element("div");
			if_block.c();
			extension_attr(div, "w-full", "");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			if_blocks[current_block_type_index].m(div, null);
			current = true;
		},
		p(ctx, [dirty]) {
			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 {
				extension_group_outros();

				extension_transition_out(if_blocks[previous_block_index], 1, 1, () => {
					if_blocks[previous_block_index] = null;
				});

				extension_check_outros();
				if_block = if_blocks[current_block_type_index];

				if (!if_block) {
					if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
					if_block.c();
				} else {
					if_block.p(ctx, dirty);
				}

				extension_transition_in(if_block, 1);
				if_block.m(div, null);
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			if_blocks[current_block_type_index].d();
		}
	};
}

function extension_DatasetDuplicatesList_svelte_instance($$self, $$props, $$invalidate) {
	let filteredPoints;

	let $groupColumns,
		$$unsubscribe_groupColumns = extension_noop,
		$$subscribe_groupColumns = () => ($$unsubscribe_groupColumns(), $$unsubscribe_groupColumns = extension_subscribe(groupColumns, $$value => $$invalidate(12, $groupColumns = $$value)), groupColumns);

	let $groupNames,
		$$unsubscribe_groupNames = extension_noop,
		$$subscribe_groupNames = () => ($$unsubscribe_groupNames(), $$unsubscribe_groupNames = extension_subscribe(groupNames, $$value => $$invalidate(9, $groupNames = $$value)), groupNames);

	let $canvasSpec,
		$$unsubscribe_canvasSpec = extension_noop,
		$$subscribe_canvasSpec = () => ($$unsubscribe_canvasSpec(), $$unsubscribe_canvasSpec = extension_subscribe(canvasSpec, $$value => $$invalidate(11, $canvasSpec = $$value)), canvasSpec);

	$$self.$$.on_destroy.push(() => $$unsubscribe_groupColumns());
	$$self.$$.on_destroy.push(() => $$unsubscribe_groupNames());
	$$self.$$.on_destroy.push(() => $$unsubscribe_canvasSpec());
	let { dataPoints } = $$props;
	let { groupColumns } = $$props;
	$$subscribe_groupColumns();
	let { groupNames } = $$props;
	$$subscribe_groupNames();
	let { selected } = $$props;
	let { canvasSpec } = $$props;
	$$subscribe_canvasSpec();
	let { tooltip } = $$props;
	let { defaultNumberShown } = $$props;
	let { storybook = false } = $$props;
	let { candidatesGroupNumber } = $$props;

	const click_handler = () => {
		extension_selectAll(selected, dataPoints.map(d => d[$canvasSpec.idColumn]));
	};

	const click_handler_1 = () => {
		extension_selectAll(selected, dataPoints.map(d => d[$canvasSpec.idColumn]));
	};

	$$self.$$set = $$props => {
		if ('dataPoints' in $$props) $$invalidate(0, dataPoints = $$props.dataPoints);
		if ('groupColumns' in $$props) $$subscribe_groupColumns($$invalidate(1, groupColumns = $$props.groupColumns));
		if ('groupNames' in $$props) $$subscribe_groupNames($$invalidate(2, groupNames = $$props.groupNames));
		if ('selected' in $$props) $$invalidate(3, selected = $$props.selected);
		if ('canvasSpec' in $$props) $$subscribe_canvasSpec($$invalidate(4, canvasSpec = $$props.canvasSpec));
		if ('tooltip' in $$props) $$invalidate(5, tooltip = $$props.tooltip);
		if ('defaultNumberShown' in $$props) $$invalidate(6, defaultNumberShown = $$props.defaultNumberShown);
		if ('storybook' in $$props) $$invalidate(7, storybook = $$props.storybook);
		if ('candidatesGroupNumber' in $$props) $$invalidate(8, candidatesGroupNumber = $$props.candidatesGroupNumber);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*$groupNames, dataPoints, $groupColumns*/ 4609) {
			$: $$invalidate(10, filteredPoints = $groupNames.map(attrs => {
				return {
					attrs,
					points: dataPoints.filter(point => {
						let match = true;

						attrs.forEach((attr, i) => {
							if (point[$groupColumns[i]] !== attr) match = false;
						});

						return match;
					})
				};
			}).sort((a, b) => b.points.length - a.points.length));
		}
	};

	return [
		dataPoints,
		groupColumns,
		groupNames,
		selected,
		canvasSpec,
		tooltip,
		defaultNumberShown,
		storybook,
		candidatesGroupNumber,
		$groupNames,
		filteredPoints,
		$canvasSpec,
		$groupColumns,
		click_handler,
		click_handler_1
	];
}

class extension_DatasetDuplicatesList extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(this, options, extension_DatasetDuplicatesList_svelte_instance, extension_DatasetDuplicatesList_svelte_create_fragment, extension_safe_not_equal, {
			dataPoints: 0,
			groupColumns: 1,
			groupNames: 2,
			selected: 3,
			canvasSpec: 4,
			tooltip: 5,
			defaultNumberShown: 6,
			storybook: 7,
			candidatesGroupNumber: 8
		});
	}
}

/* harmony default export */ const extension_DatasetDuplicatesList_svelte = (extension_DatasetDuplicatesList);
;// ./src/DuplicatesList.svelte
/* src/DuplicatesList.svelte generated by Svelte v3.59.2 */





function extension_DuplicatesList_svelte_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[16] = list[i];
	child_ctx[18] = i;
	return child_ctx;
}

// (53:4) {#if groupedDuplicates[group] !== undefined}
function extension_DuplicatesList_svelte_create_if_block(ctx) {
	let div;
	let datasetduplicateslist;
	let t;
	let current;

	datasetduplicateslist = new extension_DatasetDuplicatesList_svelte({
			props: {
				slot: "content",
				dataPoints: /*groupedDuplicates*/ ctx[7][/*group*/ ctx[16]],
				defaultNumberShown: extension_NUMBER_SHOWN,
				groupColumns: /*groupColumns*/ ctx[2],
				groupNames: /*groupNames*/ ctx[3],
				canvasSpec: /*canvasSpec*/ ctx[1],
				selected: /*selected*/ ctx[4],
				tooltip: /*tooltip*/ ctx[5],
				storybook: /*storybook*/ ctx[6],
				candidatesGroupNumber: /*i*/ ctx[18]
			}
		});

	return {
		c() {
			div = extension_internal_element("div");
			extension_create_component(datasetduplicateslist.$$.fragment);
			t = extension_space();
			extension_attr(div, "class", "py-1 w-full");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_mount_component(datasetduplicateslist, div, null);
			extension_append(div, t);
			current = true;
		},
		p(ctx, dirty) {
			const datasetduplicateslist_changes = {};
			if (dirty & /*groupedDuplicates, groupKeys, page, rowsPerPage*/ 1920) datasetduplicateslist_changes.dataPoints = /*groupedDuplicates*/ ctx[7][/*group*/ ctx[16]];
			if (dirty & /*groupColumns*/ 4) datasetduplicateslist_changes.groupColumns = /*groupColumns*/ ctx[2];
			if (dirty & /*groupNames*/ 8) datasetduplicateslist_changes.groupNames = /*groupNames*/ ctx[3];
			if (dirty & /*canvasSpec*/ 2) datasetduplicateslist_changes.canvasSpec = /*canvasSpec*/ ctx[1];
			if (dirty & /*selected*/ 16) datasetduplicateslist_changes.selected = /*selected*/ ctx[4];
			if (dirty & /*tooltip*/ 32) datasetduplicateslist_changes.tooltip = /*tooltip*/ ctx[5];
			if (dirty & /*storybook*/ 64) datasetduplicateslist_changes.storybook = /*storybook*/ ctx[6];
			datasetduplicateslist.$set(datasetduplicateslist_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(datasetduplicateslist.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(datasetduplicateslist.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(datasetduplicateslist);
		}
	};
}

// (52:2) {#each groupKeys.slice(page * rowsPerPage + 1, page * rowsPerPage + rowsPerPage) as group, i}
function extension_DuplicatesList_svelte_create_each_block(ctx) {
	let if_block_anchor;
	let current;
	let if_block = /*groupedDuplicates*/ ctx[7][/*group*/ ctx[16]] !== undefined && extension_DuplicatesList_svelte_create_if_block(ctx);

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = extension_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			extension_insert(target, if_block_anchor, anchor);
			current = true;
		},
		p(ctx, dirty) {
			if (/*groupedDuplicates*/ ctx[7][/*group*/ ctx[16]] !== undefined) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*groupedDuplicates, groupKeys, page, rowsPerPage*/ 1920) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_DuplicatesList_svelte_create_if_block(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(if_block_anchor.parentNode, if_block_anchor);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) extension_detach(if_block_anchor);
		}
	};
}

function extension_DuplicatesList_svelte_create_fragment(ctx) {
	let div;
	let t;
	let paginationcontrols;
	let updating_page;
	let current;
	let each_value = /*groupKeys*/ ctx[8].slice(/*page*/ ctx[9] * /*rowsPerPage*/ ctx[10] + 1, /*page*/ ctx[9] * /*rowsPerPage*/ ctx[10] + /*rowsPerPage*/ ctx[10]);
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = extension_DuplicatesList_svelte_create_each_block(extension_DuplicatesList_svelte_get_each_context(ctx, each_value, i));
	}

	const out = i => extension_transition_out(each_blocks[i], 1, 1, () => {
		each_blocks[i] = null;
	});

	function paginationcontrols_page_binding(value) {
		/*paginationcontrols_page_binding*/ ctx[15](value);
	}

	let paginationcontrols_props = {
		instancesPerPage: /*rowsPerPage*/ ctx[10],
		size: /*groupKeys*/ ctx[8].length
	};

	if (/*page*/ ctx[9] !== void 0) {
		paginationcontrols_props.page = /*page*/ ctx[9];
	}

	paginationcontrols = new extension_PaginationControls_svelte({ props: paginationcontrols_props });
	extension_binding_callbacks.push(() => extension_bind(paginationcontrols, 'page', paginationcontrols_page_binding));

	return {
		c() {
			div = extension_internal_element("div");

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			t = extension_space();
			extension_create_component(paginationcontrols.$$.fragment);
			extension_attr(div, "class", "flex flex-col relative items-start border-b border-midgrey pb-1 mb-1 overflow-auto flex-1");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);

			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(div, null);
				}
			}

			extension_insert(target, t, anchor);
			extension_mount_component(paginationcontrols, target, anchor);
			current = true;
		},
		p(ctx, [dirty]) {
			if (dirty & /*groupedDuplicates, groupKeys, page, rowsPerPage, NUMBER_SHOWN, groupColumns, groupNames, canvasSpec, selected, tooltip, storybook, undefined*/ 2046) {
				each_value = /*groupKeys*/ ctx[8].slice(/*page*/ ctx[9] * /*rowsPerPage*/ ctx[10] + 1, /*page*/ ctx[9] * /*rowsPerPage*/ ctx[10] + /*rowsPerPage*/ ctx[10]);
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = extension_DuplicatesList_svelte_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
						extension_transition_in(each_blocks[i], 1);
					} else {
						each_blocks[i] = extension_DuplicatesList_svelte_create_each_block(child_ctx);
						each_blocks[i].c();
						extension_transition_in(each_blocks[i], 1);
						each_blocks[i].m(div, null);
					}
				}

				extension_group_outros();

				for (i = each_value.length; i < each_blocks.length; i += 1) {
					out(i);
				}

				extension_check_outros();
			}

			const paginationcontrols_changes = {};
			if (dirty & /*rowsPerPage*/ 1024) paginationcontrols_changes.instancesPerPage = /*rowsPerPage*/ ctx[10];
			if (dirty & /*groupKeys*/ 256) paginationcontrols_changes.size = /*groupKeys*/ ctx[8].length;

			if (!updating_page && dirty & /*page*/ 512) {
				updating_page = true;
				paginationcontrols_changes.page = /*page*/ ctx[9];
				extension_add_flush_callback(() => updating_page = false);
			}

			paginationcontrols.$set(paginationcontrols_changes);
		},
		i(local) {
			if (current) return;

			for (let i = 0; i < each_value.length; i += 1) {
				extension_transition_in(each_blocks[i]);
			}

			extension_transition_in(paginationcontrols.$$.fragment, local);
			current = true;
		},
		o(local) {
			each_blocks = each_blocks.filter(Boolean);

			for (let i = 0; i < each_blocks.length; i += 1) {
				extension_transition_out(each_blocks[i]);
			}

			extension_transition_out(paginationcontrols.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_each(each_blocks, detaching);
			if (detaching) extension_detach(t);
			extension_destroy_component(paginationcontrols, detaching);
		}
	};
}

const extension_NUMBER_SHOWN = 17;

function extension_DuplicatesList_svelte_instance($$self, $$props, $$invalidate) {
	let rowsPerPage;
	let duplicateRows;

	let $filteredTable,
		$$unsubscribe_filteredTable = extension_noop,
		$$subscribe_filteredTable = () => ($$unsubscribe_filteredTable(), $$unsubscribe_filteredTable = extension_subscribe(filteredTable, $$value => $$invalidate(13, $filteredTable = $$value)), filteredTable);

	let $canvasSpec,
		$$unsubscribe_canvasSpec = extension_noop,
		$$subscribe_canvasSpec = () => ($$unsubscribe_canvasSpec(), $$unsubscribe_canvasSpec = extension_subscribe(canvasSpec, $$value => $$invalidate(14, $canvasSpec = $$value)), canvasSpec);

	$$self.$$.on_destroy.push(() => $$unsubscribe_filteredTable());
	$$self.$$.on_destroy.push(() => $$unsubscribe_canvasSpec());
	let { selectedColumn } = $$props;
	let { filteredTable } = $$props;
	$$subscribe_filteredTable();
	let { canvasSpec } = $$props;
	$$subscribe_canvasSpec();
	let { groupColumns } = $$props;
	let { groupNames } = $$props;
	let { selected } = $$props;
	let { tooltip } = $$props;
	let { storybook = false } = $$props;
	let groupedDuplicates = {};
	let groupKeys = [];
	let page = 0;
	filteredTable.subscribe(() => $$invalidate(9, page = 0));
	groupColumns.subscribe(() => $$invalidate(9, page = 0));

	function paginationcontrols_page_binding(value) {
		page = value;
		$$invalidate(9, page);
	}

	$$self.$$set = $$props => {
		if ('selectedColumn' in $$props) $$invalidate(11, selectedColumn = $$props.selectedColumn);
		if ('filteredTable' in $$props) $$subscribe_filteredTable($$invalidate(0, filteredTable = $$props.filteredTable));
		if ('canvasSpec' in $$props) $$subscribe_canvasSpec($$invalidate(1, canvasSpec = $$props.canvasSpec));
		if ('groupColumns' in $$props) $$invalidate(2, groupColumns = $$props.groupColumns);
		if ('groupNames' in $$props) $$invalidate(3, groupNames = $$props.groupNames);
		if ('selected' in $$props) $$invalidate(4, selected = $$props.selected);
		if ('tooltip' in $$props) $$invalidate(5, tooltip = $$props.tooltip);
		if ('storybook' in $$props) $$invalidate(6, storybook = $$props.storybook);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*$canvasSpec*/ 16384) {
			$: $$invalidate(10, rowsPerPage = Math.ceil(Math.max($canvasSpec.instancesPerPage / extension_NUMBER_SHOWN, 5)));
		}

		if ($$self.$$.dirty & /*$filteredTable, selectedColumn*/ 10240) {
			$: $$invalidate(12, duplicateRows = $filteredTable.filter(`(d) => d["${selectedColumn}"] !== -1`).objects());
		}

		if ($$self.$$.dirty & /*duplicateRows, selectedColumn, groupedDuplicates, groupKeys*/ 6528) {
			$: {
				$$invalidate(7, groupedDuplicates = {});

				duplicateRows.forEach(row => {
					const group = row[selectedColumn];

					if (groupedDuplicates[group] === undefined) {
						$$invalidate(7, groupedDuplicates[group] = [], groupedDuplicates);
					}

					groupedDuplicates[group].push(row);
				});

				$$invalidate(8, groupKeys = Object.keys(groupedDuplicates));
				groupKeys.sort((a, b) => groupedDuplicates[b].length - groupedDuplicates[a].length);
			}
		}
	};

	return [
		filteredTable,
		canvasSpec,
		groupColumns,
		groupNames,
		selected,
		tooltip,
		storybook,
		groupedDuplicates,
		groupKeys,
		page,
		rowsPerPage,
		selectedColumn,
		duplicateRows,
		$filteredTable,
		$canvasSpec,
		paginationcontrols_page_binding
	];
}

class extension_DuplicatesList extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(this, options, extension_DuplicatesList_svelte_instance, extension_DuplicatesList_svelte_create_fragment, extension_safe_not_equal, {
			selectedColumn: 11,
			filteredTable: 0,
			canvasSpec: 1,
			groupColumns: 2,
			groupNames: 3,
			selected: 4,
			tooltip: 5,
			storybook: 6
		});
	}
}

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


function extension_Dropdown_svelte_get_each_context(ctx, list, i) {
	const child_ctx = ctx.slice();
	child_ctx[3] = list[i];
	return child_ctx;
}

// (20:2) {#each items as item}
function extension_Dropdown_svelte_create_each_block(ctx) {
	let option;
	let t0_value = /*item*/ ctx[3] + "";
	let t0;
	let t1;
	let option_value_value;

	return {
		c() {
			option = extension_internal_element("option");
			t0 = extension_internal_text(t0_value);
			t1 = extension_space();
			option.__value = option_value_value = /*item*/ ctx[3];
			option.value = option.__value;
		},
		m(target, anchor) {
			extension_insert(target, option, anchor);
			extension_append(option, t0);
			extension_append(option, t1);
		},
		p(ctx, dirty) {
			if (dirty & /*items*/ 2 && t0_value !== (t0_value = /*item*/ ctx[3] + "")) extension_set_data(t0, t0_value);

			if (dirty & /*items*/ 2 && option_value_value !== (option_value_value = /*item*/ ctx[3])) {
				option.__value = option_value_value;
				option.value = option.__value;
			}
		},
		d(detaching) {
			if (detaching) extension_detach(option);
		}
	};
}

function extension_Dropdown_svelte_create_fragment(ctx) {
	let select;
	let mounted;
	let dispose;
	let each_value = /*items*/ ctx[1];
	let each_blocks = [];

	for (let i = 0; i < each_value.length; i += 1) {
		each_blocks[i] = extension_Dropdown_svelte_create_each_block(extension_Dropdown_svelte_get_each_context(ctx, each_value, i));
	}

	return {
		c() {
			select = extension_internal_element("select");

			for (let i = 0; i < each_blocks.length; i += 1) {
				each_blocks[i].c();
			}

			extension_attr(select, "class", "rounded border border-midgrey");
			if (/*value*/ ctx[0] === void 0) extension_add_render_callback(() => /*select_change_handler*/ ctx[2].call(select));
		},
		m(target, anchor) {
			extension_insert(target, select, anchor);

			for (let i = 0; i < each_blocks.length; i += 1) {
				if (each_blocks[i]) {
					each_blocks[i].m(select, null);
				}
			}

			extension_select_option(select, /*value*/ ctx[0], true);

			if (!mounted) {
				dispose = extension_listen(select, "change", /*select_change_handler*/ ctx[2]);
				mounted = true;
			}
		},
		p(ctx, [dirty]) {
			if (dirty & /*items*/ 2) {
				each_value = /*items*/ ctx[1];
				let i;

				for (i = 0; i < each_value.length; i += 1) {
					const child_ctx = extension_Dropdown_svelte_get_each_context(ctx, each_value, i);

					if (each_blocks[i]) {
						each_blocks[i].p(child_ctx, dirty);
					} else {
						each_blocks[i] = extension_Dropdown_svelte_create_each_block(child_ctx);
						each_blocks[i].c();
						each_blocks[i].m(select, null);
					}
				}

				for (; i < each_blocks.length; i += 1) {
					each_blocks[i].d(1);
				}

				each_blocks.length = each_value.length;
			}

			if (dirty & /*value, items*/ 3) {
				extension_select_option(select, /*value*/ ctx[0]);
			}
		},
		i: extension_noop,
		o: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(select);
			extension_destroy_each(each_blocks, detaching);
			mounted = false;
			dispose();
		}
	};
}

function extension_Dropdown_svelte_instance($$self, $$props, $$invalidate) {
	let { items } = $$props;
	let { value } = $$props;

	function select_change_handler() {
		value = extension_select_value(this);
		$$invalidate(0, value);
		$$invalidate(1, items);
	}

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

	return [value, items, select_change_handler];
}

class extension_Dropdown extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_Dropdown_svelte_instance, extension_Dropdown_svelte_create_fragment, extension_safe_not_equal, { items: 1, value: 0 });
	}
}

/* harmony default export */ const extension_Dropdown_svelte = (extension_Dropdown);
// EXTERNAL MODULE: ../../node_modules/@fortawesome/free-solid-svg-icons/faQuestionCircle.js
var extension_faQuestionCircle = __webpack_require__(3430);
;// ../../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 extension_Tooltip_svelte_add_css(target) {
	extension_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 extension_Tooltip_svelte_create_fragment(ctx) {
	let div;
	let fa;
	let current;
	fa = new extension_fa_svelte({ props: { icon: extension_faQuestionCircle/* faQuestionCircle */.wR } });

	return {
		c() {
			div = extension_internal_element("div");
			extension_create_component(fa.$$.fragment);
			extension_attr(div, "class", "w-max svelte-49ae0e");
			extension_attr(div, "data-tooltip", /*text*/ ctx[0]);
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_mount_component(fa, div, null);
			current = true;
		},
		p(ctx, [dirty]) {
			if (!current || dirty & /*text*/ 1) {
				extension_attr(div, "data-tooltip", /*text*/ ctx[0]);
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(fa);
		}
	};
}

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

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

	return [text];
}

class extension_Tooltip extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_Tooltip_svelte_instance, extension_Tooltip_svelte_create_fragment, extension_safe_not_equal, { text: 0 }, extension_Tooltip_svelte_add_css);
	}
}

/* harmony default export */ const extension_Tooltip_svelte = (extension_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 extension_Heading_svelte_create_fragment(ctx) {
	let div1;
	let div0;
	let h2;
	let t0;
	let t1;
	let tooltip;
	let current;
	tooltip = new extension_Tooltip_svelte({ props: { text: /*description*/ ctx[1] } });

	return {
		c() {
			div1 = extension_internal_element("div");
			div0 = extension_internal_element("div");
			h2 = extension_internal_element("h2");
			t0 = extension_internal_text(/*heading*/ ctx[0]);
			t1 = extension_space();
			extension_create_component(tooltip.$$.fragment);
			extension_attr(h2, "class", "text-2xl font-bold leading-7 text-gray-900 pr-2");
			extension_attr(div0, "class", "flex items-center");
			extension_attr(div1, "class", "flex items-center justify-between pb-3 pr-4");
		},
		m(target, anchor) {
			extension_insert(target, div1, anchor);
			extension_append(div1, div0);
			extension_append(div0, h2);
			extension_append(h2, t0);
			extension_append(div0, t1);
			extension_mount_component(tooltip, div0, null);
			current = true;
		},
		p(ctx, [dirty]) {
			if (!current || dirty & /*heading*/ 1) extension_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;
			extension_transition_in(tooltip.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(tooltip.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div1);
			extension_destroy_component(tooltip);
		}
	};
}

let extension_hover = false;
let extension_offsetX = 0;

function extension_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 extension_Heading extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_Heading_svelte_instance, extension_Heading_svelte_create_fragment, extension_safe_not_equal, { heading: 0, description: 1 });
	}
}

/* harmony default export */ const extension_Heading_svelte = (extension_Heading);
// EXTERNAL MODULE: ../../node_modules/html2canvas/dist/html2canvas.js
var extension_html2canvas = __webpack_require__(8317);
var extension_html2canvas_default = /*#__PURE__*/__webpack_require__.n(extension_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 extension_exportView(container, name) {
    extension_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 extension_faImage = __webpack_require__(6705);
;// ../../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 extension_ComponentHeader_svelte_create_icon_slot(ctx) {
	let fa;
	let current;
	fa = new extension_fa_svelte({ props: { icon: extension_faImage/* faImage */.jb, slot: "icon" } });

	return {
		c() {
			extension_create_component(fa.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(fa, target, anchor);
			current = true;
		},
		p: extension_noop,
		i(local) {
			if (current) return;
			extension_transition_in(fa.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(fa.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(fa, detaching);
		}
	};
}

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

	return {
		c() {
			span = extension_internal_element("span");
			span.textContent = "Download";
			extension_attr(span, "slot", "text");
		},
		m(target, anchor) {
			extension_insert(target, span, anchor);
		},
		p: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(span);
		}
	};
}

function extension_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 extension_Heading_svelte({
			props: {
				heading: /*title*/ ctx[0],
				description: /*description*/ ctx[1]
			}
		});

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

	iconbutton = new extension_IconButton_svelte({
			props: {
				$$slots: {
					text: [extension_ComponentHeader_svelte_create_text_slot],
					icon: [extension_ComponentHeader_svelte_create_icon_slot]
				},
				$$scope: { ctx }
			}
		});

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

	return {
		c() {
			div3 = extension_internal_element("div");
			div1 = extension_internal_element("div");
			extension_create_component(heading.$$.fragment);
			t0 = extension_space();
			div0 = extension_internal_element("div");
			if (default_slot) default_slot.c();
			t1 = extension_space();
			div2 = extension_internal_element("div");
			extension_create_component(iconbutton.$$.fragment);
			extension_attr(div0, "class", "flex flex-wrap");
			extension_attr(div1, "class", "flex flex-wrap");
			extension_attr(div2, "class", "pb-3 pl-3");
			extension_attr(div3, "class", "flex items-top justify-between");
		},
		m(target, anchor) {
			extension_insert(target, div3, anchor);
			extension_append(div3, div1);
			extension_mount_component(heading, div1, null);
			extension_append(div1, t0);
			extension_append(div1, div0);

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

			extension_append(div3, t1);
			extension_append(div3, div2);
			extension_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)) {
					extension_update_slot_base(
						default_slot,
						default_slot_template,
						ctx,
						/*$$scope*/ ctx[5],
						!current
						? extension_get_all_dirty_from_scope(/*$$scope*/ ctx[5])
						: extension_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;
			extension_transition_in(heading.$$.fragment, local);
			extension_transition_in(default_slot, local);
			extension_transition_in(iconbutton.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(heading.$$.fragment, local);
			extension_transition_out(default_slot, local);
			extension_transition_out(iconbutton.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div3);
			extension_destroy_component(heading);
			if (default_slot) default_slot.d(detaching);
			extension_destroy_component(iconbutton);
		}
	};
}

function extension_ComponentHeader_svelte_instance($$self, $$props, $$invalidate) {
	let { $$slots: slots = {}, $$scope } = $$props;
	let { title } = $$props;
	let { description } = $$props;
	let { container } = $$props;
	const click_handler = () => extension_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 extension_ComponentHeader extends extension_SvelteComponent {
	constructor(options) {
		super();
		extension_init(this, options, extension_ComponentHeader_svelte_instance, extension_ComponentHeader_svelte_create_fragment, extension_safe_not_equal, { title: 0, description: 1, container: 2 });
	}
}

/* harmony default export */ const extension_ComponentHeader_svelte = (extension_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 extension_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 extension_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 extension_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';
    }
}

;// ./src/CanvasDuplicates.svelte
/* src/CanvasDuplicates.svelte generated by Svelte v3.59.2 */





function extension_CanvasDuplicates_svelte_create_if_block_2(ctx) {
	let div;
	let p;
	let t1;
	let dropdown;
	let updating_value;
	let current;

	function dropdown_value_binding(value) {
		/*dropdown_value_binding*/ ctx[15](value);
	}

	let dropdown_props = { items: /*layerNames*/ ctx[10] };

	if (/*selectedLayer*/ ctx[9] !== void 0) {
		dropdown_props.value = /*selectedLayer*/ ctx[9];
	}

	dropdown = new extension_Dropdown_svelte({ props: dropdown_props });
	extension_binding_callbacks.push(() => extension_bind(dropdown, 'value', dropdown_value_binding));

	return {
		c() {
			div = extension_internal_element("div");
			p = extension_internal_element("p");
			p.textContent = "Layer:";
			t1 = extension_space();
			extension_create_component(dropdown.$$.fragment);
			extension_attr(p, "class", "mr-2");
			extension_attr(div, "class", "mr-4 flex flex-row mb-2 items-center");
		},
		m(target, anchor) {
			extension_insert(target, div, anchor);
			extension_append(div, p);
			extension_append(div, t1);
			extension_mount_component(dropdown, div, null);
			current = true;
		},
		p(ctx, dirty) {
			const dropdown_changes = {};
			if (dirty & /*layerNames*/ 1024) dropdown_changes.items = /*layerNames*/ ctx[10];

			if (!updating_value && dirty & /*selectedLayer*/ 512) {
				updating_value = true;
				dropdown_changes.value = /*selectedLayer*/ ctx[9];
				extension_add_flush_callback(() => updating_value = false);
			}

			dropdown.$set(dropdown_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(dropdown.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(dropdown.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div);
			extension_destroy_component(dropdown);
		}
	};
}

// (43:2) <ComponentHeader     title={'Duplicates'}     description={widgetSpec.description}     {container}   >
function extension_create_default_slot(ctx) {
	let if_block_anchor;
	let current;
	let if_block = /*layerNames*/ ctx[10].length > 1 && extension_CanvasDuplicates_svelte_create_if_block_2(ctx);

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = extension_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			extension_insert(target, if_block_anchor, anchor);
			current = true;
		},
		p(ctx, dirty) {
			if (/*layerNames*/ ctx[10].length > 1) {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*layerNames*/ 1024) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_CanvasDuplicates_svelte_create_if_block_2(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(if_block_anchor.parentNode, if_block_anchor);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) extension_detach(if_block_anchor);
		}
	};
}

// (69:4) {:else}
function extension_CanvasDuplicates_svelte_create_else_block(ctx) {
	let p;

	return {
		c() {
			p = extension_internal_element("p");
			p.textContent = "No duplicate columns found. A duplicate column must start with\n        'duplicates_'";
		},
		m(target, anchor) {
			extension_insert(target, p, anchor);
		},
		p: extension_noop,
		i: extension_noop,
		o: extension_noop,
		d(detaching) {
			if (detaching) extension_detach(p);
		}
	};
}

// (56:4) {#if layerNames[0] !== undefined}
function extension_CanvasDuplicates_svelte_create_if_block(ctx) {
	let if_block_anchor;
	let current;
	let if_block = /*selectedColumn*/ ctx[12] !== '' && extension_CanvasDuplicates_svelte_create_if_block_1(ctx);

	return {
		c() {
			if (if_block) if_block.c();
			if_block_anchor = extension_empty();
		},
		m(target, anchor) {
			if (if_block) if_block.m(target, anchor);
			extension_insert(target, if_block_anchor, anchor);
			current = true;
		},
		p(ctx, dirty) {
			if (/*selectedColumn*/ ctx[12] !== '') {
				if (if_block) {
					if_block.p(ctx, dirty);

					if (dirty & /*selectedColumn*/ 4096) {
						extension_transition_in(if_block, 1);
					}
				} else {
					if_block = extension_CanvasDuplicates_svelte_create_if_block_1(ctx);
					if_block.c();
					extension_transition_in(if_block, 1);
					if_block.m(if_block_anchor.parentNode, if_block_anchor);
				}
			} else if (if_block) {
				extension_group_outros();

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

				extension_check_outros();
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (if_block) if_block.d(detaching);
			if (detaching) extension_detach(if_block_anchor);
		}
	};
}

// (57:6) {#if selectedColumn !== ''}
function extension_CanvasDuplicates_svelte_create_if_block_1(ctx) {
	let duplicateslist;
	let current;

	duplicateslist = new extension_DuplicatesList_svelte({
			props: {
				selectedColumn: /*selectedColumn*/ ctx[12],
				filteredTable: /*filteredTable*/ ctx[2],
				canvasSpec: /*canvasSpec*/ ctx[3],
				groupColumns: /*groupColumns*/ ctx[4],
				groupNames: /*groupNames*/ ctx[5],
				selected: /*selected*/ ctx[6],
				tooltip: /*tooltip*/ ctx[7],
				storybook: /*storybook*/ ctx[8]
			}
		});

	return {
		c() {
			extension_create_component(duplicateslist.$$.fragment);
		},
		m(target, anchor) {
			extension_mount_component(duplicateslist, target, anchor);
			current = true;
		},
		p(ctx, dirty) {
			const duplicateslist_changes = {};
			if (dirty & /*selectedColumn*/ 4096) duplicateslist_changes.selectedColumn = /*selectedColumn*/ ctx[12];
			if (dirty & /*filteredTable*/ 4) duplicateslist_changes.filteredTable = /*filteredTable*/ ctx[2];
			if (dirty & /*canvasSpec*/ 8) duplicateslist_changes.canvasSpec = /*canvasSpec*/ ctx[3];
			if (dirty & /*groupColumns*/ 16) duplicateslist_changes.groupColumns = /*groupColumns*/ ctx[4];
			if (dirty & /*groupNames*/ 32) duplicateslist_changes.groupNames = /*groupNames*/ ctx[5];
			if (dirty & /*selected*/ 64) duplicateslist_changes.selected = /*selected*/ ctx[6];
			if (dirty & /*tooltip*/ 128) duplicateslist_changes.tooltip = /*tooltip*/ ctx[7];
			if (dirty & /*storybook*/ 256) duplicateslist_changes.storybook = /*storybook*/ ctx[8];
			duplicateslist.$set(duplicateslist_changes);
		},
		i(local) {
			if (current) return;
			extension_transition_in(duplicateslist.$$.fragment, local);
			current = true;
		},
		o(local) {
			extension_transition_out(duplicateslist.$$.fragment, local);
			current = false;
		},
		d(detaching) {
			extension_destroy_component(duplicateslist, detaching);
		}
	};
}

function extension_CanvasDuplicates_svelte_create_fragment(ctx) {
	let div1;
	let componentheader;
	let t;
	let div0;
	let current_block_type_index;
	let if_block;
	let div1_class_value;
	let current;

	componentheader = new extension_ComponentHeader_svelte({
			props: {
				title: 'Duplicates',
				description: /*widgetSpec*/ ctx[0].description,
				container: /*container*/ ctx[11],
				$$slots: { default: [extension_create_default_slot] },
				$$scope: { ctx }
			}
		});

	const if_block_creators = [extension_CanvasDuplicates_svelte_create_if_block, extension_CanvasDuplicates_svelte_create_else_block];
	const if_blocks = [];

	function select_block_type(ctx, dirty) {
		if (/*layerNames*/ ctx[10][0] !== undefined) return 0;
		return 1;
	}

	current_block_type_index = select_block_type(ctx, -1);
	if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);

	return {
		c() {
			div1 = extension_internal_element("div");
			extension_create_component(componentheader.$$.fragment);
			t = extension_space();
			div0 = extension_internal_element("div");
			if_block.c();
			extension_attr(div0, "class", "flex flex-col min-h-0 flex-1");

			extension_attr(div1, "class", div1_class_value = "flex flex-col overflow-hidden p-2 " + (/*fullSize*/ ctx[1]
			? 'h-full'
			: extension_mapHeight(/*widgetSpec*/ ctx[0].height)));
		},
		m(target, anchor) {
			extension_insert(target, div1, anchor);
			extension_mount_component(componentheader, div1, null);
			extension_append(div1, t);
			extension_append(div1, div0);
			if_blocks[current_block_type_index].m(div0, null);
			/*div0_binding*/ ctx[16](div0);
			current = true;
		},
		p(ctx, [dirty]) {
			const componentheader_changes = {};
			if (dirty & /*widgetSpec*/ 1) componentheader_changes.description = /*widgetSpec*/ ctx[0].description;
			if (dirty & /*container*/ 2048) componentheader_changes.container = /*container*/ ctx[11];

			if (dirty & /*$$scope, layerNames, selectedLayer*/ 132608) {
				componentheader_changes.$$scope = { dirty, ctx };
			}

			componentheader.$set(componentheader_changes);
			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 {
				extension_group_outros();

				extension_transition_out(if_blocks[previous_block_index], 1, 1, () => {
					if_blocks[previous_block_index] = null;
				});

				extension_check_outros();
				if_block = if_blocks[current_block_type_index];

				if (!if_block) {
					if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
					if_block.c();
				} else {
					if_block.p(ctx, dirty);
				}

				extension_transition_in(if_block, 1);
				if_block.m(div0, null);
			}

			if (!current || dirty & /*fullSize, widgetSpec*/ 3 && div1_class_value !== (div1_class_value = "flex flex-col overflow-hidden p-2 " + (/*fullSize*/ ctx[1]
			? 'h-full'
			: extension_mapHeight(/*widgetSpec*/ ctx[0].height)))) {
				extension_attr(div1, "class", div1_class_value);
			}
		},
		i(local) {
			if (current) return;
			extension_transition_in(componentheader.$$.fragment, local);
			extension_transition_in(if_block);
			current = true;
		},
		o(local) {
			extension_transition_out(componentheader.$$.fragment, local);
			extension_transition_out(if_block);
			current = false;
		},
		d(detaching) {
			if (detaching) extension_detach(div1);
			extension_destroy_component(componentheader);
			if_blocks[current_block_type_index].d();
			/*div0_binding*/ ctx[16](null);
		}
	};
}

function extension_CanvasDuplicates_svelte_instance($$self, $$props, $$invalidate) {
	let columnNames;
	let layerNames;
	let selectedColumn;

	let $filteredTable,
		$$unsubscribe_filteredTable = extension_noop,
		$$subscribe_filteredTable = () => ($$unsubscribe_filteredTable(), $$unsubscribe_filteredTable = extension_subscribe(filteredTable, $$value => $$invalidate(14, $filteredTable = $$value)), filteredTable);

	$$self.$$.on_destroy.push(() => $$unsubscribe_filteredTable());
	let { widgetSpec } = $$props;
	let { fullSize = false } = $$props;
	let { filteredTable } = $$props;
	$$subscribe_filteredTable();
	let { canvasSpec } = $$props;
	let { groupColumns } = $$props;
	let { groupNames } = $$props;
	let { selected } = $$props;
	let { tooltip } = $$props;
	let { storybook = false } = $$props;
	let selectedLayer;
	let container;

	function dropdown_value_binding(value) {
		selectedLayer = value;
		((($$invalidate(9, selectedLayer), $$invalidate(10, layerNames)), $$invalidate(13, columnNames)), $$invalidate(14, $filteredTable));
	}

	function div0_binding($$value) {
		extension_binding_callbacks[$$value ? 'unshift' : 'push'](() => {
			container = $$value;
			$$invalidate(11, container);
		});
	}

	$$self.$$set = $$props => {
		if ('widgetSpec' in $$props) $$invalidate(0, widgetSpec = $$props.widgetSpec);
		if ('fullSize' in $$props) $$invalidate(1, fullSize = $$props.fullSize);
		if ('filteredTable' in $$props) $$subscribe_filteredTable($$invalidate(2, filteredTable = $$props.filteredTable));
		if ('canvasSpec' in $$props) $$invalidate(3, canvasSpec = $$props.canvasSpec);
		if ('groupColumns' in $$props) $$invalidate(4, groupColumns = $$props.groupColumns);
		if ('groupNames' in $$props) $$invalidate(5, groupNames = $$props.groupNames);
		if ('selected' in $$props) $$invalidate(6, selected = $$props.selected);
		if ('tooltip' in $$props) $$invalidate(7, tooltip = $$props.tooltip);
		if ('storybook' in $$props) $$invalidate(8, storybook = $$props.storybook);
	};

	$$self.$$.update = () => {
		if ($$self.$$.dirty & /*$filteredTable*/ 16384) {
			$: $$invalidate(13, columnNames = $filteredTable.columnNames(d => d.startsWith('duplicates_')));
		}

		if ($$self.$$.dirty & /*columnNames*/ 8192) {
			$: $$invalidate(10, layerNames = columnNames.map(name => name.substring(11)));
		}

		if ($$self.$$.dirty & /*selectedLayer, layerNames*/ 1536) {
			$: if (selectedLayer === undefined) $$invalidate(9, selectedLayer = layerNames[0] !== undefined ? layerNames[0] : '');
		}

		if ($$self.$$.dirty & /*selectedLayer, columnNames*/ 8704) {
			$: $$invalidate(12, selectedColumn = selectedLayer === undefined
			? ''
			: columnNames.find(name => name.includes(selectedLayer)));
		}
	};

	return [
		widgetSpec,
		fullSize,
		filteredTable,
		canvasSpec,
		groupColumns,
		groupNames,
		selected,
		tooltip,
		storybook,
		selectedLayer,
		layerNames,
		container,
		selectedColumn,
		columnNames,
		$filteredTable,
		dropdown_value_binding,
		div0_binding
	];
}

class extension_CanvasDuplicates extends extension_SvelteComponent {
	constructor(options) {
		super();

		extension_init(this, options, extension_CanvasDuplicates_svelte_instance, extension_CanvasDuplicates_svelte_create_fragment, extension_safe_not_equal, {
			widgetSpec: 0,
			fullSize: 1,
			filteredTable: 2,
			canvasSpec: 3,
			groupColumns: 4,
			groupNames: 5,
			selected: 6,
			tooltip: 7,
			storybook: 8
		});
	}
}

/* harmony default export */ const extension_CanvasDuplicates_svelte = (extension_CanvasDuplicates);
;// ./src/widget.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.
 */




class extension_CanvasDuplicatesModel extends extension_base_.DOMWidgetModel {
    defaults() {
        return Object.assign(Object.assign({}, super.defaults()), { _model_name: extension_CanvasDuplicatesModel.model_name, _model_module: extension_CanvasDuplicatesModel.model_module, _model_module_version: extension_CanvasDuplicatesModel.model_module_version, _view_name: extension_CanvasDuplicatesModel.view_name, _view_module: extension_CanvasDuplicatesModel.view_module, _view_module_version: extension_CanvasDuplicatesModel.view_module_version });
    }
}
extension_CanvasDuplicatesModel.serializers = extension_serializers;
extension_CanvasDuplicatesModel.model_name = 'CanvasDuplicatesModel';
extension_CanvasDuplicatesModel.model_module = extension_MODULE_NAME;
extension_CanvasDuplicatesModel.model_module_version = extension_MODULE_VERSION;
extension_CanvasDuplicatesModel.view_name = 'CanvasDuplicatesView'; // Set to null if no view
extension_CanvasDuplicatesModel.view_module = extension_MODULE_NAME; // Set to null if no view
extension_CanvasDuplicatesModel.view_module_version = extension_MODULE_VERSION;
class extension_CanvasDuplicatesView extends extension_base_.DOMWidgetView {
    render() {
        new extension_JupyterWidget_svelte({
            target: this.el,
            props: {
                model: this.model,
                widget: extension_CanvasDuplicates_svelte,
            },
        });
    }
}

;// ./src/index.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.
 */



;// ./src/extension.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.
 */
// Entry point for the notebook bundle containing custom model definitions.
//
// Setup notebook base URL
//
// Some static assets may be required by the custom widget javascript. The base
// url for the notebook is not known at build time and is therefore computed
// dynamically.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
window.__webpack_public_path__ =
    document.querySelector('body').getAttribute('data-base-url') +
        'nbextensions/canvas_duplicates';


})();

/******/ 	return __webpack_exports__;
/******/ })()
;
});;