From 57c52339031afd785c23dba89c2ac539a4932445 Mon Sep 17 00:00:00 2001 From: Sebastian Ranoszek Date: Thu, 15 May 2025 22:01:15 +0200 Subject: [PATCH] vault backup: 2025-05-15 22:01:15 --- .obsidian/community-plugins.json | 20 + .obsidian/plugins/auto-note-mover/main.js | 2182 + .../plugins/auto-note-mover/manifest.json | 10 + .obsidian/plugins/breadcrumbs/data.json | 278 + .obsidian/plugins/breadcrumbs/main.js | 41387 ++++++++++++++++ .obsidian/plugins/breadcrumbs/manifest.json | 1 + .obsidian/plugins/breadcrumbs/styles.css | 1 + .obsidian/plugins/calendar/data.json | 10 + .obsidian/plugins/calendar/main.js | 4459 ++ .obsidian/plugins/calendar/manifest.json | 10 + .obsidian/plugins/dataview/main.js | 20876 ++++++++ .obsidian/plugins/dataview/manifest.json | 11 + .obsidian/plugins/dataview/styles.css | 141 + .../obsidian-excalidraw-plugin/data.json | 805 + .../obsidian-excalidraw-plugin/main.js | 10 + .../obsidian-excalidraw-plugin/manifest.json | 12 + .../obsidian-excalidraw-plugin/styles.css | 1 + .obsidian/plugins/obsidian-git/main.js | 418 + .obsidian/plugins/obsidian-git/manifest.json | 10 + .obsidian/plugins/obsidian-git/styles.css | 605 + .obsidian/plugins/obsidian-kanban/main.js | 153 + .../plugins/obsidian-kanban/manifest.json | 11 + .obsidian/plugins/obsidian-kanban/styles.css | 1 + .obsidian/plugins/obsidian-linter/data.json | 292 + .obsidian/plugins/obsidian-linter/main.js | 470 + .../plugins/obsidian-linter/manifest.json | 11 + .obsidian/plugins/obsidian-linter/styles.css | 1 + .../main.js | 5132 ++ .../manifest.json | 10 + .../styles.css | 62 + .obsidian/plugins/obsidian-outliner/main.js | 3418 ++ .../plugins/obsidian-outliner/manifest.json | 10 + .../plugins/obsidian-outliner/styles.css | 105 + .../obsidian-spaced-repetition/main.js | 29147 +++++++++++ .../obsidian-spaced-repetition/manifest.json | 12 + .../obsidian-spaced-repetition/styles.css | 997 + .../plugins/obsidian-style-settings/main.js | 165 + .../obsidian-style-settings/manifest.json | 10 + .../obsidian-style-settings/styles.css | 243 + .../plugins/obsidian-tasks-plugin/main.js | 446 + .../obsidian-tasks-plugin/manifest.json | 12 + .../plugins/obsidian-tasks-plugin/styles.css | 1 + .obsidian/plugins/obsidian42-brat/data.json | 21 + .obsidian/plugins/obsidian42-brat/main.js | 39 + .../plugins/obsidian42-brat/manifest.json | 14 + .obsidian/plugins/obsidian42-brat/styles.css | 26 + .../plugins/table-editor-obsidian/data.json | 6 + .../plugins/table-editor-obsidian/main.js | 236 + .../table-editor-obsidian/manifest.json | 17 + .../plugins/table-editor-obsidian/styles.css | 78 + .obsidian/plugins/tag-wrangler/main.js | 165 + .obsidian/plugins/tag-wrangler/manifest.json | 11 + .obsidian/plugins/templater-obsidian/main.js | 29 + .../plugins/templater-obsidian/manifest.json | 11 + .../plugins/templater-obsidian/styles.css | 220 + .obsidian/plugins/url-into-selection/main.js | 756 + .../plugins/url-into-selection/manifest.json | 8 + .obsidian/types.json | 70 + .obsidian/workspace.json | 53 +- Welcome.md | 5 - 60 files changed, 113701 insertions(+), 20 deletions(-) create mode 100644 .obsidian/community-plugins.json create mode 100644 .obsidian/plugins/auto-note-mover/main.js create mode 100644 .obsidian/plugins/auto-note-mover/manifest.json create mode 100644 .obsidian/plugins/breadcrumbs/data.json create mode 100644 .obsidian/plugins/breadcrumbs/main.js create mode 100644 .obsidian/plugins/breadcrumbs/manifest.json create mode 100644 .obsidian/plugins/breadcrumbs/styles.css create mode 100644 .obsidian/plugins/calendar/data.json create mode 100644 .obsidian/plugins/calendar/main.js create mode 100644 .obsidian/plugins/calendar/manifest.json create mode 100644 .obsidian/plugins/dataview/main.js create mode 100644 .obsidian/plugins/dataview/manifest.json create mode 100644 .obsidian/plugins/dataview/styles.css create mode 100644 .obsidian/plugins/obsidian-excalidraw-plugin/data.json create mode 100644 .obsidian/plugins/obsidian-excalidraw-plugin/main.js create mode 100644 .obsidian/plugins/obsidian-excalidraw-plugin/manifest.json create mode 100644 .obsidian/plugins/obsidian-excalidraw-plugin/styles.css create mode 100644 .obsidian/plugins/obsidian-git/main.js create mode 100644 .obsidian/plugins/obsidian-git/manifest.json create mode 100644 .obsidian/plugins/obsidian-git/styles.css create mode 100644 .obsidian/plugins/obsidian-kanban/main.js create mode 100644 .obsidian/plugins/obsidian-kanban/manifest.json create mode 100644 .obsidian/plugins/obsidian-kanban/styles.css create mode 100644 .obsidian/plugins/obsidian-linter/data.json create mode 100644 .obsidian/plugins/obsidian-linter/main.js create mode 100644 .obsidian/plugins/obsidian-linter/manifest.json create mode 100644 .obsidian/plugins/obsidian-linter/styles.css create mode 100644 .obsidian/plugins/obsidian-markdown-formatting-assistant-plugin/main.js create mode 100644 .obsidian/plugins/obsidian-markdown-formatting-assistant-plugin/manifest.json create mode 100644 .obsidian/plugins/obsidian-markdown-formatting-assistant-plugin/styles.css create mode 100644 .obsidian/plugins/obsidian-outliner/main.js create mode 100644 .obsidian/plugins/obsidian-outliner/manifest.json create mode 100644 .obsidian/plugins/obsidian-outliner/styles.css create mode 100644 .obsidian/plugins/obsidian-spaced-repetition/main.js create mode 100644 .obsidian/plugins/obsidian-spaced-repetition/manifest.json create mode 100644 .obsidian/plugins/obsidian-spaced-repetition/styles.css create mode 100644 .obsidian/plugins/obsidian-style-settings/main.js create mode 100644 .obsidian/plugins/obsidian-style-settings/manifest.json create mode 100644 .obsidian/plugins/obsidian-style-settings/styles.css create mode 100644 .obsidian/plugins/obsidian-tasks-plugin/main.js create mode 100644 .obsidian/plugins/obsidian-tasks-plugin/manifest.json create mode 100644 .obsidian/plugins/obsidian-tasks-plugin/styles.css create mode 100644 .obsidian/plugins/obsidian42-brat/data.json create mode 100644 .obsidian/plugins/obsidian42-brat/main.js create mode 100644 .obsidian/plugins/obsidian42-brat/manifest.json create mode 100644 .obsidian/plugins/obsidian42-brat/styles.css create mode 100644 .obsidian/plugins/table-editor-obsidian/data.json create mode 100644 .obsidian/plugins/table-editor-obsidian/main.js create mode 100644 .obsidian/plugins/table-editor-obsidian/manifest.json create mode 100644 .obsidian/plugins/table-editor-obsidian/styles.css create mode 100644 .obsidian/plugins/tag-wrangler/main.js create mode 100644 .obsidian/plugins/tag-wrangler/manifest.json create mode 100644 .obsidian/plugins/templater-obsidian/main.js create mode 100644 .obsidian/plugins/templater-obsidian/manifest.json create mode 100644 .obsidian/plugins/templater-obsidian/styles.css create mode 100644 .obsidian/plugins/url-into-selection/main.js create mode 100644 .obsidian/plugins/url-into-selection/manifest.json create mode 100644 .obsidian/types.json delete mode 100644 Welcome.md diff --git a/.obsidian/community-plugins.json b/.obsidian/community-plugins.json new file mode 100644 index 0000000..4cb1c38 --- /dev/null +++ b/.obsidian/community-plugins.json @@ -0,0 +1,20 @@ +[ + "obsidian-excalidraw-plugin", + "dataview", + "templater-obsidian", + "obsidian-tasks-plugin", + "table-editor-obsidian", + "calendar", + "obsidian-kanban", + "obsidian-git", + "obsidian-style-settings", + "tag-wrangler", + "obsidian-linter", + "url-into-selection", + "obsidian-markdown-formatting-assistant-plugin", + "obsidian-spaced-repetition", + "auto-note-mover", + "obsidian42-brat", + "obsidian-outliner", + "breadcrumbs" +] \ No newline at end of file diff --git a/.obsidian/plugins/auto-note-mover/main.js b/.obsidian/plugins/auto-note-mover/main.js new file mode 100644 index 0000000..95de755 --- /dev/null +++ b/.obsidian/plugins/auto-note-mover/main.js @@ -0,0 +1,2182 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); +var __export = (target, all) => { + __markAsModule(target); + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __reExport = (target, module2, desc) => { + if (module2 && typeof module2 === "object" || typeof module2 === "function") { + for (let key of __getOwnPropNames(module2)) + if (!__hasOwnProp.call(target, key) && key !== "default") + __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); + } + return target; +}; +var __toModule = (module2) => { + return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2); +}; +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +// main.ts +__export(exports, { + default: () => AutoNoteMover +}); +var import_obsidian6 = __toModule(require("obsidian")); + +// settings/settings.ts +var import_obsidian5 = __toModule(require("obsidian")); + +// suggests/file-suggest.ts +var import_obsidian2 = __toModule(require("obsidian")); + +// suggests/suggest.ts +var import_obsidian = __toModule(require("obsidian")); + +// node_modules/@popperjs/core/lib/enums.js +var top = "top"; +var bottom = "bottom"; +var right = "right"; +var left = "left"; +var auto = "auto"; +var basePlacements = [top, bottom, right, left]; +var start = "start"; +var end = "end"; +var clippingParents = "clippingParents"; +var viewport = "viewport"; +var popper = "popper"; +var reference = "reference"; +var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) { + return acc.concat([placement + "-" + start, placement + "-" + end]); +}, []); +var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) { + return acc.concat([placement, placement + "-" + start, placement + "-" + end]); +}, []); +var beforeRead = "beforeRead"; +var read = "read"; +var afterRead = "afterRead"; +var beforeMain = "beforeMain"; +var main = "main"; +var afterMain = "afterMain"; +var beforeWrite = "beforeWrite"; +var write = "write"; +var afterWrite = "afterWrite"; +var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; + +// node_modules/@popperjs/core/lib/dom-utils/getNodeName.js +function getNodeName(element) { + return element ? (element.nodeName || "").toLowerCase() : null; +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindow.js +function getWindow(node) { + if (node == null) { + return window; + } + if (node.toString() !== "[object Window]") { + var ownerDocument = node.ownerDocument; + return ownerDocument ? ownerDocument.defaultView || window : window; + } + return node; +} + +// node_modules/@popperjs/core/lib/dom-utils/instanceOf.js +function isElement(node) { + var OwnElement = getWindow(node).Element; + return node instanceof OwnElement || node instanceof Element; +} +function isHTMLElement(node) { + var OwnElement = getWindow(node).HTMLElement; + return node instanceof OwnElement || node instanceof HTMLElement; +} +function isShadowRoot(node) { + if (typeof ShadowRoot === "undefined") { + return false; + } + var OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; +} + +// node_modules/@popperjs/core/lib/modifiers/applyStyles.js +function applyStyles(_ref) { + var state = _ref.state; + Object.keys(state.elements).forEach(function(name) { + var style = state.styles[name] || {}; + var attributes = state.attributes[name] || {}; + var element = state.elements[name]; + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } + Object.assign(element.style, style); + Object.keys(attributes).forEach(function(name2) { + var value = attributes[name2]; + if (value === false) { + element.removeAttribute(name2); + } else { + element.setAttribute(name2, value === true ? "" : value); + } + }); + }); +} +function effect(_ref2) { + var state = _ref2.state; + var initialStyles = { + popper: { + position: state.options.strategy, + left: "0", + top: "0", + margin: "0" + }, + arrow: { + position: "absolute" + }, + reference: {} + }; + Object.assign(state.elements.popper.style, initialStyles.popper); + state.styles = initialStyles; + if (state.elements.arrow) { + Object.assign(state.elements.arrow.style, initialStyles.arrow); + } + return function() { + Object.keys(state.elements).forEach(function(name) { + var element = state.elements[name]; + var attributes = state.attributes[name] || {}; + var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); + var style = styleProperties.reduce(function(style2, property) { + style2[property] = ""; + return style2; + }, {}); + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } + Object.assign(element.style, style); + Object.keys(attributes).forEach(function(attribute) { + element.removeAttribute(attribute); + }); + }); + }; +} +var applyStyles_default = { + name: "applyStyles", + enabled: true, + phase: "write", + fn: applyStyles, + effect, + requires: ["computeStyles"] +}; + +// node_modules/@popperjs/core/lib/utils/getBasePlacement.js +function getBasePlacement(placement) { + return placement.split("-")[0]; +} + +// node_modules/@popperjs/core/lib/utils/math.js +var max = Math.max; +var min = Math.min; +var round = Math.round; + +// node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js +function getBoundingClientRect(element, includeScale) { + if (includeScale === void 0) { + includeScale = false; + } + var rect = element.getBoundingClientRect(); + var scaleX = 1; + var scaleY = 1; + if (isHTMLElement(element) && includeScale) { + var offsetHeight = element.offsetHeight; + var offsetWidth = element.offsetWidth; + if (offsetWidth > 0) { + scaleX = round(rect.width) / offsetWidth || 1; + } + if (offsetHeight > 0) { + scaleY = round(rect.height) / offsetHeight || 1; + } + } + return { + width: rect.width / scaleX, + height: rect.height / scaleY, + top: rect.top / scaleY, + right: rect.right / scaleX, + bottom: rect.bottom / scaleY, + left: rect.left / scaleX, + x: rect.left / scaleX, + y: rect.top / scaleY + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js +function getLayoutRect(element) { + var clientRect = getBoundingClientRect(element); + var width = element.offsetWidth; + var height = element.offsetHeight; + if (Math.abs(clientRect.width - width) <= 1) { + width = clientRect.width; + } + if (Math.abs(clientRect.height - height) <= 1) { + height = clientRect.height; + } + return { + x: element.offsetLeft, + y: element.offsetTop, + width, + height + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/contains.js +function contains(parent, child) { + var rootNode = child.getRootNode && child.getRootNode(); + if (parent.contains(child)) { + return true; + } else if (rootNode && isShadowRoot(rootNode)) { + var next = child; + do { + if (next && parent.isSameNode(next)) { + return true; + } + next = next.parentNode || next.host; + } while (next); + } + return false; +} + +// node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js +function getComputedStyle(element) { + return getWindow(element).getComputedStyle(element); +} + +// node_modules/@popperjs/core/lib/dom-utils/isTableElement.js +function isTableElement(element) { + return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0; +} + +// node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js +function getDocumentElement(element) { + return ((isElement(element) ? element.ownerDocument : element.document) || window.document).documentElement; +} + +// node_modules/@popperjs/core/lib/dom-utils/getParentNode.js +function getParentNode(element) { + if (getNodeName(element) === "html") { + return element; + } + return element.assignedSlot || element.parentNode || (isShadowRoot(element) ? element.host : null) || getDocumentElement(element); +} + +// node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js +function getTrueOffsetParent(element) { + if (!isHTMLElement(element) || getComputedStyle(element).position === "fixed") { + return null; + } + return element.offsetParent; +} +function getContainingBlock(element) { + var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") !== -1; + var isIE = navigator.userAgent.indexOf("Trident") !== -1; + if (isIE && isHTMLElement(element)) { + var elementCss = getComputedStyle(element); + if (elementCss.position === "fixed") { + return null; + } + } + var currentNode = getParentNode(element); + if (isShadowRoot(currentNode)) { + currentNode = currentNode.host; + } + while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) { + var css = getComputedStyle(currentNode); + if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") { + return currentNode; + } else { + currentNode = currentNode.parentNode; + } + } + return null; +} +function getOffsetParent(element) { + var window2 = getWindow(element); + var offsetParent = getTrueOffsetParent(element); + while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") { + offsetParent = getTrueOffsetParent(offsetParent); + } + if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) { + return window2; + } + return offsetParent || getContainingBlock(element) || window2; +} + +// node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js +function getMainAxisFromPlacement(placement) { + return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y"; +} + +// node_modules/@popperjs/core/lib/utils/within.js +function within(min2, value, max2) { + return max(min2, min(value, max2)); +} +function withinMaxClamp(min2, value, max2) { + var v = within(min2, value, max2); + return v > max2 ? max2 : v; +} + +// node_modules/@popperjs/core/lib/utils/getFreshSideObject.js +function getFreshSideObject() { + return { + top: 0, + right: 0, + bottom: 0, + left: 0 + }; +} + +// node_modules/@popperjs/core/lib/utils/mergePaddingObject.js +function mergePaddingObject(paddingObject) { + return Object.assign({}, getFreshSideObject(), paddingObject); +} + +// node_modules/@popperjs/core/lib/utils/expandToHashMap.js +function expandToHashMap(value, keys) { + return keys.reduce(function(hashMap, key) { + hashMap[key] = value; + return hashMap; + }, {}); +} + +// node_modules/@popperjs/core/lib/modifiers/arrow.js +var toPaddingObject = function toPaddingObject2(padding, state) { + padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, { + placement: state.placement + })) : padding; + return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); +}; +function arrow(_ref) { + var _state$modifiersData$; + var state = _ref.state, name = _ref.name, options = _ref.options; + var arrowElement = state.elements.arrow; + var popperOffsets2 = state.modifiersData.popperOffsets; + var basePlacement = getBasePlacement(state.placement); + var axis = getMainAxisFromPlacement(basePlacement); + var isVertical = [left, right].indexOf(basePlacement) >= 0; + var len = isVertical ? "height" : "width"; + if (!arrowElement || !popperOffsets2) { + return; + } + var paddingObject = toPaddingObject(options.padding, state); + var arrowRect = getLayoutRect(arrowElement); + var minProp = axis === "y" ? top : left; + var maxProp = axis === "y" ? bottom : right; + var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len]; + var startDiff = popperOffsets2[axis] - state.rects.reference[axis]; + var arrowOffsetParent = getOffsetParent(arrowElement); + var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; + var centerToReference = endDiff / 2 - startDiff / 2; + var min2 = paddingObject[minProp]; + var max2 = clientSize - arrowRect[len] - paddingObject[maxProp]; + var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; + var offset2 = within(min2, center, max2); + var axisProp = axis; + state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$); +} +function effect2(_ref2) { + var state = _ref2.state, options = _ref2.options; + var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element; + if (arrowElement == null) { + return; + } + if (typeof arrowElement === "string") { + arrowElement = state.elements.popper.querySelector(arrowElement); + if (!arrowElement) { + return; + } + } + if (true) { + if (!isHTMLElement(arrowElement)) { + console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', "To use an SVG arrow, wrap it in an HTMLElement that will be used as", "the arrow."].join(" ")); + } + } + if (!contains(state.elements.popper, arrowElement)) { + if (true) { + console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', "element."].join(" ")); + } + return; + } + state.elements.arrow = arrowElement; +} +var arrow_default = { + name: "arrow", + enabled: true, + phase: "main", + fn: arrow, + effect: effect2, + requires: ["popperOffsets"], + requiresIfExists: ["preventOverflow"] +}; + +// node_modules/@popperjs/core/lib/utils/getVariation.js +function getVariation(placement) { + return placement.split("-")[1]; +} + +// node_modules/@popperjs/core/lib/modifiers/computeStyles.js +var unsetSides = { + top: "auto", + right: "auto", + bottom: "auto", + left: "auto" +}; +function roundOffsetsByDPR(_ref) { + var x = _ref.x, y = _ref.y; + var win = window; + var dpr = win.devicePixelRatio || 1; + return { + x: round(x * dpr) / dpr || 0, + y: round(y * dpr) / dpr || 0 + }; +} +function mapToStyles(_ref2) { + var _Object$assign2; + var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed; + var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y; + var _ref3 = typeof roundOffsets === "function" ? roundOffsets({ + x, + y + }) : { + x, + y + }; + x = _ref3.x; + y = _ref3.y; + var hasX = offsets.hasOwnProperty("x"); + var hasY = offsets.hasOwnProperty("y"); + var sideX = left; + var sideY = top; + var win = window; + if (adaptive) { + var offsetParent = getOffsetParent(popper2); + var heightProp = "clientHeight"; + var widthProp = "clientWidth"; + if (offsetParent === getWindow(popper2)) { + offsetParent = getDocumentElement(popper2); + if (getComputedStyle(offsetParent).position !== "static" && position === "absolute") { + heightProp = "scrollHeight"; + widthProp = "scrollWidth"; + } + } + offsetParent = offsetParent; + if (placement === top || (placement === left || placement === right) && variation === end) { + sideY = bottom; + var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : offsetParent[heightProp]; + y -= offsetY - popperRect.height; + y *= gpuAcceleration ? 1 : -1; + } + if (placement === left || (placement === top || placement === bottom) && variation === end) { + sideX = right; + var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : offsetParent[widthProp]; + x -= offsetX - popperRect.width; + x *= gpuAcceleration ? 1 : -1; + } + } + var commonStyles = Object.assign({ + position + }, adaptive && unsetSides); + var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ + x, + y + }) : { + x, + y + }; + x = _ref4.x; + y = _ref4.y; + if (gpuAcceleration) { + var _Object$assign; + return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); + } + return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2)); +} +function computeStyles(_ref5) { + var state = _ref5.state, options = _ref5.options; + var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; + if (true) { + var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || ""; + if (adaptive && ["transform", "top", "right", "bottom", "left"].some(function(property) { + return transitionProperty.indexOf(property) >= 0; + })) { + console.warn(["Popper: Detected CSS transitions on at least one of the following", 'CSS properties: "transform", "top", "right", "bottom", "left".', "\n\n", 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', "for smooth transitions, or remove these properties from the CSS", "transition declaration on the popper element if only transitioning", "opacity or background-color for example.", "\n\n", "We recommend using the popper element as a wrapper around an inner", "element that can have any CSS property transitioned for animations."].join(" ")); + } + } + var commonStyles = { + placement: getBasePlacement(state.placement), + variation: getVariation(state.placement), + popper: state.elements.popper, + popperRect: state.rects.popper, + gpuAcceleration, + isFixed: state.options.strategy === "fixed" + }; + if (state.modifiersData.popperOffsets != null) { + state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.popperOffsets, + position: state.options.strategy, + adaptive, + roundOffsets + }))); + } + if (state.modifiersData.arrow != null) { + state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.arrow, + position: "absolute", + adaptive: false, + roundOffsets + }))); + } + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-placement": state.placement + }); +} +var computeStyles_default = { + name: "computeStyles", + enabled: true, + phase: "beforeWrite", + fn: computeStyles, + data: {} +}; + +// node_modules/@popperjs/core/lib/modifiers/eventListeners.js +var passive = { + passive: true +}; +function effect3(_ref) { + var state = _ref.state, instance = _ref.instance, options = _ref.options; + var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize; + var window2 = getWindow(state.elements.popper); + var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.addEventListener("scroll", instance.update, passive); + }); + } + if (resize) { + window2.addEventListener("resize", instance.update, passive); + } + return function() { + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.removeEventListener("scroll", instance.update, passive); + }); + } + if (resize) { + window2.removeEventListener("resize", instance.update, passive); + } + }; +} +var eventListeners_default = { + name: "eventListeners", + enabled: true, + phase: "write", + fn: function fn() { + }, + effect: effect3, + data: {} +}; + +// node_modules/@popperjs/core/lib/utils/getOppositePlacement.js +var hash = { + left: "right", + right: "left", + bottom: "top", + top: "bottom" +}; +function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, function(matched) { + return hash[matched]; + }); +} + +// node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js +var hash2 = { + start: "end", + end: "start" +}; +function getOppositeVariationPlacement(placement) { + return placement.replace(/start|end/g, function(matched) { + return hash2[matched]; + }); +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js +function getWindowScroll(node) { + var win = getWindow(node); + var scrollLeft = win.pageXOffset; + var scrollTop = win.pageYOffset; + return { + scrollLeft, + scrollTop + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js +function getWindowScrollBarX(element) { + return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; +} + +// node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js +function getViewportRect(element) { + var win = getWindow(element); + var html = getDocumentElement(element); + var visualViewport = win.visualViewport; + var width = html.clientWidth; + var height = html.clientHeight; + var x = 0; + var y = 0; + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + return { + width, + height, + x: x + getWindowScrollBarX(element), + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js +function getDocumentRect(element) { + var _element$ownerDocumen; + var html = getDocumentElement(element); + var winScroll = getWindowScroll(element); + var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; + var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); + var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); + var x = -winScroll.scrollLeft + getWindowScrollBarX(element); + var y = -winScroll.scrollTop; + if (getComputedStyle(body || html).direction === "rtl") { + x += max(html.clientWidth, body ? body.clientWidth : 0) - width; + } + return { + width, + height, + x, + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js +function isScrollParent(element) { + var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; + return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); +} + +// node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js +function getScrollParent(node) { + if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) { + return node.ownerDocument.body; + } + if (isHTMLElement(node) && isScrollParent(node)) { + return node; + } + return getScrollParent(getParentNode(node)); +} + +// node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js +function listScrollParents(element, list) { + var _element$ownerDocumen; + if (list === void 0) { + list = []; + } + var scrollParent = getScrollParent(element); + var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); + var win = getWindow(scrollParent); + var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; + var updatedList = list.concat(target); + return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target))); +} + +// node_modules/@popperjs/core/lib/utils/rectToClientRect.js +function rectToClientRect(rect) { + return Object.assign({}, rect, { + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height + }); +} + +// node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js +function getInnerBoundingClientRect(element) { + var rect = getBoundingClientRect(element); + rect.top = rect.top + element.clientTop; + rect.left = rect.left + element.clientLeft; + rect.bottom = rect.top + element.clientHeight; + rect.right = rect.left + element.clientWidth; + rect.width = element.clientWidth; + rect.height = element.clientHeight; + rect.x = rect.left; + rect.y = rect.top; + return rect; +} +function getClientRectFromMixedType(element, clippingParent) { + return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element))); +} +function getClippingParents(element) { + var clippingParents2 = listScrollParents(getParentNode(element)); + var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0; + var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; + if (!isElement(clipperElement)) { + return []; + } + return clippingParents2.filter(function(clippingParent) { + return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body"; + }); +} +function getClippingRect(element, boundary, rootBoundary) { + var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary); + var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]); + var firstClippingParent = clippingParents2[0]; + var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) { + var rect = getClientRectFromMixedType(element, clippingParent); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromMixedType(element, firstClippingParent)); + clippingRect.width = clippingRect.right - clippingRect.left; + clippingRect.height = clippingRect.bottom - clippingRect.top; + clippingRect.x = clippingRect.left; + clippingRect.y = clippingRect.top; + return clippingRect; +} + +// node_modules/@popperjs/core/lib/utils/computeOffsets.js +function computeOffsets(_ref) { + var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement; + var basePlacement = placement ? getBasePlacement(placement) : null; + var variation = placement ? getVariation(placement) : null; + var commonX = reference2.x + reference2.width / 2 - element.width / 2; + var commonY = reference2.y + reference2.height / 2 - element.height / 2; + var offsets; + switch (basePlacement) { + case top: + offsets = { + x: commonX, + y: reference2.y - element.height + }; + break; + case bottom: + offsets = { + x: commonX, + y: reference2.y + reference2.height + }; + break; + case right: + offsets = { + x: reference2.x + reference2.width, + y: commonY + }; + break; + case left: + offsets = { + x: reference2.x - element.width, + y: commonY + }; + break; + default: + offsets = { + x: reference2.x, + y: reference2.y + }; + } + var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; + if (mainAxis != null) { + var len = mainAxis === "y" ? "height" : "width"; + switch (variation) { + case start: + offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2); + break; + case end: + offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2); + break; + default: + } + } + return offsets; +} + +// node_modules/@popperjs/core/lib/utils/detectOverflow.js +function detectOverflow(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding; + var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); + var altContext = elementContext === popper ? reference : popper; + var popperRect = state.rects.popper; + var element = state.elements[altBoundary ? altContext : elementContext]; + var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary); + var referenceClientRect = getBoundingClientRect(state.elements.reference); + var popperOffsets2 = computeOffsets({ + reference: referenceClientRect, + element: popperRect, + strategy: "absolute", + placement + }); + var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2)); + var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; + var overflowOffsets = { + top: clippingClientRect.top - elementClientRect.top + paddingObject.top, + bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, + left: clippingClientRect.left - elementClientRect.left + paddingObject.left, + right: elementClientRect.right - clippingClientRect.right + paddingObject.right + }; + var offsetData = state.modifiersData.offset; + if (elementContext === popper && offsetData) { + var offset2 = offsetData[placement]; + Object.keys(overflowOffsets).forEach(function(key) { + var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; + var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x"; + overflowOffsets[key] += offset2[axis] * multiply; + }); + } + return overflowOffsets; +} + +// node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js +function computeAutoPlacement(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; + var variation = getVariation(placement); + var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) { + return getVariation(placement2) === variation; + }) : basePlacements; + var allowedPlacements = placements2.filter(function(placement2) { + return allowedAutoPlacements.indexOf(placement2) >= 0; + }); + if (allowedPlacements.length === 0) { + allowedPlacements = placements2; + if (true) { + console.error(["Popper: The `allowedAutoPlacements` option did not allow any", "placements. Ensure the `placement` option matches the variation", "of the allowed placements.", 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(" ")); + } + } + var overflows = allowedPlacements.reduce(function(acc, placement2) { + acc[placement2] = detectOverflow(state, { + placement: placement2, + boundary, + rootBoundary, + padding + })[getBasePlacement(placement2)]; + return acc; + }, {}); + return Object.keys(overflows).sort(function(a, b) { + return overflows[a] - overflows[b]; + }); +} + +// node_modules/@popperjs/core/lib/modifiers/flip.js +function getExpandedFallbackPlacements(placement) { + if (getBasePlacement(placement) === auto) { + return []; + } + var oppositePlacement = getOppositePlacement(placement); + return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; +} +function flip(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + if (state.modifiersData[name]._skip) { + return; + } + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements; + var preferredPlacement = state.options.placement; + var basePlacement = getBasePlacement(preferredPlacement); + var isBasePlacement = basePlacement === preferredPlacement; + var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); + var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) { + return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, { + placement: placement2, + boundary, + rootBoundary, + padding, + flipVariations, + allowedAutoPlacements + }) : placement2); + }, []); + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var checksMap = new Map(); + var makeFallbackChecks = true; + var firstFittingPlacement = placements2[0]; + for (var i = 0; i < placements2.length; i++) { + var placement = placements2[i]; + var _basePlacement = getBasePlacement(placement); + var isStartVariation = getVariation(placement) === start; + var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; + var len = isVertical ? "width" : "height"; + var overflow = detectOverflow(state, { + placement, + boundary, + rootBoundary, + altBoundary, + padding + }); + var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; + if (referenceRect[len] > popperRect[len]) { + mainVariationSide = getOppositePlacement(mainVariationSide); + } + var altVariationSide = getOppositePlacement(mainVariationSide); + var checks = []; + if (checkMainAxis) { + checks.push(overflow[_basePlacement] <= 0); + } + if (checkAltAxis) { + checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); + } + if (checks.every(function(check) { + return check; + })) { + firstFittingPlacement = placement; + makeFallbackChecks = false; + break; + } + checksMap.set(placement, checks); + } + if (makeFallbackChecks) { + var numberOfChecks = flipVariations ? 3 : 1; + var _loop = function _loop2(_i2) { + var fittingPlacement = placements2.find(function(placement2) { + var checks2 = checksMap.get(placement2); + if (checks2) { + return checks2.slice(0, _i2).every(function(check) { + return check; + }); + } + }); + if (fittingPlacement) { + firstFittingPlacement = fittingPlacement; + return "break"; + } + }; + for (var _i = numberOfChecks; _i > 0; _i--) { + var _ret = _loop(_i); + if (_ret === "break") + break; + } + } + if (state.placement !== firstFittingPlacement) { + state.modifiersData[name]._skip = true; + state.placement = firstFittingPlacement; + state.reset = true; + } +} +var flip_default = { + name: "flip", + enabled: true, + phase: "main", + fn: flip, + requiresIfExists: ["offset"], + data: { + _skip: false + } +}; + +// node_modules/@popperjs/core/lib/modifiers/hide.js +function getSideOffsets(overflow, rect, preventedOffsets) { + if (preventedOffsets === void 0) { + preventedOffsets = { + x: 0, + y: 0 + }; + } + return { + top: overflow.top - rect.height - preventedOffsets.y, + right: overflow.right - rect.width + preventedOffsets.x, + bottom: overflow.bottom - rect.height + preventedOffsets.y, + left: overflow.left - rect.width - preventedOffsets.x + }; +} +function isAnySideFullyClipped(overflow) { + return [top, right, bottom, left].some(function(side) { + return overflow[side] >= 0; + }); +} +function hide(_ref) { + var state = _ref.state, name = _ref.name; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var preventedOffsets = state.modifiersData.preventOverflow; + var referenceOverflow = detectOverflow(state, { + elementContext: "reference" + }); + var popperAltOverflow = detectOverflow(state, { + altBoundary: true + }); + var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); + var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); + var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); + var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); + state.modifiersData[name] = { + referenceClippingOffsets, + popperEscapeOffsets, + isReferenceHidden, + hasPopperEscaped + }; + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-reference-hidden": isReferenceHidden, + "data-popper-escaped": hasPopperEscaped + }); +} +var hide_default = { + name: "hide", + enabled: true, + phase: "main", + requiresIfExists: ["preventOverflow"], + fn: hide +}; + +// node_modules/@popperjs/core/lib/modifiers/offset.js +function distanceAndSkiddingToXY(placement, rects, offset2) { + var basePlacement = getBasePlacement(placement); + var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; + var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, { + placement + })) : offset2, skidding = _ref[0], distance = _ref[1]; + skidding = skidding || 0; + distance = (distance || 0) * invertDistance; + return [left, right].indexOf(basePlacement) >= 0 ? { + x: distance, + y: skidding + } : { + x: skidding, + y: distance + }; +} +function offset(_ref2) { + var state = _ref2.state, options = _ref2.options, name = _ref2.name; + var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset; + var data = placements.reduce(function(acc, placement) { + acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2); + return acc; + }, {}); + var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y; + if (state.modifiersData.popperOffsets != null) { + state.modifiersData.popperOffsets.x += x; + state.modifiersData.popperOffsets.y += y; + } + state.modifiersData[name] = data; +} +var offset_default = { + name: "offset", + enabled: true, + phase: "main", + requires: ["popperOffsets"], + fn: offset +}; + +// node_modules/@popperjs/core/lib/modifiers/popperOffsets.js +function popperOffsets(_ref) { + var state = _ref.state, name = _ref.name; + state.modifiersData[name] = computeOffsets({ + reference: state.rects.reference, + element: state.rects.popper, + strategy: "absolute", + placement: state.placement + }); +} +var popperOffsets_default = { + name: "popperOffsets", + enabled: true, + phase: "read", + fn: popperOffsets, + data: {} +}; + +// node_modules/@popperjs/core/lib/utils/getAltAxis.js +function getAltAxis(axis) { + return axis === "x" ? "y" : "x"; +} + +// node_modules/@popperjs/core/lib/modifiers/preventOverflow.js +function preventOverflow(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; + var overflow = detectOverflow(state, { + boundary, + rootBoundary, + padding, + altBoundary + }); + var basePlacement = getBasePlacement(state.placement); + var variation = getVariation(state.placement); + var isBasePlacement = !variation; + var mainAxis = getMainAxisFromPlacement(basePlacement); + var altAxis = getAltAxis(mainAxis); + var popperOffsets2 = state.modifiersData.popperOffsets; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, { + placement: state.placement + })) : tetherOffset; + var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? { + mainAxis: tetherOffsetValue, + altAxis: tetherOffsetValue + } : Object.assign({ + mainAxis: 0, + altAxis: 0 + }, tetherOffsetValue); + var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; + var data = { + x: 0, + y: 0 + }; + if (!popperOffsets2) { + return; + } + if (checkMainAxis) { + var _offsetModifierState$; + var mainSide = mainAxis === "y" ? top : left; + var altSide = mainAxis === "y" ? bottom : right; + var len = mainAxis === "y" ? "height" : "width"; + var offset2 = popperOffsets2[mainAxis]; + var min2 = offset2 + overflow[mainSide]; + var max2 = offset2 - overflow[altSide]; + var additive = tether ? -popperRect[len] / 2 : 0; + var minLen = variation === start ? referenceRect[len] : popperRect[len]; + var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; + var arrowElement = state.elements.arrow; + var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { + width: 0, + height: 0 + }; + var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject(); + var arrowPaddingMin = arrowPaddingObject[mainSide]; + var arrowPaddingMax = arrowPaddingObject[altSide]; + var arrowLen = within(0, referenceRect[len], arrowRect[len]); + var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; + var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; + var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); + var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; + var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; + var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset; + var tetherMax = offset2 + maxOffset - offsetModifierValue; + var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2); + popperOffsets2[mainAxis] = preventedOffset; + data[mainAxis] = preventedOffset - offset2; + } + if (checkAltAxis) { + var _offsetModifierState$2; + var _mainSide = mainAxis === "x" ? top : left; + var _altSide = mainAxis === "x" ? bottom : right; + var _offset = popperOffsets2[altAxis]; + var _len = altAxis === "y" ? "height" : "width"; + var _min = _offset + overflow[_mainSide]; + var _max = _offset - overflow[_altSide]; + var isOriginSide = [top, left].indexOf(basePlacement) !== -1; + var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; + var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; + var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; + var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); + popperOffsets2[altAxis] = _preventedOffset; + data[altAxis] = _preventedOffset - _offset; + } + state.modifiersData[name] = data; +} +var preventOverflow_default = { + name: "preventOverflow", + enabled: true, + phase: "main", + fn: preventOverflow, + requiresIfExists: ["offset"] +}; + +// node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js +function getHTMLElementScroll(element) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js +function getNodeScroll(node) { + if (node === getWindow(node) || !isHTMLElement(node)) { + return getWindowScroll(node); + } else { + return getHTMLElementScroll(node); + } +} + +// node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js +function isElementScaled(element) { + var rect = element.getBoundingClientRect(); + var scaleX = round(rect.width) / element.offsetWidth || 1; + var scaleY = round(rect.height) / element.offsetHeight || 1; + return scaleX !== 1 || scaleY !== 1; +} +function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { + if (isFixed === void 0) { + isFixed = false; + } + var isOffsetParentAnElement = isHTMLElement(offsetParent); + var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); + var documentElement = getDocumentElement(offsetParent); + var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled); + var scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + var offsets = { + x: 0, + y: 0 + }; + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== "body" || isScrollParent(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + offsets = getBoundingClientRect(offsetParent, true); + offsets.x += offsetParent.clientLeft; + offsets.y += offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } + } + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height + }; +} + +// node_modules/@popperjs/core/lib/utils/orderModifiers.js +function order(modifiers) { + var map = new Map(); + var visited = new Set(); + var result = []; + modifiers.forEach(function(modifier) { + map.set(modifier.name, modifier); + }); + function sort(modifier) { + visited.add(modifier.name); + var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); + requires.forEach(function(dep) { + if (!visited.has(dep)) { + var depModifier = map.get(dep); + if (depModifier) { + sort(depModifier); + } + } + }); + result.push(modifier); + } + modifiers.forEach(function(modifier) { + if (!visited.has(modifier.name)) { + sort(modifier); + } + }); + return result; +} +function orderModifiers(modifiers) { + var orderedModifiers = order(modifiers); + return modifierPhases.reduce(function(acc, phase) { + return acc.concat(orderedModifiers.filter(function(modifier) { + return modifier.phase === phase; + })); + }, []); +} + +// node_modules/@popperjs/core/lib/utils/debounce.js +function debounce(fn2) { + var pending; + return function() { + if (!pending) { + pending = new Promise(function(resolve) { + Promise.resolve().then(function() { + pending = void 0; + resolve(fn2()); + }); + }); + } + return pending; + }; +} + +// node_modules/@popperjs/core/lib/utils/format.js +function format(str) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + return [].concat(args).reduce(function(p, c) { + return p.replace(/%s/, c); + }, str); +} + +// node_modules/@popperjs/core/lib/utils/validateModifiers.js +var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s'; +var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available'; +var VALID_PROPERTIES = ["name", "enabled", "phase", "fn", "effect", "requires", "options"]; +function validateModifiers(modifiers) { + modifiers.forEach(function(modifier) { + [].concat(Object.keys(modifier), VALID_PROPERTIES).filter(function(value, index, self) { + return self.indexOf(value) === index; + }).forEach(function(key) { + switch (key) { + case "name": + if (typeof modifier.name !== "string") { + console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', '"' + String(modifier.name) + '"')); + } + break; + case "enabled": + if (typeof modifier.enabled !== "boolean") { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', '"' + String(modifier.enabled) + '"')); + } + break; + case "phase": + if (modifierPhases.indexOf(modifier.phase) < 0) { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(", "), '"' + String(modifier.phase) + '"')); + } + break; + case "fn": + if (typeof modifier.fn !== "function") { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', '"' + String(modifier.fn) + '"')); + } + break; + case "effect": + if (modifier.effect != null && typeof modifier.effect !== "function") { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', '"' + String(modifier.fn) + '"')); + } + break; + case "requires": + if (modifier.requires != null && !Array.isArray(modifier.requires)) { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', '"' + String(modifier.requires) + '"')); + } + break; + case "requiresIfExists": + if (!Array.isArray(modifier.requiresIfExists)) { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', '"' + String(modifier.requiresIfExists) + '"')); + } + break; + case "options": + case "data": + break; + default: + console.error('PopperJS: an invalid property has been provided to the "' + modifier.name + '" modifier, valid properties are ' + VALID_PROPERTIES.map(function(s) { + return '"' + s + '"'; + }).join(", ") + '; but "' + key + '" was provided.'); + } + modifier.requires && modifier.requires.forEach(function(requirement) { + if (modifiers.find(function(mod) { + return mod.name === requirement; + }) == null) { + console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement)); + } + }); + }); + }); +} + +// node_modules/@popperjs/core/lib/utils/uniqueBy.js +function uniqueBy(arr, fn2) { + var identifiers = new Set(); + return arr.filter(function(item) { + var identifier = fn2(item); + if (!identifiers.has(identifier)) { + identifiers.add(identifier); + return true; + } + }); +} + +// node_modules/@popperjs/core/lib/utils/mergeByName.js +function mergeByName(modifiers) { + var merged = modifiers.reduce(function(merged2, current) { + var existing = merged2[current.name]; + merged2[current.name] = existing ? Object.assign({}, existing, current, { + options: Object.assign({}, existing.options, current.options), + data: Object.assign({}, existing.data, current.data) + }) : current; + return merged2; + }, {}); + return Object.keys(merged).map(function(key) { + return merged[key]; + }); +} + +// node_modules/@popperjs/core/lib/createPopper.js +var INVALID_ELEMENT_ERROR = "Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element."; +var INFINITE_LOOP_ERROR = "Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash."; +var DEFAULT_OPTIONS = { + placement: "bottom", + modifiers: [], + strategy: "absolute" +}; +function areValidElements() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return !args.some(function(element) { + return !(element && typeof element.getBoundingClientRect === "function"); + }); +} +function popperGenerator(generatorOptions) { + if (generatorOptions === void 0) { + generatorOptions = {}; + } + var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; + return function createPopper2(reference2, popper2, options) { + if (options === void 0) { + options = defaultOptions; + } + var state = { + placement: "bottom", + orderedModifiers: [], + options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), + modifiersData: {}, + elements: { + reference: reference2, + popper: popper2 + }, + attributes: {}, + styles: {} + }; + var effectCleanupFns = []; + var isDestroyed = false; + var instance = { + state, + setOptions: function setOptions(setOptionsAction) { + var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction; + cleanupModifierEffects(); + state.options = Object.assign({}, defaultOptions, state.options, options2); + state.scrollParents = { + reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [], + popper: listScrollParents(popper2) + }; + var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers))); + state.orderedModifiers = orderedModifiers.filter(function(m) { + return m.enabled; + }); + if (true) { + var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function(_ref) { + var name = _ref.name; + return name; + }); + validateModifiers(modifiers); + if (getBasePlacement(state.options.placement) === auto) { + var flipModifier = state.orderedModifiers.find(function(_ref2) { + var name = _ref2.name; + return name === "flip"; + }); + if (!flipModifier) { + console.error(['Popper: "auto" placements require the "flip" modifier be', "present and enabled to work."].join(" ")); + } + } + var _getComputedStyle = getComputedStyle(popper2), marginTop = _getComputedStyle.marginTop, marginRight = _getComputedStyle.marginRight, marginBottom = _getComputedStyle.marginBottom, marginLeft = _getComputedStyle.marginLeft; + if ([marginTop, marginRight, marginBottom, marginLeft].some(function(margin) { + return parseFloat(margin); + })) { + console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', "between the popper and its reference element or boundary.", "To replicate margin, use the `offset` modifier, as well as", "the `padding` option in the `preventOverflow` and `flip`", "modifiers."].join(" ")); + } + } + runModifierEffects(); + return instance.update(); + }, + forceUpdate: function forceUpdate() { + if (isDestroyed) { + return; + } + var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper; + if (!areValidElements(reference3, popper3)) { + if (true) { + console.error(INVALID_ELEMENT_ERROR); + } + return; + } + state.rects = { + reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"), + popper: getLayoutRect(popper3) + }; + state.reset = false; + state.placement = state.options.placement; + state.orderedModifiers.forEach(function(modifier) { + return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); + }); + var __debug_loops__ = 0; + for (var index = 0; index < state.orderedModifiers.length; index++) { + if (true) { + __debug_loops__ += 1; + if (__debug_loops__ > 100) { + console.error(INFINITE_LOOP_ERROR); + break; + } + } + if (state.reset === true) { + state.reset = false; + index = -1; + continue; + } + var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name; + if (typeof fn2 === "function") { + state = fn2({ + state, + options: _options, + name, + instance + }) || state; + } + } + }, + update: debounce(function() { + return new Promise(function(resolve) { + instance.forceUpdate(); + resolve(state); + }); + }), + destroy: function destroy() { + cleanupModifierEffects(); + isDestroyed = true; + } + }; + if (!areValidElements(reference2, popper2)) { + if (true) { + console.error(INVALID_ELEMENT_ERROR); + } + return instance; + } + instance.setOptions(options).then(function(state2) { + if (!isDestroyed && options.onFirstUpdate) { + options.onFirstUpdate(state2); + } + }); + function runModifierEffects() { + state.orderedModifiers.forEach(function(_ref3) { + var name = _ref3.name, _ref3$options = _ref3.options, options2 = _ref3$options === void 0 ? {} : _ref3$options, effect4 = _ref3.effect; + if (typeof effect4 === "function") { + var cleanupFn = effect4({ + state, + name, + instance, + options: options2 + }); + var noopFn = function noopFn2() { + }; + effectCleanupFns.push(cleanupFn || noopFn); + } + }); + } + function cleanupModifierEffects() { + effectCleanupFns.forEach(function(fn2) { + return fn2(); + }); + effectCleanupFns = []; + } + return instance; + }; +} + +// node_modules/@popperjs/core/lib/popper.js +var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default]; +var createPopper = /* @__PURE__ */ popperGenerator({ + defaultModifiers +}); + +// suggests/suggest.ts +var wrapAround = (value, size) => { + return (value % size + size) % size; +}; +var Suggest = class { + constructor(owner, containerEl, scope) { + this.owner = owner; + this.containerEl = containerEl; + containerEl.on("click", ".suggestion-item", this.onSuggestionClick.bind(this)); + containerEl.on("mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this)); + scope.register([], "ArrowUp", (event) => { + if (!event.isComposing) { + this.setSelectedItem(this.selectedItem - 1, true); + return false; + } + }); + scope.register([], "ArrowDown", (event) => { + if (!event.isComposing) { + this.setSelectedItem(this.selectedItem + 1, true); + return false; + } + }); + scope.register([], "Enter", (event) => { + if (!event.isComposing) { + this.useSelectedItem(event); + return false; + } + }); + } + onSuggestionClick(event, el) { + event.preventDefault(); + const item = this.suggestions.indexOf(el); + this.setSelectedItem(item, false); + this.useSelectedItem(event); + } + onSuggestionMouseover(_event, el) { + const item = this.suggestions.indexOf(el); + this.setSelectedItem(item, false); + } + setSuggestions(values) { + this.containerEl.empty(); + const suggestionEls = []; + values.forEach((value) => { + const suggestionEl = this.containerEl.createDiv("suggestion-item"); + this.owner.renderSuggestion(value, suggestionEl); + suggestionEls.push(suggestionEl); + }); + this.values = values; + this.suggestions = suggestionEls; + this.setSelectedItem(0, false); + } + useSelectedItem(event) { + const currentValue = this.values[this.selectedItem]; + if (currentValue) { + this.owner.selectSuggestion(currentValue, event); + } + } + setSelectedItem(selectedIndex, scrollIntoView) { + const normalizedIndex = wrapAround(selectedIndex, this.suggestions.length); + const prevSelectedSuggestion = this.suggestions[this.selectedItem]; + const selectedSuggestion = this.suggestions[normalizedIndex]; + prevSelectedSuggestion == null ? void 0 : prevSelectedSuggestion.removeClass("is-selected"); + selectedSuggestion == null ? void 0 : selectedSuggestion.addClass("is-selected"); + this.selectedItem = normalizedIndex; + if (scrollIntoView) { + selectedSuggestion.scrollIntoView(false); + } + } +}; +var TextInputSuggest = class { + constructor(app, inputEl) { + this.app = app; + this.inputEl = inputEl; + this.scope = new import_obsidian.Scope(); + this.suggestEl = createDiv("suggestion-container"); + const suggestion = this.suggestEl.createDiv("suggestion"); + this.suggest = new Suggest(this, suggestion, this.scope); + this.scope.register([], "Escape", this.close.bind(this)); + this.inputEl.addEventListener("input", this.onInputChanged.bind(this)); + this.inputEl.addEventListener("focus", this.onInputChanged.bind(this)); + this.inputEl.addEventListener("blur", this.close.bind(this)); + this.suggestEl.on("mousedown", ".suggestion-container", (event) => { + event.preventDefault(); + }); + } + onInputChanged() { + const inputStr = this.inputEl.value; + const suggestions = this.getSuggestions(inputStr); + if (suggestions.length > 0) { + this.suggest.setSuggestions(suggestions); + this.open(this.app.dom.appContainerEl, this.inputEl); + } + } + open(container, inputEl) { + this.app.keymap.pushScope(this.scope); + container.appendChild(this.suggestEl); + this.popper = createPopper(inputEl, this.suggestEl, { + placement: "bottom-start", + modifiers: [ + { + name: "sameWidth", + enabled: true, + fn: ({ state, instance }) => { + const targetWidth = `${state.rects.reference.width}px`; + if (state.styles.popper.width === targetWidth) { + return; + } + state.styles.popper.width = targetWidth; + instance.update(); + }, + phase: "beforeWrite", + requires: ["computeStyles"] + } + ] + }); + } + close() { + this.app.keymap.popScope(this.scope); + this.suggest.setSuggestions([]); + this.popper.destroy(); + this.suggestEl.detach(); + } +}; + +// suggests/file-suggest.ts +var FolderSuggest = class extends TextInputSuggest { + getSuggestions(inputStr) { + const abstractFiles = this.app.vault.getAllLoadedFiles(); + const folders = []; + const lowerCaseInputStr = inputStr.toLowerCase(); + abstractFiles.forEach((folder) => { + if (folder instanceof import_obsidian2.TFolder && folder.path.toLowerCase().contains(lowerCaseInputStr)) { + folders.push(folder); + } + }); + return folders; + } + renderSuggestion(file, el) { + el.setText(file.path); + } + selectSuggestion(file) { + this.inputEl.value = file.path; + this.inputEl.trigger("input"); + this.close(); + } +}; + +// suggests/tag-suggest.ts +var import_obsidian3 = __toModule(require("obsidian")); +var GetAllTagsInTheVault = class extends import_obsidian3.Plugin { + constructor(app, manifest) { + super(app, manifest); + this.fileArray = this.app.vault.getMarkdownFiles(); + this.fileCache = this.fileArray.map((value) => this.app.metadataCache.getFileCache(value)); + this.tagArray = this.fileCache.map((value) => (0, import_obsidian3.getAllTags)(value)); + this.tagArrayJoin = this.tagArray.join(); + this.tagArraySplit = this.tagArrayJoin.split(","); + this.tagArrayFilter = this.tagArraySplit.filter(Boolean); + this.tagList = [...new Set(this.tagArrayFilter)]; + } + pull() { + return this.tagList; + } +}; +var TagSuggest = class extends TextInputSuggest { + getSuggestions(inputStr) { + this.tagList = new GetAllTagsInTheVault(this.app, this.manifest); + this.tagMatch = []; + this.lowerCaseInputStr = inputStr.toLowerCase(); + this.tagList.pull().forEach((Tag) => { + if (Tag.toLowerCase().contains(this.lowerCaseInputStr)) { + this.tagMatch.push(Tag); + } + }); + return this.tagMatch; + } + renderSuggestion(Tag, el) { + el.setText(Tag); + } + selectSuggestion(Tag) { + this.inputEl.value = Tag; + this.inputEl.trigger("input"); + this.close(); + } +}; + +// utils/Utils.ts +var import_obsidian4 = __toModule(require("obsidian")); +var isFmDisable = (fileCache) => { + const fm = (0, import_obsidian4.parseFrontMatterEntry)(fileCache.frontmatter, "AutoNoteMover"); + if (fm === "disable") { + return true; + } else { + return false; + } +}; +var folderOrFile = (app, path) => { + const F = app.vault.getAbstractFileByPath(path); + if (F instanceof import_obsidian4.TFile) { + return import_obsidian4.TFile; + } else if (F instanceof import_obsidian4.TFolder) { + return import_obsidian4.TFolder; + } +}; +var isTFExists = (app, path, F) => { + if (folderOrFile(app, (0, import_obsidian4.normalizePath)(path)) === F) { + return true; + } else { + return false; + } +}; +var fileMove = (app, settingFolder, fileFullName, file) => __async(void 0, null, function* () { + if (!isTFExists(app, settingFolder, import_obsidian4.TFolder)) { + console.error(`[Auto Note Mover] The destination folder "${settingFolder}" does not exist.`); + new import_obsidian4.Notice(`[Auto Note Mover] +"Error: The destination folder +"${settingFolder}" +does not exist.`); + return; + } + const newPath = (0, import_obsidian4.normalizePath)(settingFolder + "/" + fileFullName); + if (isTFExists(app, newPath, import_obsidian4.TFile) && newPath !== file.path) { + console.error(`[Auto Note Mover] Error: A file with the same name "${fileFullName}" exists at the destination folder.`); + new import_obsidian4.Notice(`[Auto Note Mover] +Error: A file with the same name +"${fileFullName}" +exists at the destination folder.`); + return; + } + if (newPath === file.path) { + return; + } + yield app.fileManager.renameFile(file, newPath); + console.log(`[Auto Note Mover] Moved the note "${fileFullName}" to the "${settingFolder}".`); + new import_obsidian4.Notice(`[Auto Note Mover] +Moved the note "${fileFullName}" +to the "${settingFolder}".`); +}); +var arrayMove = (array, fromIndex, toIndex) => { + if (toIndex < 0 || toIndex === array.length) { + return; + } + const temp = array[fromIndex]; + array[fromIndex] = array[toIndex]; + array[toIndex] = temp; +}; +var getTriggerIndicator = (trigger) => { + if (trigger === "Automatic") { + return `[A]`; + } else { + return `[M]`; + } +}; + +// settings/settings.ts +var DEFAULT_SETTINGS = { + trigger_auto_manual: "Automatic", + use_regex_to_check_for_tags: false, + statusBar_trigger_indicator: true, + folder_tag_pattern: [{ folder: "", tag: "", pattern: "" }], + use_regex_to_check_for_excluded_folder: false, + excluded_folder: [{ folder: "" }] +}; +var AutoNoteMoverSettingTab = class extends import_obsidian5.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + const { containerEl } = this; + containerEl.empty(); + this.containerEl.empty(); + this.add_auto_note_mover_setting(); + } + add_auto_note_mover_setting() { + this.containerEl.createEl("h2", { text: "Auto Note Mover" }); + const descEl = document.createDocumentFragment(); + new import_obsidian5.Setting(this.containerEl).setDesc("Auto Note Mover will automatically move the active notes to their respective folders according to the rules."); + const triggerDesc = document.createDocumentFragment(); + triggerDesc.append("Choose how the trigger will be activated.", descEl.createEl("br"), descEl.createEl("strong", { text: "Automatic " }), "is triggered when you create, edit, or rename a note, and moves the note if it matches the rules.", descEl.createEl("br"), "You can also activate the trigger with a command.", descEl.createEl("br"), descEl.createEl("strong", { text: "Manual " }), "will not automatically move notes.", descEl.createEl("br"), "You can trigger by command."); + new import_obsidian5.Setting(this.containerEl).setName("Trigger").setDesc(triggerDesc).addDropdown((dropDown) => dropDown.addOption("Automatic", "Automatic").addOption("Manual", "Manual").setValue(this.plugin.settings.trigger_auto_manual).onChange((value) => { + this.plugin.settings.trigger_auto_manual = value; + this.plugin.saveData(this.plugin.settings); + this.display(); + })); + const useRegexToCheckForTags = document.createDocumentFragment(); + useRegexToCheckForTags.append("If enabled, tags will be checked with regular expressions.", descEl.createEl("br"), "For example, if you want to match the #tag, you would write ", descEl.createEl("strong", { text: "^#tag$" }), descEl.createEl("br"), "This setting is for a specific purpose, such as specifying nested tags in bulk.", descEl.createEl("br"), descEl.createEl("strong", { + text: "If you want to use the suggested tags as they are, it is recommended to disable this setting." + })); + new import_obsidian5.Setting(this.containerEl).setName("Use regular expressions to check for tags").setDesc(useRegexToCheckForTags).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.use_regex_to_check_for_tags).onChange((value) => __async(this, null, function* () { + this.plugin.settings.use_regex_to_check_for_tags = value; + yield this.plugin.saveSettings(); + this.display(); + })); + }); + const ruleDesc = document.createDocumentFragment(); + ruleDesc.append("1. Set the destination folder.", descEl.createEl("br"), "2. Set a tag or title that matches the note you want to move. ", descEl.createEl("strong", { text: "You can set either the tag or the title. " }), descEl.createEl("br"), "3. The rules are checked in order from the top. The notes will be moved to the folder with the ", descEl.createEl("strong", { text: "first matching rule." }), descEl.createEl("br"), "Tag: Be sure to add a", descEl.createEl("strong", { text: " # " }), "at the beginning.", descEl.createEl("br"), "Title: Tested by JavaScript regular expressions.", descEl.createEl("br"), descEl.createEl("br"), "Notice:", descEl.createEl("br"), "1. Attached files will not be moved, but they will still appear in the note.", descEl.createEl("br"), '2. Auto Note Mover will not move notes that have "', descEl.createEl("strong", { text: "AutoNoteMover: disable" }), '" in the frontmatter.'); + new import_obsidian5.Setting(this.containerEl).setName("Add new rule").setDesc(ruleDesc).addButton((button) => { + button.setTooltip("Add new rule").setButtonText("+").setCta().onClick(() => __async(this, null, function* () { + this.plugin.settings.folder_tag_pattern.push({ + folder: "", + tag: "", + pattern: "" + }); + yield this.plugin.saveSettings(); + this.display(); + })); + }); + this.plugin.settings.folder_tag_pattern.forEach((folder_tag_pattern, index) => { + const settings = this.plugin.settings.folder_tag_pattern; + const settingTag = settings.map((e) => e["tag"]); + const settingPattern = settings.map((e) => e["pattern"]); + const checkArr = (arr, val) => { + return arr.some((arrVal) => val === arrVal); + }; + const s = new import_obsidian5.Setting(this.containerEl).addSearch((cb) => { + new FolderSuggest(this.app, cb.inputEl); + cb.setPlaceholder("Folder").setValue(folder_tag_pattern.folder).onChange((newFolder) => __async(this, null, function* () { + this.plugin.settings.folder_tag_pattern[index].folder = newFolder.trim(); + yield this.plugin.saveSettings(); + })); + }).addSearch((cb) => { + new TagSuggest(this.app, cb.inputEl); + cb.setPlaceholder("Tag").setValue(folder_tag_pattern.tag).onChange((newTag) => __async(this, null, function* () { + if (this.plugin.settings.folder_tag_pattern[index].pattern) { + this.display(); + return new import_obsidian5.Notice(`You can set either the tag or the title.`); + } + if (newTag && checkArr(settingTag, newTag)) { + new import_obsidian5.Notice("This tag is already used."); + return; + } + if (!this.plugin.settings.use_regex_to_check_for_tags) { + this.plugin.settings.folder_tag_pattern[index].tag = newTag.trim(); + } else if (this.plugin.settings.use_regex_to_check_for_tags) { + this.plugin.settings.folder_tag_pattern[index].tag = newTag; + } + yield this.plugin.saveSettings(); + })); + }).addSearch((cb) => { + cb.setPlaceholder("Title by regex").setValue(folder_tag_pattern.pattern).onChange((newPattern) => __async(this, null, function* () { + if (this.plugin.settings.folder_tag_pattern[index].tag) { + this.display(); + return new import_obsidian5.Notice(`You can set either the tag or the title.`); + } + if (newPattern && checkArr(settingPattern, newPattern)) { + new import_obsidian5.Notice("This pattern is already used."); + return; + } + this.plugin.settings.folder_tag_pattern[index].pattern = newPattern; + yield this.plugin.saveSettings(); + })); + }).addExtraButton((cb) => { + cb.setIcon("up-chevron-glyph").setTooltip("Move up").onClick(() => __async(this, null, function* () { + arrayMove(this.plugin.settings.folder_tag_pattern, index, index - 1); + yield this.plugin.saveSettings(); + this.display(); + })); + }).addExtraButton((cb) => { + cb.setIcon("down-chevron-glyph").setTooltip("Move down").onClick(() => __async(this, null, function* () { + arrayMove(this.plugin.settings.folder_tag_pattern, index, index + 1); + yield this.plugin.saveSettings(); + this.display(); + })); + }).addExtraButton((cb) => { + cb.setIcon("cross").setTooltip("Delete").onClick(() => __async(this, null, function* () { + this.plugin.settings.folder_tag_pattern.splice(index, 1); + yield this.plugin.saveSettings(); + this.display(); + })); + }); + s.infoEl.remove(); + }); + const useRegexToCheckForExcludedFolder = document.createDocumentFragment(); + useRegexToCheckForExcludedFolder.append("If enabled, excluded folder will be checked with regular expressions."); + new import_obsidian5.Setting(this.containerEl).setName("Use regular expressions to check for excluded folder").setDesc(useRegexToCheckForExcludedFolder).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.use_regex_to_check_for_excluded_folder).onChange((value) => __async(this, null, function* () { + this.plugin.settings.use_regex_to_check_for_excluded_folder = value; + yield this.plugin.saveSettings(); + this.display(); + })); + }); + const excludedFolderDesc = document.createDocumentFragment(); + excludedFolderDesc.append("Notes in the excluded folder will not be moved.", descEl.createEl("br"), "This takes precedence over the notes movement rules."); + new import_obsidian5.Setting(this.containerEl).setName("Add Excluded Folder").setDesc(excludedFolderDesc).addButton((button) => { + button.setTooltip("Add Excluded Folders").setButtonText("+").setCta().onClick(() => __async(this, null, function* () { + this.plugin.settings.excluded_folder.push({ + folder: "" + }); + yield this.plugin.saveSettings(); + this.display(); + })); + }); + this.plugin.settings.excluded_folder.forEach((excluded_folder, index) => { + const s = new import_obsidian5.Setting(this.containerEl).addSearch((cb) => { + new FolderSuggest(this.app, cb.inputEl); + cb.setPlaceholder("Folder").setValue(excluded_folder.folder).onChange((newFolder) => __async(this, null, function* () { + this.plugin.settings.excluded_folder[index].folder = newFolder; + yield this.plugin.saveSettings(); + })); + }).addExtraButton((cb) => { + cb.setIcon("up-chevron-glyph").setTooltip("Move up").onClick(() => __async(this, null, function* () { + arrayMove(this.plugin.settings.excluded_folder, index, index - 1); + yield this.plugin.saveSettings(); + this.display(); + })); + }).addExtraButton((cb) => { + cb.setIcon("down-chevron-glyph").setTooltip("Move down").onClick(() => __async(this, null, function* () { + arrayMove(this.plugin.settings.excluded_folder, index, index + 1); + yield this.plugin.saveSettings(); + this.display(); + })); + }).addExtraButton((cb) => { + cb.setIcon("cross").setTooltip("Delete").onClick(() => __async(this, null, function* () { + this.plugin.settings.excluded_folder.splice(index, 1); + yield this.plugin.saveSettings(); + this.display(); + })); + }); + s.infoEl.remove(); + }); + const statusBarTriggerIndicatorDesc = document.createDocumentFragment(); + statusBarTriggerIndicatorDesc.append("The status bar will display [A] if the trigger is Automatic, and [M] for Manual.", descEl.createEl("br"), "To change the setting, you need to restart Obsidian.", descEl.createEl("br"), "Desktop only."); + new import_obsidian5.Setting(this.containerEl).setName("Status Bar Trigger Indicator").setDesc(statusBarTriggerIndicatorDesc).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.statusBar_trigger_indicator).onChange((value) => __async(this, null, function* () { + this.plugin.settings.statusBar_trigger_indicator = value; + yield this.plugin.saveSettings(); + this.display(); + })); + }); + } +}; + +// main.ts +var AutoNoteMover = class extends import_obsidian6.Plugin { + onload() { + return __async(this, null, function* () { + yield this.loadSettings(); + const folderTagPattern = this.settings.folder_tag_pattern; + const excludedFolder = this.settings.excluded_folder; + const fileCheck = (file, oldPath, caller) => { + if (this.settings.trigger_auto_manual !== "Automatic" && caller !== "cmd") { + return; + } + if (!(file instanceof import_obsidian6.TFile)) + return; + if (oldPath && oldPath.split("/").pop() === file.basename + "." + file.extension) { + return; + } + const excludedFolderLength = excludedFolder.length; + for (let i = 0; i < excludedFolderLength; i++) { + if (!this.settings.use_regex_to_check_for_excluded_folder && excludedFolder[i].folder && file.parent.path === (0, import_obsidian6.normalizePath)(excludedFolder[i].folder)) { + return; + } else if (this.settings.use_regex_to_check_for_excluded_folder && excludedFolder[i].folder) { + const regex = new RegExp(excludedFolder[i].folder); + if (regex.test(file.parent.path)) { + return; + } + } + } + const fileCache = this.app.metadataCache.getFileCache(file); + if (isFmDisable(fileCache)) { + return; + } + const fileName = file.basename; + const fileFullName = file.basename + "." + file.extension; + const settingsLength = folderTagPattern.length; + const cacheTag = (0, import_obsidian6.getAllTags)(fileCache); + for (let i = 0; i < settingsLength; i++) { + const settingFolder = folderTagPattern[i].folder; + const settingTag = folderTagPattern[i].tag; + const settingPattern = folderTagPattern[i].pattern; + if (!settingPattern) { + if (!this.settings.use_regex_to_check_for_tags) { + if (cacheTag.find((e) => e === settingTag)) { + fileMove(this.app, settingFolder, fileFullName, file); + break; + } + } else if (this.settings.use_regex_to_check_for_tags) { + const regex = new RegExp(settingTag); + if (cacheTag.find((e) => regex.test(e))) { + fileMove(this.app, settingFolder, fileFullName, file); + break; + } + } + } else if (!settingTag) { + const regex = new RegExp(settingPattern); + const isMatch = regex.test(fileName); + if (isMatch) { + fileMove(this.app, settingFolder, fileFullName, file); + break; + } + } + } + }; + let triggerIndicator; + const setIndicator = () => { + if (!this.settings.statusBar_trigger_indicator) + return; + triggerIndicator.setText(getTriggerIndicator(this.settings.trigger_auto_manual)); + }; + if (this.settings.statusBar_trigger_indicator) { + triggerIndicator = this.addStatusBarItem(); + setIndicator(); + this.registerDomEvent(window, "change", setIndicator); + } + this.app.workspace.onLayoutReady(() => { + this.registerEvent(this.app.vault.on("create", (file) => fileCheck(file))); + this.registerEvent(this.app.metadataCache.on("changed", (file) => fileCheck(file))); + this.registerEvent(this.app.vault.on("rename", (file, oldPath) => fileCheck(file, oldPath))); + }); + const moveNoteCommand = (view) => { + if (isFmDisable(this.app.metadataCache.getFileCache(view.file))) { + new import_obsidian6.Notice("Auto Note Mover is disabled in the frontmatter."); + return; + } + fileCheck(view.file, void 0, "cmd"); + }; + this.addCommand({ + id: "Move-the-note", + name: "Move the note", + checkCallback: (checking) => { + const markdownView = this.app.workspace.getActiveViewOfType(import_obsidian6.MarkdownView); + if (markdownView) { + if (!checking) { + moveNoteCommand(markdownView); + } + return true; + } + } + }); + this.addCommand({ + id: "Toggle-Auto-Manual", + name: "Toggle Auto-Manual", + callback: () => { + if (this.settings.trigger_auto_manual === "Automatic") { + this.settings.trigger_auto_manual = "Manual"; + this.saveData(this.settings); + new import_obsidian6.Notice("[Auto Note Mover]\nTrigger is Manual."); + } else if (this.settings.trigger_auto_manual === "Manual") { + this.settings.trigger_auto_manual = "Automatic"; + this.saveData(this.settings); + new import_obsidian6.Notice("[Auto Note Mover]\nTrigger is Automatic."); + } + setIndicator(); + } + }); + this.addSettingTab(new AutoNoteMoverSettingTab(this.app, this)); + }); + } + onunload() { + } + loadSettings() { + return __async(this, null, function* () { + this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData()); + }); + } + saveSettings() { + return __async(this, null, function* () { + yield this.saveData(this.settings); + }); + } +}; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/auto-note-mover/manifest.json b/.obsidian/plugins/auto-note-mover/manifest.json new file mode 100644 index 0000000..6a864b7 --- /dev/null +++ b/.obsidian/plugins/auto-note-mover/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "auto-note-mover", + "name": "Auto Note Mover", + "version": "1.2.0", + "minAppVersion": "0.12.0", + "description": "Auto Note Mover will automatically move the active notes to their respective folders according to the rules.", + "author": "faru", + "authorUrl": "https://github.com/farux/", + "isDesktopOnly": false +} diff --git a/.obsidian/plugins/breadcrumbs/data.json b/.obsidian/plugins/breadcrumbs/data.json new file mode 100644 index 0000000..026171c --- /dev/null +++ b/.obsidian/plugins/breadcrumbs/data.json @@ -0,0 +1,278 @@ +{ + "is_dirty": false, + "edge_fields": [ + { + "label": "up" + }, + { + "label": "down" + }, + { + "label": "same" + }, + { + "label": "next" + }, + { + "label": "prev" + } + ], + "edge_field_groups": [ + { + "label": "ups", + "fields": [ + "up" + ] + }, + { + "label": "downs", + "fields": [ + "down" + ] + }, + { + "label": "sames", + "fields": [ + "same" + ] + }, + { + "label": "nexts", + "fields": [ + "next" + ] + }, + { + "label": "prevs", + "fields": [ + "prev" + ] + } + ], + "implied_relations": { + "transitive": [ + { + "name": "", + "rounds": 1, + "chain": [ + { + "field": "up" + } + ], + "close_field": "down", + "close_reversed": true + }, + { + "name": "", + "rounds": 1, + "chain": [ + { + "field": "down" + } + ], + "close_field": "up", + "close_reversed": true + }, + { + "name": "", + "rounds": 1, + "chain": [ + { + "field": "same" + } + ], + "close_field": "same", + "close_reversed": true + }, + { + "name": "", + "rounds": 1, + "chain": [ + { + "field": "next" + } + ], + "close_field": "prev", + "close_reversed": true + }, + { + "name": "", + "rounds": 1, + "chain": [ + { + "field": "prev" + } + ], + "close_field": "next", + "close_reversed": true + } + ] + }, + "explicit_edge_sources": { + "typed_link": {}, + "list_note": { + "default_neighbour_field": "" + }, + "tag_note": { + "default_field": "up" + }, + "regex_note": { + "default_field": "up" + }, + "dendron_note": { + "enabled": false, + "delimiter": ".", + "default_field": "up", + "display_trimmed": false + }, + "johnny_decimal_note": { + "enabled": false, + "delimiter": ".", + "default_field": "up" + }, + "date_note": { + "enabled": false, + "date_format": "yyyy-MM-dd", + "default_field": "next", + "stretch_to_existing": false + } + }, + "views": { + "page": { + "all": { + "sticky": false, + "readable_line_width": true + }, + "trail": { + "enabled": true, + "format": "grid", + "selection": "all", + "default_depth": 999, + "no_path_message": "", + "show_controls": true, + "merge_fields": false, + "field_group_labels": [ + "ups" + ], + "show_node_options": { + "ext": false, + "folder": false, + "alias": false + } + }, + "prev_next": { + "enabled": true, + "show_node_options": { + "ext": false, + "folder": false, + "alias": false + }, + "field_group_labels": { + "prev": [ + "prevs" + ], + "next": [ + "nexts" + ] + } + } + }, + "side": { + "matrix": { + "collapse": false, + "edge_sort_id": { + "field": "basename", + "order": 1 + }, + "show_node_options": { + "ext": false, + "folder": false, + "alias": false + }, + "show_attributes": [ + "source", + "implied_kind", + "round" + ], + "field_group_labels": [ + "ups", + "downs", + "sames", + "nexts", + "prevs" + ] + }, + "tree": { + "collapse": false, + "show_attributes": [], + "merge_fields": false, + "field_group_labels": [ + "downs" + ], + "edge_sort_id": { + "field": "basename", + "order": 1 + }, + "show_node_options": { + "ext": false, + "folder": false, + "alias": false + } + } + }, + "codeblocks": { + "show_node_options": { + "ext": false, + "folder": false, + "alias": false + } + } + }, + "commands": { + "rebuild_graph": { + "notify": true, + "trigger": { + "note_save": false, + "layout_change": false + } + }, + "list_index": { + "default_options": { + "fields": [], + "indent": "\\t", + "link_kind": "wiki", + "show_attributes": [], + "field_group_labels": [], + "edge_sort_id": { + "order": 1, + "field": "basename" + }, + "show_node_options": { + "ext": false, + "alias": true, + "folder": false + } + } + }, + "freeze_implied_edges": { + "default_options": { + "destination": "frontmatter" + } + }, + "thread": { + "default_options": { + "destination": "frontmatter", + "target_path_template": "{{source.folder}}/{{attr.field}} {{source.basename}}" + } + } + }, + "suggestors": { + "edge_field": { + "enabled": false, + "trigger": "." + } + }, + "debug": { + "level": "INFO" + } +} \ No newline at end of file diff --git a/.obsidian/plugins/breadcrumbs/main.js b/.obsidian/plugins/breadcrumbs/main.js new file mode 100644 index 0000000..d2e148f --- /dev/null +++ b/.obsidian/plugins/breadcrumbs/main.js @@ -0,0 +1,41387 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// node_modules/obsidian-dataview/lib/index.js +var require_lib = __commonJS({ + "node_modules/obsidian-dataview/lib/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + require("obsidian"); + var LuxonError2 = class extends Error { + }; + var InvalidDateTimeError2 = class extends LuxonError2 { + constructor(reason) { + super(`Invalid DateTime: ${reason.toMessage()}`); + } + }; + var InvalidIntervalError2 = class extends LuxonError2 { + constructor(reason) { + super(`Invalid Interval: ${reason.toMessage()}`); + } + }; + var InvalidDurationError2 = class extends LuxonError2 { + constructor(reason) { + super(`Invalid Duration: ${reason.toMessage()}`); + } + }; + var ConflictingSpecificationError2 = class extends LuxonError2 { + }; + var InvalidUnitError2 = class extends LuxonError2 { + constructor(unit) { + super(`Invalid unit ${unit}`); + } + }; + var InvalidArgumentError2 = class extends LuxonError2 { + }; + var ZoneIsAbstractError2 = class extends LuxonError2 { + constructor() { + super("Zone is an abstract class"); + } + }; + var n2 = "numeric"; + var s2 = "short"; + var l2 = "long"; + var DATE_SHORT2 = { + year: n2, + month: n2, + day: n2 + }; + var DATE_MED2 = { + year: n2, + month: s2, + day: n2 + }; + var DATE_MED_WITH_WEEKDAY2 = { + year: n2, + month: s2, + day: n2, + weekday: s2 + }; + var DATE_FULL2 = { + year: n2, + month: l2, + day: n2 + }; + var DATE_HUGE2 = { + year: n2, + month: l2, + day: n2, + weekday: l2 + }; + var TIME_SIMPLE2 = { + hour: n2, + minute: n2 + }; + var TIME_WITH_SECONDS2 = { + hour: n2, + minute: n2, + second: n2 + }; + var TIME_WITH_SHORT_OFFSET2 = { + hour: n2, + minute: n2, + second: n2, + timeZoneName: s2 + }; + var TIME_WITH_LONG_OFFSET2 = { + hour: n2, + minute: n2, + second: n2, + timeZoneName: l2 + }; + var TIME_24_SIMPLE2 = { + hour: n2, + minute: n2, + hourCycle: "h23" + }; + var TIME_24_WITH_SECONDS2 = { + hour: n2, + minute: n2, + second: n2, + hourCycle: "h23" + }; + var TIME_24_WITH_SHORT_OFFSET2 = { + hour: n2, + minute: n2, + second: n2, + hourCycle: "h23", + timeZoneName: s2 + }; + var TIME_24_WITH_LONG_OFFSET2 = { + hour: n2, + minute: n2, + second: n2, + hourCycle: "h23", + timeZoneName: l2 + }; + var DATETIME_SHORT2 = { + year: n2, + month: n2, + day: n2, + hour: n2, + minute: n2 + }; + var DATETIME_SHORT_WITH_SECONDS2 = { + year: n2, + month: n2, + day: n2, + hour: n2, + minute: n2, + second: n2 + }; + var DATETIME_MED2 = { + year: n2, + month: s2, + day: n2, + hour: n2, + minute: n2 + }; + var DATETIME_MED_WITH_SECONDS2 = { + year: n2, + month: s2, + day: n2, + hour: n2, + minute: n2, + second: n2 + }; + var DATETIME_MED_WITH_WEEKDAY2 = { + year: n2, + month: s2, + day: n2, + weekday: s2, + hour: n2, + minute: n2 + }; + var DATETIME_FULL2 = { + year: n2, + month: l2, + day: n2, + hour: n2, + minute: n2, + timeZoneName: s2 + }; + var DATETIME_FULL_WITH_SECONDS2 = { + year: n2, + month: l2, + day: n2, + hour: n2, + minute: n2, + second: n2, + timeZoneName: s2 + }; + var DATETIME_HUGE2 = { + year: n2, + month: l2, + day: n2, + weekday: l2, + hour: n2, + minute: n2, + timeZoneName: l2 + }; + var DATETIME_HUGE_WITH_SECONDS2 = { + year: n2, + month: l2, + day: n2, + weekday: l2, + hour: n2, + minute: n2, + second: n2, + timeZoneName: l2 + }; + var Zone2 = class { + /** + * The type of zone + * @abstract + * @type {string} + */ + get type() { + throw new ZoneIsAbstractError2(); + } + /** + * The name of this zone. + * @abstract + * @type {string} + */ + get name() { + throw new ZoneIsAbstractError2(); + } + get ianaName() { + return this.name; + } + /** + * Returns whether the offset is known to be fixed for the whole year. + * @abstract + * @type {boolean} + */ + get isUniversal() { + throw new ZoneIsAbstractError2(); + } + /** + * Returns the offset's common name (such as EST) at the specified timestamp + * @abstract + * @param {number} ts - Epoch milliseconds for which to get the name + * @param {Object} opts - Options to affect the format + * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. + * @param {string} opts.locale - What locale to return the offset name in. + * @return {string} + */ + offsetName(ts, opts) { + throw new ZoneIsAbstractError2(); + } + /** + * Returns the offset's value as a string + * @abstract + * @param {number} ts - Epoch milliseconds for which to get the offset + * @param {string} format - What style of offset to return. + * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively + * @return {string} + */ + formatOffset(ts, format) { + throw new ZoneIsAbstractError2(); + } + /** + * Return the offset in minutes for this zone at the specified timestamp. + * @abstract + * @param {number} ts - Epoch milliseconds for which to compute the offset + * @return {number} + */ + offset(ts) { + throw new ZoneIsAbstractError2(); + } + /** + * Return whether this Zone is equal to another zone + * @abstract + * @param {Zone} otherZone - the zone to compare + * @return {boolean} + */ + equals(otherZone) { + throw new ZoneIsAbstractError2(); + } + /** + * Return whether this Zone is valid. + * @abstract + * @type {boolean} + */ + get isValid() { + throw new ZoneIsAbstractError2(); + } + }; + var singleton$1 = null; + var SystemZone2 = class _SystemZone extends Zone2 { + /** + * Get a singleton instance of the local zone + * @return {SystemZone} + */ + static get instance() { + if (singleton$1 === null) { + singleton$1 = new _SystemZone(); + } + return singleton$1; + } + /** @override **/ + get type() { + return "system"; + } + /** @override **/ + get name() { + return new Intl.DateTimeFormat().resolvedOptions().timeZone; + } + /** @override **/ + get isUniversal() { + return false; + } + /** @override **/ + offsetName(ts, { format, locale }) { + return parseZoneInfo2(ts, format, locale); + } + /** @override **/ + formatOffset(ts, format) { + return formatOffset2(this.offset(ts), format); + } + /** @override **/ + offset(ts) { + return -new Date(ts).getTimezoneOffset(); + } + /** @override **/ + equals(otherZone) { + return otherZone.type === "system"; + } + /** @override **/ + get isValid() { + return true; + } + }; + var dtfCache2 = {}; + function makeDTF2(zone) { + if (!dtfCache2[zone]) { + dtfCache2[zone] = new Intl.DateTimeFormat("en-US", { + hour12: false, + timeZone: zone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + era: "short" + }); + } + return dtfCache2[zone]; + } + var typeToPos2 = { + year: 0, + month: 1, + day: 2, + era: 3, + hour: 4, + minute: 5, + second: 6 + }; + function hackyOffset2(dtf, date) { + const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; + return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; + } + function partsOffset2(dtf, date) { + const formatted = dtf.formatToParts(date); + const filled = []; + for (let i = 0; i < formatted.length; i++) { + const { type, value } = formatted[i]; + const pos = typeToPos2[type]; + if (type === "era") { + filled[pos] = value; + } else if (!isUndefined2(pos)) { + filled[pos] = parseInt(value, 10); + } + } + return filled; + } + var ianaZoneCache2 = {}; + var IANAZone2 = class _IANAZone extends Zone2 { + /** + * @param {string} name - Zone name + * @return {IANAZone} + */ + static create(name) { + if (!ianaZoneCache2[name]) { + ianaZoneCache2[name] = new _IANAZone(name); + } + return ianaZoneCache2[name]; + } + /** + * Reset local caches. Should only be necessary in testing scenarios. + * @return {void} + */ + static resetCache() { + ianaZoneCache2 = {}; + dtfCache2 = {}; + } + /** + * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that. + * @param {string} s - The string to check validity on + * @example IANAZone.isValidSpecifier("America/New_York") //=> true + * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false + * @deprecated This method returns false for some valid IANA names. Use isValidZone instead. + * @return {boolean} + */ + static isValidSpecifier(s3) { + return this.isValidZone(s3); + } + /** + * Returns whether the provided string identifies a real zone + * @param {string} zone - The string to check + * @example IANAZone.isValidZone("America/New_York") //=> true + * @example IANAZone.isValidZone("Fantasia/Castle") //=> false + * @example IANAZone.isValidZone("Sport~~blorp") //=> false + * @return {boolean} + */ + static isValidZone(zone) { + if (!zone) { + return false; + } + try { + new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); + return true; + } catch (e) { + return false; + } + } + constructor(name) { + super(); + this.zoneName = name; + this.valid = _IANAZone.isValidZone(name); + } + /** @override **/ + get type() { + return "iana"; + } + /** @override **/ + get name() { + return this.zoneName; + } + /** @override **/ + get isUniversal() { + return false; + } + /** @override **/ + offsetName(ts, { format, locale }) { + return parseZoneInfo2(ts, format, locale, this.name); + } + /** @override **/ + formatOffset(ts, format) { + return formatOffset2(this.offset(ts), format); + } + /** @override **/ + offset(ts) { + const date = new Date(ts); + if (isNaN(date)) + return NaN; + const dtf = makeDTF2(this.name); + let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset2(dtf, date) : hackyOffset2(dtf, date); + if (adOrBc === "BC") { + year = -Math.abs(year) + 1; + } + const adjustedHour = hour === 24 ? 0 : hour; + const asUTC = objToLocalTS2({ + year, + month, + day, + hour: adjustedHour, + minute, + second, + millisecond: 0 + }); + let asTS = +date; + const over = asTS % 1e3; + asTS -= over >= 0 ? over : 1e3 + over; + return (asUTC - asTS) / (60 * 1e3); + } + /** @override **/ + equals(otherZone) { + return otherZone.type === "iana" && otherZone.name === this.name; + } + /** @override **/ + get isValid() { + return this.valid; + } + }; + var intlLFCache2 = {}; + function getCachedLF2(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlLFCache2[key]; + if (!dtf) { + dtf = new Intl.ListFormat(locString, opts); + intlLFCache2[key] = dtf; + } + return dtf; + } + var intlDTCache2 = {}; + function getCachedDTF2(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlDTCache2[key]; + if (!dtf) { + dtf = new Intl.DateTimeFormat(locString, opts); + intlDTCache2[key] = dtf; + } + return dtf; + } + var intlNumCache2 = {}; + function getCachedINF2(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let inf = intlNumCache2[key]; + if (!inf) { + inf = new Intl.NumberFormat(locString, opts); + intlNumCache2[key] = inf; + } + return inf; + } + var intlRelCache2 = {}; + function getCachedRTF2(locString, opts = {}) { + const { base, ...cacheKeyOpts } = opts; + const key = JSON.stringify([locString, cacheKeyOpts]); + let inf = intlRelCache2[key]; + if (!inf) { + inf = new Intl.RelativeTimeFormat(locString, opts); + intlRelCache2[key] = inf; + } + return inf; + } + var sysLocaleCache2 = null; + function systemLocale2() { + if (sysLocaleCache2) { + return sysLocaleCache2; + } else { + sysLocaleCache2 = new Intl.DateTimeFormat().resolvedOptions().locale; + return sysLocaleCache2; + } + } + function parseLocaleString2(localeStr) { + const xIndex = localeStr.indexOf("-x-"); + if (xIndex !== -1) { + localeStr = localeStr.substring(0, xIndex); + } + const uIndex = localeStr.indexOf("-u-"); + if (uIndex === -1) { + return [localeStr]; + } else { + let options; + let selectedStr; + try { + options = getCachedDTF2(localeStr).resolvedOptions(); + selectedStr = localeStr; + } catch (e) { + const smaller = localeStr.substring(0, uIndex); + options = getCachedDTF2(smaller).resolvedOptions(); + selectedStr = smaller; + } + const { numberingSystem, calendar } = options; + return [selectedStr, numberingSystem, calendar]; + } + } + function intlConfigString2(localeStr, numberingSystem, outputCalendar) { + if (outputCalendar || numberingSystem) { + if (!localeStr.includes("-u-")) { + localeStr += "-u"; + } + if (outputCalendar) { + localeStr += `-ca-${outputCalendar}`; + } + if (numberingSystem) { + localeStr += `-nu-${numberingSystem}`; + } + return localeStr; + } else { + return localeStr; + } + } + function mapMonths2(f) { + const ms = []; + for (let i = 1; i <= 12; i++) { + const dt = DateTime2.utc(2009, i, 1); + ms.push(f(dt)); + } + return ms; + } + function mapWeekdays2(f) { + const ms = []; + for (let i = 1; i <= 7; i++) { + const dt = DateTime2.utc(2016, 11, 13 + i); + ms.push(f(dt)); + } + return ms; + } + function listStuff2(loc, length, englishFn, intlFn) { + const mode = loc.listingMode(); + if (mode === "error") { + return null; + } else if (mode === "en") { + return englishFn(length); + } else { + return intlFn(length); + } + } + function supportsFastNumbers2(loc) { + if (loc.numberingSystem && loc.numberingSystem !== "latn") { + return false; + } else { + return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; + } + } + var PolyNumberFormatter2 = class { + constructor(intl, forceSimple, opts) { + this.padTo = opts.padTo || 0; + this.floor = opts.floor || false; + const { padTo, floor, ...otherOpts } = opts; + if (!forceSimple || Object.keys(otherOpts).length > 0) { + const intlOpts = { useGrouping: false, ...opts }; + if (opts.padTo > 0) + intlOpts.minimumIntegerDigits = opts.padTo; + this.inf = getCachedINF2(intl, intlOpts); + } + } + format(i) { + if (this.inf) { + const fixed = this.floor ? Math.floor(i) : i; + return this.inf.format(fixed); + } else { + const fixed = this.floor ? Math.floor(i) : roundTo2(i, 3); + return padStart2(fixed, this.padTo); + } + } + }; + var PolyDateFormatter2 = class { + constructor(dt, intl, opts) { + this.opts = opts; + this.originalZone = void 0; + let z2 = void 0; + if (this.opts.timeZone) { + this.dt = dt; + } else if (dt.zone.type === "fixed") { + const gmtOffset = -1 * (dt.offset / 60); + const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; + if (dt.offset !== 0 && IANAZone2.create(offsetZ).valid) { + z2 = offsetZ; + this.dt = dt; + } else { + z2 = "UTC"; + this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset }); + this.originalZone = dt.zone; + } + } else if (dt.zone.type === "system") { + this.dt = dt; + } else if (dt.zone.type === "iana") { + this.dt = dt; + z2 = dt.zone.name; + } else { + z2 = "UTC"; + this.dt = dt.setZone("UTC").plus({ minutes: dt.offset }); + this.originalZone = dt.zone; + } + const intlOpts = { ...this.opts }; + intlOpts.timeZone = intlOpts.timeZone || z2; + this.dtf = getCachedDTF2(intl, intlOpts); + } + format() { + if (this.originalZone) { + return this.formatToParts().map(({ value }) => value).join(""); + } + return this.dtf.format(this.dt.toJSDate()); + } + formatToParts() { + const parts = this.dtf.formatToParts(this.dt.toJSDate()); + if (this.originalZone) { + return parts.map((part) => { + if (part.type === "timeZoneName") { + const offsetName = this.originalZone.offsetName(this.dt.ts, { + locale: this.dt.locale, + format: this.opts.timeZoneName + }); + return { + ...part, + value: offsetName + }; + } else { + return part; + } + }); + } + return parts; + } + resolvedOptions() { + return this.dtf.resolvedOptions(); + } + }; + var PolyRelFormatter2 = class { + constructor(intl, isEnglish, opts) { + this.opts = { style: "long", ...opts }; + if (!isEnglish && hasRelative2()) { + this.rtf = getCachedRTF2(intl, opts); + } + } + format(count, unit) { + if (this.rtf) { + return this.rtf.format(count, unit); + } else { + return formatRelativeTime2(unit, count, this.opts.numeric, this.opts.style !== "long"); + } + } + formatToParts(count, unit) { + if (this.rtf) { + return this.rtf.formatToParts(count, unit); + } else { + return []; + } + } + }; + var Locale2 = class _Locale { + static fromOpts(opts) { + return _Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); + } + static create(locale, numberingSystem, outputCalendar, defaultToEN = false) { + const specifiedLocale = locale || Settings2.defaultLocale; + const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale2()); + const numberingSystemR = numberingSystem || Settings2.defaultNumberingSystem; + const outputCalendarR = outputCalendar || Settings2.defaultOutputCalendar; + return new _Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale); + } + static resetCache() { + sysLocaleCache2 = null; + intlDTCache2 = {}; + intlNumCache2 = {}; + intlRelCache2 = {}; + } + static fromObject({ locale, numberingSystem, outputCalendar } = {}) { + return _Locale.create(locale, numberingSystem, outputCalendar); + } + constructor(locale, numbering, outputCalendar, specifiedLocale) { + const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString2(locale); + this.locale = parsedLocale; + this.numberingSystem = numbering || parsedNumberingSystem || null; + this.outputCalendar = outputCalendar || parsedOutputCalendar || null; + this.intl = intlConfigString2(this.locale, this.numberingSystem, this.outputCalendar); + this.weekdaysCache = { format: {}, standalone: {} }; + this.monthsCache = { format: {}, standalone: {} }; + this.meridiemCache = null; + this.eraCache = {}; + this.specifiedLocale = specifiedLocale; + this.fastNumbersCached = null; + } + get fastNumbers() { + if (this.fastNumbersCached == null) { + this.fastNumbersCached = supportsFastNumbers2(this); + } + return this.fastNumbersCached; + } + listingMode() { + const isActuallyEn = this.isEnglish(); + const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); + return isActuallyEn && hasNoWeirdness ? "en" : "intl"; + } + clone(alts) { + if (!alts || Object.getOwnPropertyNames(alts).length === 0) { + return this; + } else { + return _Locale.create( + alts.locale || this.specifiedLocale, + alts.numberingSystem || this.numberingSystem, + alts.outputCalendar || this.outputCalendar, + alts.defaultToEN || false + ); + } + } + redefaultToEN(alts = {}) { + return this.clone({ ...alts, defaultToEN: true }); + } + redefaultToSystem(alts = {}) { + return this.clone({ ...alts, defaultToEN: false }); + } + months(length, format = false) { + return listStuff2(this, length, months2, () => { + const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; + if (!this.monthsCache[formatStr][length]) { + this.monthsCache[formatStr][length] = mapMonths2((dt) => this.extract(dt, intl, "month")); + } + return this.monthsCache[formatStr][length]; + }); + } + weekdays(length, format = false) { + return listStuff2(this, length, weekdays2, () => { + const intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone"; + if (!this.weekdaysCache[formatStr][length]) { + this.weekdaysCache[formatStr][length] = mapWeekdays2( + (dt) => this.extract(dt, intl, "weekday") + ); + } + return this.weekdaysCache[formatStr][length]; + }); + } + meridiems() { + return listStuff2( + this, + void 0, + () => meridiems2, + () => { + if (!this.meridiemCache) { + const intl = { hour: "numeric", hourCycle: "h12" }; + this.meridiemCache = [DateTime2.utc(2016, 11, 13, 9), DateTime2.utc(2016, 11, 13, 19)].map( + (dt) => this.extract(dt, intl, "dayperiod") + ); + } + return this.meridiemCache; + } + ); + } + eras(length) { + return listStuff2(this, length, eras2, () => { + const intl = { era: length }; + if (!this.eraCache[length]) { + this.eraCache[length] = [DateTime2.utc(-40, 1, 1), DateTime2.utc(2017, 1, 1)].map( + (dt) => this.extract(dt, intl, "era") + ); + } + return this.eraCache[length]; + }); + } + extract(dt, intlOpts, field) { + const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field); + return matching ? matching.value : null; + } + numberFormatter(opts = {}) { + return new PolyNumberFormatter2(this.intl, opts.forceSimple || this.fastNumbers, opts); + } + dtFormatter(dt, intlOpts = {}) { + return new PolyDateFormatter2(dt, this.intl, intlOpts); + } + relFormatter(opts = {}) { + return new PolyRelFormatter2(this.intl, this.isEnglish(), opts); + } + listFormatter(opts = {}) { + return getCachedLF2(this.intl, opts); + } + isEnglish() { + return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); + } + equals(other) { + return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; + } + }; + var singleton3 = null; + var FixedOffsetZone2 = class _FixedOffsetZone extends Zone2 { + /** + * Get a singleton instance of UTC + * @return {FixedOffsetZone} + */ + static get utcInstance() { + if (singleton3 === null) { + singleton3 = new _FixedOffsetZone(0); + } + return singleton3; + } + /** + * Get an instance with a specified offset + * @param {number} offset - The offset in minutes + * @return {FixedOffsetZone} + */ + static instance(offset3) { + return offset3 === 0 ? _FixedOffsetZone.utcInstance : new _FixedOffsetZone(offset3); + } + /** + * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" + * @param {string} s - The offset string to parse + * @example FixedOffsetZone.parseSpecifier("UTC+6") + * @example FixedOffsetZone.parseSpecifier("UTC+06") + * @example FixedOffsetZone.parseSpecifier("UTC-6:00") + * @return {FixedOffsetZone} + */ + static parseSpecifier(s3) { + if (s3) { + const r = s3.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); + if (r) { + return new _FixedOffsetZone(signedOffset2(r[1], r[2])); + } + } + return null; + } + constructor(offset3) { + super(); + this.fixed = offset3; + } + /** @override **/ + get type() { + return "fixed"; + } + /** @override **/ + get name() { + return this.fixed === 0 ? "UTC" : `UTC${formatOffset2(this.fixed, "narrow")}`; + } + get ianaName() { + if (this.fixed === 0) { + return "Etc/UTC"; + } else { + return `Etc/GMT${formatOffset2(-this.fixed, "narrow")}`; + } + } + /** @override **/ + offsetName() { + return this.name; + } + /** @override **/ + formatOffset(ts, format) { + return formatOffset2(this.fixed, format); + } + /** @override **/ + get isUniversal() { + return true; + } + /** @override **/ + offset() { + return this.fixed; + } + /** @override **/ + equals(otherZone) { + return otherZone.type === "fixed" && otherZone.fixed === this.fixed; + } + /** @override **/ + get isValid() { + return true; + } + }; + var InvalidZone2 = class extends Zone2 { + constructor(zoneName) { + super(); + this.zoneName = zoneName; + } + /** @override **/ + get type() { + return "invalid"; + } + /** @override **/ + get name() { + return this.zoneName; + } + /** @override **/ + get isUniversal() { + return false; + } + /** @override **/ + offsetName() { + return null; + } + /** @override **/ + formatOffset() { + return ""; + } + /** @override **/ + offset() { + return NaN; + } + /** @override **/ + equals() { + return false; + } + /** @override **/ + get isValid() { + return false; + } + }; + function normalizeZone2(input, defaultZone3) { + if (isUndefined2(input) || input === null) { + return defaultZone3; + } else if (input instanceof Zone2) { + return input; + } else if (isString2(input)) { + const lowered = input.toLowerCase(); + if (lowered === "default") + return defaultZone3; + else if (lowered === "local" || lowered === "system") + return SystemZone2.instance; + else if (lowered === "utc" || lowered === "gmt") + return FixedOffsetZone2.utcInstance; + else + return FixedOffsetZone2.parseSpecifier(lowered) || IANAZone2.create(input); + } else if (isNumber2(input)) { + return FixedOffsetZone2.instance(input); + } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { + return input; + } else { + return new InvalidZone2(input); + } + } + var now3 = () => Date.now(); + var defaultZone2 = "system"; + var defaultLocale2 = null; + var defaultNumberingSystem2 = null; + var defaultOutputCalendar2 = null; + var twoDigitCutoffYear2 = 60; + var throwOnInvalid2; + var Settings2 = class { + /** + * Get the callback for returning the current timestamp. + * @type {function} + */ + static get now() { + return now3; + } + /** + * Set the callback for returning the current timestamp. + * The function should return a number, which will be interpreted as an Epoch millisecond count + * @type {function} + * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future + * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time + */ + static set now(n3) { + now3 = n3; + } + /** + * Set the default time zone to create DateTimes in. Does not affect existing instances. + * Use the value "system" to reset this value to the system's time zone. + * @type {string} + */ + static set defaultZone(zone) { + defaultZone2 = zone; + } + /** + * Get the default time zone object currently used to create DateTimes. Does not affect existing instances. + * The default value is the system's time zone (the one set on the machine that runs this code). + * @type {Zone} + */ + static get defaultZone() { + return normalizeZone2(defaultZone2, SystemZone2.instance); + } + /** + * Get the default locale to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultLocale() { + return defaultLocale2; + } + /** + * Set the default locale to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultLocale(locale) { + defaultLocale2 = locale; + } + /** + * Get the default numbering system to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultNumberingSystem() { + return defaultNumberingSystem2; + } + /** + * Set the default numbering system to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultNumberingSystem(numberingSystem) { + defaultNumberingSystem2 = numberingSystem; + } + /** + * Get the default output calendar to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultOutputCalendar() { + return defaultOutputCalendar2; + } + /** + * Set the default output calendar to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultOutputCalendar(outputCalendar) { + defaultOutputCalendar2 = outputCalendar; + } + /** + * Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. + * @type {number} + */ + static get twoDigitCutoffYear() { + return twoDigitCutoffYear2; + } + /** + * Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. + * @type {number} + * @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpreted as current century + * @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050 + * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50 + * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50 + */ + static set twoDigitCutoffYear(cutoffYear) { + twoDigitCutoffYear2 = cutoffYear % 100; + } + /** + * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals + * @type {boolean} + */ + static get throwOnInvalid() { + return throwOnInvalid2; + } + /** + * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals + * @type {boolean} + */ + static set throwOnInvalid(t) { + throwOnInvalid2 = t; + } + /** + * Reset Luxon's global caches. Should only be necessary in testing scenarios. + * @return {void} + */ + static resetCaches() { + Locale2.resetCache(); + IANAZone2.resetCache(); + } + }; + function isUndefined2(o) { + return typeof o === "undefined"; + } + function isNumber2(o) { + return typeof o === "number"; + } + function isInteger2(o) { + return typeof o === "number" && o % 1 === 0; + } + function isString2(o) { + return typeof o === "string"; + } + function isDate2(o) { + return Object.prototype.toString.call(o) === "[object Date]"; + } + function hasRelative2() { + try { + return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; + } catch (e) { + return false; + } + } + function maybeArray2(thing) { + return Array.isArray(thing) ? thing : [thing]; + } + function bestBy2(arr, by, compare) { + if (arr.length === 0) { + return void 0; + } + return arr.reduce((best, next) => { + const pair = [by(next), next]; + if (!best) { + return pair; + } else if (compare(best[0], pair[0]) === best[0]) { + return best; + } else { + return pair; + } + }, null)[1]; + } + function pick2(obj, keys) { + return keys.reduce((a, k) => { + a[k] = obj[k]; + return a; + }, {}); + } + function hasOwnProperty2(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + function integerBetween2(thing, bottom, top) { + return isInteger2(thing) && thing >= bottom && thing <= top; + } + function floorMod2(x, n3) { + return x - n3 * Math.floor(x / n3); + } + function padStart2(input, n3 = 2) { + const isNeg = input < 0; + let padded; + if (isNeg) { + padded = "-" + ("" + -input).padStart(n3, "0"); + } else { + padded = ("" + input).padStart(n3, "0"); + } + return padded; + } + function parseInteger2(string) { + if (isUndefined2(string) || string === null || string === "") { + return void 0; + } else { + return parseInt(string, 10); + } + } + function parseFloating2(string) { + if (isUndefined2(string) || string === null || string === "") { + return void 0; + } else { + return parseFloat(string); + } + } + function parseMillis2(fraction) { + if (isUndefined2(fraction) || fraction === null || fraction === "") { + return void 0; + } else { + const f = parseFloat("0." + fraction) * 1e3; + return Math.floor(f); + } + } + function roundTo2(number, digits, towardZero = false) { + const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round; + return rounder(number * factor) / factor; + } + function isLeapYear2(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + function daysInYear2(year) { + return isLeapYear2(year) ? 366 : 365; + } + function daysInMonth2(year, month) { + const modMonth = floorMod2(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; + if (modMonth === 2) { + return isLeapYear2(modYear) ? 29 : 28; + } else { + return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; + } + } + function objToLocalTS2(obj) { + let d = Date.UTC( + obj.year, + obj.month - 1, + obj.day, + obj.hour, + obj.minute, + obj.second, + obj.millisecond + ); + if (obj.year < 100 && obj.year >= 0) { + d = new Date(d); + d.setUTCFullYear(obj.year, obj.month - 1, obj.day); + } + return +d; + } + function weeksInWeekYear2(weekYear) { + const p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7, last = weekYear - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7; + return p1 === 4 || p2 === 3 ? 53 : 52; + } + function untruncateYear2(year) { + if (year > 99) { + return year; + } else + return year > Settings2.twoDigitCutoffYear ? 1900 + year : 2e3 + year; + } + function parseZoneInfo2(ts, offsetFormat, locale, timeZone = null) { + const date = new Date(ts), intlOpts = { + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit" + }; + if (timeZone) { + intlOpts.timeZone = timeZone; + } + const modified = { timeZoneName: offsetFormat, ...intlOpts }; + const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename"); + return parsed ? parsed.value : null; + } + function signedOffset2(offHourStr, offMinuteStr) { + let offHour = parseInt(offHourStr, 10); + if (Number.isNaN(offHour)) { + offHour = 0; + } + const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; + return offHour * 60 + offMinSigned; + } + function asNumber2(value) { + const numericValue = Number(value); + if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) + throw new InvalidArgumentError2(`Invalid unit value ${value}`); + return numericValue; + } + function normalizeObject2(obj, normalizer) { + const normalized = {}; + for (const u in obj) { + if (hasOwnProperty2(obj, u)) { + const v = obj[u]; + if (v === void 0 || v === null) + continue; + normalized[normalizer(u)] = asNumber2(v); + } + } + return normalized; + } + function formatOffset2(offset3, format) { + const hours = Math.trunc(Math.abs(offset3 / 60)), minutes = Math.trunc(Math.abs(offset3 % 60)), sign = offset3 >= 0 ? "+" : "-"; + switch (format) { + case "short": + return `${sign}${padStart2(hours, 2)}:${padStart2(minutes, 2)}`; + case "narrow": + return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`; + case "techie": + return `${sign}${padStart2(hours, 2)}${padStart2(minutes, 2)}`; + default: + throw new RangeError(`Value format ${format} is out of range for property format`); + } + } + function timeObject2(obj) { + return pick2(obj, ["hour", "minute", "second", "millisecond"]); + } + var monthsLong2 = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ]; + var monthsShort2 = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ]; + var monthsNarrow2 = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; + function months2(length) { + switch (length) { + case "narrow": + return [...monthsNarrow2]; + case "short": + return [...monthsShort2]; + case "long": + return [...monthsLong2]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; + case "2-digit": + return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; + default: + return null; + } + } + var weekdaysLong2 = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday" + ]; + var weekdaysShort2 = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + var weekdaysNarrow2 = ["M", "T", "W", "T", "F", "S", "S"]; + function weekdays2(length) { + switch (length) { + case "narrow": + return [...weekdaysNarrow2]; + case "short": + return [...weekdaysShort2]; + case "long": + return [...weekdaysLong2]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7"]; + default: + return null; + } + } + var meridiems2 = ["AM", "PM"]; + var erasLong2 = ["Before Christ", "Anno Domini"]; + var erasShort2 = ["BC", "AD"]; + var erasNarrow2 = ["B", "A"]; + function eras2(length) { + switch (length) { + case "narrow": + return [...erasNarrow2]; + case "short": + return [...erasShort2]; + case "long": + return [...erasLong2]; + default: + return null; + } + } + function meridiemForDateTime2(dt) { + return meridiems2[dt.hour < 12 ? 0 : 1]; + } + function weekdayForDateTime2(dt, length) { + return weekdays2(length)[dt.weekday - 1]; + } + function monthForDateTime2(dt, length) { + return months2(length)[dt.month - 1]; + } + function eraForDateTime2(dt, length) { + return eras2(length)[dt.year < 0 ? 0 : 1]; + } + function formatRelativeTime2(unit, count, numeric = "always", narrow = false) { + const units = { + years: ["year", "yr."], + quarters: ["quarter", "qtr."], + months: ["month", "mo."], + weeks: ["week", "wk."], + days: ["day", "day", "days"], + hours: ["hour", "hr."], + minutes: ["minute", "min."], + seconds: ["second", "sec."] + }; + const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; + if (numeric === "auto" && lastable) { + const isDay = unit === "days"; + switch (count) { + case 1: + return isDay ? "tomorrow" : `next ${units[unit][0]}`; + case -1: + return isDay ? "yesterday" : `last ${units[unit][0]}`; + case 0: + return isDay ? "today" : `this ${units[unit][0]}`; + } + } + const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; + return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; + } + function stringifyTokens2(splits, tokenToString) { + let s3 = ""; + for (const token of splits) { + if (token.literal) { + s3 += token.val; + } else { + s3 += tokenToString(token.val); + } + } + return s3; + } + var macroTokenToFormatOpts2 = { + D: DATE_SHORT2, + DD: DATE_MED2, + DDD: DATE_FULL2, + DDDD: DATE_HUGE2, + t: TIME_SIMPLE2, + tt: TIME_WITH_SECONDS2, + ttt: TIME_WITH_SHORT_OFFSET2, + tttt: TIME_WITH_LONG_OFFSET2, + T: TIME_24_SIMPLE2, + TT: TIME_24_WITH_SECONDS2, + TTT: TIME_24_WITH_SHORT_OFFSET2, + TTTT: TIME_24_WITH_LONG_OFFSET2, + f: DATETIME_SHORT2, + ff: DATETIME_MED2, + fff: DATETIME_FULL2, + ffff: DATETIME_HUGE2, + F: DATETIME_SHORT_WITH_SECONDS2, + FF: DATETIME_MED_WITH_SECONDS2, + FFF: DATETIME_FULL_WITH_SECONDS2, + FFFF: DATETIME_HUGE_WITH_SECONDS2 + }; + var Formatter2 = class _Formatter { + static create(locale, opts = {}) { + return new _Formatter(locale, opts); + } + static parseFormat(fmt) { + let current = null, currentFull = "", bracketed = false; + const splits = []; + for (let i = 0; i < fmt.length; i++) { + const c = fmt.charAt(i); + if (c === "'") { + if (currentFull.length > 0) { + splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + } + current = null; + currentFull = ""; + bracketed = !bracketed; + } else if (bracketed) { + currentFull += c; + } else if (c === current) { + currentFull += c; + } else { + if (currentFull.length > 0) { + splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull }); + } + currentFull = c; + current = c; + } + } + if (currentFull.length > 0) { + splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + } + return splits; + } + static macroTokenToFormatOpts(token) { + return macroTokenToFormatOpts2[token]; + } + constructor(locale, formatOpts) { + this.opts = formatOpts; + this.loc = locale; + this.systemLoc = null; + } + formatWithSystemDefault(dt, opts) { + if (this.systemLoc === null) { + this.systemLoc = this.loc.redefaultToSystem(); + } + const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts }); + return df.format(); + } + dtFormatter(dt, opts = {}) { + return this.loc.dtFormatter(dt, { ...this.opts, ...opts }); + } + formatDateTime(dt, opts) { + return this.dtFormatter(dt, opts).format(); + } + formatDateTimeParts(dt, opts) { + return this.dtFormatter(dt, opts).formatToParts(); + } + formatInterval(interval, opts) { + const df = this.dtFormatter(interval.start, opts); + return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); + } + resolvedOptions(dt, opts) { + return this.dtFormatter(dt, opts).resolvedOptions(); + } + num(n3, p = 0) { + if (this.opts.forceSimple) { + return padStart2(n3, p); + } + const opts = { ...this.opts }; + if (p > 0) { + opts.padTo = p; + } + return this.loc.numberFormatter(opts).format(n3); + } + formatDateTimeFromString(dt, fmt) { + const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset3 = (opts) => { + if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { + return "Z"; + } + return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; + }, meridiem = () => knownEnglish ? meridiemForDateTime2(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime2(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime2(dt, length) : string( + standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, + "weekday" + ), maybeMacro = (token) => { + const formatOpts = _Formatter.macroTokenToFormatOpts(token); + if (formatOpts) { + return this.formatWithSystemDefault(dt, formatOpts); + } else { + return token; + } + }, era = (length) => knownEnglish ? eraForDateTime2(dt, length) : string({ era: length }, "era"), tokenToString = (token) => { + switch (token) { + case "S": + return this.num(dt.millisecond); + case "u": + case "SSS": + return this.num(dt.millisecond, 3); + case "s": + return this.num(dt.second); + case "ss": + return this.num(dt.second, 2); + case "uu": + return this.num(Math.floor(dt.millisecond / 10), 2); + case "uuu": + return this.num(Math.floor(dt.millisecond / 100)); + case "m": + return this.num(dt.minute); + case "mm": + return this.num(dt.minute, 2); + case "h": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); + case "hh": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); + case "H": + return this.num(dt.hour); + case "HH": + return this.num(dt.hour, 2); + case "Z": + return formatOffset3({ format: "narrow", allowZ: this.opts.allowZ }); + case "ZZ": + return formatOffset3({ format: "short", allowZ: this.opts.allowZ }); + case "ZZZ": + return formatOffset3({ format: "techie", allowZ: this.opts.allowZ }); + case "ZZZZ": + return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale }); + case "ZZZZZ": + return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale }); + case "z": + return dt.zoneName; + case "a": + return meridiem(); + case "d": + return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day); + case "dd": + return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2); + case "c": + return this.num(dt.weekday); + case "ccc": + return weekday("short", true); + case "cccc": + return weekday("long", true); + case "ccccc": + return weekday("narrow", true); + case "E": + return this.num(dt.weekday); + case "EEE": + return weekday("short", false); + case "EEEE": + return weekday("long", false); + case "EEEEE": + return weekday("narrow", false); + case "L": + return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month); + case "LL": + return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2); + case "LLL": + return month("short", true); + case "LLLL": + return month("long", true); + case "LLLLL": + return month("narrow", true); + case "M": + return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month); + case "MM": + return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2); + case "MMM": + return month("short", false); + case "MMMM": + return month("long", false); + case "MMMMM": + return month("narrow", false); + case "y": + return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year); + case "yy": + return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2); + case "yyyy": + return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4); + case "yyyyyy": + return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6); + case "G": + return era("short"); + case "GG": + return era("long"); + case "GGGGG": + return era("narrow"); + case "kk": + return this.num(dt.weekYear.toString().slice(-2), 2); + case "kkkk": + return this.num(dt.weekYear, 4); + case "W": + return this.num(dt.weekNumber); + case "WW": + return this.num(dt.weekNumber, 2); + case "o": + return this.num(dt.ordinal); + case "ooo": + return this.num(dt.ordinal, 3); + case "q": + return this.num(dt.quarter); + case "qq": + return this.num(dt.quarter, 2); + case "X": + return this.num(Math.floor(dt.ts / 1e3)); + case "x": + return this.num(dt.ts); + default: + return maybeMacro(token); + } + }; + return stringifyTokens2(_Formatter.parseFormat(fmt), tokenToString); + } + formatDurationFromString(dur, fmt) { + const tokenToField = (token) => { + switch (token[0]) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + return "hour"; + case "d": + return "day"; + case "w": + return "week"; + case "M": + return "month"; + case "y": + return "year"; + default: + return null; + } + }, tokenToString = (lildur) => (token) => { + const mapped = tokenToField(token); + if (mapped) { + return this.num(lildur.get(mapped), token.length); + } else { + return token; + } + }, tokens = _Formatter.parseFormat(fmt), realTokens = tokens.reduce( + (found, { literal, val }) => literal ? found : found.concat(val), + [] + ), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)); + return stringifyTokens2(tokens, tokenToString(collapsed)); + } + }; + var Invalid2 = class { + constructor(reason, explanation) { + this.reason = reason; + this.explanation = explanation; + } + toMessage() { + if (this.explanation) { + return `${this.reason}: ${this.explanation}`; + } else { + return this.reason; + } + } + }; + var ianaRegex2 = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; + function combineRegexes2(...regexes) { + const full = regexes.reduce((f, r) => f + r.source, ""); + return RegExp(`^${full}$`); + } + function combineExtractors2(...extractors) { + return (m) => extractors.reduce( + ([mergedVals, mergedZone, cursor], ex) => { + const [val, zone, next] = ex(m, cursor); + return [{ ...mergedVals, ...val }, zone || mergedZone, next]; + }, + [{}, null, 1] + ).slice(0, 2); + } + function parse2(s3, ...patterns) { + if (s3 == null) { + return [null, null]; + } + for (const [regex2, extractor] of patterns) { + const m = regex2.exec(s3); + if (m) { + return extractor(m); + } + } + return [null, null]; + } + function simpleParse2(...keys) { + return (match3, cursor) => { + const ret = {}; + let i; + for (i = 0; i < keys.length; i++) { + ret[keys[i]] = parseInteger2(match3[cursor + i]); + } + return [ret, null, cursor + i]; + }; + } + var offsetRegex2 = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; + var isoExtendedZone2 = `(?:${offsetRegex2.source}?(?:\\[(${ianaRegex2.source})\\])?)?`; + var isoTimeBaseRegex2 = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; + var isoTimeRegex2 = RegExp(`${isoTimeBaseRegex2.source}${isoExtendedZone2}`); + var isoTimeExtensionRegex2 = RegExp(`(?:T${isoTimeRegex2.source})?`); + var isoYmdRegex2 = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; + var isoWeekRegex2 = /(\d{4})-?W(\d\d)(?:-?(\d))?/; + var isoOrdinalRegex2 = /(\d{4})-?(\d{3})/; + var extractISOWeekData2 = simpleParse2("weekYear", "weekNumber", "weekDay"); + var extractISOOrdinalData2 = simpleParse2("year", "ordinal"); + var sqlYmdRegex2 = /(\d{4})-(\d\d)-(\d\d)/; + var sqlTimeRegex2 = RegExp( + `${isoTimeBaseRegex2.source} ?(?:${offsetRegex2.source}|(${ianaRegex2.source}))?` + ); + var sqlTimeExtensionRegex2 = RegExp(`(?: ${sqlTimeRegex2.source})?`); + function int2(match3, pos, fallback) { + const m = match3[pos]; + return isUndefined2(m) ? fallback : parseInteger2(m); + } + function extractISOYmd2(match3, cursor) { + const item = { + year: int2(match3, cursor), + month: int2(match3, cursor + 1, 1), + day: int2(match3, cursor + 2, 1) + }; + return [item, null, cursor + 3]; + } + function extractISOTime2(match3, cursor) { + const item = { + hours: int2(match3, cursor, 0), + minutes: int2(match3, cursor + 1, 0), + seconds: int2(match3, cursor + 2, 0), + milliseconds: parseMillis2(match3[cursor + 3]) + }; + return [item, null, cursor + 4]; + } + function extractISOOffset2(match3, cursor) { + const local = !match3[cursor] && !match3[cursor + 1], fullOffset = signedOffset2(match3[cursor + 1], match3[cursor + 2]), zone = local ? null : FixedOffsetZone2.instance(fullOffset); + return [{}, zone, cursor + 3]; + } + function extractIANAZone2(match3, cursor) { + const zone = match3[cursor] ? IANAZone2.create(match3[cursor]) : null; + return [{}, zone, cursor + 1]; + } + var isoTimeOnly2 = RegExp(`^T?${isoTimeBaseRegex2.source}$`); + var isoDuration2 = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; + function extractISODuration2(match3) { + const [s3, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match3; + const hasNegativePrefix = s3[0] === "-"; + const negativeSeconds = secondStr && secondStr[0] === "-"; + const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num; + return [ + { + years: maybeNegate(parseFloating2(yearStr)), + months: maybeNegate(parseFloating2(monthStr)), + weeks: maybeNegate(parseFloating2(weekStr)), + days: maybeNegate(parseFloating2(dayStr)), + hours: maybeNegate(parseFloating2(hourStr)), + minutes: maybeNegate(parseFloating2(minuteStr)), + seconds: maybeNegate(parseFloating2(secondStr), secondStr === "-0"), + milliseconds: maybeNegate(parseMillis2(millisecondsStr), negativeSeconds) + } + ]; + } + var obsOffsets2 = { + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 + }; + function fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + const result = { + year: yearStr.length === 2 ? untruncateYear2(parseInteger2(yearStr)) : parseInteger2(yearStr), + month: monthsShort2.indexOf(monthStr) + 1, + day: parseInteger2(dayStr), + hour: parseInteger2(hourStr), + minute: parseInteger2(minuteStr) + }; + if (secondStr) + result.second = parseInteger2(secondStr); + if (weekdayStr) { + result.weekday = weekdayStr.length > 3 ? weekdaysLong2.indexOf(weekdayStr) + 1 : weekdaysShort2.indexOf(weekdayStr) + 1; + } + return result; + } + var rfc28222 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; + function extractRFC28222(match3) { + const [ + , + weekdayStr, + dayStr, + monthStr, + yearStr, + hourStr, + minuteStr, + secondStr, + obsOffset, + milOffset, + offHourStr, + offMinuteStr + ] = match3, result = fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + let offset3; + if (obsOffset) { + offset3 = obsOffsets2[obsOffset]; + } else if (milOffset) { + offset3 = 0; + } else { + offset3 = signedOffset2(offHourStr, offMinuteStr); + } + return [result, new FixedOffsetZone2(offset3)]; + } + function preprocessRFC28222(s3) { + return s3.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); + } + var rfc11232 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; + var rfc8502 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; + var ascii2 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; + function extractRFC1123Or8502(match3) { + const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match3, result = fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone2.utcInstance]; + } + function extractASCII2(match3) { + const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match3, result = fromStrings2(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone2.utcInstance]; + } + var isoYmdWithTimeExtensionRegex2 = combineRegexes2(isoYmdRegex2, isoTimeExtensionRegex2); + var isoWeekWithTimeExtensionRegex2 = combineRegexes2(isoWeekRegex2, isoTimeExtensionRegex2); + var isoOrdinalWithTimeExtensionRegex2 = combineRegexes2(isoOrdinalRegex2, isoTimeExtensionRegex2); + var isoTimeCombinedRegex2 = combineRegexes2(isoTimeRegex2); + var extractISOYmdTimeAndOffset2 = combineExtractors2( + extractISOYmd2, + extractISOTime2, + extractISOOffset2, + extractIANAZone2 + ); + var extractISOWeekTimeAndOffset2 = combineExtractors2( + extractISOWeekData2, + extractISOTime2, + extractISOOffset2, + extractIANAZone2 + ); + var extractISOOrdinalDateAndTime2 = combineExtractors2( + extractISOOrdinalData2, + extractISOTime2, + extractISOOffset2, + extractIANAZone2 + ); + var extractISOTimeAndOffset2 = combineExtractors2( + extractISOTime2, + extractISOOffset2, + extractIANAZone2 + ); + function parseISODate2(s3) { + return parse2( + s3, + [isoYmdWithTimeExtensionRegex2, extractISOYmdTimeAndOffset2], + [isoWeekWithTimeExtensionRegex2, extractISOWeekTimeAndOffset2], + [isoOrdinalWithTimeExtensionRegex2, extractISOOrdinalDateAndTime2], + [isoTimeCombinedRegex2, extractISOTimeAndOffset2] + ); + } + function parseRFC2822Date2(s3) { + return parse2(preprocessRFC28222(s3), [rfc28222, extractRFC28222]); + } + function parseHTTPDate2(s3) { + return parse2( + s3, + [rfc11232, extractRFC1123Or8502], + [rfc8502, extractRFC1123Or8502], + [ascii2, extractASCII2] + ); + } + function parseISODuration2(s3) { + return parse2(s3, [isoDuration2, extractISODuration2]); + } + var extractISOTimeOnly2 = combineExtractors2(extractISOTime2); + function parseISOTimeOnly2(s3) { + return parse2(s3, [isoTimeOnly2, extractISOTimeOnly2]); + } + var sqlYmdWithTimeExtensionRegex2 = combineRegexes2(sqlYmdRegex2, sqlTimeExtensionRegex2); + var sqlTimeCombinedRegex2 = combineRegexes2(sqlTimeRegex2); + var extractISOTimeOffsetAndIANAZone2 = combineExtractors2( + extractISOTime2, + extractISOOffset2, + extractIANAZone2 + ); + function parseSQL2(s3) { + return parse2( + s3, + [sqlYmdWithTimeExtensionRegex2, extractISOYmdTimeAndOffset2], + [sqlTimeCombinedRegex2, extractISOTimeOffsetAndIANAZone2] + ); + } + var INVALID$2 = "Invalid Duration"; + var lowOrderMatrix2 = { + weeks: { + days: 7, + hours: 7 * 24, + minutes: 7 * 24 * 60, + seconds: 7 * 24 * 60 * 60, + milliseconds: 7 * 24 * 60 * 60 * 1e3 + }, + days: { + hours: 24, + minutes: 24 * 60, + seconds: 24 * 60 * 60, + milliseconds: 24 * 60 * 60 * 1e3 + }, + hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 }, + minutes: { seconds: 60, milliseconds: 60 * 1e3 }, + seconds: { milliseconds: 1e3 } + }; + var casualMatrix2 = { + years: { + quarters: 4, + months: 12, + weeks: 52, + days: 365, + hours: 365 * 24, + minutes: 365 * 24 * 60, + seconds: 365 * 24 * 60 * 60, + milliseconds: 365 * 24 * 60 * 60 * 1e3 + }, + quarters: { + months: 3, + weeks: 13, + days: 91, + hours: 91 * 24, + minutes: 91 * 24 * 60, + seconds: 91 * 24 * 60 * 60, + milliseconds: 91 * 24 * 60 * 60 * 1e3 + }, + months: { + weeks: 4, + days: 30, + hours: 30 * 24, + minutes: 30 * 24 * 60, + seconds: 30 * 24 * 60 * 60, + milliseconds: 30 * 24 * 60 * 60 * 1e3 + }, + ...lowOrderMatrix2 + }; + var daysInYearAccurate2 = 146097 / 400; + var daysInMonthAccurate2 = 146097 / 4800; + var accurateMatrix2 = { + years: { + quarters: 4, + months: 12, + weeks: daysInYearAccurate2 / 7, + days: daysInYearAccurate2, + hours: daysInYearAccurate2 * 24, + minutes: daysInYearAccurate2 * 24 * 60, + seconds: daysInYearAccurate2 * 24 * 60 * 60, + milliseconds: daysInYearAccurate2 * 24 * 60 * 60 * 1e3 + }, + quarters: { + months: 3, + weeks: daysInYearAccurate2 / 28, + days: daysInYearAccurate2 / 4, + hours: daysInYearAccurate2 * 24 / 4, + minutes: daysInYearAccurate2 * 24 * 60 / 4, + seconds: daysInYearAccurate2 * 24 * 60 * 60 / 4, + milliseconds: daysInYearAccurate2 * 24 * 60 * 60 * 1e3 / 4 + }, + months: { + weeks: daysInMonthAccurate2 / 7, + days: daysInMonthAccurate2, + hours: daysInMonthAccurate2 * 24, + minutes: daysInMonthAccurate2 * 24 * 60, + seconds: daysInMonthAccurate2 * 24 * 60 * 60, + milliseconds: daysInMonthAccurate2 * 24 * 60 * 60 * 1e3 + }, + ...lowOrderMatrix2 + }; + var orderedUnits$1 = [ + "years", + "quarters", + "months", + "weeks", + "days", + "hours", + "minutes", + "seconds", + "milliseconds" + ]; + var reverseUnits2 = orderedUnits$1.slice(0).reverse(); + function clone$1(dur, alts, clear = false) { + const conf = { + values: clear ? alts.values : { ...dur.values, ...alts.values || {} }, + loc: dur.loc.clone(alts.loc), + conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, + matrix: alts.matrix || dur.matrix + }; + return new Duration2(conf); + } + function durationToMillis2(matrix, vals) { + var _a; + let sum = (_a = vals.milliseconds) != null ? _a : 0; + for (const unit of reverseUnits2.slice(1)) { + if (vals[unit]) { + sum += vals[unit] * matrix[unit]["milliseconds"]; + } + } + return sum; + } + function normalizeValues2(matrix, vals) { + const factor = durationToMillis2(matrix, vals) < 0 ? -1 : 1; + orderedUnits$1.reduceRight((previous, current) => { + if (!isUndefined2(vals[current])) { + if (previous) { + const previousVal = vals[previous] * factor; + const conv = matrix[current][previous]; + const rollUp = Math.floor(previousVal / conv); + vals[current] += rollUp * factor; + vals[previous] -= rollUp * conv * factor; + } + return current; + } else { + return previous; + } + }, null); + orderedUnits$1.reduce((previous, current) => { + if (!isUndefined2(vals[current])) { + if (previous) { + const fraction = vals[previous] % 1; + vals[previous] -= fraction; + vals[current] += fraction * matrix[previous][current]; + } + return current; + } else { + return previous; + } + }, null); + } + function removeZeroes2(vals) { + const newVals = {}; + for (const [key, value] of Object.entries(vals)) { + if (value !== 0) { + newVals[key] = value; + } + } + return newVals; + } + var Duration2 = class _Duration { + /** + * @private + */ + constructor(config) { + const accurate = config.conversionAccuracy === "longterm" || false; + let matrix = accurate ? accurateMatrix2 : casualMatrix2; + if (config.matrix) { + matrix = config.matrix; + } + this.values = config.values; + this.loc = config.loc || Locale2.create(); + this.conversionAccuracy = accurate ? "longterm" : "casual"; + this.invalid = config.invalid || null; + this.matrix = matrix; + this.isLuxonDuration = true; + } + /** + * Create Duration from a number of milliseconds. + * @param {number} count of milliseconds + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @return {Duration} + */ + static fromMillis(count, opts) { + return _Duration.fromObject({ milliseconds: count }, opts); + } + /** + * Create a Duration from a JavaScript object with keys like 'years' and 'hours'. + * If this object is empty then a zero milliseconds duration is returned. + * @param {Object} obj - the object to create the DateTime from + * @param {number} obj.years + * @param {number} obj.quarters + * @param {number} obj.months + * @param {number} obj.weeks + * @param {number} obj.days + * @param {number} obj.hours + * @param {number} obj.minutes + * @param {number} obj.seconds + * @param {number} obj.milliseconds + * @param {Object} [opts=[]] - options for creating this Duration + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the custom conversion system to use + * @return {Duration} + */ + static fromObject(obj, opts = {}) { + if (obj == null || typeof obj !== "object") { + throw new InvalidArgumentError2( + `Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}` + ); + } + return new _Duration({ + values: normalizeObject2(obj, _Duration.normalizeUnit), + loc: Locale2.fromObject(opts), + conversionAccuracy: opts.conversionAccuracy, + matrix: opts.matrix + }); + } + /** + * Create a Duration from DurationLike. + * + * @param {Object | number | Duration} durationLike + * One of: + * - object with keys like 'years' and 'hours'. + * - number representing milliseconds + * - Duration instance + * @return {Duration} + */ + static fromDurationLike(durationLike) { + if (isNumber2(durationLike)) { + return _Duration.fromMillis(durationLike); + } else if (_Duration.isDuration(durationLike)) { + return durationLike; + } else if (typeof durationLike === "object") { + return _Duration.fromObject(durationLike); + } else { + throw new InvalidArgumentError2( + `Unknown duration argument ${durationLike} of type ${typeof durationLike}` + ); + } + } + /** + * Create a Duration from an ISO 8601 duration string. + * @param {string} text - text to parse + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the preset conversion system to use + * @see https://en.wikipedia.org/wiki/ISO_8601#Durations + * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } + * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } + * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } + * @return {Duration} + */ + static fromISO(text2, opts) { + const [parsed] = parseISODuration2(text2); + if (parsed) { + return _Duration.fromObject(parsed, opts); + } else { + return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); + } + } + /** + * Create a Duration from an ISO 8601 time string. + * @param {string} text - text to parse + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the conversion system to use + * @see https://en.wikipedia.org/wiki/ISO_8601#Times + * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } + * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @return {Duration} + */ + static fromISOTime(text2, opts) { + const [parsed] = parseISOTimeOnly2(text2); + if (parsed) { + return _Duration.fromObject(parsed, opts); + } else { + return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); + } + } + /** + * Create an invalid Duration. + * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {Duration} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError2("need to specify a reason the Duration is invalid"); + } + const invalid = reason instanceof Invalid2 ? reason : new Invalid2(reason, explanation); + if (Settings2.throwOnInvalid) { + throw new InvalidDurationError2(invalid); + } else { + return new _Duration({ invalid }); + } + } + /** + * @private + */ + static normalizeUnit(unit) { + const normalized = { + year: "years", + years: "years", + quarter: "quarters", + quarters: "quarters", + month: "months", + months: "months", + week: "weeks", + weeks: "weeks", + day: "days", + days: "days", + hour: "hours", + hours: "hours", + minute: "minutes", + minutes: "minutes", + second: "seconds", + seconds: "seconds", + millisecond: "milliseconds", + milliseconds: "milliseconds" + }[unit ? unit.toLowerCase() : unit]; + if (!normalized) + throw new InvalidUnitError2(unit); + return normalized; + } + /** + * Check if an object is a Duration. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isDuration(o) { + return o && o.isLuxonDuration || false; + } + /** + * Get the locale of a Duration, such 'en-GB' + * @type {string} + */ + get locale() { + return this.isValid ? this.loc.locale : null; + } + /** + * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration + * + * @type {string} + */ + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; + } + /** + * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: + * * `S` for milliseconds + * * `s` for seconds + * * `m` for minutes + * * `h` for hours + * * `d` for days + * * `w` for weeks + * * `M` for months + * * `y` for years + * Notes: + * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits + * * Tokens can be escaped by wrapping with single quotes. + * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting. + * @param {string} fmt - the format string + * @param {Object} opts - options + * @param {boolean} [opts.floor=true] - floor numerical values + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" + * @return {string} + */ + toFormat(fmt, opts = {}) { + const fmtOpts = { + ...opts, + floor: opts.round !== false && opts.floor !== false + }; + return this.isValid ? Formatter2.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2; + } + /** + * Returns a string representation of a Duration with all units included. + * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat + * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`. + * @example + * ```js + * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 }) + * dur.toHuman() //=> '1 day, 5 hours, 6 minutes' + * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes' + * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min' + * ``` + */ + toHuman(opts = {}) { + if (!this.isValid) + return INVALID$2; + const l3 = orderedUnits$1.map((unit) => { + const val = this.values[unit]; + if (isUndefined2(val)) { + return null; + } + return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }).format(val); + }).filter((n3) => n3); + return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l3); + } + /** + * Returns a JavaScript object with this Duration's values. + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } + * @return {Object} + */ + toObject() { + if (!this.isValid) + return {}; + return { ...this.values }; + } + /** + * Returns an ISO 8601-compliant string representation of this Duration. + * @see https://en.wikipedia.org/wiki/ISO_8601#Durations + * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' + * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' + * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' + * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' + * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' + * @return {string} + */ + toISO() { + if (!this.isValid) + return null; + let s3 = "P"; + if (this.years !== 0) + s3 += this.years + "Y"; + if (this.months !== 0 || this.quarters !== 0) + s3 += this.months + this.quarters * 3 + "M"; + if (this.weeks !== 0) + s3 += this.weeks + "W"; + if (this.days !== 0) + s3 += this.days + "D"; + if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) + s3 += "T"; + if (this.hours !== 0) + s3 += this.hours + "H"; + if (this.minutes !== 0) + s3 += this.minutes + "M"; + if (this.seconds !== 0 || this.milliseconds !== 0) + s3 += roundTo2(this.seconds + this.milliseconds / 1e3, 3) + "S"; + if (s3 === "P") + s3 += "T0S"; + return s3; + } + /** + * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day. + * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours. + * @see https://en.wikipedia.org/wiki/ISO_8601#Times + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includePrefix=false] - include the `T` prefix + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' + * @return {string} + */ + toISOTime(opts = {}) { + if (!this.isValid) + return null; + const millis = this.toMillis(); + if (millis < 0 || millis >= 864e5) + return null; + opts = { + suppressMilliseconds: false, + suppressSeconds: false, + includePrefix: false, + format: "extended", + ...opts, + includeOffset: false + }; + const dateTime = DateTime2.fromMillis(millis, { zone: "UTC" }); + return dateTime.toISOTime(opts); + } + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. + * @return {string} + */ + toJSON() { + return this.toISO(); + } + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. + * @return {string} + */ + toString() { + return this.toISO(); + } + /** + * Returns an milliseconds value of this Duration. + * @return {number} + */ + toMillis() { + if (!this.isValid) + return NaN; + return durationToMillis2(this.matrix, this.values); + } + /** + * Returns an milliseconds value of this Duration. Alias of {@link toMillis} + * @return {number} + */ + valueOf() { + return this.toMillis(); + } + /** + * Make this Duration longer by the specified amount. Return a newly-constructed Duration. + * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @return {Duration} + */ + plus(duration) { + if (!this.isValid) + return this; + const dur = _Duration.fromDurationLike(duration), result = {}; + for (const k of orderedUnits$1) { + if (hasOwnProperty2(dur.values, k) || hasOwnProperty2(this.values, k)) { + result[k] = dur.get(k) + this.get(k); + } + } + return clone$1(this, { values: result }, true); + } + /** + * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. + * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @return {Duration} + */ + minus(duration) { + if (!this.isValid) + return this; + const dur = _Duration.fromDurationLike(duration); + return this.plus(dur.negate()); + } + /** + * Scale this Duration by the specified amount. Return a newly-constructed Duration. + * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. + * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 } + * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 } + * @return {Duration} + */ + mapUnits(fn) { + if (!this.isValid) + return this; + const result = {}; + for (const k of Object.keys(this.values)) { + result[k] = asNumber2(fn(this.values[k], k)); + } + return clone$1(this, { values: result }, true); + } + /** + * Get the value of unit. + * @param {string} unit - a unit such as 'minute' or 'day' + * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2 + * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0 + * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3 + * @return {number} + */ + get(unit) { + return this[_Duration.normalizeUnit(unit)]; + } + /** + * "Set" the values of specified units. Return a newly-constructed Duration. + * @param {Object} values - a mapping of units to numbers + * @example dur.set({ years: 2017 }) + * @example dur.set({ hours: 8, minutes: 30 }) + * @return {Duration} + */ + set(values) { + if (!this.isValid) + return this; + const mixed = { ...this.values, ...normalizeObject2(values, _Duration.normalizeUnit) }; + return clone$1(this, { values: mixed }); + } + /** + * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. + * @example dur.reconfigure({ locale: 'en-GB' }) + * @return {Duration} + */ + reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) { + const loc = this.loc.clone({ locale, numberingSystem }); + const opts = { loc, matrix, conversionAccuracy }; + return clone$1(this, opts); + } + /** + * Return the length of the duration in the specified unit. + * @param {string} unit - a unit such as 'minutes' or 'days' + * @example Duration.fromObject({years: 1}).as('days') //=> 365 + * @example Duration.fromObject({years: 1}).as('months') //=> 12 + * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 + * @return {number} + */ + as(unit) { + return this.isValid ? this.shiftTo(unit).get(unit) : NaN; + } + /** + * Reduce this Duration to its canonical representation in its current units. + * Assuming the overall value of the Duration is positive, this means: + * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example) + * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise + * the overall value would be negative, see second example) + * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example) + * + * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`. + * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } + * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 } + * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } + * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 } + * @return {Duration} + */ + normalize() { + if (!this.isValid) + return this; + const vals = this.toObject(); + normalizeValues2(this.matrix, vals); + return clone$1(this, { values: vals }, true); + } + /** + * Rescale units to its largest representation + * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 } + * @return {Duration} + */ + rescale() { + if (!this.isValid) + return this; + const vals = removeZeroes2(this.normalize().shiftToAll().toObject()); + return clone$1(this, { values: vals }, true); + } + /** + * Convert this Duration into its representation in a different set of units. + * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } + * @return {Duration} + */ + shiftTo(...units) { + if (!this.isValid) + return this; + if (units.length === 0) { + return this; + } + units = units.map((u) => _Duration.normalizeUnit(u)); + const built = {}, accumulated = {}, vals = this.toObject(); + let lastUnit; + for (const k of orderedUnits$1) { + if (units.indexOf(k) >= 0) { + lastUnit = k; + let own = 0; + for (const ak in accumulated) { + own += this.matrix[ak][k] * accumulated[ak]; + accumulated[ak] = 0; + } + if (isNumber2(vals[k])) { + own += vals[k]; + } + const i = Math.trunc(own); + built[k] = i; + accumulated[k] = (own * 1e3 - i * 1e3) / 1e3; + } else if (isNumber2(vals[k])) { + accumulated[k] = vals[k]; + } + } + for (const key in accumulated) { + if (accumulated[key] !== 0) { + built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; + } + } + normalizeValues2(this.matrix, built); + return clone$1(this, { values: built }, true); + } + /** + * Shift this Duration to all available units. + * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds") + * @return {Duration} + */ + shiftToAll() { + if (!this.isValid) + return this; + return this.shiftTo( + "years", + "months", + "weeks", + "days", + "hours", + "minutes", + "seconds", + "milliseconds" + ); + } + /** + * Return the negative of this Duration. + * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } + * @return {Duration} + */ + negate() { + if (!this.isValid) + return this; + const negated = {}; + for (const k of Object.keys(this.values)) { + negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; + } + return clone$1(this, { values: negated }, true); + } + /** + * Get the years. + * @type {number} + */ + get years() { + return this.isValid ? this.values.years || 0 : NaN; + } + /** + * Get the quarters. + * @type {number} + */ + get quarters() { + return this.isValid ? this.values.quarters || 0 : NaN; + } + /** + * Get the months. + * @type {number} + */ + get months() { + return this.isValid ? this.values.months || 0 : NaN; + } + /** + * Get the weeks + * @type {number} + */ + get weeks() { + return this.isValid ? this.values.weeks || 0 : NaN; + } + /** + * Get the days. + * @type {number} + */ + get days() { + return this.isValid ? this.values.days || 0 : NaN; + } + /** + * Get the hours. + * @type {number} + */ + get hours() { + return this.isValid ? this.values.hours || 0 : NaN; + } + /** + * Get the minutes. + * @type {number} + */ + get minutes() { + return this.isValid ? this.values.minutes || 0 : NaN; + } + /** + * Get the seconds. + * @return {number} + */ + get seconds() { + return this.isValid ? this.values.seconds || 0 : NaN; + } + /** + * Get the milliseconds. + * @return {number} + */ + get milliseconds() { + return this.isValid ? this.values.milliseconds || 0 : NaN; + } + /** + * Returns whether the Duration is invalid. Invalid durations are returned by diff operations + * on invalid DateTimes or Intervals. + * @return {boolean} + */ + get isValid() { + return this.invalid === null; + } + /** + * Returns an error code if this Duration became invalid, or null if the Duration is valid + * @return {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + /** + * Returns an explanation of why this Duration became invalid, or null if the Duration is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + /** + * Equality check + * Two Durations are equal iff they have the same units and the same values for each unit. + * @param {Duration} other + * @return {boolean} + */ + equals(other) { + if (!this.isValid || !other.isValid) { + return false; + } + if (!this.loc.equals(other.loc)) { + return false; + } + function eq(v1, v2) { + if (v1 === void 0 || v1 === 0) + return v2 === void 0 || v2 === 0; + return v1 === v2; + } + for (const u of orderedUnits$1) { + if (!eq(this.values[u], other.values[u])) { + return false; + } + } + return true; + } + }; + var INVALID$1 = "Invalid Interval"; + function validateStartEnd2(start, end) { + if (!start || !start.isValid) { + return Interval2.invalid("missing or invalid start"); + } else if (!end || !end.isValid) { + return Interval2.invalid("missing or invalid end"); + } else if (end < start) { + return Interval2.invalid( + "end before start", + `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}` + ); + } else { + return null; + } + } + var Interval2 = class _Interval { + /** + * @private + */ + constructor(config) { + this.s = config.start; + this.e = config.end; + this.invalid = config.invalid || null; + this.isLuxonInterval = true; + } + /** + * Create an invalid Interval. + * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {Interval} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError2("need to specify a reason the Interval is invalid"); + } + const invalid = reason instanceof Invalid2 ? reason : new Invalid2(reason, explanation); + if (Settings2.throwOnInvalid) { + throw new InvalidIntervalError2(invalid); + } else { + return new _Interval({ invalid }); + } + } + /** + * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. + * @param {DateTime|Date|Object} start + * @param {DateTime|Date|Object} end + * @return {Interval} + */ + static fromDateTimes(start, end) { + const builtStart = friendlyDateTime2(start), builtEnd = friendlyDateTime2(end); + const validateError = validateStartEnd2(builtStart, builtEnd); + if (validateError == null) { + return new _Interval({ + start: builtStart, + end: builtEnd + }); + } else { + return validateError; + } + } + /** + * Create an Interval from a start DateTime and a Duration to extend to. + * @param {DateTime|Date|Object} start + * @param {Duration|Object|number} duration - the length of the Interval. + * @return {Interval} + */ + static after(start, duration) { + const dur = Duration2.fromDurationLike(duration), dt = friendlyDateTime2(start); + return _Interval.fromDateTimes(dt, dt.plus(dur)); + } + /** + * Create an Interval from an end DateTime and a Duration to extend backwards to. + * @param {DateTime|Date|Object} end + * @param {Duration|Object|number} duration - the length of the Interval. + * @return {Interval} + */ + static before(end, duration) { + const dur = Duration2.fromDurationLike(duration), dt = friendlyDateTime2(end); + return _Interval.fromDateTimes(dt.minus(dur), dt); + } + /** + * Create an Interval from an ISO 8601 string. + * Accepts `/`, `/`, and `/` formats. + * @param {string} text - the ISO string to parse + * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO} + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @return {Interval} + */ + static fromISO(text2, opts) { + const [s3, e] = (text2 || "").split("/", 2); + if (s3 && e) { + let start, startIsValid; + try { + start = DateTime2.fromISO(s3, opts); + startIsValid = start.isValid; + } catch (e2) { + startIsValid = false; + } + let end, endIsValid; + try { + end = DateTime2.fromISO(e, opts); + endIsValid = end.isValid; + } catch (e2) { + endIsValid = false; + } + if (startIsValid && endIsValid) { + return _Interval.fromDateTimes(start, end); + } + if (startIsValid) { + const dur = Duration2.fromISO(e, opts); + if (dur.isValid) { + return _Interval.after(start, dur); + } + } else if (endIsValid) { + const dur = Duration2.fromISO(s3, opts); + if (dur.isValid) { + return _Interval.before(end, dur); + } + } + } + return _Interval.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); + } + /** + * Check if an object is an Interval. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isInterval(o) { + return o && o.isLuxonInterval || false; + } + /** + * Returns the start of the Interval + * @type {DateTime} + */ + get start() { + return this.isValid ? this.s : null; + } + /** + * Returns the end of the Interval + * @type {DateTime} + */ + get end() { + return this.isValid ? this.e : null; + } + /** + * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'. + * @type {boolean} + */ + get isValid() { + return this.invalidReason === null; + } + /** + * Returns an error code if this Interval is invalid, or null if the Interval is valid + * @type {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + /** + * Returns an explanation of why this Interval became invalid, or null if the Interval is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + /** + * Returns the length of the Interval in the specified unit. + * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in. + * @return {number} + */ + length(unit = "milliseconds") { + return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; + } + /** + * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. + * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' + * asks 'what dates are included in this interval?', not 'how many days long is this interval?' + * @param {string} [unit='milliseconds'] - the unit of time to count. + * @return {number} + */ + count(unit = "milliseconds") { + if (!this.isValid) + return NaN; + const start = this.start.startOf(unit), end = this.end.startOf(unit); + return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf()); + } + /** + * Returns whether this Interval's start and end are both in the same unit of time + * @param {string} unit - the unit of time to check sameness on + * @return {boolean} + */ + hasSame(unit) { + return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; + } + /** + * Return whether this Interval has the same start and end DateTimes. + * @return {boolean} + */ + isEmpty() { + return this.s.valueOf() === this.e.valueOf(); + } + /** + * Return whether this Interval's start is after the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isAfter(dateTime) { + if (!this.isValid) + return false; + return this.s > dateTime; + } + /** + * Return whether this Interval's end is before the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isBefore(dateTime) { + if (!this.isValid) + return false; + return this.e <= dateTime; + } + /** + * Return whether this Interval contains the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + contains(dateTime) { + if (!this.isValid) + return false; + return this.s <= dateTime && this.e > dateTime; + } + /** + * "Sets" the start and/or end dates. Returns a newly-constructed Interval. + * @param {Object} values - the values to set + * @param {DateTime} values.start - the starting DateTime + * @param {DateTime} values.end - the ending DateTime + * @return {Interval} + */ + set({ start, end } = {}) { + if (!this.isValid) + return this; + return _Interval.fromDateTimes(start || this.s, end || this.e); + } + /** + * Split this Interval at each of the specified DateTimes + * @param {...DateTime} dateTimes - the unit of time to count. + * @return {Array} + */ + splitAt(...dateTimes) { + if (!this.isValid) + return []; + const sorted = dateTimes.map(friendlyDateTime2).filter((d) => this.contains(d)).sort(), results = []; + let { s: s3 } = this, i = 0; + while (s3 < this.e) { + const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; + results.push(_Interval.fromDateTimes(s3, next)); + s3 = next; + i += 1; + } + return results; + } + /** + * Split this Interval into smaller Intervals, each of the specified length. + * Left over time is grouped into a smaller interval + * @param {Duration|Object|number} duration - The length of each resulting interval. + * @return {Array} + */ + splitBy(duration) { + const dur = Duration2.fromDurationLike(duration); + if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { + return []; + } + let { s: s3 } = this, idx = 1, next; + const results = []; + while (s3 < this.e) { + const added = this.start.plus(dur.mapUnits((x) => x * idx)); + next = +added > +this.e ? this.e : added; + results.push(_Interval.fromDateTimes(s3, next)); + s3 = next; + idx += 1; + } + return results; + } + /** + * Split this Interval into the specified number of smaller intervals. + * @param {number} numberOfParts - The number of Intervals to divide the Interval into. + * @return {Array} + */ + divideEqually(numberOfParts) { + if (!this.isValid) + return []; + return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); + } + /** + * Return whether this Interval overlaps with the specified Interval + * @param {Interval} other + * @return {boolean} + */ + overlaps(other) { + return this.e > other.s && this.s < other.e; + } + /** + * Return whether this Interval's end is adjacent to the specified Interval's start. + * @param {Interval} other + * @return {boolean} + */ + abutsStart(other) { + if (!this.isValid) + return false; + return +this.e === +other.s; + } + /** + * Return whether this Interval's start is adjacent to the specified Interval's end. + * @param {Interval} other + * @return {boolean} + */ + abutsEnd(other) { + if (!this.isValid) + return false; + return +other.e === +this.s; + } + /** + * Return whether this Interval engulfs the start and end of the specified Interval. + * @param {Interval} other + * @return {boolean} + */ + engulfs(other) { + if (!this.isValid) + return false; + return this.s <= other.s && this.e >= other.e; + } + /** + * Return whether this Interval has the same start and end as the specified Interval. + * @param {Interval} other + * @return {boolean} + */ + equals(other) { + if (!this.isValid || !other.isValid) { + return false; + } + return this.s.equals(other.s) && this.e.equals(other.e); + } + /** + * Return an Interval representing the intersection of this Interval and the specified Interval. + * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. + * Returns null if the intersection is empty, meaning, the intervals don't intersect. + * @param {Interval} other + * @return {Interval} + */ + intersection(other) { + if (!this.isValid) + return this; + const s3 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; + if (s3 >= e) { + return null; + } else { + return _Interval.fromDateTimes(s3, e); + } + } + /** + * Return an Interval representing the union of this Interval and the specified Interval. + * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. + * @param {Interval} other + * @return {Interval} + */ + union(other) { + if (!this.isValid) + return this; + const s3 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; + return _Interval.fromDateTimes(s3, e); + } + /** + * Merge an array of Intervals into a equivalent minimal set of Intervals. + * Combines overlapping and adjacent Intervals. + * @param {Array} intervals + * @return {Array} + */ + static merge(intervals) { + const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce( + ([sofar, current], item) => { + if (!current) { + return [sofar, item]; + } else if (current.overlaps(item) || current.abutsStart(item)) { + return [sofar, current.union(item)]; + } else { + return [sofar.concat([current]), item]; + } + }, + [[], null] + ); + if (final) { + found.push(final); + } + return found; + } + /** + * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. + * @param {Array} intervals + * @return {Array} + */ + static xor(intervals) { + let start = null, currentCount = 0; + const results = [], ends = intervals.map((i) => [ + { time: i.s, type: "s" }, + { time: i.e, type: "e" } + ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time); + for (const i of arr) { + currentCount += i.type === "s" ? 1 : -1; + if (currentCount === 1) { + start = i.time; + } else { + if (start && +start !== +i.time) { + results.push(_Interval.fromDateTimes(start, i.time)); + } + start = null; + } + } + return _Interval.merge(results); + } + /** + * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. + * @param {...Interval} intervals + * @return {Array} + */ + difference(...intervals) { + return _Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty()); + } + /** + * Returns a string representation of this Interval appropriate for debugging. + * @return {string} + */ + toString() { + if (!this.isValid) + return INVALID$1; + return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`; + } + /** + * Returns a localized string representing this Interval. Accepts the same options as the + * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as + * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method + * is browser-specific, but in general it will return an appropriate representation of the + * Interval in the assigned locale. Defaults to the system's locale if no locale has been + * specified. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or + * Intl.DateTimeFormat constructor options. + * @param {Object} opts - Options to override the configuration of the start DateTime. + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022 + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022 + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022 + * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM + * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p + * @return {string} + */ + toLocaleString(formatOpts = DATE_SHORT2, opts = {}) { + return this.isValid ? Formatter2.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1; + } + /** + * Returns an ISO 8601-compliant string representation of this Interval. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @param {Object} opts - The same options as {@link DateTime#toISO} + * @return {string} + */ + toISO(opts) { + if (!this.isValid) + return INVALID$1; + return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; + } + /** + * Returns an ISO 8601-compliant string representation of date of this Interval. + * The time components are ignored. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @return {string} + */ + toISODate() { + if (!this.isValid) + return INVALID$1; + return `${this.s.toISODate()}/${this.e.toISODate()}`; + } + /** + * Returns an ISO 8601-compliant string representation of time of this Interval. + * The date components are ignored. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @param {Object} opts - The same options as {@link DateTime#toISO} + * @return {string} + */ + toISOTime(opts) { + if (!this.isValid) + return INVALID$1; + return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; + } + /** + * Returns a string representation of this Interval formatted according to the specified format + * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible + * formatting tool. + * @param {string} dateFormat - The format string. This string formats the start and end time. + * See {@link DateTime#toFormat} for details. + * @param {Object} opts - Options. + * @param {string} [opts.separator = ' – '] - A separator to place between the start and end + * representations. + * @return {string} + */ + toFormat(dateFormat, { separator = " \u2013 " } = {}) { + if (!this.isValid) + return INVALID$1; + return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; + } + /** + * Return a Duration representing the time spanned by this interval. + * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } + * @return {Duration} + */ + toDuration(unit, opts) { + if (!this.isValid) { + return Duration2.invalid(this.invalidReason); + } + return this.e.diff(this.s, unit, opts); + } + /** + * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes + * @param {function} mapFn + * @return {Interval} + * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) + * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) + */ + mapEndpoints(mapFn) { + return _Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); + } + }; + var Info2 = class { + /** + * Return whether the specified zone contains a DST. + * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. + * @return {boolean} + */ + static hasDST(zone = Settings2.defaultZone) { + const proto = DateTime2.now().setZone(zone).set({ month: 12 }); + return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; + } + /** + * Return whether the specified zone is a valid IANA specifier. + * @param {string} zone - Zone to check + * @return {boolean} + */ + static isValidIANAZone(zone) { + return IANAZone2.isValidZone(zone); + } + /** + * Converts the input into a {@link Zone} instance. + * + * * If `input` is already a Zone instance, it is returned unchanged. + * * If `input` is a string containing a valid time zone name, a Zone instance + * with that name is returned. + * * If `input` is a string that doesn't refer to a known time zone, a Zone + * instance with {@link Zone#isValid} == false is returned. + * * If `input is a number, a Zone instance with the specified fixed offset + * in minutes is returned. + * * If `input` is `null` or `undefined`, the default zone is returned. + * @param {string|Zone|number} [input] - the value to be converted + * @return {Zone} + */ + static normalizeZone(input) { + return normalizeZone2(input, Settings2.defaultZone); + } + /** + * Return an array of standalone month names. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @param {string} [opts.outputCalendar='gregory'] - the calendar + * @example Info.months()[0] //=> 'January' + * @example Info.months('short')[0] //=> 'Jan' + * @example Info.months('numeric')[0] //=> '1' + * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' + * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' + * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' + * @return {Array} + */ + static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { + return (locObj || Locale2.create(locale, numberingSystem, outputCalendar)).months(length); + } + /** + * Return an array of format month names. + * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that + * changes the string. + * See {@link Info#months} + * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @param {string} [opts.outputCalendar='gregory'] - the calendar + * @return {Array} + */ + static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { + return (locObj || Locale2.create(locale, numberingSystem, outputCalendar)).months(length, true); + } + /** + * Return an array of standalone week names. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @example Info.weekdays()[0] //=> 'Monday' + * @example Info.weekdays('short')[0] //=> 'Mon' + * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' + * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' + * @return {Array} + */ + static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { + return (locObj || Locale2.create(locale, numberingSystem, null)).weekdays(length); + } + /** + * Return an array of format week names. + * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that + * changes the string. + * See {@link Info#weekdays} + * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". + * @param {Object} opts - options + * @param {string} [opts.locale=null] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @return {Array} + */ + static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { + return (locObj || Locale2.create(locale, numberingSystem, null)).weekdays(length, true); + } + /** + * Return an array of meridiems. + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @example Info.meridiems() //=> [ 'AM', 'PM' ] + * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] + * @return {Array} + */ + static meridiems({ locale = null } = {}) { + return Locale2.create(locale).meridiems(); + } + /** + * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. + * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @example Info.eras() //=> [ 'BC', 'AD' ] + * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] + * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] + * @return {Array} + */ + static eras(length = "short", { locale = null } = {}) { + return Locale2.create(locale, null, "gregory").eras(length); + } + /** + * Return the set of available features in this environment. + * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case. + * Keys: + * * `relative`: whether this environment supports relative time formatting + * @example Info.features() //=> { relative: false } + * @return {Object} + */ + static features() { + return { relative: hasRelative2() }; + } + }; + function dayDiff2(earlier, later) { + const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier); + return Math.floor(Duration2.fromMillis(ms).as("days")); + } + function highOrderDiffs2(cursor, later, units) { + const differs = [ + ["years", (a, b) => b.year - a.year], + ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], + ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], + [ + "weeks", + (a, b) => { + const days = dayDiff2(a, b); + return (days - days % 7) / 7; + } + ], + ["days", dayDiff2] + ]; + const results = {}; + const earlier = cursor; + let lowestOrder, highWater; + for (const [unit, differ] of differs) { + if (units.indexOf(unit) >= 0) { + lowestOrder = unit; + results[unit] = differ(cursor, later); + highWater = earlier.plus(results); + if (highWater > later) { + results[unit]--; + cursor = earlier.plus(results); + if (cursor > later) { + highWater = cursor; + results[unit]--; + cursor = earlier.plus(results); + } + } else { + cursor = highWater; + } + } + } + return [cursor, results, highWater, lowestOrder]; + } + function diff(earlier, later, units, opts) { + let [cursor, results, highWater, lowestOrder] = highOrderDiffs2(earlier, later, units); + const remainingMillis = later - cursor; + const lowerOrderUnits = units.filter( + (u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0 + ); + if (lowerOrderUnits.length === 0) { + if (highWater < later) { + highWater = cursor.plus({ [lowestOrder]: 1 }); + } + if (highWater !== cursor) { + results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); + } + } + const duration = Duration2.fromObject(results, opts); + if (lowerOrderUnits.length > 0) { + return Duration2.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration); + } else { + return duration; + } + } + var numberingSystems2 = { + arab: "[\u0660-\u0669]", + arabext: "[\u06F0-\u06F9]", + bali: "[\u1B50-\u1B59]", + beng: "[\u09E6-\u09EF]", + deva: "[\u0966-\u096F]", + fullwide: "[\uFF10-\uFF19]", + gujr: "[\u0AE6-\u0AEF]", + hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]", + khmr: "[\u17E0-\u17E9]", + knda: "[\u0CE6-\u0CEF]", + laoo: "[\u0ED0-\u0ED9]", + limb: "[\u1946-\u194F]", + mlym: "[\u0D66-\u0D6F]", + mong: "[\u1810-\u1819]", + mymr: "[\u1040-\u1049]", + orya: "[\u0B66-\u0B6F]", + tamldec: "[\u0BE6-\u0BEF]", + telu: "[\u0C66-\u0C6F]", + thai: "[\u0E50-\u0E59]", + tibt: "[\u0F20-\u0F29]", + latn: "\\d" + }; + var numberingSystemsUTF162 = { + arab: [1632, 1641], + arabext: [1776, 1785], + bali: [6992, 7001], + beng: [2534, 2543], + deva: [2406, 2415], + fullwide: [65296, 65303], + gujr: [2790, 2799], + khmr: [6112, 6121], + knda: [3302, 3311], + laoo: [3792, 3801], + limb: [6470, 6479], + mlym: [3430, 3439], + mong: [6160, 6169], + mymr: [4160, 4169], + orya: [2918, 2927], + tamldec: [3046, 3055], + telu: [3174, 3183], + thai: [3664, 3673], + tibt: [3872, 3881] + }; + var hanidecChars2 = numberingSystems2.hanidec.replace(/[\[|\]]/g, "").split(""); + function parseDigits2(str) { + let value = parseInt(str, 10); + if (isNaN(value)) { + value = ""; + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + if (str[i].search(numberingSystems2.hanidec) !== -1) { + value += hanidecChars2.indexOf(str[i]); + } else { + for (const key in numberingSystemsUTF162) { + const [min, max] = numberingSystemsUTF162[key]; + if (code >= min && code <= max) { + value += code - min; + } + } + } + } + return parseInt(value, 10); + } else { + return value; + } + } + function digitRegex2({ numberingSystem }, append2 = "") { + return new RegExp(`${numberingSystems2[numberingSystem || "latn"]}${append2}`); + } + var MISSING_FTP2 = "missing Intl.DateTimeFormat.formatToParts support"; + function intUnit2(regex2, post = (i) => i) { + return { regex: regex2, deser: ([s3]) => post(parseDigits2(s3)) }; + } + var NBSP2 = String.fromCharCode(160); + var spaceOrNBSP2 = `[ ${NBSP2}]`; + var spaceOrNBSPRegExp2 = new RegExp(spaceOrNBSP2, "g"); + function fixListRegex2(s3) { + return s3.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp2, spaceOrNBSP2); + } + function stripInsensitivities2(s3) { + return s3.replace(/\./g, "").replace(spaceOrNBSPRegExp2, " ").toLowerCase(); + } + function oneOf2(strings, startIndex) { + if (strings === null) { + return null; + } else { + return { + regex: RegExp(strings.map(fixListRegex2).join("|")), + deser: ([s3]) => strings.findIndex((i) => stripInsensitivities2(s3) === stripInsensitivities2(i)) + startIndex + }; + } + } + function offset2(regex2, groups) { + return { regex: regex2, deser: ([, h, m]) => signedOffset2(h, m), groups }; + } + function simple2(regex2) { + return { regex: regex2, deser: ([s3]) => s3 }; + } + function escapeToken2(value) { + return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); + } + function unitForToken2(token, loc) { + const one = digitRegex2(loc), two = digitRegex2(loc, "{2}"), three = digitRegex2(loc, "{3}"), four = digitRegex2(loc, "{4}"), six = digitRegex2(loc, "{6}"), oneOrTwo = digitRegex2(loc, "{1,2}"), oneToThree = digitRegex2(loc, "{1,3}"), oneToSix = digitRegex2(loc, "{1,6}"), oneToNine = digitRegex2(loc, "{1,9}"), twoToFour = digitRegex2(loc, "{2,4}"), fourToSix = digitRegex2(loc, "{4,6}"), literal = (t) => ({ regex: RegExp(escapeToken2(t.val)), deser: ([s3]) => s3, literal: true }), unitate = (t) => { + if (token.literal) { + return literal(t); + } + switch (t.val) { + case "G": + return oneOf2(loc.eras("short"), 0); + case "GG": + return oneOf2(loc.eras("long"), 0); + case "y": + return intUnit2(oneToSix); + case "yy": + return intUnit2(twoToFour, untruncateYear2); + case "yyyy": + return intUnit2(four); + case "yyyyy": + return intUnit2(fourToSix); + case "yyyyyy": + return intUnit2(six); + case "M": + return intUnit2(oneOrTwo); + case "MM": + return intUnit2(two); + case "MMM": + return oneOf2(loc.months("short", true), 1); + case "MMMM": + return oneOf2(loc.months("long", true), 1); + case "L": + return intUnit2(oneOrTwo); + case "LL": + return intUnit2(two); + case "LLL": + return oneOf2(loc.months("short", false), 1); + case "LLLL": + return oneOf2(loc.months("long", false), 1); + case "d": + return intUnit2(oneOrTwo); + case "dd": + return intUnit2(two); + case "o": + return intUnit2(oneToThree); + case "ooo": + return intUnit2(three); + case "HH": + return intUnit2(two); + case "H": + return intUnit2(oneOrTwo); + case "hh": + return intUnit2(two); + case "h": + return intUnit2(oneOrTwo); + case "mm": + return intUnit2(two); + case "m": + return intUnit2(oneOrTwo); + case "q": + return intUnit2(oneOrTwo); + case "qq": + return intUnit2(two); + case "s": + return intUnit2(oneOrTwo); + case "ss": + return intUnit2(two); + case "S": + return intUnit2(oneToThree); + case "SSS": + return intUnit2(three); + case "u": + return simple2(oneToNine); + case "uu": + return simple2(oneOrTwo); + case "uuu": + return intUnit2(one); + case "a": + return oneOf2(loc.meridiems(), 0); + case "kkkk": + return intUnit2(four); + case "kk": + return intUnit2(twoToFour, untruncateYear2); + case "W": + return intUnit2(oneOrTwo); + case "WW": + return intUnit2(two); + case "E": + case "c": + return intUnit2(one); + case "EEE": + return oneOf2(loc.weekdays("short", false), 1); + case "EEEE": + return oneOf2(loc.weekdays("long", false), 1); + case "ccc": + return oneOf2(loc.weekdays("short", true), 1); + case "cccc": + return oneOf2(loc.weekdays("long", true), 1); + case "Z": + case "ZZ": + return offset2(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); + case "ZZZ": + return offset2(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); + case "z": + return simple2(/[a-z_+-/]{1,256}?/i); + case " ": + return simple2(/[^\S\n\r]/); + default: + return literal(t); + } + }; + const unit = unitate(token) || { + invalidReason: MISSING_FTP2 + }; + unit.token = token; + return unit; + } + var partTypeStyleToTokenVal2 = { + year: { + "2-digit": "yy", + numeric: "yyyyy" + }, + month: { + numeric: "M", + "2-digit": "MM", + short: "MMM", + long: "MMMM" + }, + day: { + numeric: "d", + "2-digit": "dd" + }, + weekday: { + short: "EEE", + long: "EEEE" + }, + dayperiod: "a", + dayPeriod: "a", + hour12: { + numeric: "h", + "2-digit": "hh" + }, + hour24: { + numeric: "H", + "2-digit": "HH" + }, + minute: { + numeric: "m", + "2-digit": "mm" + }, + second: { + numeric: "s", + "2-digit": "ss" + }, + timeZoneName: { + long: "ZZZZZ", + short: "ZZZ" + } + }; + function tokenForPart2(part, formatOpts, resolvedOpts) { + const { type, value } = part; + if (type === "literal") { + const isSpace = /^\s+$/.test(value); + return { + literal: !isSpace, + val: isSpace ? " " : value + }; + } + const style = formatOpts[type]; + let actualType = type; + if (type === "hour") { + if (formatOpts.hour12 != null) { + actualType = formatOpts.hour12 ? "hour12" : "hour24"; + } else if (formatOpts.hourCycle != null) { + if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") { + actualType = "hour12"; + } else { + actualType = "hour24"; + } + } else { + actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; + } + } + let val = partTypeStyleToTokenVal2[actualType]; + if (typeof val === "object") { + val = val[style]; + } + if (val) { + return { + literal: false, + val + }; + } + return void 0; + } + function buildRegex2(units) { + const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); + return [`^${re}$`, units]; + } + function match2(input, regex2, handlers) { + const matches = input.match(regex2); + if (matches) { + const all = {}; + let matchIndex = 1; + for (const i in handlers) { + if (hasOwnProperty2(handlers, i)) { + const h = handlers[i], groups = h.groups ? h.groups + 1 : 1; + if (!h.literal && h.token) { + all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); + } + matchIndex += groups; + } + } + return [matches, all]; + } else { + return [matches, {}]; + } + } + function dateTimeFromMatches2(matches) { + const toField = (token) => { + switch (token) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + case "H": + return "hour"; + case "d": + return "day"; + case "o": + return "ordinal"; + case "L": + case "M": + return "month"; + case "y": + return "year"; + case "E": + case "c": + return "weekday"; + case "W": + return "weekNumber"; + case "k": + return "weekYear"; + case "q": + return "quarter"; + default: + return null; + } + }; + let zone = null; + let specificOffset; + if (!isUndefined2(matches.z)) { + zone = IANAZone2.create(matches.z); + } + if (!isUndefined2(matches.Z)) { + if (!zone) { + zone = new FixedOffsetZone2(matches.Z); + } + specificOffset = matches.Z; + } + if (!isUndefined2(matches.q)) { + matches.M = (matches.q - 1) * 3 + 1; + } + if (!isUndefined2(matches.h)) { + if (matches.h < 12 && matches.a === 1) { + matches.h += 12; + } else if (matches.h === 12 && matches.a === 0) { + matches.h = 0; + } + } + if (matches.G === 0 && matches.y) { + matches.y = -matches.y; + } + if (!isUndefined2(matches.u)) { + matches.S = parseMillis2(matches.u); + } + const vals = Object.keys(matches).reduce((r, k) => { + const f = toField(k); + if (f) { + r[f] = matches[k]; + } + return r; + }, {}); + return [vals, zone, specificOffset]; + } + var dummyDateTimeCache2 = null; + function getDummyDateTime2() { + if (!dummyDateTimeCache2) { + dummyDateTimeCache2 = DateTime2.fromMillis(1555555555555); + } + return dummyDateTimeCache2; + } + function maybeExpandMacroToken2(token, locale) { + if (token.literal) { + return token; + } + const formatOpts = Formatter2.macroTokenToFormatOpts(token.val); + const tokens = formatOptsToTokens2(formatOpts, locale); + if (tokens == null || tokens.includes(void 0)) { + return token; + } + return tokens; + } + function expandMacroTokens2(tokens, locale) { + return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken2(t, locale))); + } + function explainFromTokens2(locale, input, format) { + const tokens = expandMacroTokens2(Formatter2.parseFormat(format), locale), units = tokens.map((t) => unitForToken2(t, locale)), disqualifyingUnit = units.find((t) => t.invalidReason); + if (disqualifyingUnit) { + return { input, tokens, invalidReason: disqualifyingUnit.invalidReason }; + } else { + const [regexString, handlers] = buildRegex2(units), regex2 = RegExp(regexString, "i"), [rawMatches, matches] = match2(input, regex2, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches2(matches) : [null, null, void 0]; + if (hasOwnProperty2(matches, "a") && hasOwnProperty2(matches, "H")) { + throw new ConflictingSpecificationError2( + "Can't include meridiem when specifying 24-hour format" + ); + } + return { input, tokens, regex: regex2, rawMatches, matches, result, zone, specificOffset }; + } + } + function parseFromTokens2(locale, input, format) { + const { result, zone, specificOffset, invalidReason } = explainFromTokens2(locale, input, format); + return [result, zone, specificOffset, invalidReason]; + } + function formatOptsToTokens2(formatOpts, locale) { + if (!formatOpts) { + return null; + } + const formatter = Formatter2.create(locale, formatOpts); + const df = formatter.dtFormatter(getDummyDateTime2()); + const parts = df.formatToParts(); + const resolvedOpts = df.resolvedOptions(); + return parts.map((p) => tokenForPart2(p, formatOpts, resolvedOpts)); + } + var nonLeapLadder2 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + var leapLadder2 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; + function unitOutOfRange2(unit, value) { + return new Invalid2( + "unit out of range", + `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid` + ); + } + function dayOfWeek2(year, month, day) { + const d = new Date(Date.UTC(year, month - 1, day)); + if (year < 100 && year >= 0) { + d.setUTCFullYear(d.getUTCFullYear() - 1900); + } + const js = d.getUTCDay(); + return js === 0 ? 7 : js; + } + function computeOrdinal2(year, month, day) { + return day + (isLeapYear2(year) ? leapLadder2 : nonLeapLadder2)[month - 1]; + } + function uncomputeOrdinal2(year, ordinal) { + const table = isLeapYear2(year) ? leapLadder2 : nonLeapLadder2, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0]; + return { month: month0 + 1, day }; + } + function gregorianToWeek2(gregObj) { + const { year, month, day } = gregObj, ordinal = computeOrdinal2(year, month, day), weekday = dayOfWeek2(year, month, day); + let weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear; + if (weekNumber < 1) { + weekYear = year - 1; + weekNumber = weeksInWeekYear2(weekYear); + } else if (weekNumber > weeksInWeekYear2(year)) { + weekYear = year + 1; + weekNumber = 1; + } else { + weekYear = year; + } + return { weekYear, weekNumber, weekday, ...timeObject2(gregObj) }; + } + function weekToGregorian2(weekData) { + const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = dayOfWeek2(weekYear, 1, 4), yearInDays = daysInYear2(weekYear); + let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year; + if (ordinal < 1) { + year = weekYear - 1; + ordinal += daysInYear2(year); + } else if (ordinal > yearInDays) { + year = weekYear + 1; + ordinal -= daysInYear2(weekYear); + } else { + year = weekYear; + } + const { month, day } = uncomputeOrdinal2(year, ordinal); + return { year, month, day, ...timeObject2(weekData) }; + } + function gregorianToOrdinal2(gregData) { + const { year, month, day } = gregData; + const ordinal = computeOrdinal2(year, month, day); + return { year, ordinal, ...timeObject2(gregData) }; + } + function ordinalToGregorian2(ordinalData) { + const { year, ordinal } = ordinalData; + const { month, day } = uncomputeOrdinal2(year, ordinal); + return { year, month, day, ...timeObject2(ordinalData) }; + } + function hasInvalidWeekData2(obj) { + const validYear = isInteger2(obj.weekYear), validWeek = integerBetween2(obj.weekNumber, 1, weeksInWeekYear2(obj.weekYear)), validWeekday = integerBetween2(obj.weekday, 1, 7); + if (!validYear) { + return unitOutOfRange2("weekYear", obj.weekYear); + } else if (!validWeek) { + return unitOutOfRange2("week", obj.week); + } else if (!validWeekday) { + return unitOutOfRange2("weekday", obj.weekday); + } else + return false; + } + function hasInvalidOrdinalData2(obj) { + const validYear = isInteger2(obj.year), validOrdinal = integerBetween2(obj.ordinal, 1, daysInYear2(obj.year)); + if (!validYear) { + return unitOutOfRange2("year", obj.year); + } else if (!validOrdinal) { + return unitOutOfRange2("ordinal", obj.ordinal); + } else + return false; + } + function hasInvalidGregorianData2(obj) { + const validYear = isInteger2(obj.year), validMonth = integerBetween2(obj.month, 1, 12), validDay = integerBetween2(obj.day, 1, daysInMonth2(obj.year, obj.month)); + if (!validYear) { + return unitOutOfRange2("year", obj.year); + } else if (!validMonth) { + return unitOutOfRange2("month", obj.month); + } else if (!validDay) { + return unitOutOfRange2("day", obj.day); + } else + return false; + } + function hasInvalidTimeData2(obj) { + const { hour, minute, second, millisecond } = obj; + const validHour = integerBetween2(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween2(minute, 0, 59), validSecond = integerBetween2(second, 0, 59), validMillisecond = integerBetween2(millisecond, 0, 999); + if (!validHour) { + return unitOutOfRange2("hour", hour); + } else if (!validMinute) { + return unitOutOfRange2("minute", minute); + } else if (!validSecond) { + return unitOutOfRange2("second", second); + } else if (!validMillisecond) { + return unitOutOfRange2("millisecond", millisecond); + } else + return false; + } + var INVALID5 = "Invalid DateTime"; + var MAX_DATE2 = 864e13; + function unsupportedZone2(zone) { + return new Invalid2("unsupported zone", `the zone "${zone.name}" is not supported`); + } + function possiblyCachedWeekData2(dt) { + if (dt.weekData === null) { + dt.weekData = gregorianToWeek2(dt.c); + } + return dt.weekData; + } + function clone3(inst, alts) { + const current = { + ts: inst.ts, + zone: inst.zone, + c: inst.c, + o: inst.o, + loc: inst.loc, + invalid: inst.invalid + }; + return new DateTime2({ ...current, ...alts, old: current }); + } + function fixOffset2(localTS, o, tz) { + let utcGuess = localTS - o * 60 * 1e3; + const o2 = tz.offset(utcGuess); + if (o === o2) { + return [utcGuess, o]; + } + utcGuess -= (o2 - o) * 60 * 1e3; + const o3 = tz.offset(utcGuess); + if (o2 === o3) { + return [utcGuess, o2]; + } + return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)]; + } + function tsToObj2(ts, offset3) { + ts += offset3 * 60 * 1e3; + const d = new Date(ts); + return { + year: d.getUTCFullYear(), + month: d.getUTCMonth() + 1, + day: d.getUTCDate(), + hour: d.getUTCHours(), + minute: d.getUTCMinutes(), + second: d.getUTCSeconds(), + millisecond: d.getUTCMilliseconds() + }; + } + function objToTS2(obj, offset3, zone) { + return fixOffset2(objToLocalTS2(obj), offset3, zone); + } + function adjustTime2(inst, dur) { + const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = { + ...inst.c, + year, + month, + day: Math.min(inst.c.day, daysInMonth2(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 + }, millisToAdd = Duration2.fromObject({ + years: dur.years - Math.trunc(dur.years), + quarters: dur.quarters - Math.trunc(dur.quarters), + months: dur.months - Math.trunc(dur.months), + weeks: dur.weeks - Math.trunc(dur.weeks), + days: dur.days - Math.trunc(dur.days), + hours: dur.hours, + minutes: dur.minutes, + seconds: dur.seconds, + milliseconds: dur.milliseconds + }).as("milliseconds"), localTS = objToLocalTS2(c); + let [ts, o] = fixOffset2(localTS, oPre, inst.zone); + if (millisToAdd !== 0) { + ts += millisToAdd; + o = inst.zone.offset(ts); + } + return { ts, o }; + } + function parseDataToDateTime2(parsed, parsedZone, opts, format, text2, specificOffset) { + const { setZone, zone } = opts; + if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { + const interpretationZone = parsedZone || zone, inst = DateTime2.fromObject(parsed, { + ...opts, + zone: interpretationZone, + specificOffset + }); + return setZone ? inst : inst.setZone(zone); + } else { + return DateTime2.invalid( + new Invalid2("unparsable", `the input "${text2}" can't be parsed as ${format}`) + ); + } + } + function toTechFormat2(dt, format, allowZ = true) { + return dt.isValid ? Formatter2.create(Locale2.create("en-US"), { + allowZ, + forceSimple: true + }).formatDateTimeFromString(dt, format) : null; + } + function toISODate2(o, extended) { + const longFormat = o.c.year > 9999 || o.c.year < 0; + let c = ""; + if (longFormat && o.c.year >= 0) + c += "+"; + c += padStart2(o.c.year, longFormat ? 6 : 4); + if (extended) { + c += "-"; + c += padStart2(o.c.month); + c += "-"; + c += padStart2(o.c.day); + } else { + c += padStart2(o.c.month); + c += padStart2(o.c.day); + } + return c; + } + function toISOTime2(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) { + let c = padStart2(o.c.hour); + if (extended) { + c += ":"; + c += padStart2(o.c.minute); + if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { + c += ":"; + } + } else { + c += padStart2(o.c.minute); + } + if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { + c += padStart2(o.c.second); + if (o.c.millisecond !== 0 || !suppressMilliseconds) { + c += "."; + c += padStart2(o.c.millisecond, 3); + } + } + if (includeOffset) { + if (o.isOffsetFixed && o.offset === 0 && !extendedZone) { + c += "Z"; + } else if (o.o < 0) { + c += "-"; + c += padStart2(Math.trunc(-o.o / 60)); + c += ":"; + c += padStart2(Math.trunc(-o.o % 60)); + } else { + c += "+"; + c += padStart2(Math.trunc(o.o / 60)); + c += ":"; + c += padStart2(Math.trunc(o.o % 60)); + } + } + if (extendedZone) { + c += "[" + o.zone.ianaName + "]"; + } + return c; + } + var defaultUnitValues2 = { + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }; + var defaultWeekUnitValues2 = { + weekNumber: 1, + weekday: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }; + var defaultOrdinalUnitValues2 = { + ordinal: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }; + var orderedUnits3 = ["year", "month", "day", "hour", "minute", "second", "millisecond"]; + var orderedWeekUnits2 = [ + "weekYear", + "weekNumber", + "weekday", + "hour", + "minute", + "second", + "millisecond" + ]; + var orderedOrdinalUnits2 = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; + function normalizeUnit2(unit) { + const normalized = { + year: "year", + years: "year", + month: "month", + months: "month", + day: "day", + days: "day", + hour: "hour", + hours: "hour", + minute: "minute", + minutes: "minute", + quarter: "quarter", + quarters: "quarter", + second: "second", + seconds: "second", + millisecond: "millisecond", + milliseconds: "millisecond", + weekday: "weekday", + weekdays: "weekday", + weeknumber: "weekNumber", + weeksnumber: "weekNumber", + weeknumbers: "weekNumber", + weekyear: "weekYear", + weekyears: "weekYear", + ordinal: "ordinal" + }[unit.toLowerCase()]; + if (!normalized) + throw new InvalidUnitError2(unit); + return normalized; + } + function quickDT2(obj, opts) { + const zone = normalizeZone2(opts.zone, Settings2.defaultZone), loc = Locale2.fromObject(opts), tsNow = Settings2.now(); + let ts, o; + if (!isUndefined2(obj.year)) { + for (const u of orderedUnits3) { + if (isUndefined2(obj[u])) { + obj[u] = defaultUnitValues2[u]; + } + } + const invalid = hasInvalidGregorianData2(obj) || hasInvalidTimeData2(obj); + if (invalid) { + return DateTime2.invalid(invalid); + } + const offsetProvis = zone.offset(tsNow); + [ts, o] = objToTS2(obj, offsetProvis, zone); + } else { + ts = tsNow; + } + return new DateTime2({ ts, zone, loc, o }); + } + function diffRelative2(start, end, opts) { + const round = isUndefined2(opts.round) ? true : opts.round, format = (c, unit) => { + c = roundTo2(c, round || opts.calendary ? 0 : 2, true); + const formatter = end.loc.clone(opts).relFormatter(opts); + return formatter.format(c, unit); + }, differ = (unit) => { + if (opts.calendary) { + if (!end.hasSame(start, unit)) { + return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); + } else + return 0; + } else { + return end.diff(start, unit).get(unit); + } + }; + if (opts.unit) { + return format(differ(opts.unit), opts.unit); + } + for (const unit of opts.units) { + const count = differ(unit); + if (Math.abs(count) >= 1) { + return format(count, unit); + } + } + return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); + } + function lastOpts2(argList) { + let opts = {}, args; + if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { + opts = argList[argList.length - 1]; + args = Array.from(argList).slice(0, argList.length - 1); + } else { + args = Array.from(argList); + } + return [opts, args]; + } + var DateTime2 = class _DateTime { + /** + * @access private + */ + constructor(config) { + const zone = config.zone || Settings2.defaultZone; + let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid2("invalid input") : null) || (!zone.isValid ? unsupportedZone2(zone) : null); + this.ts = isUndefined2(config.ts) ? Settings2.now() : config.ts; + let c = null, o = null; + if (!invalid) { + const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); + if (unchanged) { + [c, o] = [config.old.c, config.old.o]; + } else { + const ot = zone.offset(this.ts); + c = tsToObj2(this.ts, ot); + invalid = Number.isNaN(c.year) ? new Invalid2("invalid input") : null; + c = invalid ? null : c; + o = invalid ? null : ot; + } + } + this._zone = zone; + this.loc = config.loc || Locale2.create(); + this.invalid = invalid; + this.weekData = null; + this.c = c; + this.o = o; + this.isLuxonDateTime = true; + } + // CONSTRUCT + /** + * Create a DateTime for the current instant, in the system's time zone. + * + * Use Settings to override these default values if needed. + * @example DateTime.now().toISO() //~> now in the ISO format + * @return {DateTime} + */ + static now() { + return new _DateTime({}); + } + /** + * Create a local DateTime + * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used + * @param {number} [month=1] - The month, 1-indexed + * @param {number} [day=1] - The day of the month, 1-indexed + * @param {number} [hour=0] - The hour of the day, in 24-hour time + * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 + * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 + * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 + * @example DateTime.local() //~> now + * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time + * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 + * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 + * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale + * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 + * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC + * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 + * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 + * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 + * @return {DateTime} + */ + static local() { + const [opts, args] = lastOpts2(arguments), [year, month, day, hour, minute, second, millisecond] = args; + return quickDT2({ year, month, day, hour, minute, second, millisecond }, opts); + } + /** + * Create a DateTime in UTC + * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used + * @param {number} [month=1] - The month, 1-indexed + * @param {number} [day=1] - The day of the month + * @param {number} [hour=0] - The hour of the day, in 24-hour time + * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 + * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 + * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 + * @param {Object} options - configuration options for the DateTime + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance + * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance + * @example DateTime.utc() //~> now + * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z + * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z + * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z + * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z + * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z + * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale + * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z + * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale + * @return {DateTime} + */ + static utc() { + const [opts, args] = lastOpts2(arguments), [year, month, day, hour, minute, second, millisecond] = args; + opts.zone = FixedOffsetZone2.utcInstance; + return quickDT2({ year, month, day, hour, minute, second, millisecond }, opts); + } + /** + * Create a DateTime from a JavaScript Date object. Uses the default zone. + * @param {Date} date - a JavaScript Date object + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @return {DateTime} + */ + static fromJSDate(date, options = {}) { + const ts = isDate2(date) ? date.valueOf() : NaN; + if (Number.isNaN(ts)) { + return _DateTime.invalid("invalid input"); + } + const zoneToUse = normalizeZone2(options.zone, Settings2.defaultZone); + if (!zoneToUse.isValid) { + return _DateTime.invalid(unsupportedZone2(zoneToUse)); + } + return new _DateTime({ + ts, + zone: zoneToUse, + loc: Locale2.fromObject(options) + }); + } + /** + * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. + * @param {number} milliseconds - a number of milliseconds since 1970 UTC + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromMillis(milliseconds, options = {}) { + if (!isNumber2(milliseconds)) { + throw new InvalidArgumentError2( + `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}` + ); + } else if (milliseconds < -MAX_DATE2 || milliseconds > MAX_DATE2) { + return _DateTime.invalid("Timestamp out of range"); + } else { + return new _DateTime({ + ts: milliseconds, + zone: normalizeZone2(options.zone, Settings2.defaultZone), + loc: Locale2.fromObject(options) + }); + } + } + /** + * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. + * @param {number} seconds - a number of seconds since 1970 UTC + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromSeconds(seconds, options = {}) { + if (!isNumber2(seconds)) { + throw new InvalidArgumentError2("fromSeconds requires a numerical input"); + } else { + return new _DateTime({ + ts: seconds * 1e3, + zone: normalizeZone2(options.zone, Settings2.defaultZone), + loc: Locale2.fromObject(options) + }); + } + } + /** + * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults. + * @param {Object} obj - the object to create the DateTime from + * @param {number} obj.year - a year, such as 1987 + * @param {number} obj.month - a month, 1-12 + * @param {number} obj.day - a day of the month, 1-31, depending on the month + * @param {number} obj.ordinal - day of the year, 1-365 or 366 + * @param {number} obj.weekYear - an ISO week year + * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year + * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday + * @param {number} obj.hour - hour of the day, 0-23 + * @param {number} obj.minute - minute of the hour, 0-59 + * @param {number} obj.second - second of the minute, 0-59 + * @param {number} obj.millisecond - millisecond of the second, 0-999 + * @param {Object} opts - options for creating this DateTime + * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' + * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }), + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' }) + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' }) + * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' + * @return {DateTime} + */ + static fromObject(obj, opts = {}) { + obj = obj || {}; + const zoneToUse = normalizeZone2(opts.zone, Settings2.defaultZone); + if (!zoneToUse.isValid) { + return _DateTime.invalid(unsupportedZone2(zoneToUse)); + } + const tsNow = Settings2.now(), offsetProvis = !isUndefined2(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), normalized = normalizeObject2(obj, normalizeUnit2), containsOrdinal = !isUndefined2(normalized.ordinal), containsGregorYear = !isUndefined2(normalized.year), containsGregorMD = !isUndefined2(normalized.month) || !isUndefined2(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale2.fromObject(opts); + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError2( + "Can't mix weekYear/weekNumber units with year/month/day or ordinals" + ); + } + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError2("Can't mix ordinal dates with month/day"); + } + const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; + let units, defaultValues, objNow = tsToObj2(tsNow, offsetProvis); + if (useWeekData) { + units = orderedWeekUnits2; + defaultValues = defaultWeekUnitValues2; + objNow = gregorianToWeek2(objNow); + } else if (containsOrdinal) { + units = orderedOrdinalUnits2; + defaultValues = defaultOrdinalUnitValues2; + objNow = gregorianToOrdinal2(objNow); + } else { + units = orderedUnits3; + defaultValues = defaultUnitValues2; + } + let foundFirst = false; + for (const u of units) { + const v = normalized[u]; + if (!isUndefined2(v)) { + foundFirst = true; + } else if (foundFirst) { + normalized[u] = defaultValues[u]; + } else { + normalized[u] = objNow[u]; + } + } + const higherOrderInvalid = useWeekData ? hasInvalidWeekData2(normalized) : containsOrdinal ? hasInvalidOrdinalData2(normalized) : hasInvalidGregorianData2(normalized), invalid = higherOrderInvalid || hasInvalidTimeData2(normalized); + if (invalid) { + return _DateTime.invalid(invalid); + } + const gregorian = useWeekData ? weekToGregorian2(normalized) : containsOrdinal ? ordinalToGregorian2(normalized) : normalized, [tsFinal, offsetFinal] = objToTS2(gregorian, offsetProvis, zoneToUse), inst = new _DateTime({ + ts: tsFinal, + zone: zoneToUse, + o: offsetFinal, + loc + }); + if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { + return _DateTime.invalid( + "mismatched weekday", + `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}` + ); + } + return inst; + } + /** + * Create a DateTime from an ISO 8601 string + * @param {string} text - the ISO string + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance + * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromISO('2016-05-25T09:08:34.123') + * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') + * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) + * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) + * @example DateTime.fromISO('2016-W05-4') + * @return {DateTime} + */ + static fromISO(text2, opts = {}) { + const [vals, parsedZone] = parseISODate2(text2); + return parseDataToDateTime2(vals, parsedZone, opts, "ISO 8601", text2); + } + /** + * Create a DateTime from an RFC 2822 string + * @param {string} text - the RFC 2822 string + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. + * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') + * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') + * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') + * @return {DateTime} + */ + static fromRFC2822(text2, opts = {}) { + const [vals, parsedZone] = parseRFC2822Date2(text2); + return parseDataToDateTime2(vals, parsedZone, opts, "RFC 2822", text2); + } + /** + * Create a DateTime from an HTTP header date + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 + * @param {string} text - the HTTP header date + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. + * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') + * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') + * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') + * @return {DateTime} + */ + static fromHTTP(text2, opts = {}) { + const [vals, parsedZone] = parseHTTPDate2(text2); + return parseDataToDateTime2(vals, parsedZone, opts, "HTTP", opts); + } + /** + * Create a DateTime from an input string and format string. + * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens). + * @param {string} text - the string to parse + * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale + * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromFormat(text2, fmt, opts = {}) { + if (isUndefined2(text2) || isUndefined2(fmt)) { + throw new InvalidArgumentError2("fromFormat requires an input string and a format"); + } + const { locale = null, numberingSystem = null } = opts, localeToUse = Locale2.fromOpts({ + locale, + numberingSystem, + defaultToEN: true + }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens2(localeToUse, text2, fmt); + if (invalid) { + return _DateTime.invalid(invalid); + } else { + return parseDataToDateTime2(vals, parsedZone, opts, `format ${fmt}`, text2, specificOffset); + } + } + /** + * @deprecated use fromFormat instead + */ + static fromString(text2, fmt, opts = {}) { + return _DateTime.fromFormat(text2, fmt, opts); + } + /** + * Create a DateTime from a SQL date, time, or datetime + * Defaults to en-US if no locale has been specified, regardless of the system's locale + * @param {string} text - the string to parse + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale + * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @example DateTime.fromSQL('2017-05-15') + * @example DateTime.fromSQL('2017-05-15 09:12:34') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) + * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) + * @example DateTime.fromSQL('09:12:34.342') + * @return {DateTime} + */ + static fromSQL(text2, opts = {}) { + const [vals, parsedZone] = parseSQL2(text2); + return parseDataToDateTime2(vals, parsedZone, opts, "SQL", text2); + } + /** + * Create an invalid DateTime. + * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent. + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {DateTime} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError2("need to specify a reason the DateTime is invalid"); + } + const invalid = reason instanceof Invalid2 ? reason : new Invalid2(reason, explanation); + if (Settings2.throwOnInvalid) { + throw new InvalidDateTimeError2(invalid); + } else { + return new _DateTime({ invalid }); + } + } + /** + * Check if an object is an instance of DateTime. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isDateTime(o) { + return o && o.isLuxonDateTime || false; + } + /** + * Produce the format string for a set of options + * @param formatOpts + * @param localeOpts + * @returns {string} + */ + static parseFormatForOpts(formatOpts, localeOpts = {}) { + const tokenList = formatOptsToTokens2(formatOpts, Locale2.fromObject(localeOpts)); + return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join(""); + } + /** + * Produce the the fully expanded format token for the locale + * Does NOT quote characters, so quoted tokens will not round trip correctly + * @param fmt + * @param localeOpts + * @returns {string} + */ + static expandFormat(fmt, localeOpts = {}) { + const expanded = expandMacroTokens2(Formatter2.parseFormat(fmt), Locale2.fromObject(localeOpts)); + return expanded.map((t) => t.val).join(""); + } + // INFO + /** + * Get the value of unit. + * @param {string} unit - a unit such as 'minute' or 'day' + * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 + * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 + * @return {number} + */ + get(unit) { + return this[unit]; + } + /** + * Returns whether the DateTime is valid. Invalid DateTimes occur when: + * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 + * * The DateTime was created by an operation on another invalid date + * @type {boolean} + */ + get isValid() { + return this.invalid === null; + } + /** + * Returns an error code if this DateTime is invalid, or null if the DateTime is valid + * @type {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + /** + * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + /** + * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime + * + * @type {string} + */ + get locale() { + return this.isValid ? this.loc.locale : null; + } + /** + * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime + * + * @type {string} + */ + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; + } + /** + * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime + * + * @type {string} + */ + get outputCalendar() { + return this.isValid ? this.loc.outputCalendar : null; + } + /** + * Get the time zone associated with this DateTime. + * @type {Zone} + */ + get zone() { + return this._zone; + } + /** + * Get the name of the time zone. + * @type {string} + */ + get zoneName() { + return this.isValid ? this.zone.name : null; + } + /** + * Get the year + * @example DateTime.local(2017, 5, 25).year //=> 2017 + * @type {number} + */ + get year() { + return this.isValid ? this.c.year : NaN; + } + /** + * Get the quarter + * @example DateTime.local(2017, 5, 25).quarter //=> 2 + * @type {number} + */ + get quarter() { + return this.isValid ? Math.ceil(this.c.month / 3) : NaN; + } + /** + * Get the month (1-12). + * @example DateTime.local(2017, 5, 25).month //=> 5 + * @type {number} + */ + get month() { + return this.isValid ? this.c.month : NaN; + } + /** + * Get the day of the month (1-30ish). + * @example DateTime.local(2017, 5, 25).day //=> 25 + * @type {number} + */ + get day() { + return this.isValid ? this.c.day : NaN; + } + /** + * Get the hour of the day (0-23). + * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 + * @type {number} + */ + get hour() { + return this.isValid ? this.c.hour : NaN; + } + /** + * Get the minute of the hour (0-59). + * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 + * @type {number} + */ + get minute() { + return this.isValid ? this.c.minute : NaN; + } + /** + * Get the second of the minute (0-59). + * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 + * @type {number} + */ + get second() { + return this.isValid ? this.c.second : NaN; + } + /** + * Get the millisecond of the second (0-999). + * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 + * @type {number} + */ + get millisecond() { + return this.isValid ? this.c.millisecond : NaN; + } + /** + * Get the week year + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2014, 12, 31).weekYear //=> 2015 + * @type {number} + */ + get weekYear() { + return this.isValid ? possiblyCachedWeekData2(this).weekYear : NaN; + } + /** + * Get the week number of the week year (1-52ish). + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 + * @type {number} + */ + get weekNumber() { + return this.isValid ? possiblyCachedWeekData2(this).weekNumber : NaN; + } + /** + * Get the day of the week. + * 1 is Monday and 7 is Sunday + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2014, 11, 31).weekday //=> 4 + * @type {number} + */ + get weekday() { + return this.isValid ? possiblyCachedWeekData2(this).weekday : NaN; + } + /** + * Get the ordinal (meaning the day of the year) + * @example DateTime.local(2017, 5, 25).ordinal //=> 145 + * @type {number|DateTime} + */ + get ordinal() { + return this.isValid ? gregorianToOrdinal2(this.c).ordinal : NaN; + } + /** + * Get the human readable short month name, such as 'Oct'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).monthShort //=> Oct + * @type {string} + */ + get monthShort() { + return this.isValid ? Info2.months("short", { locObj: this.loc })[this.month - 1] : null; + } + /** + * Get the human readable long month name, such as 'October'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).monthLong //=> October + * @type {string} + */ + get monthLong() { + return this.isValid ? Info2.months("long", { locObj: this.loc })[this.month - 1] : null; + } + /** + * Get the human readable short weekday, such as 'Mon'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon + * @type {string} + */ + get weekdayShort() { + return this.isValid ? Info2.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null; + } + /** + * Get the human readable long weekday, such as 'Monday'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday + * @type {string} + */ + get weekdayLong() { + return this.isValid ? Info2.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null; + } + /** + * Get the UTC offset of this DateTime in minutes + * @example DateTime.now().offset //=> -240 + * @example DateTime.utc().offset //=> 0 + * @type {number} + */ + get offset() { + return this.isValid ? +this.o : NaN; + } + /** + * Get the short human name for the zone's current offset, for example "EST" or "EDT". + * Defaults to the system's locale if no locale has been specified + * @type {string} + */ + get offsetNameShort() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "short", + locale: this.locale + }); + } else { + return null; + } + } + /** + * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". + * Defaults to the system's locale if no locale has been specified + * @type {string} + */ + get offsetNameLong() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "long", + locale: this.locale + }); + } else { + return null; + } + } + /** + * Get whether this zone's offset ever changes, as in a DST. + * @type {boolean} + */ + get isOffsetFixed() { + return this.isValid ? this.zone.isUniversal : null; + } + /** + * Get whether the DateTime is in a DST. + * @type {boolean} + */ + get isInDST() { + if (this.isOffsetFixed) { + return false; + } else { + return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset; + } + } + /** + * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC + * in this DateTime's zone. During DST changes local time can be ambiguous, for example + * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`. + * This method will return both possible DateTimes if this DateTime's local time is ambiguous. + * @returns {DateTime[]} + */ + getPossibleOffsets() { + if (!this.isValid || this.isOffsetFixed) { + return [this]; + } + const dayMs = 864e5; + const minuteMs = 6e4; + const localTS = objToLocalTS2(this.c); + const oEarlier = this.zone.offset(localTS - dayMs); + const oLater = this.zone.offset(localTS + dayMs); + const o1 = this.zone.offset(localTS - oEarlier * minuteMs); + const o2 = this.zone.offset(localTS - oLater * minuteMs); + if (o1 === o2) { + return [this]; + } + const ts1 = localTS - o1 * minuteMs; + const ts2 = localTS - o2 * minuteMs; + const c1 = tsToObj2(ts1, o1); + const c2 = tsToObj2(ts2, o2); + if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) { + return [clone3(this, { ts: ts1 }), clone3(this, { ts: ts2 })]; + } + return [this]; + } + /** + * Returns true if this DateTime is in a leap year, false otherwise + * @example DateTime.local(2016).isInLeapYear //=> true + * @example DateTime.local(2013).isInLeapYear //=> false + * @type {boolean} + */ + get isInLeapYear() { + return isLeapYear2(this.year); + } + /** + * Returns the number of days in this DateTime's month + * @example DateTime.local(2016, 2).daysInMonth //=> 29 + * @example DateTime.local(2016, 3).daysInMonth //=> 31 + * @type {number} + */ + get daysInMonth() { + return daysInMonth2(this.year, this.month); + } + /** + * Returns the number of days in this DateTime's year + * @example DateTime.local(2016).daysInYear //=> 366 + * @example DateTime.local(2013).daysInYear //=> 365 + * @type {number} + */ + get daysInYear() { + return this.isValid ? daysInYear2(this.year) : NaN; + } + /** + * Returns the number of weeks in this DateTime's year + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2004).weeksInWeekYear //=> 53 + * @example DateTime.local(2013).weeksInWeekYear //=> 52 + * @type {number} + */ + get weeksInWeekYear() { + return this.isValid ? weeksInWeekYear2(this.weekYear) : NaN; + } + /** + * Returns the resolved Intl options for this DateTime. + * This is useful in understanding the behavior of formatting methods + * @param {Object} opts - the same options as toLocaleString + * @return {Object} + */ + resolvedLocaleOptions(opts = {}) { + const { locale, numberingSystem, calendar } = Formatter2.create( + this.loc.clone(opts), + opts + ).resolvedOptions(this); + return { locale, numberingSystem, outputCalendar: calendar }; + } + // TRANSFORM + /** + * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. + * + * Equivalent to {@link DateTime#setZone}('utc') + * @param {number} [offset=0] - optionally, an offset from UTC in minutes + * @param {Object} [opts={}] - options to pass to `setZone()` + * @return {DateTime} + */ + toUTC(offset3 = 0, opts = {}) { + return this.setZone(FixedOffsetZone2.instance(offset3), opts); + } + /** + * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. + * + * Equivalent to `setZone('local')` + * @return {DateTime} + */ + toLocal() { + return this.setZone(Settings2.defaultZone); + } + /** + * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. + * + * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones. + * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class. + * @param {Object} opts - options + * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. + * @return {DateTime} + */ + setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) { + zone = normalizeZone2(zone, Settings2.defaultZone); + if (zone.equals(this.zone)) { + return this; + } else if (!zone.isValid) { + return _DateTime.invalid(unsupportedZone2(zone)); + } else { + let newTS = this.ts; + if (keepLocalTime || keepCalendarTime) { + const offsetGuess = zone.offset(this.ts); + const asObj = this.toObject(); + [newTS] = objToTS2(asObj, offsetGuess, zone); + } + return clone3(this, { ts: newTS, zone }); + } + } + /** + * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. + * @param {Object} properties - the properties to set + * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) + * @return {DateTime} + */ + reconfigure({ locale, numberingSystem, outputCalendar } = {}) { + const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); + return clone3(this, { loc }); + } + /** + * "Set" the locale. Returns a newly-constructed DateTime. + * Just a convenient alias for reconfigure({ locale }) + * @example DateTime.local(2017, 5, 25).setLocale('en-GB') + * @return {DateTime} + */ + setLocale(locale) { + return this.reconfigure({ locale }); + } + /** + * "Set" the values of specified units. Returns a newly-constructed DateTime. + * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}. + * @param {Object} values - a mapping of units to numbers + * @example dt.set({ year: 2017 }) + * @example dt.set({ hour: 8, minute: 30 }) + * @example dt.set({ weekday: 5 }) + * @example dt.set({ year: 2005, ordinal: 234 }) + * @return {DateTime} + */ + set(values) { + if (!this.isValid) + return this; + const normalized = normalizeObject2(values, normalizeUnit2), settingWeekStuff = !isUndefined2(normalized.weekYear) || !isUndefined2(normalized.weekNumber) || !isUndefined2(normalized.weekday), containsOrdinal = !isUndefined2(normalized.ordinal), containsGregorYear = !isUndefined2(normalized.year), containsGregorMD = !isUndefined2(normalized.month) || !isUndefined2(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError2( + "Can't mix weekYear/weekNumber units with year/month/day or ordinals" + ); + } + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError2("Can't mix ordinal dates with month/day"); + } + let mixed; + if (settingWeekStuff) { + mixed = weekToGregorian2({ ...gregorianToWeek2(this.c), ...normalized }); + } else if (!isUndefined2(normalized.ordinal)) { + mixed = ordinalToGregorian2({ ...gregorianToOrdinal2(this.c), ...normalized }); + } else { + mixed = { ...this.toObject(), ...normalized }; + if (isUndefined2(normalized.day)) { + mixed.day = Math.min(daysInMonth2(mixed.year, mixed.month), mixed.day); + } + } + const [ts, o] = objToTS2(mixed, this.o, this.zone); + return clone3(this, { ts, o }); + } + /** + * Add a period of time to this DateTime and return the resulting DateTime + * + * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. + * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @example DateTime.now().plus(123) //~> in 123 milliseconds + * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes + * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow + * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday + * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min + * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min + * @return {DateTime} + */ + plus(duration) { + if (!this.isValid) + return this; + const dur = Duration2.fromDurationLike(duration); + return clone3(this, adjustTime2(this, dur)); + } + /** + * Subtract a period of time to this DateTime and return the resulting DateTime + * See {@link DateTime#plus} + * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + @return {DateTime} + */ + minus(duration) { + if (!this.isValid) + return this; + const dur = Duration2.fromDurationLike(duration).negate(); + return clone3(this, adjustTime2(this, dur)); + } + /** + * "Set" this DateTime to the beginning of a unit of time. + * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. + * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' + * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' + * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays + * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' + * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' + * @return {DateTime} + */ + startOf(unit) { + if (!this.isValid) + return this; + const o = {}, normalizedUnit = Duration2.normalizeUnit(unit); + switch (normalizedUnit) { + case "years": + o.month = 1; + case "quarters": + case "months": + o.day = 1; + case "weeks": + case "days": + o.hour = 0; + case "hours": + o.minute = 0; + case "minutes": + o.second = 0; + case "seconds": + o.millisecond = 0; + break; + } + if (normalizedUnit === "weeks") { + o.weekday = 1; + } + if (normalizedUnit === "quarters") { + const q = Math.ceil(this.month / 3); + o.month = (q - 1) * 3 + 1; + } + return this.set(o); + } + /** + * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time + * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. + * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays + * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' + * @return {DateTime} + */ + endOf(unit) { + return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit).minus(1) : this; + } + // OUTPUT + /** + * Returns a string representation of this DateTime formatted according to the specified format string. + * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). + * Defaults to en-US if no locale has been specified, regardless of the system's locale. + * @param {string} fmt - the format string + * @param {Object} opts - opts to override the configuration options on this DateTime + * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' + * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' + * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' + * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' + * @return {string} + */ + toFormat(fmt, opts = {}) { + return this.isValid ? Formatter2.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID5; + } + /** + * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. + * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation + * of the DateTime in the assigned locale. + * Defaults to the system's locale if no locale has been specified + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options + * @param {Object} opts - opts to override the configuration options on this DateTime + * @example DateTime.now().toLocaleString(); //=> 4/20/2017 + * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' + * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' + * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022' + * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' + * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' + * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' + * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' + * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' + * @return {string} + */ + toLocaleString(formatOpts = DATE_SHORT2, opts = {}) { + return this.isValid ? Formatter2.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID5; + } + /** + * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. + * Defaults to the system's locale if no locale has been specified + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts + * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. + * @example DateTime.now().toLocaleParts(); //=> [ + * //=> { type: 'day', value: '25' }, + * //=> { type: 'literal', value: '/' }, + * //=> { type: 'month', value: '05' }, + * //=> { type: 'literal', value: '/' }, + * //=> { type: 'year', value: '1982' } + * //=> ] + */ + toLocaleParts(opts = {}) { + return this.isValid ? Formatter2.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.extendedZone=false] - add the time zone format extension + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' + * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' + * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' + * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' + * @return {string} + */ + toISO({ + format = "extended", + suppressSeconds = false, + suppressMilliseconds = false, + includeOffset = true, + extendedZone = false + } = {}) { + if (!this.isValid) { + return null; + } + const ext = format === "extended"; + let c = toISODate2(this, ext); + c += "T"; + c += toISOTime2(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); + return c; + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime's date component + * @param {Object} opts - options + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' + * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' + * @return {string} + */ + toISODate({ format = "extended" } = {}) { + if (!this.isValid) { + return null; + } + return toISODate2(this, format === "extended"); + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime's week date + * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' + * @return {string} + */ + toISOWeekDate() { + return toTechFormat2(this, "kkkk-'W'WW-c"); + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime's time component + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.extendedZone=true] - add the time zone format extension + * @param {boolean} [opts.includePrefix=false] - include the `T` prefix + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' + * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' + * @return {string} + */ + toISOTime({ + suppressMilliseconds = false, + suppressSeconds = false, + includeOffset = true, + includePrefix = false, + extendedZone = false, + format = "extended" + } = {}) { + if (!this.isValid) { + return null; + } + let c = includePrefix ? "T" : ""; + return c + toISOTime2( + this, + format === "extended", + suppressSeconds, + suppressMilliseconds, + includeOffset, + extendedZone + ); + } + /** + * Returns an RFC 2822-compatible string representation of this DateTime + * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' + * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' + * @return {string} + */ + toRFC2822() { + return toTechFormat2(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); + } + /** + * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT. + * Specifically, the string conforms to RFC 1123. + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 + * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' + * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' + * @return {string} + */ + toHTTP() { + return toTechFormat2(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); + } + /** + * Returns a string representation of this DateTime appropriate for use in SQL Date + * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' + * @return {string} + */ + toSQLDate() { + if (!this.isValid) { + return null; + } + return toISODate2(this, true); + } + /** + * Returns a string representation of this DateTime appropriate for use in SQL Time + * @param {Object} opts - options + * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' + * @example DateTime.utc().toSQL() //=> '05:15:16.345' + * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' + * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' + * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' + * @return {string} + */ + toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { + let fmt = "HH:mm:ss.SSS"; + if (includeZone || includeOffset) { + if (includeOffsetSpace) { + fmt += " "; + } + if (includeZone) { + fmt += "z"; + } else if (includeOffset) { + fmt += "ZZ"; + } + } + return toTechFormat2(this, fmt, true); + } + /** + * Returns a string representation of this DateTime appropriate for use in SQL DateTime + * @param {Object} opts - options + * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' + * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' + * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' + * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' + * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' + * @return {string} + */ + toSQL(opts = {}) { + if (!this.isValid) { + return null; + } + return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; + } + /** + * Returns a string representation of this DateTime appropriate for debugging + * @return {string} + */ + toString() { + return this.isValid ? this.toISO() : INVALID5; + } + /** + * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis} + * @return {number} + */ + valueOf() { + return this.toMillis(); + } + /** + * Returns the epoch milliseconds of this DateTime. + * @return {number} + */ + toMillis() { + return this.isValid ? this.ts : NaN; + } + /** + * Returns the epoch seconds of this DateTime. + * @return {number} + */ + toSeconds() { + return this.isValid ? this.ts / 1e3 : NaN; + } + /** + * Returns the epoch seconds (as a whole number) of this DateTime. + * @return {number} + */ + toUnixInteger() { + return this.isValid ? Math.floor(this.ts / 1e3) : NaN; + } + /** + * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. + * @return {string} + */ + toJSON() { + return this.toISO(); + } + /** + * Returns a BSON serializable equivalent to this DateTime. + * @return {Date} + */ + toBSON() { + return this.toJSDate(); + } + /** + * Returns a JavaScript object with this DateTime's year, month, day, and so on. + * @param opts - options for generating the object + * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output + * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } + * @return {Object} + */ + toObject(opts = {}) { + if (!this.isValid) + return {}; + const base = { ...this.c }; + if (opts.includeConfig) { + base.outputCalendar = this.outputCalendar; + base.numberingSystem = this.loc.numberingSystem; + base.locale = this.loc.locale; + } + return base; + } + /** + * Returns a JavaScript Date equivalent to this DateTime. + * @return {Date} + */ + toJSDate() { + return new Date(this.isValid ? this.ts : NaN); + } + // COMPARE + /** + * Return the difference between two DateTimes as a Duration. + * @param {DateTime} otherDateTime - the DateTime to compare this one to + * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @example + * var i1 = DateTime.fromISO('1982-05-25T09:45'), + * i2 = DateTime.fromISO('1983-10-14T10:30'); + * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } + * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } + * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } + * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } + * @return {Duration} + */ + diff(otherDateTime, unit = "milliseconds", opts = {}) { + if (!this.isValid || !otherDateTime.isValid) { + return Duration2.invalid("created by diffing an invalid DateTime"); + } + const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts }; + const units = maybeArray2(unit).map(Duration2.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts); + return otherIsLater ? diffed.negate() : diffed; + } + /** + * Return the difference between this DateTime and right now. + * See {@link DateTime#diff} + * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @return {Duration} + */ + diffNow(unit = "milliseconds", opts = {}) { + return this.diff(_DateTime.now(), unit, opts); + } + /** + * Return an Interval spanning between this DateTime and another DateTime + * @param {DateTime} otherDateTime - the other end point of the Interval + * @return {Interval} + */ + until(otherDateTime) { + return this.isValid ? Interval2.fromDateTimes(this, otherDateTime) : this; + } + /** + * Return whether this DateTime is in the same unit of time as another DateTime. + * Higher-order units must also be identical for this function to return `true`. + * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed. + * @param {DateTime} otherDateTime - the other DateTime + * @param {string} unit - the unit of time to check sameness on + * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day + * @return {boolean} + */ + hasSame(otherDateTime, unit) { + if (!this.isValid) + return false; + const inputMs = otherDateTime.valueOf(); + const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true }); + return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit); + } + /** + * Equality check + * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid. + * To compare just the millisecond values, use `+dt1 === +dt2`. + * @param {DateTime} other - the other DateTime + * @return {boolean} + */ + equals(other) { + return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); + } + /** + * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your + * platform supports Intl.RelativeTimeFormat. Rounds down by default. + * @param {Object} options - options that affect the output + * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. + * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" + * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" + * @param {boolean} [options.round=true] - whether to round the numbers in the output. + * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. + * @param {string} options.locale - override the locale of this DateTime + * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this + * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" + * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" + * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" + * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" + * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" + * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" + */ + toRelative(options = {}) { + if (!this.isValid) + return null; + const base = options.base || _DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; + let units = ["years", "months", "days", "hours", "minutes", "seconds"]; + let unit = options.unit; + if (Array.isArray(options.unit)) { + units = options.unit; + unit = void 0; + } + return diffRelative2(base, this.plus(padding), { + ...options, + numeric: "always", + units, + unit + }); + } + /** + * Returns a string representation of this date relative to today, such as "yesterday" or "next month". + * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. + * @param {Object} options - options that affect the output + * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. + * @param {string} options.locale - override the locale of this DateTime + * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" + * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this + * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" + * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" + * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" + * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" + */ + toRelativeCalendar(options = {}) { + if (!this.isValid) + return null; + return diffRelative2(options.base || _DateTime.fromObject({}, { zone: this.zone }), this, { + ...options, + numeric: "auto", + units: ["years", "months", "days"], + calendary: true + }); + } + /** + * Return the min of several date times + * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum + * @return {DateTime} the min DateTime, or undefined if called with no argument + */ + static min(...dateTimes) { + if (!dateTimes.every(_DateTime.isDateTime)) { + throw new InvalidArgumentError2("min requires all arguments be DateTimes"); + } + return bestBy2(dateTimes, (i) => i.valueOf(), Math.min); + } + /** + * Return the max of several date times + * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum + * @return {DateTime} the max DateTime, or undefined if called with no argument + */ + static max(...dateTimes) { + if (!dateTimes.every(_DateTime.isDateTime)) { + throw new InvalidArgumentError2("max requires all arguments be DateTimes"); + } + return bestBy2(dateTimes, (i) => i.valueOf(), Math.max); + } + // MISC + /** + * Explain how a string would be parsed by fromFormat() + * @param {string} text - the string to parse + * @param {string} fmt - the format the string is expected to be in (see description) + * @param {Object} options - options taken by fromFormat() + * @return {Object} + */ + static fromFormatExplain(text2, fmt, options = {}) { + const { locale = null, numberingSystem = null } = options, localeToUse = Locale2.fromOpts({ + locale, + numberingSystem, + defaultToEN: true + }); + return explainFromTokens2(localeToUse, text2, fmt); + } + /** + * @deprecated use fromFormatExplain instead + */ + static fromStringExplain(text2, fmt, options = {}) { + return _DateTime.fromFormatExplain(text2, fmt, options); + } + // FORMAT PRESETS + /** + * {@link DateTime#toLocaleString} format like 10/14/1983 + * @type {Object} + */ + static get DATE_SHORT() { + return DATE_SHORT2; + } + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983' + * @type {Object} + */ + static get DATE_MED() { + return DATE_MED2; + } + /** + * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983' + * @type {Object} + */ + static get DATE_MED_WITH_WEEKDAY() { + return DATE_MED_WITH_WEEKDAY2; + } + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983' + * @type {Object} + */ + static get DATE_FULL() { + return DATE_FULL2; + } + /** + * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983' + * @type {Object} + */ + static get DATE_HUGE() { + return DATE_HUGE2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_SIMPLE() { + return TIME_SIMPLE2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_SECONDS() { + return TIME_WITH_SECONDS2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_SHORT_OFFSET() { + return TIME_WITH_SHORT_OFFSET2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_LONG_OFFSET() { + return TIME_WITH_LONG_OFFSET2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30', always 24-hour. + * @type {Object} + */ + static get TIME_24_SIMPLE() { + return TIME_24_SIMPLE2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_SECONDS() { + return TIME_24_WITH_SECONDS2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_SHORT_OFFSET() { + return TIME_24_WITH_SHORT_OFFSET2; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_LONG_OFFSET() { + return TIME_24_WITH_LONG_OFFSET2; + } + /** + * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_SHORT() { + return DATETIME_SHORT2; + } + /** + * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_SHORT_WITH_SECONDS() { + return DATETIME_SHORT_WITH_SECONDS2; + } + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED() { + return DATETIME_MED2; + } + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED_WITH_SECONDS() { + return DATETIME_MED_WITH_SECONDS2; + } + /** + * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED_WITH_WEEKDAY() { + return DATETIME_MED_WITH_WEEKDAY2; + } + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_FULL() { + return DATETIME_FULL2; + } + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_FULL_WITH_SECONDS() { + return DATETIME_FULL_WITH_SECONDS2; + } + /** + * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_HUGE() { + return DATETIME_HUGE2; + } + /** + * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_HUGE_WITH_SECONDS() { + return DATETIME_HUGE_WITH_SECONDS2; + } + }; + function friendlyDateTime2(dateTimeish) { + if (DateTime2.isDateTime(dateTimeish)) { + return dateTimeish; + } else if (dateTimeish && dateTimeish.valueOf && isNumber2(dateTimeish.valueOf())) { + return DateTime2.fromJSDate(dateTimeish); + } else if (dateTimeish && typeof dateTimeish === "object") { + return DateTime2.fromObject(dateTimeish); + } else { + throw new InvalidArgumentError2( + `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}` + ); + } + } + var DEFAULT_QUERY_SETTINGS = { + renderNullAs: "\\-", + taskCompletionTracking: false, + taskCompletionUseEmojiShorthand: false, + taskCompletionText: "completion", + taskCompletionDateFormat: "yyyy-MM-dd", + recursiveSubTaskCompletion: false, + warnOnEmptyResult: true, + refreshEnabled: true, + refreshInterval: 2500, + defaultDateFormat: "MMMM dd, yyyy", + defaultDateTimeFormat: "h:mm a - MMMM dd, yyyy", + maxRecursiveRenderDepth: 4, + tableIdColumnName: "File", + tableGroupColumnName: "Group", + showResultCount: true + }; + var DEFAULT_EXPORT_SETTINGS = { + allowHtml: true + }; + ({ + ...DEFAULT_QUERY_SETTINGS, + ...DEFAULT_EXPORT_SETTINGS, + ...{ + inlineQueryPrefix: "=", + inlineJsQueryPrefix: "$=", + inlineQueriesInCodeblocks: true, + enableInlineDataview: true, + enableDataviewJs: false, + enableInlineDataviewJs: false, + prettyRenderInlineFields: true, + prettyRenderInlineFieldsInLivePreview: true, + dataviewJsKeyword: "dataviewjs" + } + }); + var Success = class _Success { + constructor(value) { + this.value = value; + this.successful = true; + } + map(f) { + return new _Success(f(this.value)); + } + flatMap(f) { + return f(this.value); + } + mapErr(f) { + return this; + } + bimap(succ2, _fail) { + return this.map(succ2); + } + orElse(_value) { + return this.value; + } + cast() { + return this; + } + orElseThrow(_message) { + return this.value; + } + }; + var Failure = class _Failure { + constructor(error) { + this.error = error; + this.successful = false; + } + map(_f) { + return this; + } + flatMap(_f) { + return this; + } + mapErr(f) { + return new _Failure(f(this.error)); + } + bimap(_succ, fail2) { + return this.mapErr(fail2); + } + orElse(value) { + return value; + } + cast() { + return this; + } + orElseThrow(message) { + if (message) + throw new Error(message(this.error)); + else + throw new Error("" + this.error); + } + }; + var Result; + (function(Result2) { + function success(value) { + return new Success(value); + } + Result2.success = success; + function failure(error) { + return new Failure(error); + } + Result2.failure = failure; + function flatMap2(first, second, f) { + if (first.successful) { + if (second.successful) + return f(first.value, second.value); + else + return failure(second.error); + } else { + return failure(first.error); + } + } + Result2.flatMap2 = flatMap2; + function map2(first, second, f) { + return flatMap2(first, second, (a, b) => success(f(a, b))); + } + Result2.map2 = map2; + })(Result || (Result = {})); + var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; + var parsimmon_umd_min = { exports: {} }; + parsimmon_umd_min.exports; + (function(module3, exports2) { + !function(n3, t) { + module3.exports = t(); + }("undefined" != typeof self ? self : commonjsGlobal, function() { + return function(n3) { + var t = {}; + function r(e) { + if (t[e]) + return t[e].exports; + var u = t[e] = { i: e, l: false, exports: {} }; + return n3[e].call(u.exports, u, u.exports, r), u.l = true, u.exports; + } + return r.m = n3, r.c = t, r.d = function(n4, t2, e) { + r.o(n4, t2) || Object.defineProperty(n4, t2, { configurable: false, enumerable: true, get: e }); + }, r.r = function(n4) { + Object.defineProperty(n4, "__esModule", { value: true }); + }, r.n = function(n4) { + var t2 = n4 && n4.__esModule ? function() { + return n4.default; + } : function() { + return n4; + }; + return r.d(t2, "a", t2), t2; + }, r.o = function(n4, t2) { + return Object.prototype.hasOwnProperty.call(n4, t2); + }, r.p = "", r(r.s = 0); + }([function(n3, t, r) { + function e(n4) { + if (!(this instanceof e)) + return new e(n4); + this._ = n4; + } + var u = e.prototype; + function o(n4, t2) { + for (var r2 = 0; r2 < n4; r2++) + t2(r2); + } + function i(n4, t2, r2) { + return function(n5, t3) { + o(t3.length, function(r3) { + n5(t3[r3], r3, t3); + }); + }(function(r3, e2, u2) { + t2 = n4(t2, r3, e2, u2); + }, r2), t2; + } + function a(n4, t2) { + return i(function(t3, r2, e2, u2) { + return t3.concat([n4(r2, e2, u2)]); + }, [], t2); + } + function f(n4, t2) { + var r2 = { v: 0, buf: t2 }; + return o(n4, function() { + var n5; + r2 = { v: r2.v << 1 | (n5 = r2.buf, n5[0] >> 7), buf: function(n6) { + var t3 = i(function(n7, t4, r3, e2) { + return n7.concat(r3 === e2.length - 1 ? Buffer.from([t4, 0]).readUInt16BE(0) : e2.readUInt16BE(r3)); + }, [], n6); + return Buffer.from(a(function(n7) { + return (n7 << 1 & 65535) >> 8; + }, t3)); + }(r2.buf) }; + }), r2; + } + function c() { + return "undefined" != typeof Buffer; + } + function s3() { + if (!c()) + throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser."); + } + function l3(n4) { + s3(); + var t2 = i(function(n5, t3) { + return n5 + t3; + }, 0, n4); + if (t2 % 8 != 0) + throw new Error("The bits [" + n4.join(", ") + "] add up to " + t2 + " which is not an even number of bytes; the total should be divisible by 8"); + var r2, u2 = t2 / 8, o2 = (r2 = function(n5) { + return n5 > 48; + }, i(function(n5, t3) { + return n5 || (r2(t3) ? t3 : n5); + }, null, n4)); + if (o2) + throw new Error(o2 + " bit range requested exceeds 48 bit (6 byte) Number max."); + return new e(function(t3, r3) { + var e2 = u2 + r3; + return e2 > t3.length ? x(r3, u2.toString() + " bytes") : b(e2, i(function(n5, t4) { + var r4 = f(t4, n5.buf); + return { coll: n5.coll.concat(r4.v), buf: r4.buf }; + }, { coll: [], buf: t3.slice(r3, e2) }, n4).coll); + }); + } + function h(n4, t2) { + return new e(function(r2, e2) { + return s3(), e2 + t2 > r2.length ? x(e2, t2 + " bytes for " + n4) : b(e2 + t2, r2.slice(e2, e2 + t2)); + }); + } + function p(n4, t2) { + if ("number" != typeof (r2 = t2) || Math.floor(r2) !== r2 || t2 < 0 || t2 > 6) + throw new Error(n4 + " requires integer length in range [0, 6]."); + var r2; + } + function d(n4) { + return p("uintBE", n4), h("uintBE(" + n4 + ")", n4).map(function(t2) { + return t2.readUIntBE(0, n4); + }); + } + function v(n4) { + return p("uintLE", n4), h("uintLE(" + n4 + ")", n4).map(function(t2) { + return t2.readUIntLE(0, n4); + }); + } + function g(n4) { + return p("intBE", n4), h("intBE(" + n4 + ")", n4).map(function(t2) { + return t2.readIntBE(0, n4); + }); + } + function m(n4) { + return p("intLE", n4), h("intLE(" + n4 + ")", n4).map(function(t2) { + return t2.readIntLE(0, n4); + }); + } + function y(n4) { + return n4 instanceof e; + } + function E(n4) { + return "[object Array]" === {}.toString.call(n4); + } + function w(n4) { + return c() && Buffer.isBuffer(n4); + } + function b(n4, t2) { + return { status: true, index: n4, value: t2, furthest: -1, expected: [] }; + } + function x(n4, t2) { + return E(t2) || (t2 = [t2]), { status: false, index: -1, value: null, furthest: n4, expected: t2 }; + } + function B(n4, t2) { + if (!t2) + return n4; + if (n4.furthest > t2.furthest) + return n4; + var r2 = n4.furthest === t2.furthest ? function(n5, t3) { + if (function() { + if (void 0 !== e._supportsSet) + return e._supportsSet; + var n6 = "undefined" != typeof Set; + return e._supportsSet = n6, n6; + }() && Array.from) { + for (var r3 = new Set(n5), u2 = 0; u2 < t3.length; u2++) + r3.add(t3[u2]); + var o2 = Array.from(r3); + return o2.sort(), o2; + } + for (var i2 = {}, a2 = 0; a2 < n5.length; a2++) + i2[n5[a2]] = true; + for (var f2 = 0; f2 < t3.length; f2++) + i2[t3[f2]] = true; + var c2 = []; + for (var s4 in i2) + ({}).hasOwnProperty.call(i2, s4) && c2.push(s4); + return c2.sort(), c2; + }(n4.expected, t2.expected) : t2.expected; + return { status: n4.status, index: n4.index, value: n4.value, furthest: t2.furthest, expected: r2 }; + } + var j = {}; + function S(n4, t2) { + if (w(n4)) + return { offset: t2, line: -1, column: -1 }; + n4 in j || (j[n4] = {}); + for (var r2 = j[n4], e2 = 0, u2 = 0, o2 = 0, i2 = t2; i2 >= 0; ) { + if (i2 in r2) { + e2 = r2[i2].line, 0 === o2 && (o2 = r2[i2].lineStart); + break; + } + ("\n" === n4.charAt(i2) || "\r" === n4.charAt(i2) && "\n" !== n4.charAt(i2 + 1)) && (u2++, 0 === o2 && (o2 = i2 + 1)), i2--; + } + var a2 = e2 + u2, f2 = t2 - o2; + return r2[t2] = { line: a2, lineStart: o2 }, { offset: t2, line: a2 + 1, column: f2 + 1 }; + } + function _(n4) { + if (!y(n4)) + throw new Error("not a parser: " + n4); + } + function L(n4, t2) { + return "string" == typeof n4 ? n4.charAt(t2) : n4[t2]; + } + function O(n4) { + if ("number" != typeof n4) + throw new Error("not a number: " + n4); + } + function k(n4) { + if ("function" != typeof n4) + throw new Error("not a function: " + n4); + } + function P(n4) { + if ("string" != typeof n4) + throw new Error("not a string: " + n4); + } + var q = 2, A = 3, I = 8, F = 5 * I, M = 4 * I, z2 = " "; + function R(n4, t2) { + return new Array(t2 + 1).join(n4); + } + function U(n4, t2, r2) { + var e2 = t2 - n4.length; + return e2 <= 0 ? n4 : R(r2, e2) + n4; + } + function W(n4, t2, r2, e2) { + return { from: n4 - t2 > 0 ? n4 - t2 : 0, to: n4 + r2 > e2 ? e2 : n4 + r2 }; + } + function D(n4, t2) { + var r2, e2, u2, o2, f2, c2 = t2.index, s4 = c2.offset, l4 = 1; + if (s4 === n4.length) + return "Got the end of the input"; + if (w(n4)) { + var h2 = s4 - s4 % I, p2 = s4 - h2, d2 = W(h2, F, M + I, n4.length), v2 = a(function(n5) { + return a(function(n6) { + return U(n6.toString(16), 2, "0"); + }, n5); + }, function(n5, t3) { + var r3 = n5.length, e3 = [], u3 = 0; + if (r3 <= t3) + return [n5.slice()]; + for (var o3 = 0; o3 < r3; o3++) + e3[u3] || e3.push([]), e3[u3].push(n5[o3]), (o3 + 1) % t3 == 0 && u3++; + return e3; + }(n4.slice(d2.from, d2.to).toJSON().data, I)); + o2 = function(n5) { + return 0 === n5.from && 1 === n5.to ? { from: n5.from, to: n5.to } : { from: n5.from / I, to: Math.floor(n5.to / I) }; + }(d2), e2 = h2 / I, r2 = 3 * p2, p2 >= 4 && (r2 += 1), l4 = 2, u2 = a(function(n5) { + return n5.length <= 4 ? n5.join(" ") : n5.slice(0, 4).join(" ") + " " + n5.slice(4).join(" "); + }, v2), (f2 = (8 * (o2.to > 0 ? o2.to - 1 : o2.to)).toString(16).length) < 2 && (f2 = 2); + } else { + var g2 = n4.split(/\r\n|[\n\r\u2028\u2029]/); + r2 = c2.column - 1, e2 = c2.line - 1, o2 = W(e2, q, A, g2.length), u2 = g2.slice(o2.from, o2.to), f2 = o2.to.toString().length; + } + var m2 = e2 - o2.from; + return w(n4) && (f2 = (8 * (o2.to > 0 ? o2.to - 1 : o2.to)).toString(16).length) < 2 && (f2 = 2), i(function(t3, e3, u3) { + var i2, a2 = u3 === m2, c3 = a2 ? "> " : z2; + return i2 = w(n4) ? U((8 * (o2.from + u3)).toString(16), f2, "0") : U((o2.from + u3 + 1).toString(), f2, " "), [].concat(t3, [c3 + i2 + " | " + e3], a2 ? [z2 + R(" ", f2) + " | " + U("", r2, " ") + R("^", l4)] : []); + }, [], u2).join("\n"); + } + function N(n4, t2) { + return ["\n", "-- PARSING FAILED " + R("-", 50), "\n\n", D(n4, t2), "\n\n", (r2 = t2.expected, 1 === r2.length ? "Expected:\n\n" + r2[0] : "Expected one of the following: \n\n" + r2.join(", ")), "\n"].join(""); + var r2; + } + function G(n4) { + return void 0 !== n4.flags ? n4.flags : [n4.global ? "g" : "", n4.ignoreCase ? "i" : "", n4.multiline ? "m" : "", n4.unicode ? "u" : "", n4.sticky ? "y" : ""].join(""); + } + function C() { + for (var n4 = [].slice.call(arguments), t2 = n4.length, r2 = 0; r2 < t2; r2 += 1) + _(n4[r2]); + return e(function(r3, e2) { + for (var u2, o2 = new Array(t2), i2 = 0; i2 < t2; i2 += 1) { + if (!(u2 = B(n4[i2]._(r3, e2), u2)).status) + return u2; + o2[i2] = u2.value, e2 = u2.index; + } + return B(b(e2, o2), u2); + }); + } + function J() { + var n4 = [].slice.call(arguments); + if (0 === n4.length) + throw new Error("seqMap needs at least one argument"); + var t2 = n4.pop(); + return k(t2), C.apply(null, n4).map(function(n5) { + return t2.apply(null, n5); + }); + } + function T() { + var n4 = [].slice.call(arguments), t2 = n4.length; + if (0 === t2) + return Y("zero alternates"); + for (var r2 = 0; r2 < t2; r2 += 1) + _(n4[r2]); + return e(function(t3, r3) { + for (var e2, u2 = 0; u2 < n4.length; u2 += 1) + if ((e2 = B(n4[u2]._(t3, r3), e2)).status) + return e2; + return e2; + }); + } + function V(n4, t2) { + return H(n4, t2).or(X([])); + } + function H(n4, t2) { + return _(n4), _(t2), J(n4, t2.then(n4).many(), function(n5, t3) { + return [n5].concat(t3); + }); + } + function K(n4) { + P(n4); + var t2 = "'" + n4 + "'"; + return e(function(r2, e2) { + var u2 = e2 + n4.length, o2 = r2.slice(e2, u2); + return o2 === n4 ? b(u2, o2) : x(e2, t2); + }); + } + function Q(n4, t2) { + !function(n5) { + if (!(n5 instanceof RegExp)) + throw new Error("not a regexp: " + n5); + for (var t3 = G(n5), r3 = 0; r3 < t3.length; r3++) { + var e2 = t3.charAt(r3); + if ("i" !== e2 && "m" !== e2 && "u" !== e2 && "s" !== e2) + throw new Error('unsupported regexp flag "' + e2 + '": ' + n5); + } + }(n4), arguments.length >= 2 ? O(t2) : t2 = 0; + var r2 = function(n5) { + return RegExp("^(?:" + n5.source + ")", G(n5)); + }(n4), u2 = "" + n4; + return e(function(n5, e2) { + var o2 = r2.exec(n5.slice(e2)); + if (o2) { + if (0 <= t2 && t2 <= o2.length) { + var i2 = o2[0], a2 = o2[t2]; + return b(e2 + i2.length, a2); + } + return x(e2, "valid match group (0 to " + o2.length + ") in " + u2); + } + return x(e2, u2); + }); + } + function X(n4) { + return e(function(t2, r2) { + return b(r2, n4); + }); + } + function Y(n4) { + return e(function(t2, r2) { + return x(r2, n4); + }); + } + function Z(n4) { + if (y(n4)) + return e(function(t2, r2) { + var e2 = n4._(t2, r2); + return e2.index = r2, e2.value = "", e2; + }); + if ("string" == typeof n4) + return Z(K(n4)); + if (n4 instanceof RegExp) + return Z(Q(n4)); + throw new Error("not a string, regexp, or parser: " + n4); + } + function $(n4) { + return _(n4), e(function(t2, r2) { + var e2 = n4._(t2, r2), u2 = t2.slice(r2, e2.index); + return e2.status ? x(r2, 'not "' + u2 + '"') : b(r2, null); + }); + } + function nn(n4) { + return k(n4), e(function(t2, r2) { + var e2 = L(t2, r2); + return r2 < t2.length && n4(e2) ? b(r2 + 1, e2) : x(r2, "a character/byte matching " + n4); + }); + } + function tn(n4, t2) { + arguments.length < 2 && (t2 = n4, n4 = void 0); + var r2 = e(function(n5, e2) { + return r2._ = t2()._, r2._(n5, e2); + }); + return n4 ? r2.desc(n4) : r2; + } + function rn() { + return Y("fantasy-land/empty"); + } + u.parse = function(n4) { + if ("string" != typeof n4 && !w(n4)) + throw new Error(".parse must be called with a string or Buffer as its argument"); + var t2, r2 = this.skip(an)._(n4, 0); + return t2 = r2.status ? { status: true, value: r2.value } : { status: false, index: S(n4, r2.furthest), expected: r2.expected }, delete j[n4], t2; + }, u.tryParse = function(n4) { + var t2 = this.parse(n4); + if (t2.status) + return t2.value; + var r2 = N(n4, t2), e2 = new Error(r2); + throw e2.type = "ParsimmonError", e2.result = t2, e2; + }, u.assert = function(n4, t2) { + return this.chain(function(r2) { + return n4(r2) ? X(r2) : Y(t2); + }); + }, u.or = function(n4) { + return T(this, n4); + }, u.trim = function(n4) { + return this.wrap(n4, n4); + }, u.wrap = function(n4, t2) { + return J(n4, this, t2, function(n5, t3) { + return t3; + }); + }, u.thru = function(n4) { + return n4(this); + }, u.then = function(n4) { + return _(n4), C(this, n4).map(function(n5) { + return n5[1]; + }); + }, u.many = function() { + var n4 = this; + return e(function(t2, r2) { + for (var e2 = [], u2 = void 0; ; ) { + if (!(u2 = B(n4._(t2, r2), u2)).status) + return B(b(r2, e2), u2); + if (r2 === u2.index) + throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause"); + r2 = u2.index, e2.push(u2.value); + } + }); + }, u.tieWith = function(n4) { + return P(n4), this.map(function(t2) { + if (function(n5) { + if (!E(n5)) + throw new Error("not an array: " + n5); + }(t2), t2.length) { + P(t2[0]); + for (var r2 = t2[0], e2 = 1; e2 < t2.length; e2++) + P(t2[e2]), r2 += n4 + t2[e2]; + return r2; + } + return ""; + }); + }, u.tie = function() { + return this.tieWith(""); + }, u.times = function(n4, t2) { + var r2 = this; + return arguments.length < 2 && (t2 = n4), O(n4), O(t2), e(function(e2, u2) { + for (var o2 = [], i2 = void 0, a2 = void 0, f2 = 0; f2 < n4; f2 += 1) { + if (a2 = B(i2 = r2._(e2, u2), a2), !i2.status) + return a2; + u2 = i2.index, o2.push(i2.value); + } + for (; f2 < t2 && (a2 = B(i2 = r2._(e2, u2), a2), i2.status); f2 += 1) + u2 = i2.index, o2.push(i2.value); + return B(b(u2, o2), a2); + }); + }, u.result = function(n4) { + return this.map(function() { + return n4; + }); + }, u.atMost = function(n4) { + return this.times(0, n4); + }, u.atLeast = function(n4) { + return J(this.times(n4), this.many(), function(n5, t2) { + return n5.concat(t2); + }); + }, u.map = function(n4) { + k(n4); + var t2 = this; + return e(function(r2, e2) { + var u2 = t2._(r2, e2); + return u2.status ? B(b(u2.index, n4(u2.value)), u2) : u2; + }); + }, u.contramap = function(n4) { + k(n4); + var t2 = this; + return e(function(r2, e2) { + var u2 = t2.parse(n4(r2.slice(e2))); + return u2.status ? b(e2 + r2.length, u2.value) : u2; + }); + }, u.promap = function(n4, t2) { + return k(n4), k(t2), this.contramap(n4).map(t2); + }, u.skip = function(n4) { + return C(this, n4).map(function(n5) { + return n5[0]; + }); + }, u.mark = function() { + return J(en, this, en, function(n4, t2, r2) { + return { start: n4, value: t2, end: r2 }; + }); + }, u.node = function(n4) { + return J(en, this, en, function(t2, r2, e2) { + return { name: n4, value: r2, start: t2, end: e2 }; + }); + }, u.sepBy = function(n4) { + return V(this, n4); + }, u.sepBy1 = function(n4) { + return H(this, n4); + }, u.lookahead = function(n4) { + return this.skip(Z(n4)); + }, u.notFollowedBy = function(n4) { + return this.skip($(n4)); + }, u.desc = function(n4) { + E(n4) || (n4 = [n4]); + var t2 = this; + return e(function(r2, e2) { + var u2 = t2._(r2, e2); + return u2.status || (u2.expected = n4), u2; + }); + }, u.fallback = function(n4) { + return this.or(X(n4)); + }, u.ap = function(n4) { + return J(n4, this, function(n5, t2) { + return n5(t2); + }); + }, u.chain = function(n4) { + var t2 = this; + return e(function(r2, e2) { + var u2 = t2._(r2, e2); + return u2.status ? B(n4(u2.value)._(r2, u2.index), u2) : u2; + }); + }, u.concat = u.or, u.empty = rn, u.of = X, u["fantasy-land/ap"] = u.ap, u["fantasy-land/chain"] = u.chain, u["fantasy-land/concat"] = u.concat, u["fantasy-land/empty"] = u.empty, u["fantasy-land/of"] = u.of, u["fantasy-land/map"] = u.map; + var en = e(function(n4, t2) { + return b(t2, S(n4, t2)); + }), un = e(function(n4, t2) { + return t2 >= n4.length ? x(t2, "any character/byte") : b(t2 + 1, L(n4, t2)); + }), on = e(function(n4, t2) { + return b(n4.length, n4.slice(t2)); + }), an = e(function(n4, t2) { + return t2 < n4.length ? x(t2, "EOF") : b(t2, null); + }), fn = Q(/[0-9]/).desc("a digit"), cn = Q(/[0-9]*/).desc("optional digits"), sn = Q(/[a-z]/i).desc("a letter"), ln = Q(/[a-z]*/i).desc("optional letters"), hn = Q(/\s*/).desc("optional whitespace"), pn = Q(/\s+/).desc("whitespace"), dn = K("\r"), vn = K("\n"), gn = K("\r\n"), mn = T(gn, vn, dn).desc("newline"), yn = T(mn, an); + e.all = on, e.alt = T, e.any = un, e.cr = dn, e.createLanguage = function(n4) { + var t2 = {}; + for (var r2 in n4) + ({}).hasOwnProperty.call(n4, r2) && function(r3) { + t2[r3] = tn(function() { + return n4[r3](t2); + }); + }(r2); + return t2; + }, e.crlf = gn, e.custom = function(n4) { + return e(n4(b, x)); + }, e.digit = fn, e.digits = cn, e.empty = rn, e.end = yn, e.eof = an, e.fail = Y, e.formatError = N, e.index = en, e.isParser = y, e.lazy = tn, e.letter = sn, e.letters = ln, e.lf = vn, e.lookahead = Z, e.makeFailure = x, e.makeSuccess = b, e.newline = mn, e.noneOf = function(n4) { + return nn(function(t2) { + return n4.indexOf(t2) < 0; + }).desc("none of '" + n4 + "'"); + }, e.notFollowedBy = $, e.of = X, e.oneOf = function(n4) { + for (var t2 = n4.split(""), r2 = 0; r2 < t2.length; r2++) + t2[r2] = "'" + t2[r2] + "'"; + return nn(function(t3) { + return n4.indexOf(t3) >= 0; + }).desc(t2); + }, e.optWhitespace = hn, e.Parser = e, e.range = function(n4, t2) { + return nn(function(r2) { + return n4 <= r2 && r2 <= t2; + }).desc(n4 + "-" + t2); + }, e.regex = Q, e.regexp = Q, e.sepBy = V, e.sepBy1 = H, e.seq = C, e.seqMap = J, e.seqObj = function() { + for (var n4, t2 = {}, r2 = 0, u2 = (n4 = arguments, Array.prototype.slice.call(n4)), o2 = u2.length, i2 = 0; i2 < o2; i2 += 1) { + var a2 = u2[i2]; + if (!y(a2)) { + if (E(a2) && 2 === a2.length && "string" == typeof a2[0] && y(a2[1])) { + var f2 = a2[0]; + if (Object.prototype.hasOwnProperty.call(t2, f2)) + throw new Error("seqObj: duplicate key " + f2); + t2[f2] = true, r2++; + continue; + } + throw new Error("seqObj arguments must be parsers or [string, parser] array pairs."); + } + } + if (0 === r2) + throw new Error("seqObj expects at least one named parser, found zero"); + return e(function(n5, t3) { + for (var r3, e2 = {}, i3 = 0; i3 < o2; i3 += 1) { + var a3, f3; + if (E(u2[i3]) ? (a3 = u2[i3][0], f3 = u2[i3][1]) : (a3 = null, f3 = u2[i3]), !(r3 = B(f3._(n5, t3), r3)).status) + return r3; + a3 && (e2[a3] = r3.value), t3 = r3.index; + } + return B(b(t3, e2), r3); + }); + }, e.string = K, e.succeed = X, e.takeWhile = function(n4) { + return k(n4), e(function(t2, r2) { + for (var e2 = r2; e2 < t2.length && n4(L(t2, e2)); ) + e2++; + return b(e2, t2.slice(r2, e2)); + }); + }, e.test = nn, e.whitespace = pn, e["fantasy-land/empty"] = rn, e["fantasy-land/of"] = X, e.Binary = { bitSeq: l3, bitSeqObj: function(n4) { + s3(); + var t2 = {}, r2 = 0, e2 = a(function(n5) { + if (E(n5)) { + var e3 = n5; + if (2 !== e3.length) + throw new Error("[" + e3.join(", ") + "] should be length 2, got length " + e3.length); + if (P(e3[0]), O(e3[1]), Object.prototype.hasOwnProperty.call(t2, e3[0])) + throw new Error("duplicate key in bitSeqObj: " + e3[0]); + return t2[e3[0]] = true, r2++, e3; + } + return O(n5), [null, n5]; + }, n4); + if (r2 < 1) + throw new Error("bitSeqObj expects at least one named pair, got [" + n4.join(", ") + "]"); + var u2 = a(function(n5) { + return n5[0]; + }, e2); + return l3(a(function(n5) { + return n5[1]; + }, e2)).map(function(n5) { + return i(function(n6, t3) { + return null !== t3[0] && (n6[t3[0]] = t3[1]), n6; + }, {}, a(function(t3, r3) { + return [t3, n5[r3]]; + }, u2)); + }); + }, byte: function(n4) { + if (s3(), O(n4), n4 > 255) + throw new Error("Value specified to byte constructor (" + n4 + "=0x" + n4.toString(16) + ") is larger in value than a single byte."); + var t2 = (n4 > 15 ? "0x" : "0x0") + n4.toString(16); + return e(function(r2, e2) { + var u2 = L(r2, e2); + return u2 === n4 ? b(e2 + 1, u2) : x(e2, t2); + }); + }, buffer: function(n4) { + return h("buffer", n4).map(function(n5) { + return Buffer.from(n5); + }); + }, encodedString: function(n4, t2) { + return h("string", t2).map(function(t3) { + return t3.toString(n4); + }); + }, uintBE: d, uint8BE: d(1), uint16BE: d(2), uint32BE: d(4), uintLE: v, uint8LE: v(1), uint16LE: v(2), uint32LE: v(4), intBE: g, int8BE: g(1), int16BE: g(2), int32BE: g(4), intLE: m, int8LE: m(1), int16LE: m(2), int32LE: m(4), floatBE: h("floatBE", 4).map(function(n4) { + return n4.readFloatBE(0); + }), floatLE: h("floatLE", 4).map(function(n4) { + return n4.readFloatLE(0); + }), doubleBE: h("doubleBE", 8).map(function(n4) { + return n4.readDoubleBE(0); + }), doubleLE: h("doubleLE", 8).map(function(n4) { + return n4.readDoubleLE(0); + }) }, n3.exports = e; + }]); + }); + })(parsimmon_umd_min, parsimmon_umd_min.exports); + var parsimmon_umd_minExports = parsimmon_umd_min.exports; + var emojiRegex2 = () => { + return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC3\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA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95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; + }; + function normalizeDuration(dur) { + if (dur === void 0 || dur === null) + return dur; + return dur.shiftToAll().normalize(); + } + function getFileTitle(path) { + if (path.includes("/")) + path = path.substring(path.lastIndexOf("/") + 1); + if (path.endsWith(".md")) + path = path.substring(0, path.length - 3); + return path; + } + parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex2(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u).map((str) => str.toLocaleLowerCase()), parsimmon_umd_minExports.whitespace.map((_) => "-"), parsimmon_umd_minExports.any.map((_) => "")).many().map((result) => result.join("")); + var HEADER_CANONICALIZER = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex2(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u), parsimmon_umd_minExports.whitespace.map((_) => " "), parsimmon_umd_minExports.any.map((_) => " ")).many().map((result) => { + return result.join("").split(/\s+/).join(" ").trim(); + }); + function normalizeHeaderForLink(header) { + return HEADER_CANONICALIZER.tryParse(header); + } + function renderMinimalDuration(dur) { + dur = normalizeDuration(dur); + dur = Duration2.fromObject(Object.fromEntries(Object.entries(dur.toObject()).filter(([, quantity]) => quantity != 0))); + return dur.toHuman(); + } + var Values; + (function(Values2) { + function toString(field, setting = DEFAULT_QUERY_SETTINGS, recursive = false) { + let wrapped = wrapValue(field); + if (!wrapped) + return setting.renderNullAs; + switch (wrapped.type) { + case "null": + return setting.renderNullAs; + case "string": + return wrapped.value; + case "number": + case "boolean": + return "" + wrapped.value; + case "html": + return wrapped.value.outerHTML; + case "widget": + return wrapped.value.markdown(); + case "link": + return wrapped.value.markdown(); + case "function": + return ""; + case "array": + let result = ""; + if (recursive) + result += "["; + result += wrapped.value.map((f) => toString(f, setting, true)).join(", "); + if (recursive) + result += "]"; + return result; + case "object": + return "{ " + Object.entries(wrapped.value).map((e) => e[0] + ": " + toString(e[1], setting, true)).join(", ") + " }"; + case "date": + if (wrapped.value.second == 0 && wrapped.value.hour == 0 && wrapped.value.minute == 0) { + return wrapped.value.toFormat(setting.defaultDateFormat); + } + return wrapped.value.toFormat(setting.defaultDateTimeFormat); + case "duration": + return renderMinimalDuration(wrapped.value); + } + } + Values2.toString = toString; + function wrapValue(val) { + if (isNull(val)) + return { type: "null", value: val }; + else if (isNumber3(val)) + return { type: "number", value: val }; + else if (isString3(val)) + return { type: "string", value: val }; + else if (isBoolean(val)) + return { type: "boolean", value: val }; + else if (isDuration(val)) + return { type: "duration", value: val }; + else if (isDate3(val)) + return { type: "date", value: val }; + else if (isWidget(val)) + return { type: "widget", value: val }; + else if (isArray(val)) + return { type: "array", value: val }; + else if (isLink(val)) + return { type: "link", value: val }; + else if (isFunction(val)) + return { type: "function", value: val }; + else if (isHtml(val)) + return { type: "html", value: val }; + else if (isObject(val)) + return { type: "object", value: val }; + else + return void 0; + } + Values2.wrapValue = wrapValue; + function mapLeaves(val, func) { + if (isObject(val)) { + let result = {}; + for (let [key, value] of Object.entries(val)) + result[key] = mapLeaves(value, func); + return result; + } else if (isArray(val)) { + let result = []; + for (let value of val) + result.push(mapLeaves(value, func)); + return result; + } else { + return func(val); + } + } + Values2.mapLeaves = mapLeaves; + function compareValue(val1, val2, linkNormalizer) { + var _a, _b; + if (val1 === void 0) + val1 = null; + if (val2 === void 0) + val2 = null; + if (val1 === null && val2 === null) + return 0; + else if (val1 === null) + return -1; + else if (val2 === null) + return 1; + let wrap1 = wrapValue(val1); + let wrap2 = wrapValue(val2); + if (wrap1 === void 0 && wrap2 === void 0) + return 0; + else if (wrap1 === void 0) + return -1; + else if (wrap2 === void 0) + return 1; + if (wrap1.type != wrap2.type) + return wrap1.type.localeCompare(wrap2.type); + if (wrap1.value === wrap2.value) + return 0; + switch (wrap1.type) { + case "string": + return wrap1.value.localeCompare(wrap2.value); + case "number": + if (wrap1.value < wrap2.value) + return -1; + else if (wrap1.value == wrap2.value) + return 0; + return 1; + case "null": + return 0; + case "boolean": + if (wrap1.value == wrap2.value) + return 0; + else + return wrap1.value ? 1 : -1; + case "link": + let link1 = wrap1.value; + let link2 = wrap2.value; + let normalize = linkNormalizer !== null && linkNormalizer !== void 0 ? linkNormalizer : (x) => x; + let pathCompare = normalize(link1.path).localeCompare(normalize(link2.path)); + if (pathCompare != 0) + return pathCompare; + let typeCompare = link1.type.localeCompare(link2.type); + if (typeCompare != 0) + return typeCompare; + if (link1.subpath && !link2.subpath) + return 1; + if (!link1.subpath && link2.subpath) + return -1; + if (!link1.subpath && !link2.subpath) + return 0; + return ((_a = link1.subpath) !== null && _a !== void 0 ? _a : "").localeCompare((_b = link2.subpath) !== null && _b !== void 0 ? _b : ""); + case "date": + return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1; + case "duration": + return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1; + case "array": + let f1 = wrap1.value; + let f2 = wrap2.value; + for (let index = 0; index < Math.min(f1.length, f2.length); index++) { + let comp = compareValue(f1[index], f2[index]); + if (comp != 0) + return comp; + } + return f1.length - f2.length; + case "object": + let o1 = wrap1.value; + let o2 = wrap2.value; + let k1 = Array.from(Object.keys(o1)); + let k2 = Array.from(Object.keys(o2)); + k1.sort(); + k2.sort(); + let keyCompare = compareValue(k1, k2); + if (keyCompare != 0) + return keyCompare; + for (let key of k1) { + let comp = compareValue(o1[key], o2[key]); + if (comp != 0) + return comp; + } + return 0; + case "widget": + case "html": + case "function": + return 0; + } + } + Values2.compareValue = compareValue; + function typeOf(val) { + var _a; + return (_a = wrapValue(val)) === null || _a === void 0 ? void 0 : _a.type; + } + Values2.typeOf = typeOf; + function isTruthy(field) { + let wrapped = wrapValue(field); + if (!wrapped) + return false; + switch (wrapped.type) { + case "number": + return wrapped.value != 0; + case "string": + return wrapped.value.length > 0; + case "boolean": + return wrapped.value; + case "link": + return !!wrapped.value.path; + case "date": + return wrapped.value.toMillis() != 0; + case "duration": + return wrapped.value.as("seconds") != 0; + case "object": + return Object.keys(wrapped.value).length > 0; + case "array": + return wrapped.value.length > 0; + case "null": + return false; + case "html": + case "widget": + case "function": + return true; + } + } + Values2.isTruthy = isTruthy; + function deepCopy(field) { + if (field === null || field === void 0) + return field; + if (Values2.isArray(field)) { + return [].concat(field.map((v) => deepCopy(v))); + } else if (Values2.isObject(field)) { + let result = {}; + for (let [key, value] of Object.entries(field)) + result[key] = deepCopy(value); + return result; + } else { + return field; + } + } + Values2.deepCopy = deepCopy; + function isString3(val) { + return typeof val == "string"; + } + Values2.isString = isString3; + function isNumber3(val) { + return typeof val == "number"; + } + Values2.isNumber = isNumber3; + function isDate3(val) { + return val instanceof DateTime2; + } + Values2.isDate = isDate3; + function isDuration(val) { + return val instanceof Duration2; + } + Values2.isDuration = isDuration; + function isNull(val) { + return val === null || val === void 0; + } + Values2.isNull = isNull; + function isArray(val) { + return Array.isArray(val); + } + Values2.isArray = isArray; + function isBoolean(val) { + return typeof val === "boolean"; + } + Values2.isBoolean = isBoolean; + function isLink(val) { + return val instanceof Link; + } + Values2.isLink = isLink; + function isWidget(val) { + return val instanceof Widget; + } + Values2.isWidget = isWidget; + function isHtml(val) { + if (typeof HTMLElement !== "undefined") { + return val instanceof HTMLElement; + } else { + return false; + } + } + Values2.isHtml = isHtml; + function isObject(val) { + return typeof val == "object" && !isHtml(val) && !isWidget(val) && !isArray(val) && !isDuration(val) && !isDate3(val) && !isLink(val) && val !== void 0 && !isNull(val); + } + Values2.isObject = isObject; + function isFunction(val) { + return typeof val == "function"; + } + Values2.isFunction = isFunction; + })(Values || (Values = {})); + var Groupings; + (function(Groupings2) { + function isElementGroup(entry) { + return Values.isObject(entry) && Object.keys(entry).length == 2 && "key" in entry && "rows" in entry; + } + Groupings2.isElementGroup = isElementGroup; + function isGrouping(entry) { + for (let element2 of entry) + if (!isElementGroup(element2)) + return false; + return true; + } + Groupings2.isGrouping = isGrouping; + function count(elements) { + if (isGrouping(elements)) { + let result = 0; + for (let subgroup of elements) + result += count(subgroup.rows); + return result; + } else { + return elements.length; + } + } + Groupings2.count = count; + })(Groupings || (Groupings = {})); + var Link = class _Link { + /** Create a link to a specific file. */ + static file(path, embed = false, display) { + return new _Link({ + path, + embed, + display, + subpath: void 0, + type: "file" + }); + } + static infer(linkpath, embed = false, display) { + if (linkpath.includes("#^")) { + let split = linkpath.split("#^"); + return _Link.block(split[0], split[1], embed, display); + } else if (linkpath.includes("#")) { + let split = linkpath.split("#"); + return _Link.header(split[0], split[1], embed, display); + } else + return _Link.file(linkpath, embed, display); + } + /** Create a link to a specific file and header in that file. */ + static header(path, header, embed, display) { + return new _Link({ + path, + embed, + display, + subpath: normalizeHeaderForLink(header), + type: "header" + }); + } + /** Create a link to a specific file and block in that file. */ + static block(path, blockId, embed, display) { + return new _Link({ + path, + embed, + display, + subpath: blockId, + type: "block" + }); + } + static fromObject(object) { + return new _Link(object); + } + constructor(fields) { + Object.assign(this, fields); + } + /** Checks for link equality (i.e., that the links are pointing to the same exact location). */ + equals(other) { + if (other == void 0 || other == null) + return false; + return this.path == other.path && this.type == other.type && this.subpath == other.subpath; + } + /** Convert this link to it's markdown representation. */ + toString() { + return this.markdown(); + } + /** Convert this link to a raw object which is serialization-friendly. */ + toObject() { + return { path: this.path, type: this.type, subpath: this.subpath, display: this.display, embed: this.embed }; + } + /** Update this link with a new path. */ + //@ts-ignore; error appeared after updating Obsidian to 0.15.4; it also updated other packages but didn't say which + withPath(path) { + return new _Link(Object.assign({}, this, { path })); + } + /** Return a new link which points to the same location but with a new display value. */ + withDisplay(display) { + return new _Link(Object.assign({}, this, { display })); + } + /** Convert a file link into a link to a specific header. */ + withHeader(header) { + return _Link.header(this.path, header, this.embed, this.display); + } + /** Convert any link into a link to its file. */ + toFile() { + return _Link.file(this.path, this.embed, this.display); + } + /** Convert this link into an embedded link. */ + toEmbed() { + if (this.embed) { + return this; + } else { + let link = new _Link(this); + link.embed = true; + return link; + } + } + /** Convert this link into a non-embedded link. */ + fromEmbed() { + if (!this.embed) { + return this; + } else { + let link = new _Link(this); + link.embed = false; + return link; + } + } + /** Convert this link to markdown so it can be rendered. */ + markdown() { + let result = (this.embed ? "!" : "") + "[[" + this.obsidianLink(); + if (this.display) { + result += "|" + this.display; + } else { + result += "|" + getFileTitle(this.path); + if (this.type == "header" || this.type == "block") + result += " > " + this.subpath; + } + result += "]]"; + return result; + } + /** Convert the inner part of the link to something that Obsidian can open / understand. */ + obsidianLink() { + var _a, _b; + const escaped = this.path.replace("|", "\\|"); + if (this.type == "header") + return escaped + "#" + ((_a = this.subpath) === null || _a === void 0 ? void 0 : _a.replace("|", "\\|")); + if (this.type == "block") + return escaped + "#^" + ((_b = this.subpath) === null || _b === void 0 ? void 0 : _b.replace("|", "\\|")); + else + return escaped; + } + /** The stripped name of the file this link points to. */ + fileName() { + return getFileTitle(this.path).replace(".md", ""); + } + }; + var Widget = class { + constructor($widget) { + this.$widget = $widget; + } + }; + var ListPairWidget = class extends Widget { + constructor(key, value) { + super("dataview:list-pair"); + this.key = key; + this.value = value; + } + markdown() { + return `${Values.toString(this.key)}: ${Values.toString(this.value)}`; + } + }; + var ExternalLinkWidget = class extends Widget { + constructor(url, display) { + super("dataview:external-link"); + this.url = url; + this.display = display; + } + markdown() { + var _a; + return `[${(_a = this.display) !== null && _a !== void 0 ? _a : this.url}](${this.url})`; + } + }; + var Widgets; + (function(Widgets2) { + function listPair(key, value) { + return new ListPairWidget(key, value); + } + Widgets2.listPair = listPair; + function externalLink(url, display) { + return new ExternalLinkWidget(url, display); + } + Widgets2.externalLink = externalLink; + function isListPair(widget) { + return widget.$widget === "dataview:list-pair"; + } + Widgets2.isListPair = isListPair; + function isExternalLink(widget) { + return widget.$widget === "dataview:external-link"; + } + Widgets2.isExternalLink = isExternalLink; + function isBuiltin(widget) { + return isListPair(widget) || isExternalLink(widget); + } + Widgets2.isBuiltin = isBuiltin; + })(Widgets || (Widgets = {})); + var Fields; + (function(Fields2) { + function variable(name) { + return { type: "variable", name }; + } + Fields2.variable = variable; + function literal(value) { + return { type: "literal", value }; + } + Fields2.literal = literal; + function binaryOp(left, op, right) { + return { type: "binaryop", left, op, right }; + } + Fields2.binaryOp = binaryOp; + function index(obj, index2) { + return { type: "index", object: obj, index: index2 }; + } + Fields2.index = index; + function indexVariable(name) { + let parts = name.split("."); + let result = Fields2.variable(parts[0]); + for (let index2 = 1; index2 < parts.length; index2++) { + result = Fields2.index(result, Fields2.literal(parts[index2])); + } + return result; + } + Fields2.indexVariable = indexVariable; + function lambda(args, value) { + return { type: "lambda", arguments: args, value }; + } + Fields2.lambda = lambda; + function func(func2, args) { + return { type: "function", func: func2, arguments: args }; + } + Fields2.func = func; + function list(values) { + return { type: "list", values }; + } + Fields2.list = list; + function object(values) { + return { type: "object", values }; + } + Fields2.object = object; + function negate(child) { + return { type: "negated", child }; + } + Fields2.negate = negate; + function isCompareOp(op) { + return op == "<=" || op == "<" || op == ">" || op == ">=" || op == "!=" || op == "="; + } + Fields2.isCompareOp = isCompareOp; + Fields2.NULL = Fields2.literal(null); + })(Fields || (Fields = {})); + var Sources; + (function(Sources2) { + function tag(tag2) { + return { type: "tag", tag: tag2 }; + } + Sources2.tag = tag; + function csv(path) { + return { type: "csv", path }; + } + Sources2.csv = csv; + function folder(prefix) { + return { type: "folder", folder: prefix }; + } + Sources2.folder = folder; + function link(file, incoming) { + return { type: "link", file, direction: incoming ? "incoming" : "outgoing" }; + } + Sources2.link = link; + function binaryOp(left, op, right) { + return { type: "binaryop", left, op, right }; + } + Sources2.binaryOp = binaryOp; + function and(left, right) { + return { type: "binaryop", left, op: "&", right }; + } + Sources2.and = and; + function or(left, right) { + return { type: "binaryop", left, op: "|", right }; + } + Sources2.or = or; + function negate(child) { + return { type: "negate", child }; + } + Sources2.negate = negate; + function empty2() { + return { type: "empty" }; + } + Sources2.empty = empty2; + })(Sources || (Sources = {})); + var EMOJI_REGEX = new RegExp(emojiRegex2(), ""); + var DURATION_TYPES = { + year: Duration2.fromObject({ years: 1 }), + years: Duration2.fromObject({ years: 1 }), + yr: Duration2.fromObject({ years: 1 }), + yrs: Duration2.fromObject({ years: 1 }), + month: Duration2.fromObject({ months: 1 }), + months: Duration2.fromObject({ months: 1 }), + mo: Duration2.fromObject({ months: 1 }), + mos: Duration2.fromObject({ months: 1 }), + week: Duration2.fromObject({ weeks: 1 }), + weeks: Duration2.fromObject({ weeks: 1 }), + wk: Duration2.fromObject({ weeks: 1 }), + wks: Duration2.fromObject({ weeks: 1 }), + w: Duration2.fromObject({ weeks: 1 }), + day: Duration2.fromObject({ days: 1 }), + days: Duration2.fromObject({ days: 1 }), + d: Duration2.fromObject({ days: 1 }), + hour: Duration2.fromObject({ hours: 1 }), + hours: Duration2.fromObject({ hours: 1 }), + hr: Duration2.fromObject({ hours: 1 }), + hrs: Duration2.fromObject({ hours: 1 }), + h: Duration2.fromObject({ hours: 1 }), + minute: Duration2.fromObject({ minutes: 1 }), + minutes: Duration2.fromObject({ minutes: 1 }), + min: Duration2.fromObject({ minutes: 1 }), + mins: Duration2.fromObject({ minutes: 1 }), + m: Duration2.fromObject({ minutes: 1 }), + second: Duration2.fromObject({ seconds: 1 }), + seconds: Duration2.fromObject({ seconds: 1 }), + sec: Duration2.fromObject({ seconds: 1 }), + secs: Duration2.fromObject({ seconds: 1 }), + s: Duration2.fromObject({ seconds: 1 }) + }; + var DATE_SHORTHANDS = { + now: () => DateTime2.local(), + today: () => DateTime2.local().startOf("day"), + yesterday: () => DateTime2.local().startOf("day").minus(Duration2.fromObject({ days: 1 })), + tomorrow: () => DateTime2.local().startOf("day").plus(Duration2.fromObject({ days: 1 })), + sow: () => DateTime2.local().startOf("week"), + "start-of-week": () => DateTime2.local().startOf("week"), + eow: () => DateTime2.local().endOf("week"), + "end-of-week": () => DateTime2.local().endOf("week"), + soy: () => DateTime2.local().startOf("year"), + "start-of-year": () => DateTime2.local().startOf("year"), + eoy: () => DateTime2.local().endOf("year"), + "end-of-year": () => DateTime2.local().endOf("year"), + som: () => DateTime2.local().startOf("month"), + "start-of-month": () => DateTime2.local().startOf("month"), + eom: () => DateTime2.local().endOf("month"), + "end-of-month": () => DateTime2.local().endOf("month") + }; + var KEYWORDS = ["FROM", "WHERE", "LIMIT", "GROUP", "FLATTEN"]; + function splitOnUnescapedPipe(link) { + let pipe = -1; + while ((pipe = link.indexOf("|", pipe + 1)) >= 0) { + if (pipe > 0 && link[pipe - 1] == "\\") + continue; + return [link.substring(0, pipe).replace(/\\\|/g, "|"), link.substring(pipe + 1)]; + } + return [link.replace(/\\\|/g, "|"), void 0]; + } + function parseInnerLink(rawlink) { + let [link, display] = splitOnUnescapedPipe(rawlink); + return Link.infer(link, false, display); + } + function createBinaryParser(child, sep, combine) { + return parsimmon_umd_minExports.seqMap(child, parsimmon_umd_minExports.seq(parsimmon_umd_minExports.optWhitespace, sep, parsimmon_umd_minExports.optWhitespace, child).many(), (first, rest) => { + if (rest.length == 0) + return first; + let node = combine(first, rest[0][1], rest[0][3]); + for (let index = 1; index < rest.length; index++) { + node = combine(node, rest[index][1], rest[index][3]); + } + return node; + }); + } + function chainOpt(base, ...funcs) { + return parsimmon_umd_minExports.custom((success, failure) => { + return (input, i) => { + let result = base._(input, i); + if (!result.status) + return result; + for (let func of funcs) { + let next = func(result.value)._(input, result.index); + if (!next.status) + return result; + result = next; + } + return result; + }; + }); + } + var EXPRESSION = parsimmon_umd_minExports.createLanguage({ + // A floating point number; the decimal point is optional. + number: (q) => parsimmon_umd_minExports.regexp(/-?[0-9]+(\.[0-9]+)?/).map((str) => Number.parseFloat(str)).desc("number"), + // A quote-surrounded string which supports escape characters ('\'). + string: (q) => parsimmon_umd_minExports.string('"').then(parsimmon_umd_minExports.alt(q.escapeCharacter, parsimmon_umd_minExports.noneOf('"\\')).atLeast(0).map((chars) => chars.join(""))).skip(parsimmon_umd_minExports.string('"')).desc("string"), + escapeCharacter: (_) => parsimmon_umd_minExports.string("\\").then(parsimmon_umd_minExports.any).map((escaped) => { + if (escaped === '"') + return '"'; + if (escaped === "\\") + return "\\"; + else + return "\\" + escaped; + }), + // A boolean true/false value. + bool: (_) => parsimmon_umd_minExports.regexp(/true|false|True|False/).map((str) => str.toLowerCase() == "true").desc("boolean ('true' or 'false')"), + // A tag of the form '#stuff/hello-there'. + tag: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("#"), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]/).desc("text")).many(), (start, rest) => start + rest.join("")).desc("tag ('#hello/stuff')"), + // A variable identifier, which is alphanumeric and must start with a letter or... emoji. + identifier: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/\p{Letter}/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/[0-9\p{Letter}_-]/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")).many(), (first, rest) => first + rest.join("")).desc("variable identifier"), + // An Obsidian link of the form [[]]. + link: (_) => parsimmon_umd_minExports.regexp(/\[\[([^\[\]]*?)\]\]/u, 1).map((linkInner) => parseInnerLink(linkInner)).desc("file link"), + // An embeddable link which can start with '!'. This overlaps with the normal negation operator, so it is only + // provided for metadata parsing. + embedLink: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!").atMost(1), q.link, (p, l3) => { + if (p.length > 0) + l3.embed = true; + return l3; + }).desc("file link"), + // Binary plus or minus operator. + binaryPlusMinus: (_) => parsimmon_umd_minExports.regexp(/\+|-/).map((str) => str).desc("'+' or '-'"), + // Binary times or divide operator. + binaryMulDiv: (_) => parsimmon_umd_minExports.regexp(/\*|\/|%/).map((str) => str).desc("'*' or '/' or '%'"), + // Binary comparison operator. + binaryCompareOp: (_) => parsimmon_umd_minExports.regexp(/>=|<=|!=|>|<|=/).map((str) => str).desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"), + // Binary boolean combination operator. + binaryBooleanOp: (_) => parsimmon_umd_minExports.regexp(/and|or|&|\|/i).map((str) => { + if (str.toLowerCase() == "and") + return "&"; + else if (str.toLowerCase() == "or") + return "|"; + else + return str; + }).desc("'and' or 'or'"), + // A date which can be YYYY-MM[-DDTHH:mm:ss]. + rootDate: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/\d{4}/), parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (year, _2, month) => { + return DateTime2.fromObject({ year: Number.parseInt(year), month: Number.parseInt(month) }); + }).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"), + dateShorthand: (_) => parsimmon_umd_minExports.alt(...Object.keys(DATE_SHORTHANDS).sort((a, b) => b.length - a.length).map(parsimmon_umd_minExports.string)), + date: (q) => chainOpt(q.rootDate, (ym) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, day) => ym.set({ day: Number.parseInt(day) })), (ymd) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("T"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, hour) => ymd.set({ hour: Number.parseInt(hour) })), (ymdh) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, minute) => ymdh.set({ minute: Number.parseInt(minute) })), (ymdhm) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, second) => ymdhm.set({ second: Number.parseInt(second) })), (ymdhms) => parsimmon_umd_minExports.alt( + parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), parsimmon_umd_minExports.regexp(/\d{3}/), (_, millisecond) => ymdhms.set({ millisecond: Number.parseInt(millisecond) })), + parsimmon_umd_minExports.succeed(ymdhms) + // pass + ), (dt) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("+").or(parsimmon_umd_minExports.string("-")), parsimmon_umd_minExports.regexp(/\d{1,2}(:\d{2})?/), (pm, hr) => dt.setZone("UTC" + pm + hr, { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("Z"), () => dt.setZone("utc", { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.regexp(/[0-9A-Za-z+-\/]+/u), parsimmon_umd_minExports.string("]"), (_a, zone, _b) => dt.setZone(zone, { keepLocalTime: true })))).assert((dt) => dt.isValid, "valid date").desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"), + // A date, plus various shorthand times of day it could be. + datePlus: (q) => parsimmon_umd_minExports.alt(q.dateShorthand.map((d) => DATE_SHORTHANDS[d]()), q.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"), + // A duration of time. + durationType: (_) => parsimmon_umd_minExports.alt(...Object.keys(DURATION_TYPES).sort((a, b) => b.length - a.length).map(parsimmon_umd_minExports.string)), + duration: (q) => parsimmon_umd_minExports.seqMap(q.number, parsimmon_umd_minExports.optWhitespace, q.durationType, (count, _, t) => DURATION_TYPES[t].mapUnits((x) => x * count)).sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).or(parsimmon_umd_minExports.optWhitespace)).map((durations) => durations.reduce((p, c) => p.plus(c))).desc("duration like 4hr2min"), + // A raw null value. + rawNull: (_) => parsimmon_umd_minExports.string("null"), + // Source parsing. + tagSource: (q) => q.tag.map((tag) => Sources.tag(tag)), + csvSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("csv(").skip(parsimmon_umd_minExports.optWhitespace), q.string, parsimmon_umd_minExports.string(")"), (_1, path, _2) => Sources.csv(path)), + linkIncomingSource: (q) => q.link.map((link) => Sources.link(link.path, true)), + linkOutgoingSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("outgoing(").skip(parsimmon_umd_minExports.optWhitespace), q.link, parsimmon_umd_minExports.string(")"), (_1, link, _2) => Sources.link(link.path, false)), + folderSource: (q) => q.string.map((str) => Sources.folder(str)), + parensSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.source, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field), + negateSource: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.string("!")), q.atomSource, (_, source) => Sources.negate(source)), + atomSource: (q) => parsimmon_umd_minExports.alt(q.parensSource, q.negateSource, q.linkOutgoingSource, q.linkIncomingSource, q.folderSource, q.tagSource, q.csvSource), + binaryOpSource: (q) => createBinaryParser(q.atomSource, q.binaryBooleanOp.map((s3) => s3), Sources.binaryOp), + source: (q) => q.binaryOpSource, + // Field parsing. + variableField: (q) => q.identifier.chain((r) => { + if (KEYWORDS.includes(r.toUpperCase())) { + return parsimmon_umd_minExports.fail("Variable fields cannot be a keyword (" + KEYWORDS.join(" or ") + ")"); + } else { + return parsimmon_umd_minExports.succeed(Fields.variable(r)); + } + }).desc("variable"), + numberField: (q) => q.number.map((val) => Fields.literal(val)).desc("number"), + stringField: (q) => q.string.map((val) => Fields.literal(val)).desc("string"), + boolField: (q) => q.bool.map((val) => Fields.literal(val)).desc("boolean"), + dateField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("date("), parsimmon_umd_minExports.optWhitespace, q.datePlus, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, date, _2, postfix) => Fields.literal(date)).desc("date"), + durationField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("dur("), parsimmon_umd_minExports.optWhitespace, q.duration, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, dur, _2, postfix) => Fields.literal(dur)).desc("duration"), + nullField: (q) => q.rawNull.map((_) => Fields.NULL), + linkField: (q) => q.link.map((f) => Fields.literal(f)), + listField: (q) => q.field.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("[").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.string("]"))).map((l3) => Fields.list(l3)).desc("list ('[1, 2, 3]')"), + objectField: (q) => parsimmon_umd_minExports.seqMap(q.identifier.or(q.string), parsimmon_umd_minExports.string(":").trim(parsimmon_umd_minExports.optWhitespace), q.field, (name, _sep, value) => { + return { name, value }; + }).sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("{").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.string("}"))).map((vals) => { + let res = {}; + for (let entry of vals) + res[entry.name] = entry.value; + return Fields.object(res); + }).desc("object ('{ a: 1, b: 2 }')"), + atomInlineField: (q) => parsimmon_umd_minExports.alt(q.date, q.duration.map((d) => normalizeDuration(d)), q.string, q.tag, q.embedLink, q.bool, q.number, q.rawNull), + inlineFieldList: (q) => q.atomInlineField.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).lookahead(q.atomInlineField)), + inlineField: (q) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(q.atomInlineField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace), q.inlineFieldList, (f, _s, l3) => [f].concat(l3)), q.atomInlineField), + atomField: (q) => parsimmon_umd_minExports.alt( + // Place embed links above negated fields as they are the special parser case '![[thing]]' and are generally unambigious. + q.embedLink.map((l3) => Fields.literal(l3)), + q.negatedField, + q.linkField, + q.listField, + q.objectField, + q.lambdaField, + q.parensField, + q.boolField, + q.numberField, + q.stringField, + q.dateField, + q.durationField, + q.nullField, + q.variableField + ), + indexField: (q) => parsimmon_umd_minExports.seqMap(q.atomField, parsimmon_umd_minExports.alt(q.dotPostfix, q.indexPostfix, q.functionPostfix).many(), (obj, postfixes) => { + let result = obj; + for (let post of postfixes) { + switch (post.type) { + case "dot": + result = Fields.index(result, Fields.literal(post.field)); + break; + case "index": + result = Fields.index(result, post.field); + break; + case "function": + result = Fields.func(result, post.fields); + break; + } + } + return result; + }), + negatedField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!"), q.indexField, (_, field) => Fields.negate(field)).desc("negated field"), + parensField: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field), + lambdaField: (q) => parsimmon_umd_minExports.seqMap(q.identifier.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("(").trim(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.string(")").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.string("=>").trim(parsimmon_umd_minExports.optWhitespace), q.field, (ident, _ignore, value) => { + return { type: "lambda", arguments: ident, value }; + }), + dotPostfix: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), q.identifier, (_, field) => { + return { type: "dot", field }; + }), + indexPostfix: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.optWhitespace, q.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string("]"), (_, _2, field, _3, _4) => { + return { type: "index", field }; + }), + functionPostfix: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.field.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_, _1, fields, _2, _3) => { + return { type: "function", fields }; + }), + // The precedence hierarchy of operators - multiply/divide, add/subtract, compare, and then boolean operations. + binaryMulDivField: (q) => createBinaryParser(q.indexField, q.binaryMulDiv, Fields.binaryOp), + binaryPlusMinusField: (q) => createBinaryParser(q.binaryMulDivField, q.binaryPlusMinus, Fields.binaryOp), + binaryCompareField: (q) => createBinaryParser(q.binaryPlusMinusField, q.binaryCompareOp, Fields.binaryOp), + binaryBooleanField: (q) => createBinaryParser(q.binaryCompareField, q.binaryBooleanOp, Fields.binaryOp), + binaryOpField: (q) => q.binaryBooleanField, + field: (q) => q.binaryOpField + }); + function parseField(text2) { + try { + return Result.success(EXPRESSION.field.tryParse(text2)); + } catch (error) { + return Result.failure("" + error); + } + } + var QueryFields; + (function(QueryFields2) { + function named(name, field) { + return { name, field }; + } + QueryFields2.named = named; + function sortBy(field, dir) { + return { field, direction: dir }; + } + QueryFields2.sortBy = sortBy; + })(QueryFields || (QueryFields = {})); + function captureRaw(base) { + return parsimmon_umd_minExports.custom((success, failure) => { + return (input, i) => { + let result = base._(input, i); + if (!result.status) + return result; + return Object.assign({}, result, { value: [result.value, input.substring(i, result.index)] }); + }; + }); + } + function stripNewlines(text2) { + return text2.split(/[\r\n]+/).map((t) => t.trim()).join(""); + } + function precededByWhitespaceIfNotEof(if_eof, parser) { + return parsimmon_umd_minExports.eof.map(if_eof).or(parsimmon_umd_minExports.whitespace.then(parser)); + } + var QUERY_LANGUAGE = parsimmon_umd_minExports.createLanguage({ + // Simple atom parsing, like words, identifiers, numbers. + queryType: (q) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/TABLE|LIST|TASK|CALENDAR/i)).map((str) => str.toLowerCase()).desc("query type ('TABLE', 'LIST', 'TASK', or 'CALENDAR')"), + explicitNamedField: (q) => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.whitespace), parsimmon_umd_minExports.regexp(/AS/i).skip(parsimmon_umd_minExports.whitespace), EXPRESSION.identifier.or(EXPRESSION.string), (field, _as, ident) => QueryFields.named(ident, field)), + namedField: (q) => parsimmon_umd_minExports.alt(q.explicitNamedField, captureRaw(EXPRESSION.field).map(([value, text2]) => QueryFields.named(stripNewlines(text2), value))), + sortField: (q) => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1), (field, dir) => { + let direction = dir.length == 0 ? "ascending" : dir[0].toLowerCase(); + if (direction == "desc") + direction = "descending"; + if (direction == "asc") + direction = "ascending"; + return { + field, + direction + }; + }), + headerClause: (q) => q.queryType.chain((type) => { + switch (type) { + case "table": { + return precededByWhitespaceIfNotEof(() => ({ type, fields: [], showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_minExports.optWhitespace).atMost(1), parsimmon_umd_minExports.sepBy(q.namedField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (withoutId, fields) => { + return { type, fields, showId: withoutId.length == 0 }; + })); + } + case "list": + return precededByWhitespaceIfNotEof(() => ({ type, format: void 0, showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_minExports.optWhitespace).atMost(1), EXPRESSION.field.atMost(1), (withoutId, format) => { + return { + type, + format: format.length == 1 ? format[0] : void 0, + showId: withoutId.length == 0 + }; + })); + case "task": + return parsimmon_umd_minExports.succeed({ type }); + case "calendar": + return parsimmon_umd_minExports.whitespace.then(parsimmon_umd_minExports.seqMap(q.namedField, (field) => { + return { + type, + showId: true, + field + }; + })); + default: + return parsimmon_umd_minExports.fail(`Unrecognized query type '${type}'`); + } + }).desc("TABLE or LIST or TASK or CALENDAR"), + fromClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FROM/i), parsimmon_umd_minExports.whitespace, EXPRESSION.source, (_1, _2, source) => source), + whereClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WHERE/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (where, _, field) => { + return { type: "where", clause: field }; + }).desc("WHERE "), + sortByClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/SORT/i), parsimmon_umd_minExports.whitespace, q.sortField.sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (sort, _1, fields) => { + return { type: "sort", fields }; + }).desc("SORT field [ASC/DESC]"), + limitClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/LIMIT/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (limit, _1, field) => { + return { type: "limit", amount: field }; + }).desc("LIMIT "), + flattenClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FLATTEN/i).skip(parsimmon_umd_minExports.whitespace), q.namedField, (_, field) => { + return { type: "flatten", field }; + }).desc("FLATTEN [AS ]"), + groupByClause: (q) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/GROUP BY/i).skip(parsimmon_umd_minExports.whitespace), q.namedField, (_, field) => { + return { type: "group", field }; + }).desc("GROUP BY [AS ]"), + // Full query parsing. + clause: (q) => parsimmon_umd_minExports.alt(q.fromClause, q.whereClause, q.sortByClause, q.limitClause, q.groupByClause, q.flattenClause), + query: (q) => parsimmon_umd_minExports.seqMap(q.headerClause.trim(parsimmon_umd_minExports.optWhitespace), q.fromClause.trim(parsimmon_umd_minExports.optWhitespace).atMost(1), q.clause.trim(parsimmon_umd_minExports.optWhitespace).many(), (header, from, clauses) => { + return { + header, + source: from.length == 0 ? Sources.folder("") : from[0], + operations: clauses, + settings: DEFAULT_QUERY_SETTINGS + }; + }) + }); + var getAPI = (app) => { + var _a; + if (app) + return (_a = app.plugins.plugins.dataview) === null || _a === void 0 ? void 0 : _a.api; + else + return window.DataviewAPI; + }; + var isPluginEnabled = (app) => app.plugins.enabledPlugins.has("dataview"); + exports.DATE_SHORTHANDS = DATE_SHORTHANDS; + exports.DURATION_TYPES = DURATION_TYPES; + exports.EXPRESSION = EXPRESSION; + exports.KEYWORDS = KEYWORDS; + exports.QUERY_LANGUAGE = QUERY_LANGUAGE; + exports.getAPI = getAPI; + exports.isPluginEnabled = isPluginEnabled; + exports.parseField = parseField; + } +}); + +// node_modules/graphology/dist/graphology.umd.min.js +var require_graphology_umd_min = __commonJS({ + "node_modules/graphology/dist/graphology.umd.min.js"(exports, module2) { + !function(t, e) { + "object" == typeof exports && "undefined" != typeof module2 ? module2.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).graphology = e(); + }(exports, function() { + "use strict"; + function t(e2) { + return t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t2) { + return typeof t2; + } : function(t2) { + return t2 && "function" == typeof Symbol && t2.constructor === Symbol && t2 !== Symbol.prototype ? "symbol" : typeof t2; + }, t(e2); + } + function e(t2, e2) { + t2.prototype = Object.create(e2.prototype), t2.prototype.constructor = t2, r(t2, e2); + } + function n2(t2) { + return n2 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t3) { + return t3.__proto__ || Object.getPrototypeOf(t3); + }, n2(t2); + } + function r(t2, e2) { + return r = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t3, e3) { + return t3.__proto__ = e3, t3; + }, r(t2, e2); + } + function i() { + if ("undefined" == typeof Reflect || !Reflect.construct) + return false; + if (Reflect.construct.sham) + return false; + if ("function" == typeof Proxy) + return true; + try { + return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { + })), true; + } catch (t2) { + return false; + } + } + function o(t2, e2, n3) { + return o = i() ? Reflect.construct.bind() : function(t3, e3, n4) { + var i2 = [null]; + i2.push.apply(i2, e3); + var o2 = new (Function.bind.apply(t3, i2))(); + return n4 && r(o2, n4.prototype), o2; + }, o.apply(null, arguments); + } + function a(t2) { + var e2 = "function" == typeof Map ? /* @__PURE__ */ new Map() : void 0; + return a = function(t3) { + if (null === t3 || (i2 = t3, -1 === Function.toString.call(i2).indexOf("[native code]"))) + return t3; + var i2; + if ("function" != typeof t3) + throw new TypeError("Super expression must either be null or a function"); + if (void 0 !== e2) { + if (e2.has(t3)) + return e2.get(t3); + e2.set(t3, a2); + } + function a2() { + return o(t3, arguments, n2(this).constructor); + } + return a2.prototype = Object.create(t3.prototype, { constructor: { value: a2, enumerable: false, writable: true, configurable: true } }), r(a2, t3); + }, a(t2); + } + function c(t2) { + if (void 0 === t2) + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return t2; + } + var u = function() { + for (var t2 = arguments[0], e2 = 1, n3 = arguments.length; e2 < n3; e2++) + if (arguments[e2]) + for (var r2 in arguments[e2]) + t2[r2] = arguments[e2][r2]; + return t2; + }; + function d(t2, e2, n3, r2) { + var i2 = t2._nodes.get(e2), o2 = null; + return i2 ? o2 = "mixed" === r2 ? i2.out && i2.out[n3] || i2.undirected && i2.undirected[n3] : "directed" === r2 ? i2.out && i2.out[n3] : i2.undirected && i2.undirected[n3] : o2; + } + function s2(e2) { + return "object" === t(e2) && null !== e2; + } + function h(t2) { + var e2; + for (e2 in t2) + return false; + return true; + } + function p(t2, e2, n3) { + Object.defineProperty(t2, e2, { enumerable: false, configurable: false, writable: true, value: n3 }); + } + function f(t2, e2, n3) { + var r2 = { enumerable: true, configurable: true }; + "function" == typeof n3 ? r2.get = n3 : (r2.value = n3, r2.writable = false), Object.defineProperty(t2, e2, r2); + } + function l2(t2) { + return !!s2(t2) && !(t2.attributes && !Array.isArray(t2.attributes)); + } + "function" == typeof Object.assign && (u = Object.assign); + var g, y = { exports: {} }, w = "object" == typeof Reflect ? Reflect : null, v = w && "function" == typeof w.apply ? w.apply : function(t2, e2, n3) { + return Function.prototype.apply.call(t2, e2, n3); + }; + g = w && "function" == typeof w.ownKeys ? w.ownKeys : Object.getOwnPropertySymbols ? function(t2) { + return Object.getOwnPropertyNames(t2).concat(Object.getOwnPropertySymbols(t2)); + } : function(t2) { + return Object.getOwnPropertyNames(t2); + }; + var b = Number.isNaN || function(t2) { + return t2 != t2; + }; + function m() { + m.init.call(this); + } + y.exports = m, y.exports.once = function(t2, e2) { + return new Promise(function(n3, r2) { + function i2(n4) { + t2.removeListener(e2, o2), r2(n4); + } + function o2() { + "function" == typeof t2.removeListener && t2.removeListener("error", i2), n3([].slice.call(arguments)); + } + U(t2, e2, o2, { once: true }), "error" !== e2 && function(t3, e3, n4) { + "function" == typeof t3.on && U(t3, "error", e3, n4); + }(t2, i2, { once: true }); + }); + }, m.EventEmitter = m, m.prototype._events = void 0, m.prototype._eventsCount = 0, m.prototype._maxListeners = void 0; + var k = 10; + function _(t2) { + if ("function" != typeof t2) + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof t2); + } + function G(t2) { + return void 0 === t2._maxListeners ? m.defaultMaxListeners : t2._maxListeners; + } + function x(t2, e2, n3, r2) { + var i2, o2, a2, c2; + if (_(n3), void 0 === (o2 = t2._events) ? (o2 = t2._events = /* @__PURE__ */ Object.create(null), t2._eventsCount = 0) : (void 0 !== o2.newListener && (t2.emit("newListener", e2, n3.listener ? n3.listener : n3), o2 = t2._events), a2 = o2[e2]), void 0 === a2) + a2 = o2[e2] = n3, ++t2._eventsCount; + else if ("function" == typeof a2 ? a2 = o2[e2] = r2 ? [n3, a2] : [a2, n3] : r2 ? a2.unshift(n3) : a2.push(n3), (i2 = G(t2)) > 0 && a2.length > i2 && !a2.warned) { + a2.warned = true; + var u2 = new Error("Possible EventEmitter memory leak detected. " + a2.length + " " + String(e2) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + u2.name = "MaxListenersExceededWarning", u2.emitter = t2, u2.type = e2, u2.count = a2.length, c2 = u2, console && console.warn && console.warn(c2); + } + return t2; + } + function E() { + if (!this.fired) + return this.target.removeListener(this.type, this.wrapFn), this.fired = true, 0 === arguments.length ? this.listener.call(this.target) : this.listener.apply(this.target, arguments); + } + function A(t2, e2, n3) { + var r2 = { fired: false, wrapFn: void 0, target: t2, type: e2, listener: n3 }, i2 = E.bind(r2); + return i2.listener = n3, r2.wrapFn = i2, i2; + } + function L(t2, e2, n3) { + var r2 = t2._events; + if (void 0 === r2) + return []; + var i2 = r2[e2]; + return void 0 === i2 ? [] : "function" == typeof i2 ? n3 ? [i2.listener || i2] : [i2] : n3 ? function(t3) { + for (var e3 = new Array(t3.length), n4 = 0; n4 < e3.length; ++n4) + e3[n4] = t3[n4].listener || t3[n4]; + return e3; + }(i2) : D(i2, i2.length); + } + function S(t2) { + var e2 = this._events; + if (void 0 !== e2) { + var n3 = e2[t2]; + if ("function" == typeof n3) + return 1; + if (void 0 !== n3) + return n3.length; + } + return 0; + } + function D(t2, e2) { + for (var n3 = new Array(e2), r2 = 0; r2 < e2; ++r2) + n3[r2] = t2[r2]; + return n3; + } + function U(t2, e2, n3, r2) { + if ("function" == typeof t2.on) + r2.once ? t2.once(e2, n3) : t2.on(e2, n3); + else { + if ("function" != typeof t2.addEventListener) + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof t2); + t2.addEventListener(e2, function i2(o2) { + r2.once && t2.removeEventListener(e2, i2), n3(o2); + }); + } + } + function N(t2) { + if ("function" != typeof t2) + throw new Error("obliterator/iterator: expecting a function!"); + this.next = t2; + } + Object.defineProperty(m, "defaultMaxListeners", { enumerable: true, get: function() { + return k; + }, set: function(t2) { + if ("number" != typeof t2 || t2 < 0 || b(t2)) + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + t2 + "."); + k = t2; + } }), m.init = function() { + void 0 !== this._events && this._events !== Object.getPrototypeOf(this)._events || (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0; + }, m.prototype.setMaxListeners = function(t2) { + if ("number" != typeof t2 || t2 < 0 || b(t2)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + t2 + "."); + return this._maxListeners = t2, this; + }, m.prototype.getMaxListeners = function() { + return G(this); + }, m.prototype.emit = function(t2) { + for (var e2 = [], n3 = 1; n3 < arguments.length; n3++) + e2.push(arguments[n3]); + var r2 = "error" === t2, i2 = this._events; + if (void 0 !== i2) + r2 = r2 && void 0 === i2.error; + else if (!r2) + return false; + if (r2) { + var o2; + if (e2.length > 0 && (o2 = e2[0]), o2 instanceof Error) + throw o2; + var a2 = new Error("Unhandled error." + (o2 ? " (" + o2.message + ")" : "")); + throw a2.context = o2, a2; + } + var c2 = i2[t2]; + if (void 0 === c2) + return false; + if ("function" == typeof c2) + v(c2, this, e2); + else { + var u2 = c2.length, d2 = D(c2, u2); + for (n3 = 0; n3 < u2; ++n3) + v(d2[n3], this, e2); + } + return true; + }, m.prototype.addListener = function(t2, e2) { + return x(this, t2, e2, false); + }, m.prototype.on = m.prototype.addListener, m.prototype.prependListener = function(t2, e2) { + return x(this, t2, e2, true); + }, m.prototype.once = function(t2, e2) { + return _(e2), this.on(t2, A(this, t2, e2)), this; + }, m.prototype.prependOnceListener = function(t2, e2) { + return _(e2), this.prependListener(t2, A(this, t2, e2)), this; + }, m.prototype.removeListener = function(t2, e2) { + var n3, r2, i2, o2, a2; + if (_(e2), void 0 === (r2 = this._events)) + return this; + if (void 0 === (n3 = r2[t2])) + return this; + if (n3 === e2 || n3.listener === e2) + 0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : (delete r2[t2], r2.removeListener && this.emit("removeListener", t2, n3.listener || e2)); + else if ("function" != typeof n3) { + for (i2 = -1, o2 = n3.length - 1; o2 >= 0; o2--) + if (n3[o2] === e2 || n3[o2].listener === e2) { + a2 = n3[o2].listener, i2 = o2; + break; + } + if (i2 < 0) + return this; + 0 === i2 ? n3.shift() : function(t3, e3) { + for (; e3 + 1 < t3.length; e3++) + t3[e3] = t3[e3 + 1]; + t3.pop(); + }(n3, i2), 1 === n3.length && (r2[t2] = n3[0]), void 0 !== r2.removeListener && this.emit("removeListener", t2, a2 || e2); + } + return this; + }, m.prototype.off = m.prototype.removeListener, m.prototype.removeAllListeners = function(t2) { + var e2, n3, r2; + if (void 0 === (n3 = this._events)) + return this; + if (void 0 === n3.removeListener) + return 0 === arguments.length ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : void 0 !== n3[t2] && (0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : delete n3[t2]), this; + if (0 === arguments.length) { + var i2, o2 = Object.keys(n3); + for (r2 = 0; r2 < o2.length; ++r2) + "removeListener" !== (i2 = o2[r2]) && this.removeAllListeners(i2); + return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this; + } + if ("function" == typeof (e2 = n3[t2])) + this.removeListener(t2, e2); + else if (void 0 !== e2) + for (r2 = e2.length - 1; r2 >= 0; r2--) + this.removeListener(t2, e2[r2]); + return this; + }, m.prototype.listeners = function(t2) { + return L(this, t2, true); + }, m.prototype.rawListeners = function(t2) { + return L(this, t2, false); + }, m.listenerCount = function(t2, e2) { + return "function" == typeof t2.listenerCount ? t2.listenerCount(e2) : S.call(t2, e2); + }, m.prototype.listenerCount = S, m.prototype.eventNames = function() { + return this._eventsCount > 0 ? g(this._events) : []; + }, "undefined" != typeof Symbol && (N.prototype[Symbol.iterator] = function() { + return this; + }), N.of = function() { + var t2 = arguments, e2 = t2.length, n3 = 0; + return new N(function() { + return n3 >= e2 ? { done: true } : { done: false, value: t2[n3++] }; + }); + }, N.empty = function() { + return new N(function() { + return { done: true }; + }); + }, N.fromSequence = function(t2) { + var e2 = 0, n3 = t2.length; + return new N(function() { + return e2 >= n3 ? { done: true } : { done: false, value: t2[e2++] }; + }); + }, N.is = function(t2) { + return t2 instanceof N || "object" == typeof t2 && null !== t2 && "function" == typeof t2.next; + }; + var O = N, j = {}; + j.ARRAY_BUFFER_SUPPORT = "undefined" != typeof ArrayBuffer, j.SYMBOL_SUPPORT = "undefined" != typeof Symbol; + var C = O, M = j, z2 = M.ARRAY_BUFFER_SUPPORT, W = M.SYMBOL_SUPPORT; + var P = function(t2) { + var e2 = function(t3) { + return "string" == typeof t3 || Array.isArray(t3) || z2 && ArrayBuffer.isView(t3) ? C.fromSequence(t3) : "object" != typeof t3 || null === t3 ? null : W && "function" == typeof t3[Symbol.iterator] ? t3[Symbol.iterator]() : "function" == typeof t3.next ? t3 : null; + }(t2); + if (!e2) + throw new Error("obliterator: target is not iterable nor a valid iterator."); + return e2; + }, R = P, K = function(t2, e2) { + for (var n3, r2 = arguments.length > 1 ? e2 : 1 / 0, i2 = r2 !== 1 / 0 ? new Array(r2) : [], o2 = 0, a2 = R(t2); ; ) { + if (o2 === r2) + return i2; + if ((n3 = a2.next()).done) + return o2 !== e2 && (i2.length = o2), i2; + i2[o2++] = n3.value; + } + }, T = function(t2) { + function n3(e2) { + var n4; + return (n4 = t2.call(this) || this).name = "GraphError", n4.message = e2, n4; + } + return e(n3, t2), n3; + }(a(Error)), B = function(t2) { + function n3(e2) { + var r2; + return (r2 = t2.call(this, e2) || this).name = "InvalidArgumentsGraphError", "function" == typeof Error.captureStackTrace && Error.captureStackTrace(c(r2), n3.prototype.constructor), r2; + } + return e(n3, t2), n3; + }(T), F = function(t2) { + function n3(e2) { + var r2; + return (r2 = t2.call(this, e2) || this).name = "NotFoundGraphError", "function" == typeof Error.captureStackTrace && Error.captureStackTrace(c(r2), n3.prototype.constructor), r2; + } + return e(n3, t2), n3; + }(T), I = function(t2) { + function n3(e2) { + var r2; + return (r2 = t2.call(this, e2) || this).name = "UsageGraphError", "function" == typeof Error.captureStackTrace && Error.captureStackTrace(c(r2), n3.prototype.constructor), r2; + } + return e(n3, t2), n3; + }(T); + function Y(t2, e2) { + this.key = t2, this.attributes = e2, this.clear(); + } + function q(t2, e2) { + this.key = t2, this.attributes = e2, this.clear(); + } + function J(t2, e2) { + this.key = t2, this.attributes = e2, this.clear(); + } + function V(t2, e2, n3, r2, i2) { + this.key = e2, this.attributes = i2, this.undirected = t2, this.source = n3, this.target = r2; + } + Y.prototype.clear = function() { + this.inDegree = 0, this.outDegree = 0, this.undirectedDegree = 0, this.undirectedLoops = 0, this.directedLoops = 0, this.in = {}, this.out = {}, this.undirected = {}; + }, q.prototype.clear = function() { + this.inDegree = 0, this.outDegree = 0, this.directedLoops = 0, this.in = {}, this.out = {}; + }, J.prototype.clear = function() { + this.undirectedDegree = 0, this.undirectedLoops = 0, this.undirected = {}; + }, V.prototype.attach = function() { + var t2 = "out", e2 = "in"; + this.undirected && (t2 = e2 = "undirected"); + var n3 = this.source.key, r2 = this.target.key; + this.source[t2][r2] = this, this.undirected && n3 === r2 || (this.target[e2][n3] = this); + }, V.prototype.attachMulti = function() { + var t2 = "out", e2 = "in", n3 = this.source.key, r2 = this.target.key; + this.undirected && (t2 = e2 = "undirected"); + var i2 = this.source[t2], o2 = i2[r2]; + if (void 0 === o2) + return i2[r2] = this, void (this.undirected && n3 === r2 || (this.target[e2][n3] = this)); + o2.previous = this, this.next = o2, i2[r2] = this, this.target[e2][n3] = this; + }, V.prototype.detach = function() { + var t2 = this.source.key, e2 = this.target.key, n3 = "out", r2 = "in"; + this.undirected && (n3 = r2 = "undirected"), delete this.source[n3][e2], delete this.target[r2][t2]; + }, V.prototype.detachMulti = function() { + var t2 = this.source.key, e2 = this.target.key, n3 = "out", r2 = "in"; + this.undirected && (n3 = r2 = "undirected"), void 0 === this.previous ? void 0 === this.next ? (delete this.source[n3][e2], delete this.target[r2][t2]) : (this.next.previous = void 0, this.source[n3][e2] = this.next, this.target[r2][t2] = this.next) : (this.previous.next = this.next, void 0 !== this.next && (this.next.previous = this.previous)); + }; + function H(t2, e2, n3, r2, i2, o2, a2) { + var c2, u2, d2, s3; + if (r2 = "" + r2, 0 === n3) { + if (!(c2 = t2._nodes.get(r2))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(r2, '" node in the graph.')); + d2 = i2, s3 = o2; + } else if (3 === n3) { + if (i2 = "" + i2, !(u2 = t2._edges.get(i2))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(i2, '" edge in the graph.')); + var h2 = u2.source.key, p2 = u2.target.key; + if (r2 === h2) + c2 = u2.target; + else { + if (r2 !== p2) + throw new F("Graph.".concat(e2, ': the "').concat(r2, '" node is not attached to the "').concat(i2, '" edge (').concat(h2, ", ").concat(p2, ").")); + c2 = u2.source; + } + d2 = o2, s3 = a2; + } else { + if (!(u2 = t2._edges.get(r2))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(r2, '" edge in the graph.')); + c2 = 1 === n3 ? u2.source : u2.target, d2 = i2, s3 = o2; + } + return [c2, d2, s3]; + } + var Q = [{ name: function(t2) { + return "get".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2 = H(this, e2, n3, t3, r2, i2), a2 = o2[0], c2 = o2[1]; + return a2.attributes[c2]; + }; + } }, { name: function(t2) { + return "get".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2) { + return H(this, e2, n3, t3, r2)[0].attributes; + }; + } }, { name: function(t2) { + return "has".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2 = H(this, e2, n3, t3, r2, i2), a2 = o2[0], c2 = o2[1]; + return a2.attributes.hasOwnProperty(c2); + }; + } }, { name: function(t2) { + return "set".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2, o2) { + var a2 = H(this, e2, n3, t3, r2, i2, o2), c2 = a2[0], u2 = a2[1], d2 = a2[2]; + return c2.attributes[u2] = d2, this.emit("nodeAttributesUpdated", { key: c2.key, type: "set", attributes: c2.attributes, name: u2 }), this; + }; + } }, { name: function(t2) { + return "update".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2, o2) { + var a2 = H(this, e2, n3, t3, r2, i2, o2), c2 = a2[0], u2 = a2[1], d2 = a2[2]; + if ("function" != typeof d2) + throw new B("Graph.".concat(e2, ": updater should be a function.")); + var s3 = c2.attributes, h2 = d2(s3[u2]); + return s3[u2] = h2, this.emit("nodeAttributesUpdated", { key: c2.key, type: "set", attributes: c2.attributes, name: u2 }), this; + }; + } }, { name: function(t2) { + return "remove".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2 = H(this, e2, n3, t3, r2, i2), a2 = o2[0], c2 = o2[1]; + return delete a2.attributes[c2], this.emit("nodeAttributesUpdated", { key: a2.key, type: "remove", attributes: a2.attributes, name: c2 }), this; + }; + } }, { name: function(t2) { + return "replace".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2 = H(this, e2, n3, t3, r2, i2), a2 = o2[0], c2 = o2[1]; + if (!s2(c2)) + throw new B("Graph.".concat(e2, ": provided attributes are not a plain object.")); + return a2.attributes = c2, this.emit("nodeAttributesUpdated", { key: a2.key, type: "replace", attributes: a2.attributes }), this; + }; + } }, { name: function(t2) { + return "merge".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2 = H(this, e2, n3, t3, r2, i2), a2 = o2[0], c2 = o2[1]; + if (!s2(c2)) + throw new B("Graph.".concat(e2, ": provided attributes are not a plain object.")); + return u(a2.attributes, c2), this.emit("nodeAttributesUpdated", { key: a2.key, type: "merge", attributes: a2.attributes, data: c2 }), this; + }; + } }, { name: function(t2) { + return "update".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2 = H(this, e2, n3, t3, r2, i2), a2 = o2[0], c2 = o2[1]; + if ("function" != typeof c2) + throw new B("Graph.".concat(e2, ": provided updater is not a function.")); + return a2.attributes = c2(a2.attributes), this.emit("nodeAttributesUpdated", { key: a2.key, type: "update", attributes: a2.attributes }), this; + }; + } }]; + var X = [{ name: function(t2) { + return "get".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2) { + var i2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 2) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var o2 = "" + t3, a2 = "" + r2; + if (r2 = arguments[2], !(i2 = d(this, o2, a2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(o2, '" - "').concat(a2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(i2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + return i2.attributes[r2]; + }; + } }, { name: function(t2) { + return "get".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3) { + var r2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 1) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var i2 = "" + t3, o2 = "" + arguments[1]; + if (!(r2 = d(this, i2, o2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(i2, '" - "').concat(o2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(r2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + return r2.attributes; + }; + } }, { name: function(t2) { + return "has".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2) { + var i2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 2) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var o2 = "" + t3, a2 = "" + r2; + if (r2 = arguments[2], !(i2 = d(this, o2, a2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(o2, '" - "').concat(a2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(i2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + return i2.attributes.hasOwnProperty(r2); + }; + } }, { name: function(t2) { + return "set".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 3) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var a2 = "" + t3, c2 = "" + r2; + if (r2 = arguments[2], i2 = arguments[3], !(o2 = d(this, a2, c2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(a2, '" - "').concat(c2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(o2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + return o2.attributes[r2] = i2, this.emit("edgeAttributesUpdated", { key: o2.key, type: "set", attributes: o2.attributes, name: r2 }), this; + }; + } }, { name: function(t2) { + return "update".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2, i2) { + var o2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 3) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var a2 = "" + t3, c2 = "" + r2; + if (r2 = arguments[2], i2 = arguments[3], !(o2 = d(this, a2, c2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(a2, '" - "').concat(c2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(o2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + if ("function" != typeof i2) + throw new B("Graph.".concat(e2, ": updater should be a function.")); + return o2.attributes[r2] = i2(o2.attributes[r2]), this.emit("edgeAttributesUpdated", { key: o2.key, type: "set", attributes: o2.attributes, name: r2 }), this; + }; + } }, { name: function(t2) { + return "remove".concat(t2, "Attribute"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2) { + var i2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 2) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var o2 = "" + t3, a2 = "" + r2; + if (r2 = arguments[2], !(i2 = d(this, o2, a2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(o2, '" - "').concat(a2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(i2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + return delete i2.attributes[r2], this.emit("edgeAttributesUpdated", { key: i2.key, type: "remove", attributes: i2.attributes, name: r2 }), this; + }; + } }, { name: function(t2) { + return "replace".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2) { + var i2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 2) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var o2 = "" + t3, a2 = "" + r2; + if (r2 = arguments[2], !(i2 = d(this, o2, a2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(o2, '" - "').concat(a2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(i2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + if (!s2(r2)) + throw new B("Graph.".concat(e2, ": provided attributes are not a plain object.")); + return i2.attributes = r2, this.emit("edgeAttributesUpdated", { key: i2.key, type: "replace", attributes: i2.attributes }), this; + }; + } }, { name: function(t2) { + return "merge".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2) { + var i2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 2) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var o2 = "" + t3, a2 = "" + r2; + if (r2 = arguments[2], !(i2 = d(this, o2, a2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(o2, '" - "').concat(a2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(i2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + if (!s2(r2)) + throw new B("Graph.".concat(e2, ": provided attributes are not a plain object.")); + return u(i2.attributes, r2), this.emit("edgeAttributesUpdated", { key: i2.key, type: "merge", attributes: i2.attributes, data: r2 }), this; + }; + } }, { name: function(t2) { + return "update".concat(t2, "Attributes"); + }, attacher: function(t2, e2, n3) { + t2.prototype[e2] = function(t3, r2) { + var i2; + if ("mixed" !== this.type && "mixed" !== n3 && n3 !== this.type) + throw new I("Graph.".concat(e2, ": cannot find this type of edges in your ").concat(this.type, " graph.")); + if (arguments.length > 2) { + if (this.multi) + throw new I("Graph.".concat(e2, ": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.")); + var o2 = "" + t3, a2 = "" + r2; + if (r2 = arguments[2], !(i2 = d(this, o2, a2, n3))) + throw new F("Graph.".concat(e2, ': could not find an edge for the given path ("').concat(o2, '" - "').concat(a2, '").')); + } else { + if ("mixed" !== n3) + throw new I("Graph.".concat(e2, ": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.")); + if (t3 = "" + t3, !(i2 = this._edges.get(t3))) + throw new F("Graph.".concat(e2, ': could not find the "').concat(t3, '" edge in the graph.')); + } + if ("function" != typeof r2) + throw new B("Graph.".concat(e2, ": provided updater is not a function.")); + return i2.attributes = r2(i2.attributes), this.emit("edgeAttributesUpdated", { key: i2.key, type: "update", attributes: i2.attributes }), this; + }; + } }]; + var Z = O, $ = P, tt = function() { + var t2 = arguments, e2 = null, n3 = -1; + return new Z(function() { + for (var r2 = null; ; ) { + if (null === e2) { + if (++n3 >= t2.length) + return { done: true }; + e2 = $(t2[n3]); + } + if (true !== (r2 = e2.next()).done) + break; + e2 = null; + } + return r2; + }); + }, et = [{ name: "edges", type: "mixed" }, { name: "inEdges", type: "directed", direction: "in" }, { name: "outEdges", type: "directed", direction: "out" }, { name: "inboundEdges", type: "mixed", direction: "in" }, { name: "outboundEdges", type: "mixed", direction: "out" }, { name: "directedEdges", type: "directed" }, { name: "undirectedEdges", type: "undirected" }]; + function nt(t2, e2, n3, r2) { + var i2 = false; + for (var o2 in e2) + if (o2 !== r2) { + var a2 = e2[o2]; + if (i2 = n3(a2.key, a2.attributes, a2.source.key, a2.target.key, a2.source.attributes, a2.target.attributes, a2.undirected), t2 && i2) + return a2.key; + } + } + function rt(t2, e2, n3, r2) { + var i2, o2, a2, c2 = false; + for (var u2 in e2) + if (u2 !== r2) { + i2 = e2[u2]; + do { + if (o2 = i2.source, a2 = i2.target, c2 = n3(i2.key, i2.attributes, o2.key, a2.key, o2.attributes, a2.attributes, i2.undirected), t2 && c2) + return i2.key; + i2 = i2.next; + } while (void 0 !== i2); + } + } + function it(t2, e2) { + var n3, r2 = Object.keys(t2), i2 = r2.length, o2 = 0; + return new O(function() { + do { + if (n3) + n3 = n3.next; + else { + if (o2 >= i2) + return { done: true }; + var a2 = r2[o2++]; + if (a2 === e2) { + n3 = void 0; + continue; + } + n3 = t2[a2]; + } + } while (!n3); + return { done: false, value: { edge: n3.key, attributes: n3.attributes, source: n3.source.key, target: n3.target.key, sourceAttributes: n3.source.attributes, targetAttributes: n3.target.attributes, undirected: n3.undirected } }; + }); + } + function ot(t2, e2, n3, r2) { + var i2 = e2[n3]; + if (i2) { + var o2 = i2.source, a2 = i2.target; + return r2(i2.key, i2.attributes, o2.key, a2.key, o2.attributes, a2.attributes, i2.undirected) && t2 ? i2.key : void 0; + } + } + function at(t2, e2, n3, r2) { + var i2 = e2[n3]; + if (i2) { + var o2 = false; + do { + if (o2 = r2(i2.key, i2.attributes, i2.source.key, i2.target.key, i2.source.attributes, i2.target.attributes, i2.undirected), t2 && o2) + return i2.key; + i2 = i2.next; + } while (void 0 !== i2); + } + } + function ct(t2, e2) { + var n3 = t2[e2]; + return void 0 !== n3.next ? new O(function() { + if (!n3) + return { done: true }; + var t3 = { edge: n3.key, attributes: n3.attributes, source: n3.source.key, target: n3.target.key, sourceAttributes: n3.source.attributes, targetAttributes: n3.target.attributes, undirected: n3.undirected }; + return n3 = n3.next, { done: false, value: t3 }; + }) : O.of({ edge: n3.key, attributes: n3.attributes, source: n3.source.key, target: n3.target.key, sourceAttributes: n3.source.attributes, targetAttributes: n3.target.attributes, undirected: n3.undirected }); + } + function ut(t2, e2) { + if (0 === t2.size) + return []; + if ("mixed" === e2 || e2 === t2.type) + return "function" == typeof Array.from ? Array.from(t2._edges.keys()) : K(t2._edges.keys(), t2._edges.size); + for (var n3, r2, i2 = "undirected" === e2 ? t2.undirectedSize : t2.directedSize, o2 = new Array(i2), a2 = "undirected" === e2, c2 = t2._edges.values(), u2 = 0; true !== (n3 = c2.next()).done; ) + (r2 = n3.value).undirected === a2 && (o2[u2++] = r2.key); + return o2; + } + function dt(t2, e2, n3, r2) { + if (0 !== e2.size) { + for (var i2, o2, a2 = "mixed" !== n3 && n3 !== e2.type, c2 = "undirected" === n3, u2 = false, d2 = e2._edges.values(); true !== (i2 = d2.next()).done; ) + if (o2 = i2.value, !a2 || o2.undirected === c2) { + var s3 = o2, h2 = s3.key, p2 = s3.attributes, f2 = s3.source, l3 = s3.target; + if (u2 = r2(h2, p2, f2.key, l3.key, f2.attributes, l3.attributes, o2.undirected), t2 && u2) + return h2; + } + } + } + function st(t2, e2) { + if (0 === t2.size) + return O.empty(); + var n3 = "mixed" !== e2 && e2 !== t2.type, r2 = "undirected" === e2, i2 = t2._edges.values(); + return new O(function() { + for (var t3, e3; ; ) { + if ((t3 = i2.next()).done) + return t3; + if (e3 = t3.value, !n3 || e3.undirected === r2) + break; + } + return { value: { edge: e3.key, attributes: e3.attributes, source: e3.source.key, target: e3.target.key, sourceAttributes: e3.source.attributes, targetAttributes: e3.target.attributes, undirected: e3.undirected }, done: false }; + }); + } + function ht(t2, e2, n3, r2, i2, o2) { + var a2, c2 = e2 ? rt : nt; + if ("undirected" !== n3) { + if ("out" !== r2 && (a2 = c2(t2, i2.in, o2), t2 && a2)) + return a2; + if ("in" !== r2 && (a2 = c2(t2, i2.out, o2, r2 ? void 0 : i2.key), t2 && a2)) + return a2; + } + if ("directed" !== n3 && (a2 = c2(t2, i2.undirected, o2), t2 && a2)) + return a2; + } + function pt(t2, e2, n3, r2) { + var i2 = []; + return ht(false, t2, e2, n3, r2, function(t3) { + i2.push(t3); + }), i2; + } + function ft(t2, e2, n3) { + var r2 = O.empty(); + return "undirected" !== t2 && ("out" !== e2 && void 0 !== n3.in && (r2 = tt(r2, it(n3.in))), "in" !== e2 && void 0 !== n3.out && (r2 = tt(r2, it(n3.out, e2 ? void 0 : n3.key)))), "directed" !== t2 && void 0 !== n3.undirected && (r2 = tt(r2, it(n3.undirected))), r2; + } + function lt(t2, e2, n3, r2, i2, o2, a2) { + var c2, u2 = n3 ? at : ot; + if ("undirected" !== e2) { + if (void 0 !== i2.in && "out" !== r2 && (c2 = u2(t2, i2.in, o2, a2), t2 && c2)) + return c2; + if (void 0 !== i2.out && "in" !== r2 && (r2 || i2.key !== o2) && (c2 = u2(t2, i2.out, o2, a2), t2 && c2)) + return c2; + } + if ("directed" !== e2 && void 0 !== i2.undirected && (c2 = u2(t2, i2.undirected, o2, a2), t2 && c2)) + return c2; + } + function gt(t2, e2, n3, r2, i2) { + var o2 = []; + return lt(false, t2, e2, n3, r2, i2, function(t3) { + o2.push(t3); + }), o2; + } + function yt(t2, e2, n3, r2) { + var i2 = O.empty(); + return "undirected" !== t2 && (void 0 !== n3.in && "out" !== e2 && r2 in n3.in && (i2 = tt(i2, ct(n3.in, r2))), void 0 !== n3.out && "in" !== e2 && r2 in n3.out && (e2 || n3.key !== r2) && (i2 = tt(i2, ct(n3.out, r2)))), "directed" !== t2 && void 0 !== n3.undirected && r2 in n3.undirected && (i2 = tt(i2, ct(n3.undirected, r2))), i2; + } + var wt = [{ name: "neighbors", type: "mixed" }, { name: "inNeighbors", type: "directed", direction: "in" }, { name: "outNeighbors", type: "directed", direction: "out" }, { name: "inboundNeighbors", type: "mixed", direction: "in" }, { name: "outboundNeighbors", type: "mixed", direction: "out" }, { name: "directedNeighbors", type: "directed" }, { name: "undirectedNeighbors", type: "undirected" }]; + function vt() { + this.A = null, this.B = null; + } + function bt(t2, e2, n3, r2, i2) { + for (var o2 in r2) { + var a2 = r2[o2], c2 = a2.source, u2 = a2.target, d2 = c2 === n3 ? u2 : c2; + if (!e2 || !e2.has(d2.key)) { + var s3 = i2(d2.key, d2.attributes); + if (t2 && s3) + return d2.key; + } + } + } + function mt(t2, e2, n3, r2, i2) { + if ("mixed" !== e2) { + if ("undirected" === e2) + return bt(t2, null, r2, r2.undirected, i2); + if ("string" == typeof n3) + return bt(t2, null, r2, r2[n3], i2); + } + var o2, a2 = new vt(); + if ("undirected" !== e2) { + if ("out" !== n3) { + if (o2 = bt(t2, null, r2, r2.in, i2), t2 && o2) + return o2; + a2.wrap(r2.in); + } + if ("in" !== n3) { + if (o2 = bt(t2, a2, r2, r2.out, i2), t2 && o2) + return o2; + a2.wrap(r2.out); + } + } + if ("directed" !== e2 && (o2 = bt(t2, a2, r2, r2.undirected, i2), t2 && o2)) + return o2; + } + function kt(t2, e2, n3) { + var r2 = Object.keys(n3), i2 = r2.length, o2 = 0; + return new O(function() { + var a2 = null; + do { + if (o2 >= i2) + return t2 && t2.wrap(n3), { done: true }; + var c2 = n3[r2[o2++]], u2 = c2.source, d2 = c2.target; + a2 = u2 === e2 ? d2 : u2, t2 && t2.has(a2.key) && (a2 = null); + } while (null === a2); + return { done: false, value: { neighbor: a2.key, attributes: a2.attributes } }; + }); + } + function _t(t2, e2) { + var n3 = e2.name, r2 = e2.type, i2 = e2.direction; + t2.prototype[n3] = function(t3) { + if ("mixed" !== r2 && "mixed" !== this.type && r2 !== this.type) + return []; + t3 = "" + t3; + var e3 = this._nodes.get(t3); + if (void 0 === e3) + throw new F("Graph.".concat(n3, ': could not find the "').concat(t3, '" node in the graph.')); + return function(t4, e4, n4) { + if ("mixed" !== t4) { + if ("undirected" === t4) + return Object.keys(n4.undirected); + if ("string" == typeof e4) + return Object.keys(n4[e4]); + } + var r3 = []; + return mt(false, t4, e4, n4, function(t5) { + r3.push(t5); + }), r3; + }("mixed" === r2 ? this.type : r2, i2, e3); + }; + } + function Gt(t2, e2) { + var n3 = e2.name, r2 = e2.type, i2 = e2.direction, o2 = n3.slice(0, -1) + "Entries"; + t2.prototype[o2] = function(t3) { + if ("mixed" !== r2 && "mixed" !== this.type && r2 !== this.type) + return O.empty(); + t3 = "" + t3; + var e3 = this._nodes.get(t3); + if (void 0 === e3) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t3, '" node in the graph.')); + return function(t4, e4, n4) { + if ("mixed" !== t4) { + if ("undirected" === t4) + return kt(null, n4, n4.undirected); + if ("string" == typeof e4) + return kt(null, n4, n4[e4]); + } + var r3 = O.empty(), i3 = new vt(); + return "undirected" !== t4 && ("out" !== e4 && (r3 = tt(r3, kt(i3, n4, n4.in))), "in" !== e4 && (r3 = tt(r3, kt(i3, n4, n4.out)))), "directed" !== t4 && (r3 = tt(r3, kt(i3, n4, n4.undirected))), r3; + }("mixed" === r2 ? this.type : r2, i2, e3); + }; + } + function xt(t2, e2, n3, r2, i2) { + for (var o2, a2, c2, u2, d2, s3, h2, p2 = r2._nodes.values(), f2 = r2.type; true !== (o2 = p2.next()).done; ) { + var l3 = false; + if (a2 = o2.value, "undirected" !== f2) + for (c2 in u2 = a2.out) { + d2 = u2[c2]; + do { + if (s3 = d2.target, l3 = true, h2 = i2(a2.key, s3.key, a2.attributes, s3.attributes, d2.key, d2.attributes, d2.undirected), t2 && h2) + return d2; + d2 = d2.next; + } while (d2); + } + if ("directed" !== f2) { + for (c2 in u2 = a2.undirected) + if (!(e2 && a2.key > c2)) { + d2 = u2[c2]; + do { + if ((s3 = d2.target).key !== c2 && (s3 = d2.source), l3 = true, h2 = i2(a2.key, s3.key, a2.attributes, s3.attributes, d2.key, d2.attributes, d2.undirected), t2 && h2) + return d2; + d2 = d2.next; + } while (d2); + } + } + if (n3 && !l3 && (h2 = i2(a2.key, null, a2.attributes, null, null, null, null), t2 && h2)) + return null; + } + } + function Et(t2) { + if (!s2(t2)) + throw new B('Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.'); + if (!("key" in t2)) + throw new B("Graph.import: serialized node is missing its key."); + if ("attributes" in t2 && (!s2(t2.attributes) || null === t2.attributes)) + throw new B("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted."); + } + function At(t2) { + if (!s2(t2)) + throw new B('Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.'); + if (!("source" in t2)) + throw new B("Graph.import: serialized edge is missing its source."); + if (!("target" in t2)) + throw new B("Graph.import: serialized edge is missing its target."); + if ("attributes" in t2 && (!s2(t2.attributes) || null === t2.attributes)) + throw new B("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted."); + if ("undirected" in t2 && "boolean" != typeof t2.undirected) + throw new B("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted."); + } + vt.prototype.wrap = function(t2) { + null === this.A ? this.A = t2 : null === this.B && (this.B = t2); + }, vt.prototype.has = function(t2) { + return null !== this.A && t2 in this.A || null !== this.B && t2 in this.B; + }; + var Lt, St = (Lt = 255 & Math.floor(256 * Math.random()), function() { + return Lt++; + }), Dt = /* @__PURE__ */ new Set(["directed", "undirected", "mixed"]), Ut = /* @__PURE__ */ new Set(["domain", "_events", "_eventsCount", "_maxListeners"]), Nt = { allowSelfLoops: true, multi: false, type: "mixed" }; + function Ot(t2, e2, n3) { + var r2 = new t2.NodeDataClass(e2, n3); + return t2._nodes.set(e2, r2), t2.emit("nodeAdded", { key: e2, attributes: n3 }), r2; + } + function jt(t2, e2, n3, r2, i2, o2, a2, c2) { + if (!r2 && "undirected" === t2.type) + throw new I("Graph.".concat(e2, ": you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.")); + if (r2 && "directed" === t2.type) + throw new I("Graph.".concat(e2, ": you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.")); + if (c2 && !s2(c2)) + throw new B("Graph.".concat(e2, ': invalid attributes. Expecting an object but got "').concat(c2, '"')); + if (o2 = "" + o2, a2 = "" + a2, c2 = c2 || {}, !t2.allowSelfLoops && o2 === a2) + throw new I("Graph.".concat(e2, ': source & target are the same ("').concat(o2, `"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`)); + var u2 = t2._nodes.get(o2), d2 = t2._nodes.get(a2); + if (!u2) + throw new F("Graph.".concat(e2, ': source node "').concat(o2, '" not found.')); + if (!d2) + throw new F("Graph.".concat(e2, ': target node "').concat(a2, '" not found.')); + var h2 = { key: null, undirected: r2, source: o2, target: a2, attributes: c2 }; + if (n3) + i2 = t2._edgeKeyGenerator(); + else if (i2 = "" + i2, t2._edges.has(i2)) + throw new I("Graph.".concat(e2, ': the "').concat(i2, '" edge already exists in the graph.')); + if (!t2.multi && (r2 ? void 0 !== u2.undirected[a2] : void 0 !== u2.out[a2])) + throw new I("Graph.".concat(e2, ': an edge linking "').concat(o2, '" to "').concat(a2, `" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`)); + var p2 = new V(r2, i2, u2, d2, c2); + t2._edges.set(i2, p2); + var f2 = o2 === a2; + return r2 ? (u2.undirectedDegree++, d2.undirectedDegree++, f2 && (u2.undirectedLoops++, t2._undirectedSelfLoopCount++)) : (u2.outDegree++, d2.inDegree++, f2 && (u2.directedLoops++, t2._directedSelfLoopCount++)), t2.multi ? p2.attachMulti() : p2.attach(), r2 ? t2._undirectedSize++ : t2._directedSize++, h2.key = i2, t2.emit("edgeAdded", h2), i2; + } + function Ct(t2, e2, n3, r2, i2, o2, a2, c2, d2) { + if (!r2 && "undirected" === t2.type) + throw new I("Graph.".concat(e2, ": you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead.")); + if (r2 && "directed" === t2.type) + throw new I("Graph.".concat(e2, ": you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead.")); + if (c2) { + if (d2) { + if ("function" != typeof c2) + throw new B("Graph.".concat(e2, ': invalid updater function. Expecting a function but got "').concat(c2, '"')); + } else if (!s2(c2)) + throw new B("Graph.".concat(e2, ': invalid attributes. Expecting an object but got "').concat(c2, '"')); + } + var h2; + if (o2 = "" + o2, a2 = "" + a2, d2 && (h2 = c2, c2 = void 0), !t2.allowSelfLoops && o2 === a2) + throw new I("Graph.".concat(e2, ': source & target are the same ("').concat(o2, `"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`)); + var p2, f2, l3 = t2._nodes.get(o2), g2 = t2._nodes.get(a2); + if (!n3 && (p2 = t2._edges.get(i2))) { + if (!(p2.source.key === o2 && p2.target.key === a2 || r2 && p2.source.key === a2 && p2.target.key === o2)) + throw new I("Graph.".concat(e2, ': inconsistency detected when attempting to merge the "').concat(i2, '" edge with "').concat(o2, '" source & "').concat(a2, '" target vs. ("').concat(p2.source.key, '", "').concat(p2.target.key, '").')); + f2 = p2; + } + if (f2 || t2.multi || !l3 || (f2 = r2 ? l3.undirected[a2] : l3.out[a2]), f2) { + var y2 = [f2.key, false, false, false]; + if (d2 ? !h2 : !c2) + return y2; + if (d2) { + var w2 = f2.attributes; + f2.attributes = h2(w2), t2.emit("edgeAttributesUpdated", { type: "replace", key: f2.key, attributes: f2.attributes }); + } else + u(f2.attributes, c2), t2.emit("edgeAttributesUpdated", { type: "merge", key: f2.key, attributes: f2.attributes, data: c2 }); + return y2; + } + c2 = c2 || {}, d2 && h2 && (c2 = h2(c2)); + var v2 = { key: null, undirected: r2, source: o2, target: a2, attributes: c2 }; + if (n3) + i2 = t2._edgeKeyGenerator(); + else if (i2 = "" + i2, t2._edges.has(i2)) + throw new I("Graph.".concat(e2, ': the "').concat(i2, '" edge already exists in the graph.')); + var b2 = false, m2 = false; + l3 || (l3 = Ot(t2, o2, {}), b2 = true, o2 === a2 && (g2 = l3, m2 = true)), g2 || (g2 = Ot(t2, a2, {}), m2 = true), p2 = new V(r2, i2, l3, g2, c2), t2._edges.set(i2, p2); + var k2 = o2 === a2; + return r2 ? (l3.undirectedDegree++, g2.undirectedDegree++, k2 && (l3.undirectedLoops++, t2._undirectedSelfLoopCount++)) : (l3.outDegree++, g2.inDegree++, k2 && (l3.directedLoops++, t2._directedSelfLoopCount++)), t2.multi ? p2.attachMulti() : p2.attach(), r2 ? t2._undirectedSize++ : t2._directedSize++, v2.key = i2, t2.emit("edgeAdded", v2), [i2, true, b2, m2]; + } + function Mt(t2, e2) { + t2._edges.delete(e2.key); + var n3 = e2.source, r2 = e2.target, i2 = e2.attributes, o2 = e2.undirected, a2 = n3 === r2; + o2 ? (n3.undirectedDegree--, r2.undirectedDegree--, a2 && (n3.undirectedLoops--, t2._undirectedSelfLoopCount--)) : (n3.outDegree--, r2.inDegree--, a2 && (n3.directedLoops--, t2._directedSelfLoopCount--)), t2.multi ? e2.detachMulti() : e2.detach(), o2 ? t2._undirectedSize-- : t2._directedSize--, t2.emit("edgeDropped", { key: e2.key, attributes: i2, source: n3.key, target: r2.key, undirected: o2 }); + } + var zt = function(n3) { + function r2(t2) { + var e2; + if (e2 = n3.call(this) || this, "boolean" != typeof (t2 = u({}, Nt, t2)).multi) + throw new B(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "`.concat(t2.multi, '".')); + if (!Dt.has(t2.type)) + throw new B(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "`.concat(t2.type, '".')); + if ("boolean" != typeof t2.allowSelfLoops) + throw new B(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "`.concat(t2.allowSelfLoops, '".')); + var r3 = "mixed" === t2.type ? Y : "directed" === t2.type ? q : J; + p(c(e2), "NodeDataClass", r3); + var i3 = "geid_" + St() + "_", o2 = 0; + return p(c(e2), "_attributes", {}), p(c(e2), "_nodes", /* @__PURE__ */ new Map()), p(c(e2), "_edges", /* @__PURE__ */ new Map()), p(c(e2), "_directedSize", 0), p(c(e2), "_undirectedSize", 0), p(c(e2), "_directedSelfLoopCount", 0), p(c(e2), "_undirectedSelfLoopCount", 0), p(c(e2), "_edgeKeyGenerator", function() { + var t3; + do { + t3 = i3 + o2++; + } while (e2._edges.has(t3)); + return t3; + }), p(c(e2), "_options", t2), Ut.forEach(function(t3) { + return p(c(e2), t3, e2[t3]); + }), f(c(e2), "order", function() { + return e2._nodes.size; + }), f(c(e2), "size", function() { + return e2._edges.size; + }), f(c(e2), "directedSize", function() { + return e2._directedSize; + }), f(c(e2), "undirectedSize", function() { + return e2._undirectedSize; + }), f(c(e2), "selfLoopCount", function() { + return e2._directedSelfLoopCount + e2._undirectedSelfLoopCount; + }), f(c(e2), "directedSelfLoopCount", function() { + return e2._directedSelfLoopCount; + }), f(c(e2), "undirectedSelfLoopCount", function() { + return e2._undirectedSelfLoopCount; + }), f(c(e2), "multi", e2._options.multi), f(c(e2), "type", e2._options.type), f(c(e2), "allowSelfLoops", e2._options.allowSelfLoops), f(c(e2), "implementation", function() { + return "graphology"; + }), e2; + } + e(r2, n3); + var i2 = r2.prototype; + return i2._resetInstanceCounters = function() { + this._directedSize = 0, this._undirectedSize = 0, this._directedSelfLoopCount = 0, this._undirectedSelfLoopCount = 0; + }, i2.hasNode = function(t2) { + return this._nodes.has("" + t2); + }, i2.hasDirectedEdge = function(t2, e2) { + if ("undirected" === this.type) + return false; + if (1 === arguments.length) { + var n4 = "" + t2, r3 = this._edges.get(n4); + return !!r3 && !r3.undirected; + } + if (2 === arguments.length) { + t2 = "" + t2, e2 = "" + e2; + var i3 = this._nodes.get(t2); + return !!i3 && i3.out.hasOwnProperty(e2); + } + throw new B("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length, ", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.")); + }, i2.hasUndirectedEdge = function(t2, e2) { + if ("directed" === this.type) + return false; + if (1 === arguments.length) { + var n4 = "" + t2, r3 = this._edges.get(n4); + return !!r3 && r3.undirected; + } + if (2 === arguments.length) { + t2 = "" + t2, e2 = "" + e2; + var i3 = this._nodes.get(t2); + return !!i3 && i3.undirected.hasOwnProperty(e2); + } + throw new B("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length, ", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.")); + }, i2.hasEdge = function(t2, e2) { + if (1 === arguments.length) { + var n4 = "" + t2; + return this._edges.has(n4); + } + if (2 === arguments.length) { + t2 = "" + t2, e2 = "" + e2; + var r3 = this._nodes.get(t2); + return !!r3 && (void 0 !== r3.out && r3.out.hasOwnProperty(e2) || void 0 !== r3.undirected && r3.undirected.hasOwnProperty(e2)); + } + throw new B("Graph.hasEdge: invalid arity (".concat(arguments.length, ", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.")); + }, i2.directedEdge = function(t2, e2) { + if ("undirected" !== this.type) { + if (t2 = "" + t2, e2 = "" + e2, this.multi) + throw new I("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead."); + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.directedEdge: could not find the "'.concat(t2, '" source node in the graph.')); + if (!this._nodes.has(e2)) + throw new F('Graph.directedEdge: could not find the "'.concat(e2, '" target node in the graph.')); + var r3 = n4.out && n4.out[e2] || void 0; + return r3 ? r3.key : void 0; + } + }, i2.undirectedEdge = function(t2, e2) { + if ("directed" !== this.type) { + if (t2 = "" + t2, e2 = "" + e2, this.multi) + throw new I("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead."); + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.undirectedEdge: could not find the "'.concat(t2, '" source node in the graph.')); + if (!this._nodes.has(e2)) + throw new F('Graph.undirectedEdge: could not find the "'.concat(e2, '" target node in the graph.')); + var r3 = n4.undirected && n4.undirected[e2] || void 0; + return r3 ? r3.key : void 0; + } + }, i2.edge = function(t2, e2) { + if (this.multi) + throw new I("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead."); + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.edge: could not find the "'.concat(t2, '" source node in the graph.')); + if (!this._nodes.has(e2)) + throw new F('Graph.edge: could not find the "'.concat(e2, '" target node in the graph.')); + var r3 = n4.out && n4.out[e2] || n4.undirected && n4.undirected[e2] || void 0; + if (r3) + return r3.key; + }, i2.areDirectedNeighbors = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.areDirectedNeighbors: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" !== this.type && (e2 in n4.in || e2 in n4.out); + }, i2.areOutNeighbors = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.areOutNeighbors: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" !== this.type && e2 in n4.out; + }, i2.areInNeighbors = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.areInNeighbors: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" !== this.type && e2 in n4.in; + }, i2.areUndirectedNeighbors = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.areUndirectedNeighbors: could not find the "'.concat(t2, '" node in the graph.')); + return "directed" !== this.type && e2 in n4.undirected; + }, i2.areNeighbors = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.areNeighbors: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" !== this.type && (e2 in n4.in || e2 in n4.out) || "directed" !== this.type && e2 in n4.undirected; + }, i2.areInboundNeighbors = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.areInboundNeighbors: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" !== this.type && e2 in n4.in || "directed" !== this.type && e2 in n4.undirected; + }, i2.areOutboundNeighbors = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.areOutboundNeighbors: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" !== this.type && e2 in n4.out || "directed" !== this.type && e2 in n4.undirected; + }, i2.inDegree = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.inDegree: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" === this.type ? 0 : e2.inDegree; + }, i2.outDegree = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.outDegree: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" === this.type ? 0 : e2.outDegree; + }, i2.directedDegree = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.directedDegree: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" === this.type ? 0 : e2.inDegree + e2.outDegree; + }, i2.undirectedDegree = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.undirectedDegree: could not find the "'.concat(t2, '" node in the graph.')); + return "directed" === this.type ? 0 : e2.undirectedDegree; + }, i2.inboundDegree = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.inboundDegree: could not find the "'.concat(t2, '" node in the graph.')); + var n4 = 0; + return "directed" !== this.type && (n4 += e2.undirectedDegree), "undirected" !== this.type && (n4 += e2.inDegree), n4; + }, i2.outboundDegree = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.outboundDegree: could not find the "'.concat(t2, '" node in the graph.')); + var n4 = 0; + return "directed" !== this.type && (n4 += e2.undirectedDegree), "undirected" !== this.type && (n4 += e2.outDegree), n4; + }, i2.degree = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.degree: could not find the "'.concat(t2, '" node in the graph.')); + var n4 = 0; + return "directed" !== this.type && (n4 += e2.undirectedDegree), "undirected" !== this.type && (n4 += e2.inDegree + e2.outDegree), n4; + }, i2.inDegreeWithoutSelfLoops = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.inDegreeWithoutSelfLoops: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" === this.type ? 0 : e2.inDegree - e2.directedLoops; + }, i2.outDegreeWithoutSelfLoops = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.outDegreeWithoutSelfLoops: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" === this.type ? 0 : e2.outDegree - e2.directedLoops; + }, i2.directedDegreeWithoutSelfLoops = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.directedDegreeWithoutSelfLoops: could not find the "'.concat(t2, '" node in the graph.')); + return "undirected" === this.type ? 0 : e2.inDegree + e2.outDegree - 2 * e2.directedLoops; + }, i2.undirectedDegreeWithoutSelfLoops = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.undirectedDegreeWithoutSelfLoops: could not find the "'.concat(t2, '" node in the graph.')); + return "directed" === this.type ? 0 : e2.undirectedDegree - 2 * e2.undirectedLoops; + }, i2.inboundDegreeWithoutSelfLoops = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.inboundDegreeWithoutSelfLoops: could not find the "'.concat(t2, '" node in the graph.')); + var n4 = 0, r3 = 0; + return "directed" !== this.type && (n4 += e2.undirectedDegree, r3 += 2 * e2.undirectedLoops), "undirected" !== this.type && (n4 += e2.inDegree, r3 += e2.directedLoops), n4 - r3; + }, i2.outboundDegreeWithoutSelfLoops = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.outboundDegreeWithoutSelfLoops: could not find the "'.concat(t2, '" node in the graph.')); + var n4 = 0, r3 = 0; + return "directed" !== this.type && (n4 += e2.undirectedDegree, r3 += 2 * e2.undirectedLoops), "undirected" !== this.type && (n4 += e2.outDegree, r3 += e2.directedLoops), n4 - r3; + }, i2.degreeWithoutSelfLoops = function(t2) { + t2 = "" + t2; + var e2 = this._nodes.get(t2); + if (!e2) + throw new F('Graph.degreeWithoutSelfLoops: could not find the "'.concat(t2, '" node in the graph.')); + var n4 = 0, r3 = 0; + return "directed" !== this.type && (n4 += e2.undirectedDegree, r3 += 2 * e2.undirectedLoops), "undirected" !== this.type && (n4 += e2.inDegree + e2.outDegree, r3 += 2 * e2.directedLoops), n4 - r3; + }, i2.source = function(t2) { + t2 = "" + t2; + var e2 = this._edges.get(t2); + if (!e2) + throw new F('Graph.source: could not find the "'.concat(t2, '" edge in the graph.')); + return e2.source.key; + }, i2.target = function(t2) { + t2 = "" + t2; + var e2 = this._edges.get(t2); + if (!e2) + throw new F('Graph.target: could not find the "'.concat(t2, '" edge in the graph.')); + return e2.target.key; + }, i2.extremities = function(t2) { + t2 = "" + t2; + var e2 = this._edges.get(t2); + if (!e2) + throw new F('Graph.extremities: could not find the "'.concat(t2, '" edge in the graph.')); + return [e2.source.key, e2.target.key]; + }, i2.opposite = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._edges.get(e2); + if (!n4) + throw new F('Graph.opposite: could not find the "'.concat(e2, '" edge in the graph.')); + var r3 = n4.source.key, i3 = n4.target.key; + if (t2 === r3) + return i3; + if (t2 === i3) + return r3; + throw new F('Graph.opposite: the "'.concat(t2, '" node is not attached to the "').concat(e2, '" edge (').concat(r3, ", ").concat(i3, ").")); + }, i2.hasExtremity = function(t2, e2) { + t2 = "" + t2, e2 = "" + e2; + var n4 = this._edges.get(t2); + if (!n4) + throw new F('Graph.hasExtremity: could not find the "'.concat(t2, '" edge in the graph.')); + return n4.source.key === e2 || n4.target.key === e2; + }, i2.isUndirected = function(t2) { + t2 = "" + t2; + var e2 = this._edges.get(t2); + if (!e2) + throw new F('Graph.isUndirected: could not find the "'.concat(t2, '" edge in the graph.')); + return e2.undirected; + }, i2.isDirected = function(t2) { + t2 = "" + t2; + var e2 = this._edges.get(t2); + if (!e2) + throw new F('Graph.isDirected: could not find the "'.concat(t2, '" edge in the graph.')); + return !e2.undirected; + }, i2.isSelfLoop = function(t2) { + t2 = "" + t2; + var e2 = this._edges.get(t2); + if (!e2) + throw new F('Graph.isSelfLoop: could not find the "'.concat(t2, '" edge in the graph.')); + return e2.source === e2.target; + }, i2.addNode = function(t2, e2) { + var n4 = function(t3, e3, n5) { + if (n5 && !s2(n5)) + throw new B('Graph.addNode: invalid attributes. Expecting an object but got "'.concat(n5, '"')); + if (e3 = "" + e3, n5 = n5 || {}, t3._nodes.has(e3)) + throw new I('Graph.addNode: the "'.concat(e3, '" node already exist in the graph.')); + var r3 = new t3.NodeDataClass(e3, n5); + return t3._nodes.set(e3, r3), t3.emit("nodeAdded", { key: e3, attributes: n5 }), r3; + }(this, t2, e2); + return n4.key; + }, i2.mergeNode = function(t2, e2) { + if (e2 && !s2(e2)) + throw new B('Graph.mergeNode: invalid attributes. Expecting an object but got "'.concat(e2, '"')); + t2 = "" + t2, e2 = e2 || {}; + var n4 = this._nodes.get(t2); + return n4 ? (e2 && (u(n4.attributes, e2), this.emit("nodeAttributesUpdated", { type: "merge", key: t2, attributes: n4.attributes, data: e2 })), [t2, false]) : (n4 = new this.NodeDataClass(t2, e2), this._nodes.set(t2, n4), this.emit("nodeAdded", { key: t2, attributes: e2 }), [t2, true]); + }, i2.updateNode = function(t2, e2) { + if (e2 && "function" != typeof e2) + throw new B('Graph.updateNode: invalid updater function. Expecting a function but got "'.concat(e2, '"')); + t2 = "" + t2; + var n4 = this._nodes.get(t2); + if (n4) { + if (e2) { + var r3 = n4.attributes; + n4.attributes = e2(r3), this.emit("nodeAttributesUpdated", { type: "replace", key: t2, attributes: n4.attributes }); + } + return [t2, false]; + } + var i3 = e2 ? e2({}) : {}; + return n4 = new this.NodeDataClass(t2, i3), this._nodes.set(t2, n4), this.emit("nodeAdded", { key: t2, attributes: i3 }), [t2, true]; + }, i2.dropNode = function(t2) { + t2 = "" + t2; + var e2, n4 = this._nodes.get(t2); + if (!n4) + throw new F('Graph.dropNode: could not find the "'.concat(t2, '" node in the graph.')); + if ("undirected" !== this.type) { + for (var r3 in n4.out) { + e2 = n4.out[r3]; + do { + Mt(this, e2), e2 = e2.next; + } while (e2); + } + for (var i3 in n4.in) { + e2 = n4.in[i3]; + do { + Mt(this, e2), e2 = e2.next; + } while (e2); + } + } + if ("directed" !== this.type) + for (var o2 in n4.undirected) { + e2 = n4.undirected[o2]; + do { + Mt(this, e2), e2 = e2.next; + } while (e2); + } + this._nodes.delete(t2), this.emit("nodeDropped", { key: t2, attributes: n4.attributes }); + }, i2.dropEdge = function(t2) { + var e2; + if (arguments.length > 1) { + var n4 = "" + arguments[0], r3 = "" + arguments[1]; + if (!(e2 = d(this, n4, r3, this.type))) + throw new F('Graph.dropEdge: could not find the "'.concat(n4, '" -> "').concat(r3, '" edge in the graph.')); + } else if (t2 = "" + t2, !(e2 = this._edges.get(t2))) + throw new F('Graph.dropEdge: could not find the "'.concat(t2, '" edge in the graph.')); + return Mt(this, e2), this; + }, i2.dropDirectedEdge = function(t2, e2) { + if (arguments.length < 2) + throw new I("Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead."); + if (this.multi) + throw new I("Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones."); + var n4 = d(this, t2 = "" + t2, e2 = "" + e2, "directed"); + if (!n4) + throw new F('Graph.dropDirectedEdge: could not find a "'.concat(t2, '" -> "').concat(e2, '" edge in the graph.')); + return Mt(this, n4), this; + }, i2.dropUndirectedEdge = function(t2, e2) { + if (arguments.length < 2) + throw new I("Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead."); + if (this.multi) + throw new I("Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones."); + var n4 = d(this, t2, e2, "undirected"); + if (!n4) + throw new F('Graph.dropUndirectedEdge: could not find a "'.concat(t2, '" -> "').concat(e2, '" edge in the graph.')); + return Mt(this, n4), this; + }, i2.clear = function() { + this._edges.clear(), this._nodes.clear(), this._resetInstanceCounters(), this.emit("cleared"); + }, i2.clearEdges = function() { + for (var t2, e2 = this._nodes.values(); true !== (t2 = e2.next()).done; ) + t2.value.clear(); + this._edges.clear(), this._resetInstanceCounters(), this.emit("edgesCleared"); + }, i2.getAttribute = function(t2) { + return this._attributes[t2]; + }, i2.getAttributes = function() { + return this._attributes; + }, i2.hasAttribute = function(t2) { + return this._attributes.hasOwnProperty(t2); + }, i2.setAttribute = function(t2, e2) { + return this._attributes[t2] = e2, this.emit("attributesUpdated", { type: "set", attributes: this._attributes, name: t2 }), this; + }, i2.updateAttribute = function(t2, e2) { + if ("function" != typeof e2) + throw new B("Graph.updateAttribute: updater should be a function."); + var n4 = this._attributes[t2]; + return this._attributes[t2] = e2(n4), this.emit("attributesUpdated", { type: "set", attributes: this._attributes, name: t2 }), this; + }, i2.removeAttribute = function(t2) { + return delete this._attributes[t2], this.emit("attributesUpdated", { type: "remove", attributes: this._attributes, name: t2 }), this; + }, i2.replaceAttributes = function(t2) { + if (!s2(t2)) + throw new B("Graph.replaceAttributes: provided attributes are not a plain object."); + return this._attributes = t2, this.emit("attributesUpdated", { type: "replace", attributes: this._attributes }), this; + }, i2.mergeAttributes = function(t2) { + if (!s2(t2)) + throw new B("Graph.mergeAttributes: provided attributes are not a plain object."); + return u(this._attributes, t2), this.emit("attributesUpdated", { type: "merge", attributes: this._attributes, data: t2 }), this; + }, i2.updateAttributes = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.updateAttributes: provided updater is not a function."); + return this._attributes = t2(this._attributes), this.emit("attributesUpdated", { type: "update", attributes: this._attributes }), this; + }, i2.updateEachNodeAttributes = function(t2, e2) { + if ("function" != typeof t2) + throw new B("Graph.updateEachNodeAttributes: expecting an updater function."); + if (e2 && !l2(e2)) + throw new B("Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}"); + for (var n4, r3, i3 = this._nodes.values(); true !== (n4 = i3.next()).done; ) + (r3 = n4.value).attributes = t2(r3.key, r3.attributes); + this.emit("eachNodeAttributesUpdated", { hints: e2 || null }); + }, i2.updateEachEdgeAttributes = function(t2, e2) { + if ("function" != typeof t2) + throw new B("Graph.updateEachEdgeAttributes: expecting an updater function."); + if (e2 && !l2(e2)) + throw new B("Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}"); + for (var n4, r3, i3, o2, a2 = this._edges.values(); true !== (n4 = a2.next()).done; ) + i3 = (r3 = n4.value).source, o2 = r3.target, r3.attributes = t2(r3.key, r3.attributes, i3.key, o2.key, i3.attributes, o2.attributes, r3.undirected); + this.emit("eachEdgeAttributesUpdated", { hints: e2 || null }); + }, i2.forEachAdjacencyEntry = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.forEachAdjacencyEntry: expecting a callback."); + xt(false, false, false, this, t2); + }, i2.forEachAdjacencyEntryWithOrphans = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback."); + xt(false, false, true, this, t2); + }, i2.forEachAssymetricAdjacencyEntry = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.forEachAssymetricAdjacencyEntry: expecting a callback."); + xt(false, true, false, this, t2); + }, i2.forEachAssymetricAdjacencyEntryWithOrphans = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback."); + xt(false, true, true, this, t2); + }, i2.nodes = function() { + return "function" == typeof Array.from ? Array.from(this._nodes.keys()) : K(this._nodes.keys(), this._nodes.size); + }, i2.forEachNode = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.forEachNode: expecting a callback."); + for (var e2, n4, r3 = this._nodes.values(); true !== (e2 = r3.next()).done; ) + t2((n4 = e2.value).key, n4.attributes); + }, i2.findNode = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.findNode: expecting a callback."); + for (var e2, n4, r3 = this._nodes.values(); true !== (e2 = r3.next()).done; ) + if (t2((n4 = e2.value).key, n4.attributes)) + return n4.key; + }, i2.mapNodes = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.mapNode: expecting a callback."); + for (var e2, n4, r3 = this._nodes.values(), i3 = new Array(this.order), o2 = 0; true !== (e2 = r3.next()).done; ) + n4 = e2.value, i3[o2++] = t2(n4.key, n4.attributes); + return i3; + }, i2.someNode = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.someNode: expecting a callback."); + for (var e2, n4, r3 = this._nodes.values(); true !== (e2 = r3.next()).done; ) + if (t2((n4 = e2.value).key, n4.attributes)) + return true; + return false; + }, i2.everyNode = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.everyNode: expecting a callback."); + for (var e2, n4, r3 = this._nodes.values(); true !== (e2 = r3.next()).done; ) + if (!t2((n4 = e2.value).key, n4.attributes)) + return false; + return true; + }, i2.filterNodes = function(t2) { + if ("function" != typeof t2) + throw new B("Graph.filterNodes: expecting a callback."); + for (var e2, n4, r3 = this._nodes.values(), i3 = []; true !== (e2 = r3.next()).done; ) + t2((n4 = e2.value).key, n4.attributes) && i3.push(n4.key); + return i3; + }, i2.reduceNodes = function(t2, e2) { + if ("function" != typeof t2) + throw new B("Graph.reduceNodes: expecting a callback."); + if (arguments.length < 2) + throw new B("Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array."); + for (var n4, r3, i3 = e2, o2 = this._nodes.values(); true !== (n4 = o2.next()).done; ) + i3 = t2(i3, (r3 = n4.value).key, r3.attributes); + return i3; + }, i2.nodeEntries = function() { + var t2 = this._nodes.values(); + return new O(function() { + var e2 = t2.next(); + if (e2.done) + return e2; + var n4 = e2.value; + return { value: { node: n4.key, attributes: n4.attributes }, done: false }; + }); + }, i2.export = function() { + var t2 = this, e2 = new Array(this._nodes.size), n4 = 0; + this._nodes.forEach(function(t3, r4) { + e2[n4++] = function(t4, e3) { + var n5 = { key: t4 }; + return h(e3.attributes) || (n5.attributes = u({}, e3.attributes)), n5; + }(r4, t3); + }); + var r3 = new Array(this._edges.size); + return n4 = 0, this._edges.forEach(function(e3, i3) { + r3[n4++] = function(t3, e4, n5) { + var r4 = { key: e4, source: n5.source.key, target: n5.target.key }; + return h(n5.attributes) || (r4.attributes = u({}, n5.attributes)), "mixed" === t3 && n5.undirected && (r4.undirected = true), r4; + }(t2.type, i3, e3); + }), { options: { type: this.type, multi: this.multi, allowSelfLoops: this.allowSelfLoops }, attributes: this.getAttributes(), nodes: e2, edges: r3 }; + }, i2.import = function(t2) { + var e2, n4, i3, o2, a2, c2 = this, u2 = arguments.length > 1 && void 0 !== arguments[1] && arguments[1]; + if (t2 instanceof r2) + return t2.forEachNode(function(t3, e3) { + u2 ? c2.mergeNode(t3, e3) : c2.addNode(t3, e3); + }), t2.forEachEdge(function(t3, e3, n5, r3, i4, o3, a3) { + u2 ? a3 ? c2.mergeUndirectedEdgeWithKey(t3, n5, r3, e3) : c2.mergeDirectedEdgeWithKey(t3, n5, r3, e3) : a3 ? c2.addUndirectedEdgeWithKey(t3, n5, r3, e3) : c2.addDirectedEdgeWithKey(t3, n5, r3, e3); + }), this; + if (!s2(t2)) + throw new B("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance."); + if (t2.attributes) { + if (!s2(t2.attributes)) + throw new B("Graph.import: invalid attributes. Expecting a plain object."); + u2 ? this.mergeAttributes(t2.attributes) : this.replaceAttributes(t2.attributes); + } + if (t2.nodes) { + if (i3 = t2.nodes, !Array.isArray(i3)) + throw new B("Graph.import: invalid nodes. Expecting an array."); + for (e2 = 0, n4 = i3.length; e2 < n4; e2++) { + Et(o2 = i3[e2]); + var d2 = o2, h2 = d2.key, p2 = d2.attributes; + u2 ? this.mergeNode(h2, p2) : this.addNode(h2, p2); + } + } + if (t2.edges) { + var f2 = false; + if ("undirected" === this.type && (f2 = true), i3 = t2.edges, !Array.isArray(i3)) + throw new B("Graph.import: invalid edges. Expecting an array."); + for (e2 = 0, n4 = i3.length; e2 < n4; e2++) { + At(a2 = i3[e2]); + var l3 = a2, g2 = l3.source, y2 = l3.target, w2 = l3.attributes, v2 = l3.undirected, b2 = void 0 === v2 ? f2 : v2; + "key" in a2 ? (u2 ? b2 ? this.mergeUndirectedEdgeWithKey : this.mergeDirectedEdgeWithKey : b2 ? this.addUndirectedEdgeWithKey : this.addDirectedEdgeWithKey).call(this, a2.key, g2, y2, w2) : (u2 ? b2 ? this.mergeUndirectedEdge : this.mergeDirectedEdge : b2 ? this.addUndirectedEdge : this.addDirectedEdge).call(this, g2, y2, w2); + } + } + return this; + }, i2.nullCopy = function(t2) { + var e2 = new r2(u({}, this._options, t2)); + return e2.replaceAttributes(u({}, this.getAttributes())), e2; + }, i2.emptyCopy = function(t2) { + var e2 = this.nullCopy(t2); + return this._nodes.forEach(function(t3, n4) { + var r3 = u({}, t3.attributes); + t3 = new e2.NodeDataClass(n4, r3), e2._nodes.set(n4, t3); + }), e2; + }, i2.copy = function(t2) { + if ("string" == typeof (t2 = t2 || {}).type && t2.type !== this.type && "mixed" !== t2.type) + throw new I('Graph.copy: cannot create an incompatible copy from "'.concat(this.type, '" type to "').concat(t2.type, '" because this would mean losing information about the current graph.')); + if ("boolean" == typeof t2.multi && t2.multi !== this.multi && true !== t2.multi) + throw new I("Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph."); + if ("boolean" == typeof t2.allowSelfLoops && t2.allowSelfLoops !== this.allowSelfLoops && true !== t2.allowSelfLoops) + throw new I("Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph."); + for (var e2, n4, r3 = this.emptyCopy(t2), i3 = this._edges.values(); true !== (e2 = i3.next()).done; ) + jt(r3, "copy", false, (n4 = e2.value).undirected, n4.key, n4.source.key, n4.target.key, u({}, n4.attributes)); + return r3; + }, i2.toJSON = function() { + return this.export(); + }, i2.toString = function() { + return "[object Graph]"; + }, i2.inspect = function() { + var e2 = this, n4 = {}; + this._nodes.forEach(function(t2, e3) { + n4[e3] = t2.attributes; + }); + var r3 = {}, i3 = {}; + this._edges.forEach(function(t2, n5) { + var o3, a3 = t2.undirected ? "--" : "->", c2 = "", u2 = t2.source.key, d2 = t2.target.key; + t2.undirected && u2 > d2 && (o3 = u2, u2 = d2, d2 = o3); + var s3 = "(".concat(u2, ")").concat(a3, "(").concat(d2, ")"); + n5.startsWith("geid_") ? e2.multi && (void 0 === i3[s3] ? i3[s3] = 0 : i3[s3]++, c2 += "".concat(i3[s3], ". ")) : c2 += "[".concat(n5, "]: "), r3[c2 += s3] = t2.attributes; + }); + var o2 = {}; + for (var a2 in this) + this.hasOwnProperty(a2) && !Ut.has(a2) && "function" != typeof this[a2] && "symbol" !== t(a2) && (o2[a2] = this[a2]); + return o2.attributes = this._attributes, o2.nodes = n4, o2.edges = r3, p(o2, "constructor", this.constructor), o2; + }, r2; + }(y.exports.EventEmitter); + "undefined" != typeof Symbol && (zt.prototype[Symbol.for("nodejs.util.inspect.custom")] = zt.prototype.inspect), [{ name: function(t2) { + return "".concat(t2, "Edge"); + }, generateKey: true }, { name: function(t2) { + return "".concat(t2, "DirectedEdge"); + }, generateKey: true, type: "directed" }, { name: function(t2) { + return "".concat(t2, "UndirectedEdge"); + }, generateKey: true, type: "undirected" }, { name: function(t2) { + return "".concat(t2, "EdgeWithKey"); + } }, { name: function(t2) { + return "".concat(t2, "DirectedEdgeWithKey"); + }, type: "directed" }, { name: function(t2) { + return "".concat(t2, "UndirectedEdgeWithKey"); + }, type: "undirected" }].forEach(function(t2) { + ["add", "merge", "update"].forEach(function(e2) { + var n3 = t2.name(e2), r2 = "add" === e2 ? jt : Ct; + t2.generateKey ? zt.prototype[n3] = function(i2, o2, a2) { + return r2(this, n3, true, "undirected" === (t2.type || this.type), null, i2, o2, a2, "update" === e2); + } : zt.prototype[n3] = function(i2, o2, a2, c2) { + return r2(this, n3, false, "undirected" === (t2.type || this.type), i2, o2, a2, c2, "update" === e2); + }; + }); + }), function(t2) { + Q.forEach(function(e2) { + var n3 = e2.name, r2 = e2.attacher; + r2(t2, n3("Node"), 0), r2(t2, n3("Source"), 1), r2(t2, n3("Target"), 2), r2(t2, n3("Opposite"), 3); + }); + }(zt), function(t2) { + X.forEach(function(e2) { + var n3 = e2.name, r2 = e2.attacher; + r2(t2, n3("Edge"), "mixed"), r2(t2, n3("DirectedEdge"), "directed"), r2(t2, n3("UndirectedEdge"), "undirected"); + }); + }(zt), function(t2) { + et.forEach(function(e2) { + !function(t3, e3) { + var n3 = e3.name, r2 = e3.type, i2 = e3.direction; + t3.prototype[n3] = function(t4, e4) { + if ("mixed" !== r2 && "mixed" !== this.type && r2 !== this.type) + return []; + if (!arguments.length) + return ut(this, r2); + if (1 === arguments.length) { + t4 = "" + t4; + var o2 = this._nodes.get(t4); + if (void 0 === o2) + throw new F("Graph.".concat(n3, ': could not find the "').concat(t4, '" node in the graph.')); + return pt(this.multi, "mixed" === r2 ? this.type : r2, i2, o2); + } + if (2 === arguments.length) { + t4 = "" + t4, e4 = "" + e4; + var a2 = this._nodes.get(t4); + if (!a2) + throw new F("Graph.".concat(n3, ': could not find the "').concat(t4, '" source node in the graph.')); + if (!this._nodes.has(e4)) + throw new F("Graph.".concat(n3, ': could not find the "').concat(e4, '" target node in the graph.')); + return gt(r2, this.multi, i2, a2, e4); + } + throw new B("Graph.".concat(n3, ": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length, ").")); + }; + }(t2, e2), function(t3, e3) { + var n3 = e3.name, r2 = e3.type, i2 = e3.direction, o2 = "forEach" + n3[0].toUpperCase() + n3.slice(1, -1); + t3.prototype[o2] = function(t4, e4, n4) { + if ("mixed" === r2 || "mixed" === this.type || r2 === this.type) { + if (1 === arguments.length) + return dt(false, this, r2, n4 = t4); + if (2 === arguments.length) { + t4 = "" + t4, n4 = e4; + var a3 = this._nodes.get(t4); + if (void 0 === a3) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t4, '" node in the graph.')); + return ht(false, this.multi, "mixed" === r2 ? this.type : r2, i2, a3, n4); + } + if (3 === arguments.length) { + t4 = "" + t4, e4 = "" + e4; + var c3 = this._nodes.get(t4); + if (!c3) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t4, '" source node in the graph.')); + if (!this._nodes.has(e4)) + throw new F("Graph.".concat(o2, ': could not find the "').concat(e4, '" target node in the graph.')); + return lt(false, r2, this.multi, i2, c3, e4, n4); + } + throw new B("Graph.".concat(o2, ": too many arguments (expecting 1, 2 or 3 and got ").concat(arguments.length, ").")); + } + }; + var a2 = "map" + n3[0].toUpperCase() + n3.slice(1); + t3.prototype[a2] = function() { + var t4, e4 = Array.prototype.slice.call(arguments), n4 = e4.pop(); + if (0 === e4.length) { + var i3 = 0; + "directed" !== r2 && (i3 += this.undirectedSize), "undirected" !== r2 && (i3 += this.directedSize), t4 = new Array(i3); + var a3 = 0; + e4.push(function(e5, r3, i4, o3, c3, u3, d2) { + t4[a3++] = n4(e5, r3, i4, o3, c3, u3, d2); + }); + } else + t4 = [], e4.push(function(e5, r3, i4, o3, a4, c3, u3) { + t4.push(n4(e5, r3, i4, o3, a4, c3, u3)); + }); + return this[o2].apply(this, e4), t4; + }; + var c2 = "filter" + n3[0].toUpperCase() + n3.slice(1); + t3.prototype[c2] = function() { + var t4 = Array.prototype.slice.call(arguments), e4 = t4.pop(), n4 = []; + return t4.push(function(t5, r3, i3, o3, a3, c3, u3) { + e4(t5, r3, i3, o3, a3, c3, u3) && n4.push(t5); + }), this[o2].apply(this, t4), n4; + }; + var u2 = "reduce" + n3[0].toUpperCase() + n3.slice(1); + t3.prototype[u2] = function() { + var t4, e4, n4 = Array.prototype.slice.call(arguments); + if (n4.length < 2 || n4.length > 4) + throw new B("Graph.".concat(u2, ": invalid number of arguments (expecting 2, 3 or 4 and got ").concat(n4.length, ").")); + if ("function" == typeof n4[n4.length - 1] && "function" != typeof n4[n4.length - 2]) + throw new B("Graph.".concat(u2, ": missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.")); + 2 === n4.length ? (t4 = n4[0], e4 = n4[1], n4 = []) : 3 === n4.length ? (t4 = n4[1], e4 = n4[2], n4 = [n4[0]]) : 4 === n4.length && (t4 = n4[2], e4 = n4[3], n4 = [n4[0], n4[1]]); + var r3 = e4; + return n4.push(function(e5, n5, i3, o3, a3, c3, u3) { + r3 = t4(r3, e5, n5, i3, o3, a3, c3, u3); + }), this[o2].apply(this, n4), r3; + }; + }(t2, e2), function(t3, e3) { + var n3 = e3.name, r2 = e3.type, i2 = e3.direction, o2 = "find" + n3[0].toUpperCase() + n3.slice(1, -1); + t3.prototype[o2] = function(t4, e4, n4) { + if ("mixed" !== r2 && "mixed" !== this.type && r2 !== this.type) + return false; + if (1 === arguments.length) + return dt(true, this, r2, n4 = t4); + if (2 === arguments.length) { + t4 = "" + t4, n4 = e4; + var a3 = this._nodes.get(t4); + if (void 0 === a3) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t4, '" node in the graph.')); + return ht(true, this.multi, "mixed" === r2 ? this.type : r2, i2, a3, n4); + } + if (3 === arguments.length) { + t4 = "" + t4, e4 = "" + e4; + var c3 = this._nodes.get(t4); + if (!c3) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t4, '" source node in the graph.')); + if (!this._nodes.has(e4)) + throw new F("Graph.".concat(o2, ': could not find the "').concat(e4, '" target node in the graph.')); + return lt(true, r2, this.multi, i2, c3, e4, n4); + } + throw new B("Graph.".concat(o2, ": too many arguments (expecting 1, 2 or 3 and got ").concat(arguments.length, ").")); + }; + var a2 = "some" + n3[0].toUpperCase() + n3.slice(1, -1); + t3.prototype[a2] = function() { + var t4 = Array.prototype.slice.call(arguments), e4 = t4.pop(); + return t4.push(function(t5, n4, r3, i3, o3, a3, c3) { + return e4(t5, n4, r3, i3, o3, a3, c3); + }), !!this[o2].apply(this, t4); + }; + var c2 = "every" + n3[0].toUpperCase() + n3.slice(1, -1); + t3.prototype[c2] = function() { + var t4 = Array.prototype.slice.call(arguments), e4 = t4.pop(); + return t4.push(function(t5, n4, r3, i3, o3, a3, c3) { + return !e4(t5, n4, r3, i3, o3, a3, c3); + }), !this[o2].apply(this, t4); + }; + }(t2, e2), function(t3, e3) { + var n3 = e3.name, r2 = e3.type, i2 = e3.direction, o2 = n3.slice(0, -1) + "Entries"; + t3.prototype[o2] = function(t4, e4) { + if ("mixed" !== r2 && "mixed" !== this.type && r2 !== this.type) + return O.empty(); + if (!arguments.length) + return st(this, r2); + if (1 === arguments.length) { + t4 = "" + t4; + var n4 = this._nodes.get(t4); + if (!n4) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t4, '" node in the graph.')); + return ft(r2, i2, n4); + } + if (2 === arguments.length) { + t4 = "" + t4, e4 = "" + e4; + var a2 = this._nodes.get(t4); + if (!a2) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t4, '" source node in the graph.')); + if (!this._nodes.has(e4)) + throw new F("Graph.".concat(o2, ': could not find the "').concat(e4, '" target node in the graph.')); + return yt(r2, i2, a2, e4); + } + throw new B("Graph.".concat(o2, ": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length, ").")); + }; + }(t2, e2); + }); + }(zt), function(t2) { + wt.forEach(function(e2) { + _t(t2, e2), function(t3, e3) { + var n3 = e3.name, r2 = e3.type, i2 = e3.direction, o2 = "forEach" + n3[0].toUpperCase() + n3.slice(1, -1); + t3.prototype[o2] = function(t4, e4) { + if ("mixed" === r2 || "mixed" === this.type || r2 === this.type) { + t4 = "" + t4; + var n4 = this._nodes.get(t4); + if (void 0 === n4) + throw new F("Graph.".concat(o2, ': could not find the "').concat(t4, '" node in the graph.')); + mt(false, "mixed" === r2 ? this.type : r2, i2, n4, e4); + } + }; + var a2 = "map" + n3[0].toUpperCase() + n3.slice(1); + t3.prototype[a2] = function(t4, e4) { + var n4 = []; + return this[o2](t4, function(t5, r3) { + n4.push(e4(t5, r3)); + }), n4; + }; + var c2 = "filter" + n3[0].toUpperCase() + n3.slice(1); + t3.prototype[c2] = function(t4, e4) { + var n4 = []; + return this[o2](t4, function(t5, r3) { + e4(t5, r3) && n4.push(t5); + }), n4; + }; + var u2 = "reduce" + n3[0].toUpperCase() + n3.slice(1); + t3.prototype[u2] = function(t4, e4, n4) { + if (arguments.length < 3) + throw new B("Graph.".concat(u2, ": missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.")); + var r3 = n4; + return this[o2](t4, function(t5, n5) { + r3 = e4(r3, t5, n5); + }), r3; + }; + }(t2, e2), function(t3, e3) { + var n3 = e3.name, r2 = e3.type, i2 = e3.direction, o2 = n3[0].toUpperCase() + n3.slice(1, -1), a2 = "find" + o2; + t3.prototype[a2] = function(t4, e4) { + if ("mixed" === r2 || "mixed" === this.type || r2 === this.type) { + t4 = "" + t4; + var n4 = this._nodes.get(t4); + if (void 0 === n4) + throw new F("Graph.".concat(a2, ': could not find the "').concat(t4, '" node in the graph.')); + return mt(true, "mixed" === r2 ? this.type : r2, i2, n4, e4); + } + }; + var c2 = "some" + o2; + t3.prototype[c2] = function(t4, e4) { + return !!this[a2](t4, e4); + }; + var u2 = "every" + o2; + t3.prototype[u2] = function(t4, e4) { + return !this[a2](t4, function(t5, n4) { + return !e4(t5, n4); + }); + }; + }(t2, e2), Gt(t2, e2); + }); + }(zt); + var Wt = function(t2) { + function n3(e2) { + var n4 = u({ type: "directed" }, e2); + if ("multi" in n4 && false !== n4.multi) + throw new B("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!"); + if ("directed" !== n4.type) + throw new B('DirectedGraph.from: inconsistent "' + n4.type + '" type in given options!'); + return t2.call(this, n4) || this; + } + return e(n3, t2), n3; + }(zt), Pt = function(t2) { + function n3(e2) { + var n4 = u({ type: "undirected" }, e2); + if ("multi" in n4 && false !== n4.multi) + throw new B("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!"); + if ("undirected" !== n4.type) + throw new B('UndirectedGraph.from: inconsistent "' + n4.type + '" type in given options!'); + return t2.call(this, n4) || this; + } + return e(n3, t2), n3; + }(zt), Rt = function(t2) { + function n3(e2) { + var n4 = u({ multi: true }, e2); + if ("multi" in n4 && true !== n4.multi) + throw new B("MultiGraph.from: inconsistent indication that the graph should be simple in given options!"); + return t2.call(this, n4) || this; + } + return e(n3, t2), n3; + }(zt), Kt = function(t2) { + function n3(e2) { + var n4 = u({ type: "directed", multi: true }, e2); + if ("multi" in n4 && true !== n4.multi) + throw new B("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!"); + if ("directed" !== n4.type) + throw new B('MultiDirectedGraph.from: inconsistent "' + n4.type + '" type in given options!'); + return t2.call(this, n4) || this; + } + return e(n3, t2), n3; + }(zt), Tt = function(t2) { + function n3(e2) { + var n4 = u({ type: "undirected", multi: true }, e2); + if ("multi" in n4 && true !== n4.multi) + throw new B("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!"); + if ("undirected" !== n4.type) + throw new B('MultiUndirectedGraph.from: inconsistent "' + n4.type + '" type in given options!'); + return t2.call(this, n4) || this; + } + return e(n3, t2), n3; + }(zt); + function Bt(t2) { + t2.from = function(e2, n3) { + var r2 = u({}, e2.options, n3), i2 = new t2(r2); + return i2.import(e2), i2; + }; + } + return Bt(zt), Bt(Wt), Bt(Pt), Bt(Rt), Bt(Kt), Bt(Tt), zt.Graph = zt, zt.DirectedGraph = Wt, zt.UndirectedGraph = Pt, zt.MultiGraph = Rt, zt.MultiDirectedGraph = Kt, zt.MultiUndirectedGraph = Tt, zt.InvalidArgumentsGraphError = B, zt.NotFoundGraphError = F, zt.UsageGraphError = I, zt; + }); + } +}); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => BreadcrumbsPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian37 = require("obsidian"); + +// src/codeblocks/index.ts +var import_obsidian = require("obsidian"); + +// src/external/dataview/index.ts +var import_obsidian_dataview = __toESM(require_lib()); + +// src/logger/index.ts +var LOG_LEVELS = [ + "DEBUG", + "INFO", + "WARN", + "ERROR", + // Some features log data + "FEAT" +]; +var LEVEL_COLOURS = { + DEBUG: "#999", + INFO: null, + WARN: "#f90", + ERROR: "#f00", + FEAT: "#0f0" +}; +var build_prefix = (level) => { + const colour = LEVEL_COLOURS[level]; + const prefix = `[BC:${level}][${(/* @__PURE__ */ new Date()).toISOString().split("T")[1]}]`; + return [ + colour ? `%c${prefix}` : prefix, + colour ? `color: ${LEVEL_COLOURS[level]};` : "", + "\n" + ]; +}; +var Logger = class { + constructor(level) { + this.set_level(level); + } + debug(...args) { + if (this.level_i <= 0) { + console.log(...build_prefix("DEBUG"), ...args); + } + } + info(...args) { + if (this.level_i <= 1) { + console.log(...build_prefix("INFO"), ...args); + } + } + warn(...args) { + if (this.level_i <= 2) { + console.log(...build_prefix("WARN"), ...args); + } + } + error(...args) { + if (this.level_i <= 3) { + console.log(...build_prefix("ERROR"), ...args); + } + } + feat(...args) { + if (this.level_i <= 4) { + console.log(...build_prefix("FEAT"), ...args); + } + } + set_level(level) { + this.level_i = LOG_LEVELS.findIndex((l2) => l2 === level); + } +}; +var log = new Logger("INFO"); + +// src/external/dataview/index.ts +var await_if_enabled = (plugin) => new Promise((resolve) => { + var _a; + if ((0, import_obsidian_dataview.isPluginEnabled)(plugin.app)) { + if ((_a = (0, import_obsidian_dataview.getAPI)(plugin.app)) == null ? void 0 : _a.index.initialized) { + log.debug("dataview > already initialized"); + resolve(); + } + plugin.registerEvent( + plugin.app.metadataCache.on( + //@ts-ignore: It's there if dataview is enabled + "dataview:index-ready", + () => { + log.debug("dataview > ready"); + resolve(); + } + ) + ); + } else { + log.debug("dataview > not enabled"); + resolve(); + } +}); +var dataview_plugin = { + get_api: import_obsidian_dataview.getAPI, + is_enabled: import_obsidian_dataview.isPluginEnabled, + await_if_enabled +}; + +// src/utils/arrays.ts +var ensure_is_array = (maybe_array) => { + if (Array.isArray(maybe_array)) + return maybe_array; + return [maybe_array]; +}; +var ensure_square_array = (arr, fill, pre) => { + const max_width = Math.max(...arr.map((row) => row.length)); + return arr.map((row) => { + const diff = max_width - row.length; + if (pre) { + return Array(diff).fill(fill).concat(row); + } else { + return row.concat(Array(diff).fill(fill)); + } + }); +}; +var transpose = (arr) => { + const transposed = []; + if (!arr.length) + return transposed; + for (let i = 0; i < arr.at(0).length; i++) { + transposed.push([]); + for (let j = 0; j < arr.length; j++) { + transposed[i].push(arr[j][i]); + } + } + return transposed; +}; +var gather_by_runs = (arr, get_value) => { + const runs = []; + for (let i = 0; i < arr.length; i++) { + const last_run = runs.at(-1); + const value = get_value(arr[i]); + if (last_run && last_run.value === value) { + last_run.last = i; + } else { + runs.push({ value, first: i, last: i }); + } + } + return runs; +}; +var group_by = (list, get_value, project = (item) => item) => { + const grouped = {}; + list.forEach((item) => { + const key = get_value(item); + if (key === void 0) + return; + const group = grouped[key]; + const projected = project(item); + if (!group) + grouped[key] = [projected]; + else + group.push(projected); + }); + return grouped; +}; +var group_projection = (grouped, projector) => { + const projected = {}; + Object.entries(grouped).forEach(([key, items]) => { + projected[key] = projector(items); + }); + return projected; +}; +var remove_duplicates = (arr) => { + const set = new Set(arr); + return Array.from(set); +}; +var remove_duplicates_by = (arr, get_value) => { + const set = /* @__PURE__ */ new Set(); + const unique = []; + arr.forEach((item) => { + const value = get_value(item); + if (set.has(value)) + return; + set.add(value); + unique.push(item); + }); + return unique; +}; + +// src/utils/objects.ts +function deep_merge_objects(obj1, obj2) { + const result = { ...obj1 }; + for (const key in obj2) { + const val1 = obj1[key]; + const val2 = obj2[key]; + if (typeof val1 === "object" && typeof val2 === "object" && !Array.isArray(val1) && !Array.isArray(val2)) { + result[key] = deep_merge_objects(val1, val2); + } else if (val1 === void 0) { + result[key] = val2; + } + } + return result; +} +var deep_access = (obj, path) => { + let current = obj; + for (const key of path) { + if (current[key] === void 0) { + return void 0; + } + current = current[key]; + } + return current; +}; +var untyped_pick = (obj, keys) => Object.fromEntries( + Object.entries(obj).filter(([key]) => keys.includes(key)) +); +var remove_nullish_keys = (obj) => Object.fromEntries( + Object.entries(obj).filter( + ([_, val]) => val !== null && val !== void 0 + ) +); + +// src/utils/strings.ts +var split_and_trim = (str, delimiter = ",") => { + if (!str || str === "") + return []; + else + return str.split(delimiter).map((str2) => str2.trim()); +}; +var quote_join = (arr, quote = '"', joiner = ", ") => arr.map((str) => quote + str + quote).join(joiner); +var ensure_starts_with = (str, prefix) => str.startsWith(prefix) ? str : prefix + str; +var ensure_ends_with = (str, suffix) => str.endsWith(suffix) ? str : str + suffix; +var ensure_not_ends_with = (str, suffix) => str.endsWith(suffix) ? str.slice(0, -suffix.length) : str; +var TEMPLATE_REGEX = /{{(.*?)}}/g; +var resolve_templates = (str, templates) => { + var _a; + let resolved = str.slice(); + (_a = resolved.match(TEMPLATE_REGEX)) == null ? void 0 : _a.forEach((match2) => { + const key = match2.slice(2, -2); + const value = deep_access(templates, key.split(".")); + if (value !== void 0) { + resolved = resolved.replace(match2, String(value)); + } + }); + return resolved; +}; +var wrap_in_codeblock = (str, lang = "") => "```" + lang + "\n" + str + "\n```"; + +// src/utils/paths.ts +var ensure_ext = (path, ext = "md") => ensure_ends_with(path, "." + ext); +var drop_ext = (path) => path.replace(/\.[^.]+$/, ""); +var extname = (path) => path.split(".").pop(); +var drop_folder = (path) => path.split("/").pop(); +var dirname = (path) => path.split("/").slice(0, -1).join("/"); +var basename = (path) => drop_ext(path.split("/").pop()); +var normalise = (path) => path.replace(/\/+/g, "/").replace(/^\//, ""); +var build = (folder, basename2, ext) => ensure_ext(normalise(folder + "/" + basename2), ext); +var show = (path, show_node_options) => { + let output = path.slice(); + if (!(show_node_options == null ? void 0 : show_node_options.folder)) { + output = drop_folder(output); + } + if (!(show_node_options == null ? void 0 : show_node_options.ext)) { + output = drop_ext(output); + } + return output; +}; +var Paths = { + ensure_ext, + extname, + basename, + dirname, + drop_ext, + drop_folder, + build, + normalise, + show +}; + +// node_modules/zod/lib/index.mjs +var util; +(function(util2) { + util2.assertEqual = (val) => val; + function assertIs(_arg) { + } + util2.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util2.assertNever = assertNever; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +var ZodError = class _ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; +var errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; +var overrideErrorMap = errorMap; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} +var makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + overrideMap, + overrideMap === errorMap ? void 0 : errorMap + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue); +} +var ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s2 of results) { + if (s2.status === "aborted") + return INVALID; + if (s2.status === "dirty") + status.dirty(); + arrayValue.push(s2.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +}; +var INVALID = Object.freeze({ + status: "aborted" +}); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; +})(errorUtil || (errorUtil = {})); +var _ZodEnum_cache; +var _ZodNativeEnum_cache; +var ParseInputLazyPath = class { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +}; +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + var _a, _b; + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +var ZodType = class { + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex; +var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let regex2 = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; + if (args.precision) { + regex2 = `${regex2}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + regex2 = `${regex2}(\\.\\d+)?`; + } + return regex2; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex2 = `${regex2}(${opts.join("|")})`; + return new RegExp(`^${regex2}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +var ZodString = class _ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex2 = datetimeRegex(check); + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex2 = dateRegex; + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex2 = timeRegex(check); + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex2, validation, message) { + return this.refinement((data) => regex2.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a, _b; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex2, message) { + return this._addCheck({ + kind: "regex", + regex: regex2, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / Math.pow(10, decCount); +} +var ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); +}; +var ZodNull = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); +}; +var ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); +}; +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); +}; +var ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } +}; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); +}; +var ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; + } +} +var ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + return this._cached = { shape, keys }; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") + ; + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new _ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + }); + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +var ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; +var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} +var ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } +}; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); +}; +var ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}; +var ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element2 of elements2) { + if (element2.status === "aborted") + return INVALID; + if (element2.status === "dirty") + status.dirty(); + parsedSet.add(element2.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); +}; +var ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class _ZodEnum extends ZodType { + constructor() { + super(...arguments); + _ZodEnum_cache.set(this, void 0); + } + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { + __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); + } + if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return _ZodEnum.create(values, { + ...this._def, + ...newDef + }); + } + exclude(values, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); + } +}; +_ZodEnum_cache = /* @__PURE__ */ new WeakMap(); +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + constructor() { + super(...arguments); + _ZodNativeEnum_cache.set(this, void 0); + } + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { + __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"); + } + if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap(); +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var BRAND = Symbol("zod_brand"); +var ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}; +var ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a, b) { + return new _ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}; +var ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + if (isValid(result)) { + result.value = Object.freeze(result.value); + } + return result; + } + unwrap() { + return this._def.innerType; + } +}; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); +}; +function custom(check, params = {}, fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); +} +var late = { + object: ZodObject.lazycreate +}; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +var nanType = ZodNaN.create; +var bigIntType = ZodBigInt.create; +var booleanType = ZodBoolean.create; +var dateType = ZodDate.create; +var symbolType = ZodSymbol.create; +var undefinedType = ZodUndefined.create; +var nullType = ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +var neverType = ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +var strictObjectType = ZodObject.strictCreate; +var unionType = ZodUnion.create; +var discriminatedUnionType = ZodDiscriminatedUnion.create; +var intersectionType = ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +var mapType = ZodMap.create; +var setType = ZodSet.create; +var functionType = ZodFunction.create; +var lazyType = ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional.create; +var nullableType = ZodNullable.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: (arg) => ZodString.create({ ...arg, coerce: true }), + number: (arg) => ZodNumber.create({ ...arg, coerce: true }), + boolean: (arg) => ZodBoolean.create({ + ...arg, + coerce: true + }), + bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), + date: (arg) => ZodDate.create({ ...arg, coerce: true }) +}; +var NEVER = INVALID; +var z = /* @__PURE__ */ Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap, + getErrorMap, + makeIssue, + EMPTY_PATH, + addIssueToContext, + ParseStatus, + INVALID, + DIRTY, + OK, + isAborted, + isDirty, + isValid, + isAsync, + get util() { + return util; + }, + get objectUtil() { + return objectUtil; + }, + ZodParsedType, + getParsedType, + ZodType, + datetimeRegex, + ZodString, + ZodNumber, + ZodBigInt, + ZodBoolean, + ZodDate, + ZodSymbol, + ZodUndefined, + ZodNull, + ZodAny, + ZodUnknown, + ZodNever, + ZodVoid, + ZodArray, + ZodObject, + ZodUnion, + ZodDiscriminatedUnion, + ZodIntersection, + ZodTuple, + ZodRecord, + ZodMap, + ZodSet, + ZodFunction, + ZodLazy, + ZodLiteral, + ZodEnum, + ZodNativeEnum, + ZodPromise, + ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional, + ZodNullable, + ZodDefault, + ZodCatch, + ZodNaN, + BRAND, + ZodBranded, + ZodPipeline, + ZodReadonly, + custom, + Schema: ZodType, + ZodSchema: ZodType, + late, + get ZodFirstPartyTypeKind() { + return ZodFirstPartyTypeKind; + }, + coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + "enum": enumType, + "function": functionType, + "instanceof": instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + "null": nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean, + onumber, + optional: optionalType, + ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + "undefined": undefinedType, + union: unionType, + unknown: unknownType, + "void": voidType, + NEVER, + ZodIssueCode, + quotelessJson, + ZodError +}); + +// src/const/graph.ts +var EXPLICIT_EDGE_SOURCES = [ + "typed_link", + "tag_note", + "list_note", + "dendron_note", + "johnny_decimal_note", + "dataview_note", + "date_note", + "folder_note", + "regex_note" + // TODO: "zetel_note", // Can date_notes do this already? +]; +var SIMPLE_EDGE_SORT_FIELDS = [ + // The order they were added to the graph + // Hidden because I don't think anyone really cares about that order + // "graph", + "basename", + "path", + "field", + // Whether the edge is explicit or not + // Uses source and implied_kind as tie-breakers for explicit == true and false, respectively + "explicit" +]; +var COMPLEX_EDGE_SORT_FIELD_PREFIXES = ["neighbour-field"]; + +// src/graph/MyMultiGraph.ts +var import_graphology = __toESM(require_graphology_umd_min()); + +// src/utils/result.ts +var succ = (data) => ({ + ok: true, + data +}); +var fail = (error) => ({ + ok: false, + error +}); +var graph_build_fail = (error) => fail(error); + +// src/graph/objectify_mappers.ts +var objectify_edge_mapper = (cb) => (edge_id, attr2, source_id, target_id, source_attr, target_attr, undirected) => cb({ + id: edge_id, + attr: attr2, + source_id, + target_id, + source_attr, + target_attr, + undirected +}); +var objectify_edge = objectify_edge_mapper((e) => e); + +// src/graph/utils.ts +var is_self_loop = (edge) => edge.source_id === edge.target_id; +var stringify_node = (node_id, node_attr, options) => { + var _a, _b; + if (((_a = options == null ? void 0 : options.show_node_options) == null ? void 0 : _a.alias) && ((_b = node_attr.aliases) == null ? void 0 : _b.length)) { + return node_attr.aliases.at(0); + } else if (options == null ? void 0 : options.trim_basename_delimiter) { + return Paths.drop_ext(node_id).split("/").pop().split(options.trim_basename_delimiter).last(); + } else { + return Paths.show(node_id, options == null ? void 0 : options.show_node_options); + } +}; +var sorters = { + path: (order) => (a, b) => a.target_id.localeCompare(b.target_id) * order, + basename: (order) => (a, b) => { + const [a_field, b_field] = [ + Paths.drop_folder(a.target_id), + Paths.drop_folder(b.target_id) + ]; + return a_field.localeCompare(b_field) * order; + }, + field: (order) => (a, b) => { + var _a, _b; + const [a_field, b_field] = [ + (_a = a.attr.field) != null ? _a : "null", + (_b = b.attr.field) != null ? _b : "null" + ]; + return a_field.localeCompare(b_field) * order; + } +}; +var get_edge_sorter = (sort, graph) => { + switch (sort.field) { + case "path": { + return sorters.path(sort.order); + } + case "basename": { + return sorters.basename(sort.order); + } + case "field": { + return sorters.field(sort.order); + } + case "explicit": { + return (a, b) => { + if (a.attr.explicit === true && b.attr.explicit === true) { + return a.attr.source.localeCompare(b.attr.source) * sort.order; + } else if (a.attr.explicit === false && b.attr.explicit === false) { + return a.attr.implied_kind.localeCompare(b.attr.implied_kind) * sort.order; + } else { + return a.attr.explicit ? sort.order : -sort.order; + } + }; + } + default: { + if (!COMPLEX_EDGE_SORT_FIELD_PREFIXES.some( + (f) => sort.field.startsWith(f + ":") + )) { + throw new Error(`Invalid sort field: ${sort.field}`); + } + switch (sort.field.split(":")[0]) { + case "neighbour": + case "neighbour-field": { + const field = sort.field.split(":", 2).at(1); + const cache = {}; + return (a, b) => { + var _a, _b, _c, _d; + const [a_neighbour, b_neighbour] = [ + (_b = cache[_a = a.target_id]) != null ? _b : cache[_a] = graph.get_out_edges(a.target_id).filter((e) => has_edge_attrs(e, { field })).at(0), + (_d = cache[_c = b.target_id]) != null ? _d : cache[_c] = graph.get_out_edges(b.target_id).filter((e) => has_edge_attrs(e, { field })).at(0) + ]; + if (!a_neighbour || !b_neighbour) { + return a_neighbour ? -sort.order : b_neighbour ? sort.order : 0; + } else { + return sorters.path(sort.order)( + a_neighbour, + b_neighbour + ); + } + }; + } + default: { + return (_a, _b) => sort.order; + } + } + } + } +}; +var has_edge_attrs = (edge, attrs) => { + var _a; + return attrs === void 0 || [ + attrs.field === void 0 || edge.attr.field === attrs.field, + attrs.explicit === void 0 || edge.attr.explicit === attrs.explicit, + attrs.$or_fields === void 0 || attrs.$or_fields.includes((_a = edge.attr.field) != null ? _a : "null"), + attrs.$or_target_ids === void 0 || attrs.$or_target_ids.includes(edge.target_id) + ].every(Boolean); +}; + +// src/graph/MyMultiGraph.ts +var EDGE_ATTRIBUTES = [ + "field", + "explicit", + "source", + "implied_kind", + "round" +]; +var BCGraph = class extends import_graphology.MultiGraph { + constructor(input) { + var _a, _b; + super(); + /** Uniquely identify an edge based on its: + * - source_id + * - target_id + * - field + */ + this.make_edge_id = (source_id, target_id, attr2) => `${source_id}|${attr2.field}|${target_id}`; + // NOTE: These fields shouldn't actually dedupe an edge... I think what the user would consider an edge to be the same + // even if it was added for different reasons, but still to and from the same nodes, using the same field. + // Consider the commands/freeze-crumbs/index.md note as an example. If these fields were included, the implied relations would still show + // even tho there are now frozen real relations serving the exact same purpose. + // |${attr.explicit ? "explicit|" + attr.source : "implied|" + attr.implied_kind} + /** Return true if the edge was added. + * Won't be added if it already exists (based on it's {@link this.make_edge_id}), + * or if it's target_node has ingore_in_edges */ + this.safe_add_directed_edge = (source_id, target_id, attr2) => { + if (this.getNodeAttribute(target_id, "ignore_in_edges")) { + log.debug( + `ignore-in-edge > ${source_id} -${attr2.field}-> ${target_id}` + ); + return false; + } else if (this.getNodeAttribute(source_id, "ignore_out_edges")) { + log.debug( + `ignore-out-edge > ${source_id} -${attr2.field}-> ${target_id}` + ); + return false; + } + const edge_id = this.make_edge_id(source_id, target_id, attr2); + if (!this.hasDirectedEdge(edge_id)) { + this.addDirectedEdgeWithKey(edge_id, source_id, target_id, attr2); + return true; + } else { + return false; + } + }; + /** safely returns [] if node_id and !hasNode(node_id) */ + this.get_in_edges = (node_id) => node_id ? this.hasNode(node_id) ? this.mapInEdges(node_id, objectify_edge) : [] : this.mapInEdges(objectify_edge); + /** safely returns [] if node_id and !hasNode(node_id) */ + this.get_out_edges = (node_id) => node_id ? this.hasNode(node_id) ? this.mapOutEdges(node_id, objectify_edge) : [] : this.mapOutEdges(objectify_edge); + if (input) { + (_a = input.nodes) == null ? void 0 : _a.forEach( + ({ id, attr: attr2 }) => this.safe_add_node(id, attr2) + ); + (_b = input.edges) == null ? void 0 : _b.forEach((edge) => { + this.safe_add_node(edge.source_id, { resolved: true }); + this.safe_add_node(edge.target_id, { resolved: true }); + this.safe_add_directed_edge( + edge.source_id, + edge.target_id, + edge.attr + ); + }); + } + } + safe_add_node(id, attr2) { + try { + this.addNode(id, attr2); + return true; + } catch (error) { + return false; + } + } + /** Upsert a node by it's id (path). If it exists, patch attr, else addNode */ + upsert_node(id, attr2) { + if (this.hasNode(id)) { + Object.keys(attr2).forEach((key) => { + this.setNodeAttribute( + id, + key, + attr2[key] + ); + }); + } else { + this.addNode(id, attr2); + } + } + safe_rename_node(old_id, new_id) { + const exists = { + old: this.hasNode(old_id), + new: this.hasNode(new_id) + }; + if (!exists.old) { + return fail({ exists, message: "old_id doesn't exist" }); + } else if (exists.new) { + return fail({ exists, message: "new_id already exists" }); + } else { + this.addNode(new_id, this.getNodeAttributes(old_id)); + const old_edges = { + in: this.get_in_edges(old_id), + out: this.get_out_edges(old_id) + }; + this.dropNode(old_id); + old_edges.in.forEach((old_in_edge) => { + is_self_loop(old_in_edge) ? this.safe_add_directed_edge( + new_id, + new_id, + old_in_edge.attr + ) : this.safe_add_directed_edge( + old_in_edge.source_id, + new_id, + old_in_edge.attr + ); + }); + old_edges.out.forEach((old_out_edge) => { + !is_self_loop(old_out_edge) && this.safe_add_directed_edge( + new_id, + old_out_edge.target_id, + old_out_edge.attr + ); + }); + } + return succ({ exists }); + } +}; + +// src/utils/edge_fields.ts +var resolve_field_group_labels = (edge_field_groups, field_group_labels) => remove_duplicates( + edge_field_groups.filter((group) => field_group_labels.includes(group.label)).flatMap((group) => group.fields) +); + +// src/utils/url.ts +var url_search_params = (obj, options) => { + const { delimiter } = Object.assign({ delimiter: " " }, options); + let params = ""; + for (const key in obj) { + params += `${key}=${obj[key]}${delimiter}`; + } + params = params.slice(0, -1); + if ((options == null ? void 0 : options.trim_lone_param) && Object.keys(obj).length === 1) { + params = params.split("=", 2)[1]; + } + return params; +}; + +// src/utils/mermaid.ts +var MERMAID_DIRECTIONS = ["LR", "RL", "TB", "BT"]; +var MERMAID_RENDERER = ["dagre", "elk"]; +var MERMAID_CURVE_STYLES = [ + "basis", + "bumpX", + "bumpY", + "cardinal", + "catmullRom", + "linear", + "monotoneX", + "monotoneY", + "natural", + "step", + "stepAfter", + "stepBefore" +]; +var build_arrow = (e) => e.attr.explicit ? "-->" : "-.->"; +var build_attrs = (attr2, show_attributes) => { + const params = (show_attributes == null ? void 0 : show_attributes.length) ? url_search_params(untyped_pick(attr2, show_attributes), { + trim_lone_param: true + }) : null; + return (params == null ? void 0 : params.length) ? `|"${params}"|` : ""; +}; +var from_edges = (edges, config) => { + var _a, _b, _c, _d, _e; + const resolved = Object.assign( + { direction: "LR", kind: "flowchart" }, + remove_nullish_keys( + config != null ? config : {} + ) + ); + const flowchart_init = remove_nullish_keys({ + curve: resolved.curve_style, + defaultRenderer: resolved.renderer + }); + const lines = [ + // NOTE: Regardless of kind, the below field should always be flowchart + `%%{ init: { "flowchart": ${JSON.stringify(flowchart_init)} } }%%`, + `${resolved.kind} ${resolved.direction}` + ]; + const node_map = remove_duplicates_by( + // NOTE: This is _pretty_ inefficient, but necessary. + // If we just take all unique target_ids, we miss source nodes that don't have any incoming edges. + edges.flatMap((e) => [ + { path: e.source_id, attr: e.source_attr }, + { path: e.target_id, attr: e.target_attr } + ]), + (n2) => n2.path + ).reduce( + (map, node, i) => { + var _a2, _b2; + return map.set(node.path, { + i, + attr: node.attr, + label: (_b2 = (_a2 = resolved.get_node_label) == null ? void 0 : _a2.call(resolved, node.path, node.attr)) != null ? _b2 : node.path + }); + }, + /* @__PURE__ */ new Map() + ); + node_map.forEach((node) => { + lines.push(` ${node.i}("${node.label}")`); + }); + lines.push(""); + const mermaid_edges = []; + for (const edge of edges) { + const [source_i, target_i] = [ + node_map.get(edge.source_id).i, + node_map.get(edge.target_id).i + ]; + const opposing_edge_i = resolved.collapse_opposing_edges !== false ? mermaid_edges.findIndex( + (existing) => ( + // NOTE: This is pretty intense, all opposing edges will collapse, because now there's no direction semantics + target_i === existing.source_i && source_i === existing.target_i + ) + ) : -1; + if (opposing_edge_i === -1) { + mermaid_edges.push({ + source_i, + target_i, + arrow: build_arrow(edge), + attr: edge.attr, + collapsed_attr: Object.fromEntries( + (_b = (_a = resolved.show_attributes) == null ? void 0 : _a.map((attr2) => { + var _a2; + return [ + attr2, + /* @__PURE__ */ new Set([ + // @ts-ignore: If the property is not in the object, it will be undefined + (_a2 = edge.attr[attr2]) != null ? _a2 : "_" + ]) + ]; + })) != null ? _b : [] + ) + }); + } else { + const existing = mermaid_edges[opposing_edge_i]; + existing.arrow = edge.attr.explicit || existing.attr.explicit ? "---" : "-.-"; + (_c = resolved.show_attributes) == null ? void 0 : _c.forEach((attr2) => { + var _a2; + existing.collapsed_attr[attr2].add( + // @ts-ignore: If the property is not in the object, it will be undefined + (_a2 = edge.attr[attr2]) != null ? _a2 : "_" + ); + }); + } + } + mermaid_edges.forEach(({ arrow, collapsed_attr, source_i, target_i }) => { + const attrs = build_attrs( + Object.fromEntries( + Object.entries(collapsed_attr).map(([key, set]) => [ + key, + [...set.values()].join("|") + ]) + ), + resolved.show_attributes + ); + lines.push(` ${source_i} ${arrow}${attrs} ${target_i}`); + }); + lines.push(""); + const active_note_i = resolved.active_node_id ? (_d = node_map.get(resolved.active_node_id)) == null ? void 0 : _d.i : void 0; + if (active_note_i !== void 0) { + lines.push(` class ${active_note_i} BC-active-node`); + } + switch ((_e = resolved.click) == null ? void 0 : _e.method) { + case "class": { + const nodes = [...node_map.values()]; + if (nodes.length) { + lines.push( + ` class ${nodes.filter((n2) => n2.i !== active_note_i).map((n2) => n2.i)} internal-link` + ); + } + const unresolved_nodes = nodes.filter((n2) => !n2.attr.resolved); + if (unresolved_nodes.length) { + lines.push( + ` class ${unresolved_nodes.map((n2) => n2.i)} is-unresolved` + ); + } + break; + } + case "href": { + node_map.forEach((node, path) => { + var _a2; + lines.push( + ` click ${node.i} "${(_a2 = resolved.click) == null ? void 0 : _a2.getter(path, node.attr)}"` + ); + }); + break; + } + case "callback": { + node_map.forEach((node) => { + var _a2; + lines.push( + ` click ${node.i} call ${(_a2 = resolved.click) == null ? void 0 : _a2.callback_name}()` + ); + }); + break; + } + } + return lines.join("\n"); +}; +var _encode = (code) => { + const bytes = new TextEncoder().encode(code); + return btoa(String.fromCharCode(...bytes)); +}; +var to_image_link = (code) => `https://mermaid.ink/img/${_encode(code)}`; +var to_live_edit_link = (code) => { + const state = { + code, + // NOTE: For some reason, having both true doesn't trigger the initial render? + autoSync: false, + updateDiagram: true, + mermaid: { theme: "default" } + }; + const encoded = _encode(JSON.stringify(state, void 0, 2)); + return `https://mermaid.live/edit#base64:${encoded}`; +}; +var Mermaid = { + from_edges, + to_image_link, + to_live_edit_link, + RENDERERS: MERMAID_RENDERER, + DIRECTIONS: MERMAID_DIRECTIONS, + CURVE_STYLES: MERMAID_CURVE_STYLES +}; + +// src/utils/zod.ts +var not_string_msg = (field, received) => `Expected a string (text), but got: \`${received}\` (${typeof received}). _Try wrapping the value in quotes._ +**Example**: \`${field}: "${received}"\``; +var invalid_enum_msg = (field, options, received) => `Expected one of the following options: ${quote_join(options, "`", ", or ")}, but got: \`${received}\`. +**Example**: \`${field}: ${options[0]}\``; +var not_array_msg = (field, options, received) => `This field is now expected to be a YAML list (array), but got: \`${received}\` (${typeof received}). _Try wrapping it in square brackets._ +**Example**: \`${field}: [${options.slice(0, 2).join(", ")}]\`, or possibly: \`${field}: [${received}]\``; +var dynamic_enum_schema = (options, field) => z.string().superRefine((received, ctx) => { + if (options.includes(received)) { + return true; + } else { + ctx.addIssue({ + options, + received, + code: "invalid_enum_value", + // NOTE: Leave the default path on _this_ object, but pass the override into the error message + message: invalid_enum_msg( + field != null ? field : ctx.path.join("."), + options, + received + ) + }); + return false; + } +}); +var dynamic_enum_array_schema = (field, options, received) => z.array(dynamic_enum_schema(options), { + invalid_type_error: not_array_msg(field, options, received) +}); +var zod = { + error: { + not_string: not_string_msg, + invalid_enum: invalid_enum_msg, + not_array: not_array_msg + }, + schema: { + dynamic_enum: dynamic_enum_schema, + dynamic_enum_array: dynamic_enum_array_schema + } +}; + +// src/codeblocks/schema.ts +var FIELDS = [ + "type", + "title", + "start-note", + "fields", + "field-groups", + "depth", + "flat", + "collapse", + "merge-fields", + "dataview-from", + "content", + "sort", + "field-prefix", + "show-attributes", + "mermaid-direction", + "mermaid-renderer", + "mermaid-curve" +]; +var BOOLEANS = [true, false]; +var build2 = (input, data) => { + var _a, _b, _c, _d, _e, _f, _g, _h; + const field_labels = data.edge_fields.map((f) => f.label); + const group_labels = data.field_groups.map((f) => f.label); + return z.object({ + title: z.string({ + message: zod.error.not_string("title", input["title"]) + }).optional(), + "start-note": z.string({ + message: zod.error.not_string( + "start-note", + input["start-note"] + ) + }).optional(), + "dataview-from": z.string({ + message: zod.error.not_string( + "dataview-from", + input["dataview-from"] + ) + }).optional(), + flat: z.boolean({ + message: zod.error.invalid_enum( + "flat", + BOOLEANS, + input["flat"] + ) + }).default(false), + collapse: z.boolean({ + message: zod.error.invalid_enum( + "collapse", + BOOLEANS, + input["collapse"] + ) + }).default(false), + "merge-fields": z.boolean({ + message: zod.error.invalid_enum( + "merge-fields", + BOOLEANS, + input["merge-fields"] + ) + }).default(true), + content: z.enum(["open", "closed"], { + message: zod.error.invalid_enum( + "content", + ["open", "closed"], + input["content"] + ) + }).optional(), + type: z.enum(["tree", "mermaid", "markmap"], { + message: zod.error.invalid_enum( + "type", + ["tree", "mermaid", "markmap"], + input["type"] + ) + }).default("tree"), + "mermaid-renderer": z.enum(Mermaid.RENDERERS, { + message: zod.error.invalid_enum( + "mermaid-renderer", + Mermaid.RENDERERS, + input["mermaid-renderer"] + ) + }).optional(), + "mermaid-direction": z.enum(Mermaid.DIRECTIONS, { + message: zod.error.invalid_enum( + "mermaid-direction", + Mermaid.DIRECTIONS, + input["mermaid-direction"] + ) + }).optional(), + "mermaid-curve": z.enum(Mermaid.CURVE_STYLES, { + message: zod.error.invalid_enum( + "mermaid-curve", + Mermaid.CURVE_STYLES, + input["mermaid-curve"] + ) + }).optional(), + "show-attributes": z.array(z.enum(EDGE_ATTRIBUTES), { + message: zod.error.not_array( + "show-attributes", + EDGE_ATTRIBUTES, + input["show-attributes"] + ) + }).optional(), + fields: zod.schema.dynamic_enum_array("fields", field_labels, input["fields"]).optional(), + "field-groups": zod.schema.dynamic_enum_array( + "field-groups", + group_labels, + input["field-groups"] + ).optional(), + depth: z.array( + z.number({ + invalid_type_error: `Expected a number, but got: \`${input["depth"]}\` (${typeof input["depth"]}). _Try using a number (integer)._ +**Example**: \`depth: [0]\`, or \`depth: [0, 3]\`` + }).min( + 0, + `Minimum depth cannot be less than \`0\`, but got: \`${input["depth"]}\` _Try using a non-negative number (greater than or equal to zero \`0\`)._ +**Example**: \`depth: [0]\`, or possibly: \`depth: [${typeof input["depth"] === "number" ? -1 * input["depth"] : input["depth"]}\`]` + ), + { + invalid_type_error: `Expected a YAML list (array) of one or two numbers, but got: \`${input["depth"]}\` (${typeof input["depth"]}). _Try wrapping it in square brackets._ +**Example**: \`depth: [0]\`, or \`depth: [0, 3]\`, or possibly: \`depth: [${input["depth"]}]\`` + } + ).min( + 1, + `At least one item is required, but got: \`[${input["depth"]}]\`. _Try adding a number to the list._ +**Example**: \`depth: [0]\`, or \`depth: [0, 3]\`` + ).max( + 2, + // NOTE: I _could_ do something like: + // or possibly \`depth: [${(input["depth"])?.slice(0, 2).join(", ")}]\` + // But even that mess isn't safe. What if it's a string or something without join? + `Maximum of two items allowed, but got: \`[${input["depth"]}]\`. _Try removing one of the numbers._ +**Example**: \`depth: [${(_b = (_a = input["depth"]) == null ? void 0 : _a[0]) != null ? _b : 0}]\`, or possibly \`depth: [${(_d = (_c = input["depth"]) == null ? void 0 : _c[0]) != null ? _d : 0}, 3]\`` + ).transform((v) => { + if (v.length === 1) + return [v[0], Infinity]; + else + return v; + }).refine((v) => v[0] <= v[1], { + message: `Minimum depth cannot be greater than maximum depth. _Try swapping the numbers._ +**Example**: \`depth: [0, 3]\`, or possibly: \`depth: [${(_f = (_e = input["depth"]) == null ? void 0 : _e[1]) != null ? _f : 0}, ${(_h = (_g = input["depth"]) == null ? void 0 : _g[0]) != null ? _h : 3}]\`` + }).default([0, Infinity]), + sort: z.preprocess( + (v) => { + if (typeof v === "string") { + const [field, order] = v.split(" "); + return { field, order: order != null ? order : "asc" }; + } else { + return v; + } + }, + z.object({ + // TODO: Use a custom zod schema to retain string template literals here + // https://github.com/colinhacks/zod?tab=readme-ov-file#custom-schemas + field: zod.schema.dynamic_enum( + [ + ...SIMPLE_EDGE_SORT_FIELDS, + ...data.edge_fields.map( + (f) => `neighbour-field:${f.label}` + ) + ], + "sort" + ), + order: z.union( + [ + z.enum(["asc", "desc"]), + // Something very weird happening... + // If a note has two codeblocks, the one that gets rendered first seems to override config in the other? + // So when the `sort` field of the second comes in for parsing, + // It's already been transformed, and so sort.order is a number, not a string... + z.literal(1), + z.literal(-1) + ], + { + // SOURCE: https://github.com/colinhacks/zod/issues/117#issuecomment-1595801389 + errorMap: (_err, ctx) => ({ + message: zod.error.invalid_enum( + "sort.order", + ["asc", "desc"], + ctx.data + ) + }) + } + ).transform( + (v) => v === "asc" ? 1 : v === "desc" ? -1 : v + ) + }) + ).default({ + order: 1, + field: "basename" + }) + }).passthrough().default({}).transform((options) => { + if (options["field-groups"]) { + const field_labels2 = resolve_field_group_labels( + data.field_groups, + options["field-groups"] + ); + if (options.fields) { + options.fields = remove_duplicates( + options.fields.concat(field_labels2) + ); + } else { + options.fields = field_labels2; + } + } + return options; + }).superRefine((options, ctx) => { + if (options["mermaid-curve"] && options["mermaid-renderer"]) { + ctx.addIssue({ + code: "custom", + path: ["mermaid-curve"], + message: `Cannot specify both a mermaid curve and a renderer. _Try removing one of the fields._ +**Example**: \`mermaid-curve: ${options["mermaid-curve"]}\`, or \`mermaid-renderer: ${options["mermaid-renderer"]}\`` + }); + return false; + } + return true; + }); +}; +var CodeblockSchema = { + FIELDS, + build: build2 +}; + +// src/codeblocks/index.ts +var parse_source = (source, data) => { + var _a; + const errors = []; + let yaml; + try { + yaml = (_a = (0, import_obsidian.parseYaml)(source)) != null ? _a : {}; + log.debug("Codeblock > parsed_yaml >", yaml); + } catch (error) { + log.error("Codeblock > parse_source > ", error); + errors.push({ + path: "yaml", + code: "invalid_yaml", + message: "Invalid codeblock YAML. Check the console for more information (press `Ctrl + Shift + I` to open the console)." + }); + return { parsed: null, errors }; + } + const parsed = CodeblockSchema.build(yaml, data).safeParse(yaml); + if (!parsed.success) { + errors.push( + ...remove_duplicates_by( + parsed.error.issues, + (issue) => issue.path.join(".") + ).map((issue) => ({ + message: issue.message, + code: "invalid_field_value", + path: issue.path.map((key) => typeof key === "number" ? key + 1 : key).join(" > ") + })) + ); + return { + errors, + parsed: null + }; + } + const invalid_fields = Object.keys(parsed.data).filter( + (key) => !CodeblockSchema.FIELDS.includes(key) + ); + if (invalid_fields.length) { + errors.push({ + path: "yaml", + code: "invalid_yaml", + message: `The following is not a valid codeblock field: \`${invalid_fields[0]}\`. Valid options are: ${quote_join(CodeblockSchema.FIELDS, "`", ", or ")}` + }); + } + return { parsed: parsed.data, errors }; +}; +var postprocess_options = (source_path, parsed, errors, plugin) => { + var _a; + let file_path = source_path; + if (parsed["start-note"]) { + const normalised = Paths.normalise( + Paths.ensure_ext(parsed["start-note"], "md") + ); + const start_file = plugin.app.metadataCache.getFirstLinkpathDest( + normalised, + file_path + ); + if (start_file) { + file_path = start_file.path; + } else { + errors.push({ + path: "start-note", + code: "invalid_field_value", + message: `Could not find note \`${normalised}\` in your vault. Try a different path.` + }); + } + } + if (parsed["dataview-from"]) { + try { + const pages = (_a = dataview_plugin.get_api(plugin.app)) == null ? void 0 : _a.pages(parsed["dataview-from"]); + parsed["dataview-from-paths"] = pages == null ? void 0 : pages.map( + (page) => page.file.path + ); + } catch (error) { + errors.push({ + path: "dataview-from", + code: "invalid_field_value", + message: `Input \`${parsed["dataview-from"]}\` is not a valid Dataview query. +You can use \`app.plugins.plugins.dataview.api.pages("")\` to test your query in the console (press \`Ctrl + Shift + I\` to open the console).` + }); + } + } + return { options: parsed, file_path }; +}; +var active_codeblocks = /* @__PURE__ */ new Map(); +var register = (codeBlock) => { + active_codeblocks.set(codeBlock.id, codeBlock); +}; +var unregister = (codeBlock) => { + active_codeblocks.delete(codeBlock.id); +}; +var update_all = () => { + for (const codeBlock of active_codeblocks.values()) { + void codeBlock.update(); + } +}; +var Codeblocks = { + parse_source, + postprocess_options, + register, + unregister, + update_all +}; + +// src/graph/traverse.ts +var breadth_first = (graph, start_node, callback, edge_filter) => { + const visited_edge_ids = /* @__PURE__ */ new Set(); + const stack = graph.get_out_edges(start_node).map((edge) => ({ edge, depth: 0 })).filter((item) => !edge_filter || edge_filter(item)); + while (stack.length > 0) { + const item = stack.shift(); + if (visited_edge_ids.has(item.edge.id)) + continue; + else + visited_edge_ids.add(item.edge.id); + callback(item); + graph.get_out_edges(item.edge.target_id).map((out_edge) => ({ edge: out_edge, depth: item.depth + 1 })).filter((out_item) => !edge_filter || edge_filter(out_item)).forEach((item2) => stack.push(item2)); + } +}; +var gather_items = (graph, start_node, edge_filter) => { + const items = []; + breadth_first(graph, start_node, (item) => items.push(item), edge_filter); + return items; +}; +var MAX_DEPTH = 100; +var build_tree = (graph, source_id, { depth, max_depth }, edge_filter, visited_edge_ids = /* @__PURE__ */ new Set()) => { + depth != null ? depth : depth = 0; + max_depth != null ? max_depth : max_depth = MAX_DEPTH; + const tree = []; + if (depth <= max_depth) { + for (const edge of graph.get_out_edges(source_id).filter((edge2) => !edge_filter || edge_filter(edge2, depth))) { + if (visited_edge_ids.has(edge.id)) + continue; + else + visited_edge_ids.add(edge.id); + const children2 = build_tree( + graph, + edge.target_id, + { depth: depth + 1, max_depth }, + edge_filter, + visited_edge_ids + ); + tree.push({ edge, depth, children: children2 }); + } + } + return tree; +}; +var flatten_tree = (tree) => { + const traversal_items = []; + tree.forEach(({ edge, depth, children: children2 }) => { + traversal_items.push({ edge, depth }); + traversal_items.push(...flatten_tree(children2)); + }); + return traversal_items; +}; +var tree_to_all_paths = (tree) => { + const paths = []; + tree.forEach(({ edge, children: children2 }) => { + if (children2.length === 0) { + paths.push([edge]); + } else { + const child_paths = tree_to_all_paths(children2); + child_paths.forEach((path) => paths.push([edge, ...path])); + } + }); + return paths; +}; +var sort_edge_tree = (tree, sorter) => { + tree.forEach((nested_path) => { + nested_path.children = sort_edge_tree(nested_path.children, sorter); + }); + return tree.sort((a, b) => sorter(a.edge, b.edge)); +}; +var get_transitive_chain_target_ids = (graph, start_node, chain, edge_filter) => { + const target_ids = []; + Traverse.breadth_first( + graph, + start_node, + (item) => { + if (item.depth === chain.length - 1) { + target_ids.push(item.edge.target_id); + } + }, + (item) => ( + // Ensures we don't go over the chain length ("max_depth") + chain[item.depth] && // Check if the edge has the attrs we're looking for + has_edge_attrs(item.edge, chain[item.depth]) && (!edge_filter || edge_filter(item)) + ) + ); + return target_ids; +}; +var Traverse = { + breadth_first, + gather_items, + build_tree, + flatten_tree, + tree_to_all_paths, + sort_edge_tree, + get_transitive_chain_target_ids +}; + +// src/utils/links.ts +var resolve_to_absolute_path = (app, relative_path, source_path) => { + const folder = app.fileManager.getNewFileParent(source_path, relative_path); + return Paths.build(folder.path, Paths.basename(relative_path), "md"); +}; +var ify = (path, display, options) => { + switch (options.link_kind) { + case "none": { + return display; + } + case "wiki": { + const no_ext = Paths.drop_ext(path); + return display === path ? `[[${no_ext}]]` : `[[${no_ext}|${display}]]`; + } + case "markdown": { + return display === path ? `[${path}](${path})` : `[${display}](${path})`; + } + } +}; +var Links = { + ify, + resolve_to_absolute_path +}; + +// src/commands/list_index/index.ts +var ListIndex; +((ListIndex2) => { + ListIndex2.DEFAULT_OPTIONS = { + fields: [], + indent: "\\t", + link_kind: "wiki", + show_attributes: [], + field_group_labels: [], + edge_sort_id: { + order: 1, + field: "basename" + }, + show_node_options: { + ext: false, + alias: true, + folder: false + } + }; + ListIndex2.edge_tree_to_list_index = (tree, options) => { + let index = ""; + const real_indent = options.indent.replace(/\\t/g, " "); + tree.forEach(({ children: children2, depth, edge }) => { + const display = stringify_node(edge.target_id, edge.target_attr, { + show_node_options: options.show_node_options + }); + const link = Links.ify(edge.target_id, display, { + link_kind: options.link_kind + }); + const attr2 = options.show_attributes.length ? ` (${url_search_params( + untyped_pick(edge.attr, options.show_attributes), + { trim_lone_param: true } + )})` : ""; + index += real_indent.repeat(depth) + `- ${link}${attr2} +`; + index += (0, ListIndex2.edge_tree_to_list_index)(children2, options); + }); + return index; + }; + ListIndex2.build = (graph, start_node, options) => (0, ListIndex2.edge_tree_to_list_index)( + Traverse.sort_edge_tree( + Traverse.build_tree( + graph, + start_node, + options, + (e) => has_edge_attrs(e, { $or_fields: options.fields }) + ), + get_edge_sorter(options.edge_sort_id, graph) + ), + options + ); +})(ListIndex || (ListIndex = {})); + +// src/const/settings.ts +var DEFAULT_EDGE_SORT_ID = { field: "basename", order: 1 }; +var DEFAULT_SHOW_NODE_OPTIONS = { + ext: false, + folder: false, + alias: false +}; +var DEFAULT_SETTINGS = { + is_dirty: false, + edge_fields: [ + { label: "up" }, + { label: "down" }, + { label: "same" }, + { label: "next" }, + { label: "prev" } + ], + edge_field_groups: [ + { + label: "ups", + fields: ["up"] + }, + { + label: "downs", + fields: ["down"] + }, + { + label: "sames", + fields: ["same"] + }, + { + label: "nexts", + fields: ["next"] + }, + { + label: "prevs", + fields: ["prev"] + } + ], + implied_relations: { + transitive: [ + { + name: "", + rounds: 1, + chain: [{ field: "up" }], + close_field: "down", + close_reversed: true + }, + { + name: "", + rounds: 1, + chain: [{ field: "down" }], + close_field: "up", + close_reversed: true + }, + { + name: "", + rounds: 1, + chain: [{ field: "same" }], + close_field: "same", + close_reversed: true + }, + { + name: "", + rounds: 1, + chain: [{ field: "next" }], + close_field: "prev", + close_reversed: true + }, + { + name: "", + rounds: 1, + chain: [{ field: "prev" }], + close_field: "next", + close_reversed: true + } + ] + }, + explicit_edge_sources: { + typed_link: {}, + list_note: { + // Disabled by default + default_neighbour_field: "" + }, + tag_note: { + default_field: "up" + }, + regex_note: { + default_field: "up" + }, + dendron_note: { + enabled: false, + delimiter: ".", + default_field: "up", + display_trimmed: false + }, + johnny_decimal_note: { + enabled: false, + delimiter: ".", + default_field: "up" + }, + date_note: { + enabled: false, + date_format: "yyyy-MM-dd", + default_field: "next", + stretch_to_existing: false + } + }, + views: { + page: { + all: { + sticky: false, + readable_line_width: true + }, + trail: { + enabled: true, + format: "grid", + selection: "all", + default_depth: 999, + no_path_message: "", + show_controls: true, + merge_fields: false, + field_group_labels: ["ups"], + show_node_options: { ...DEFAULT_SHOW_NODE_OPTIONS } + }, + prev_next: { + enabled: true, + show_node_options: { ...DEFAULT_SHOW_NODE_OPTIONS }, + field_group_labels: { + prev: ["prevs"], + next: ["nexts"] + } + } + }, + side: { + matrix: { + collapse: false, + edge_sort_id: { ...DEFAULT_EDGE_SORT_ID }, + show_node_options: { ...DEFAULT_SHOW_NODE_OPTIONS }, + show_attributes: ["source", "implied_kind", "round"], + field_group_labels: ["ups", "downs", "sames", "nexts", "prevs"] + }, + tree: { + collapse: false, + show_attributes: [], + merge_fields: false, + field_group_labels: ["downs"], + edge_sort_id: { ...DEFAULT_EDGE_SORT_ID }, + show_node_options: { ...DEFAULT_SHOW_NODE_OPTIONS } + } + }, + codeblocks: { + show_node_options: { ...DEFAULT_SHOW_NODE_OPTIONS } + } + }, + commands: { + rebuild_graph: { + notify: true, + trigger: { + note_save: false, + layout_change: false + } + }, + list_index: { + default_options: ListIndex.DEFAULT_OPTIONS + }, + freeze_implied_edges: { + default_options: { + destination: "frontmatter" + } + }, + thread: { + default_options: { + destination: "frontmatter", + target_path_template: "{{source.folder}}/{{attr.field}} {{source.basename}}" + } + } + }, + suggestors: { + edge_field: { + enabled: false, + trigger: "." + } + }, + debug: { + level: "INFO" + } +}; + +// src/const/views.ts +var VIEW_IDS = { + matrix: "bc-matrix-view", + tree: "bc-tree-view" +}; + +// src/const/metadata_fields.ts +var METADATA_FIELDS_MAP = { + "BC-tag-note-tag": { + property_type: "text" + }, + "BC-tag-note-field": { + property_type: "text" + }, + "BC-tag-note-exact": { + property_type: "checkbox" + }, + // + "BC-regex-note-regex": { + property_type: "text" + }, + "BC-regex-note-flags": { + property_type: "text" + }, + "BC-regex-note-field": { + property_type: "text" + }, + // + "BC-folder-note-field": { + property_type: "text" + }, + "BC-folder-note-recurse": { + property_type: "checkbox" + }, + // + "BC-list-note-field": { + property_type: "text" + }, + "BC-list-note-neighbour-field": { + property_type: "text" + }, + "BC-list-note-exclude-index": { + property_type: "checkbox" + }, + // + "BC-dendron-note-field": { + property_type: "text" + }, + // + "BC-johnny-decimal-note-field": { + property_type: "text" + }, + // + "BC-dataview-note-query": { + property_type: "text" + }, + "BC-dataview-note-field": { + property_type: "text" + }, + // + "BC-ignore-in-edges": { + property_type: "checkbox" + }, + "BC-ignore-out-edges": { + property_type: "checkbox" + } +}; +var META_ALIAS = { + "tag-note-tag": "BC-tag-note-tag", + "tag-note-field": "BC-tag-note-field", + "tag-note-exact": "BC-tag-note-exact", + // + "regex-note-regex": "BC-regex-note-regex", + "regex-note-flags": "BC-regex-note-flags", + "regex-note-field": "BC-regex-note-field", + // + "folder-note-field": "BC-folder-note-field", + "folder-note-recurse": "BC-folder-note-recurse", + // + "list-note-field": "BC-list-note-field", + "list-note-neighbour-field": "BC-list-note-neighbour-field", + "list-note-exclude-index": "BC-list-note-exclude-index", + // + "dendron-note-field": "BC-dendron-note-field", + // + "johnny-decimal-note-field": "BC-johnny-decimal-note-field", + // + "dataview-note-query": "BC-dataview-note-query", + "dataview-note-field": "BC-dataview-note-field", + // + "ignore-in-edges": "BC-ignore-in-edges", + "ignore-out-edges": "BC-ignore-out-edges" +}; + +// src/utils/timer.ts +var Timer = class { + constructor() { + this.start = performance.now(); + } + elapsed() { + return performance.now() - this.start; + } + elapsed_str(digits = 0) { + return this.elapsed().toFixed(digits); + } + reset() { + this.start = performance.now(); + } + elapsedMessage(action, reset = false) { + const msg = `${action} took ${this.elapsed_str(2)}ms`; + if (reset) + this.reset(); + return msg; + } +}; + +// src/graph/builders/explicit/dataview_note.ts +var import_obsidian2 = require("obsidian"); +var get_dataview_note_info = (plugin, metadata, path) => { + if (!metadata) { + return fail(void 0); + } + const query = metadata[META_ALIAS["dataview-note-query"]]; + if (!query) { + return fail(void 0); + } else if (typeof query !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: "dataview-note-query is not a string" + }); + } + const field = metadata[META_ALIAS["dataview-note-field"]]; + if (!field) { + return fail(void 0); + } else if (typeof field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: "dataview-note-field is not a string" + }); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `dataview-note-field is not a valid field: '${field}'` + }); + } + return succ({ + field, + query + }); +}; +var _add_explicit_edges_dataview_note = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + (_a = all_files.obsidian) == null ? void 0 : _a.forEach( + ({ file: dataview_note_file, cache: dataview_note_cache }) => { + if (!dataview_note_cache) + return; + const dataview_note_info = get_dataview_note_info( + plugin, + dataview_note_cache == null ? void 0 : dataview_note_cache.frontmatter, + dataview_note_file.path + ); + if (!dataview_note_info.ok) { + if (dataview_note_info.error) + errors.push(dataview_note_info.error); + return; + } else { + new import_obsidian2.Notice( + "dataview-notes are not implemented without Dataview enabled" + ); + } + } + ); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((dataview_note_page) => { + const dataview_note_path = dataview_note_page.file.path; + const dataview_note_info = get_dataview_note_info( + plugin, + dataview_note_page, + dataview_note_path + ); + if (!dataview_note_info.ok) { + if (dataview_note_info.error) + errors.push(dataview_note_info.error); + return; + } + const { field, query } = dataview_note_info.data; + let pages = []; + try { + pages = dataview_plugin.get_api().pages(query, dataview_note_path).values; + } catch (error) { + log.warn( + "dataview-note > DV API error:", + error instanceof Error ? error.message : error + ); + return errors.push({ + code: "invalid_field_value", + path: dataview_note_path, + message: `dataview-note-query is not a valid dataview query: '${query}'` + }); + } + pages.forEach((page) => { + graph.safe_add_directed_edge( + dataview_note_page.file.path, + page.file.path, + { + field, + explicit: true, + source: "dataview_note" + } + ); + }); + }); + return { errors }; +}; + +// node_modules/luxon/src/errors.js +var LuxonError = class extends Error { +}; +var InvalidDateTimeError = class extends LuxonError { + constructor(reason) { + super(`Invalid DateTime: ${reason.toMessage()}`); + } +}; +var InvalidIntervalError = class extends LuxonError { + constructor(reason) { + super(`Invalid Interval: ${reason.toMessage()}`); + } +}; +var InvalidDurationError = class extends LuxonError { + constructor(reason) { + super(`Invalid Duration: ${reason.toMessage()}`); + } +}; +var ConflictingSpecificationError = class extends LuxonError { +}; +var InvalidUnitError = class extends LuxonError { + constructor(unit) { + super(`Invalid unit ${unit}`); + } +}; +var InvalidArgumentError = class extends LuxonError { +}; +var ZoneIsAbstractError = class extends LuxonError { + constructor() { + super("Zone is an abstract class"); + } +}; + +// node_modules/luxon/src/impl/formats.js +var n = "numeric"; +var s = "short"; +var l = "long"; +var DATE_SHORT = { + year: n, + month: n, + day: n +}; +var DATE_MED = { + year: n, + month: s, + day: n +}; +var DATE_MED_WITH_WEEKDAY = { + year: n, + month: s, + day: n, + weekday: s +}; +var DATE_FULL = { + year: n, + month: l, + day: n +}; +var DATE_HUGE = { + year: n, + month: l, + day: n, + weekday: l +}; +var TIME_SIMPLE = { + hour: n, + minute: n +}; +var TIME_WITH_SECONDS = { + hour: n, + minute: n, + second: n +}; +var TIME_WITH_SHORT_OFFSET = { + hour: n, + minute: n, + second: n, + timeZoneName: s +}; +var TIME_WITH_LONG_OFFSET = { + hour: n, + minute: n, + second: n, + timeZoneName: l +}; +var TIME_24_SIMPLE = { + hour: n, + minute: n, + hourCycle: "h23" +}; +var TIME_24_WITH_SECONDS = { + hour: n, + minute: n, + second: n, + hourCycle: "h23" +}; +var TIME_24_WITH_SHORT_OFFSET = { + hour: n, + minute: n, + second: n, + hourCycle: "h23", + timeZoneName: s +}; +var TIME_24_WITH_LONG_OFFSET = { + hour: n, + minute: n, + second: n, + hourCycle: "h23", + timeZoneName: l +}; +var DATETIME_SHORT = { + year: n, + month: n, + day: n, + hour: n, + minute: n +}; +var DATETIME_SHORT_WITH_SECONDS = { + year: n, + month: n, + day: n, + hour: n, + minute: n, + second: n +}; +var DATETIME_MED = { + year: n, + month: s, + day: n, + hour: n, + minute: n +}; +var DATETIME_MED_WITH_SECONDS = { + year: n, + month: s, + day: n, + hour: n, + minute: n, + second: n +}; +var DATETIME_MED_WITH_WEEKDAY = { + year: n, + month: s, + day: n, + weekday: s, + hour: n, + minute: n +}; +var DATETIME_FULL = { + year: n, + month: l, + day: n, + hour: n, + minute: n, + timeZoneName: s +}; +var DATETIME_FULL_WITH_SECONDS = { + year: n, + month: l, + day: n, + hour: n, + minute: n, + second: n, + timeZoneName: s +}; +var DATETIME_HUGE = { + year: n, + month: l, + day: n, + weekday: l, + hour: n, + minute: n, + timeZoneName: l +}; +var DATETIME_HUGE_WITH_SECONDS = { + year: n, + month: l, + day: n, + weekday: l, + hour: n, + minute: n, + second: n, + timeZoneName: l +}; + +// node_modules/luxon/src/zone.js +var Zone = class { + /** + * The type of zone + * @abstract + * @type {string} + */ + get type() { + throw new ZoneIsAbstractError(); + } + /** + * The name of this zone. + * @abstract + * @type {string} + */ + get name() { + throw new ZoneIsAbstractError(); + } + get ianaName() { + return this.name; + } + /** + * Returns whether the offset is known to be fixed for the whole year. + * @abstract + * @type {boolean} + */ + get isUniversal() { + throw new ZoneIsAbstractError(); + } + /** + * Returns the offset's common name (such as EST) at the specified timestamp + * @abstract + * @param {number} ts - Epoch milliseconds for which to get the name + * @param {Object} opts - Options to affect the format + * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. + * @param {string} opts.locale - What locale to return the offset name in. + * @return {string} + */ + offsetName(ts, opts) { + throw new ZoneIsAbstractError(); + } + /** + * Returns the offset's value as a string + * @abstract + * @param {number} ts - Epoch milliseconds for which to get the offset + * @param {string} format - What style of offset to return. + * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively + * @return {string} + */ + formatOffset(ts, format) { + throw new ZoneIsAbstractError(); + } + /** + * Return the offset in minutes for this zone at the specified timestamp. + * @abstract + * @param {number} ts - Epoch milliseconds for which to compute the offset + * @return {number} + */ + offset(ts) { + throw new ZoneIsAbstractError(); + } + /** + * Return whether this Zone is equal to another zone + * @abstract + * @param {Zone} otherZone - the zone to compare + * @return {boolean} + */ + equals(otherZone) { + throw new ZoneIsAbstractError(); + } + /** + * Return whether this Zone is valid. + * @abstract + * @type {boolean} + */ + get isValid() { + throw new ZoneIsAbstractError(); + } +}; + +// node_modules/luxon/src/zones/systemZone.js +var singleton = null; +var SystemZone = class _SystemZone extends Zone { + /** + * Get a singleton instance of the local zone + * @return {SystemZone} + */ + static get instance() { + if (singleton === null) { + singleton = new _SystemZone(); + } + return singleton; + } + /** @override **/ + get type() { + return "system"; + } + /** @override **/ + get name() { + return new Intl.DateTimeFormat().resolvedOptions().timeZone; + } + /** @override **/ + get isUniversal() { + return false; + } + /** @override **/ + offsetName(ts, { format, locale }) { + return parseZoneInfo(ts, format, locale); + } + /** @override **/ + formatOffset(ts, format) { + return formatOffset(this.offset(ts), format); + } + /** @override **/ + offset(ts) { + return -new Date(ts).getTimezoneOffset(); + } + /** @override **/ + equals(otherZone) { + return otherZone.type === "system"; + } + /** @override **/ + get isValid() { + return true; + } +}; + +// node_modules/luxon/src/zones/IANAZone.js +var dtfCache = {}; +function makeDTF(zone) { + if (!dtfCache[zone]) { + dtfCache[zone] = new Intl.DateTimeFormat("en-US", { + hour12: false, + timeZone: zone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + era: "short" + }); + } + return dtfCache[zone]; +} +var typeToPos = { + year: 0, + month: 1, + day: 2, + era: 3, + hour: 4, + minute: 5, + second: 6 +}; +function hackyOffset(dtf, date) { + const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; + return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; +} +function partsOffset(dtf, date) { + const formatted = dtf.formatToParts(date); + const filled = []; + for (let i = 0; i < formatted.length; i++) { + const { type, value } = formatted[i]; + const pos = typeToPos[type]; + if (type === "era") { + filled[pos] = value; + } else if (!isUndefined(pos)) { + filled[pos] = parseInt(value, 10); + } + } + return filled; +} +var ianaZoneCache = {}; +var IANAZone = class _IANAZone extends Zone { + /** + * @param {string} name - Zone name + * @return {IANAZone} + */ + static create(name) { + if (!ianaZoneCache[name]) { + ianaZoneCache[name] = new _IANAZone(name); + } + return ianaZoneCache[name]; + } + /** + * Reset local caches. Should only be necessary in testing scenarios. + * @return {void} + */ + static resetCache() { + ianaZoneCache = {}; + dtfCache = {}; + } + /** + * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that. + * @param {string} s - The string to check validity on + * @example IANAZone.isValidSpecifier("America/New_York") //=> true + * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false + * @deprecated This method returns false for some valid IANA names. Use isValidZone instead. + * @return {boolean} + */ + static isValidSpecifier(s2) { + return this.isValidZone(s2); + } + /** + * Returns whether the provided string identifies a real zone + * @param {string} zone - The string to check + * @example IANAZone.isValidZone("America/New_York") //=> true + * @example IANAZone.isValidZone("Fantasia/Castle") //=> false + * @example IANAZone.isValidZone("Sport~~blorp") //=> false + * @return {boolean} + */ + static isValidZone(zone) { + if (!zone) { + return false; + } + try { + new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); + return true; + } catch (e) { + return false; + } + } + constructor(name) { + super(); + this.zoneName = name; + this.valid = _IANAZone.isValidZone(name); + } + /** @override **/ + get type() { + return "iana"; + } + /** @override **/ + get name() { + return this.zoneName; + } + /** @override **/ + get isUniversal() { + return false; + } + /** @override **/ + offsetName(ts, { format, locale }) { + return parseZoneInfo(ts, format, locale, this.name); + } + /** @override **/ + formatOffset(ts, format) { + return formatOffset(this.offset(ts), format); + } + /** @override **/ + offset(ts) { + const date = new Date(ts); + if (isNaN(date)) + return NaN; + const dtf = makeDTF(this.name); + let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date); + if (adOrBc === "BC") { + year = -Math.abs(year) + 1; + } + const adjustedHour = hour === 24 ? 0 : hour; + const asUTC = objToLocalTS({ + year, + month, + day, + hour: adjustedHour, + minute, + second, + millisecond: 0 + }); + let asTS = +date; + const over = asTS % 1e3; + asTS -= over >= 0 ? over : 1e3 + over; + return (asUTC - asTS) / (60 * 1e3); + } + /** @override **/ + equals(otherZone) { + return otherZone.type === "iana" && otherZone.name === this.name; + } + /** @override **/ + get isValid() { + return this.valid; + } +}; + +// node_modules/luxon/src/impl/locale.js +var intlLFCache = {}; +function getCachedLF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlLFCache[key]; + if (!dtf) { + dtf = new Intl.ListFormat(locString, opts); + intlLFCache[key] = dtf; + } + return dtf; +} +var intlDTCache = {}; +function getCachedDTF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlDTCache[key]; + if (!dtf) { + dtf = new Intl.DateTimeFormat(locString, opts); + intlDTCache[key] = dtf; + } + return dtf; +} +var intlNumCache = {}; +function getCachedINF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let inf = intlNumCache[key]; + if (!inf) { + inf = new Intl.NumberFormat(locString, opts); + intlNumCache[key] = inf; + } + return inf; +} +var intlRelCache = {}; +function getCachedRTF(locString, opts = {}) { + const { base, ...cacheKeyOpts } = opts; + const key = JSON.stringify([locString, cacheKeyOpts]); + let inf = intlRelCache[key]; + if (!inf) { + inf = new Intl.RelativeTimeFormat(locString, opts); + intlRelCache[key] = inf; + } + return inf; +} +var sysLocaleCache = null; +function systemLocale() { + if (sysLocaleCache) { + return sysLocaleCache; + } else { + sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; + return sysLocaleCache; + } +} +var weekInfoCache = {}; +function getCachedWeekInfo(locString) { + let data = weekInfoCache[locString]; + if (!data) { + const locale = new Intl.Locale(locString); + data = "getWeekInfo" in locale ? locale.getWeekInfo() : locale.weekInfo; + weekInfoCache[locString] = data; + } + return data; +} +function parseLocaleString(localeStr) { + const xIndex = localeStr.indexOf("-x-"); + if (xIndex !== -1) { + localeStr = localeStr.substring(0, xIndex); + } + const uIndex = localeStr.indexOf("-u-"); + if (uIndex === -1) { + return [localeStr]; + } else { + let options; + let selectedStr; + try { + options = getCachedDTF(localeStr).resolvedOptions(); + selectedStr = localeStr; + } catch (e) { + const smaller = localeStr.substring(0, uIndex); + options = getCachedDTF(smaller).resolvedOptions(); + selectedStr = smaller; + } + const { numberingSystem, calendar } = options; + return [selectedStr, numberingSystem, calendar]; + } +} +function intlConfigString(localeStr, numberingSystem, outputCalendar) { + if (outputCalendar || numberingSystem) { + if (!localeStr.includes("-u-")) { + localeStr += "-u"; + } + if (outputCalendar) { + localeStr += `-ca-${outputCalendar}`; + } + if (numberingSystem) { + localeStr += `-nu-${numberingSystem}`; + } + return localeStr; + } else { + return localeStr; + } +} +function mapMonths(f) { + const ms = []; + for (let i = 1; i <= 12; i++) { + const dt = DateTime.utc(2009, i, 1); + ms.push(f(dt)); + } + return ms; +} +function mapWeekdays(f) { + const ms = []; + for (let i = 1; i <= 7; i++) { + const dt = DateTime.utc(2016, 11, 13 + i); + ms.push(f(dt)); + } + return ms; +} +function listStuff(loc, length, englishFn, intlFn) { + const mode = loc.listingMode(); + if (mode === "error") { + return null; + } else if (mode === "en") { + return englishFn(length); + } else { + return intlFn(length); + } +} +function supportsFastNumbers(loc) { + if (loc.numberingSystem && loc.numberingSystem !== "latn") { + return false; + } else { + return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; + } +} +var PolyNumberFormatter = class { + constructor(intl, forceSimple, opts) { + this.padTo = opts.padTo || 0; + this.floor = opts.floor || false; + const { padTo, floor, ...otherOpts } = opts; + if (!forceSimple || Object.keys(otherOpts).length > 0) { + const intlOpts = { useGrouping: false, ...opts }; + if (opts.padTo > 0) + intlOpts.minimumIntegerDigits = opts.padTo; + this.inf = getCachedINF(intl, intlOpts); + } + } + format(i) { + if (this.inf) { + const fixed = this.floor ? Math.floor(i) : i; + return this.inf.format(fixed); + } else { + const fixed = this.floor ? Math.floor(i) : roundTo(i, 3); + return padStart(fixed, this.padTo); + } + } +}; +var PolyDateFormatter = class { + constructor(dt, intl, opts) { + this.opts = opts; + this.originalZone = void 0; + let z2 = void 0; + if (this.opts.timeZone) { + this.dt = dt; + } else if (dt.zone.type === "fixed") { + const gmtOffset = -1 * (dt.offset / 60); + const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; + if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { + z2 = offsetZ; + this.dt = dt; + } else { + z2 = "UTC"; + this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset }); + this.originalZone = dt.zone; + } + } else if (dt.zone.type === "system") { + this.dt = dt; + } else if (dt.zone.type === "iana") { + this.dt = dt; + z2 = dt.zone.name; + } else { + z2 = "UTC"; + this.dt = dt.setZone("UTC").plus({ minutes: dt.offset }); + this.originalZone = dt.zone; + } + const intlOpts = { ...this.opts }; + intlOpts.timeZone = intlOpts.timeZone || z2; + this.dtf = getCachedDTF(intl, intlOpts); + } + format() { + if (this.originalZone) { + return this.formatToParts().map(({ value }) => value).join(""); + } + return this.dtf.format(this.dt.toJSDate()); + } + formatToParts() { + const parts = this.dtf.formatToParts(this.dt.toJSDate()); + if (this.originalZone) { + return parts.map((part) => { + if (part.type === "timeZoneName") { + const offsetName = this.originalZone.offsetName(this.dt.ts, { + locale: this.dt.locale, + format: this.opts.timeZoneName + }); + return { + ...part, + value: offsetName + }; + } else { + return part; + } + }); + } + return parts; + } + resolvedOptions() { + return this.dtf.resolvedOptions(); + } +}; +var PolyRelFormatter = class { + constructor(intl, isEnglish, opts) { + this.opts = { style: "long", ...opts }; + if (!isEnglish && hasRelative()) { + this.rtf = getCachedRTF(intl, opts); + } + } + format(count, unit) { + if (this.rtf) { + return this.rtf.format(count, unit); + } else { + return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); + } + } + formatToParts(count, unit) { + if (this.rtf) { + return this.rtf.formatToParts(count, unit); + } else { + return []; + } + } +}; +var fallbackWeekSettings = { + firstDay: 1, + minimalDays: 4, + weekend: [6, 7] +}; +var Locale = class _Locale { + static fromOpts(opts) { + return _Locale.create( + opts.locale, + opts.numberingSystem, + opts.outputCalendar, + opts.weekSettings, + opts.defaultToEN + ); + } + static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) { + const specifiedLocale = locale || Settings.defaultLocale; + const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); + const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; + const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; + const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings; + return new _Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale); + } + static resetCache() { + sysLocaleCache = null; + intlDTCache = {}; + intlNumCache = {}; + intlRelCache = {}; + } + static fromObject({ locale, numberingSystem, outputCalendar, weekSettings } = {}) { + return _Locale.create(locale, numberingSystem, outputCalendar, weekSettings); + } + constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) { + const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale); + this.locale = parsedLocale; + this.numberingSystem = numbering || parsedNumberingSystem || null; + this.outputCalendar = outputCalendar || parsedOutputCalendar || null; + this.weekSettings = weekSettings; + this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); + this.weekdaysCache = { format: {}, standalone: {} }; + this.monthsCache = { format: {}, standalone: {} }; + this.meridiemCache = null; + this.eraCache = {}; + this.specifiedLocale = specifiedLocale; + this.fastNumbersCached = null; + } + get fastNumbers() { + if (this.fastNumbersCached == null) { + this.fastNumbersCached = supportsFastNumbers(this); + } + return this.fastNumbersCached; + } + listingMode() { + const isActuallyEn = this.isEnglish(); + const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); + return isActuallyEn && hasNoWeirdness ? "en" : "intl"; + } + clone(alts) { + if (!alts || Object.getOwnPropertyNames(alts).length === 0) { + return this; + } else { + return _Locale.create( + alts.locale || this.specifiedLocale, + alts.numberingSystem || this.numberingSystem, + alts.outputCalendar || this.outputCalendar, + validateWeekSettings(alts.weekSettings) || this.weekSettings, + alts.defaultToEN || false + ); + } + } + redefaultToEN(alts = {}) { + return this.clone({ ...alts, defaultToEN: true }); + } + redefaultToSystem(alts = {}) { + return this.clone({ ...alts, defaultToEN: false }); + } + months(length, format = false) { + return listStuff(this, length, months, () => { + const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; + if (!this.monthsCache[formatStr][length]) { + this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, "month")); + } + return this.monthsCache[formatStr][length]; + }); + } + weekdays(length, format = false) { + return listStuff(this, length, weekdays, () => { + const intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone"; + if (!this.weekdaysCache[formatStr][length]) { + this.weekdaysCache[formatStr][length] = mapWeekdays( + (dt) => this.extract(dt, intl, "weekday") + ); + } + return this.weekdaysCache[formatStr][length]; + }); + } + meridiems() { + return listStuff( + this, + void 0, + () => meridiems, + () => { + if (!this.meridiemCache) { + const intl = { hour: "numeric", hourCycle: "h12" }; + this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map( + (dt) => this.extract(dt, intl, "dayperiod") + ); + } + return this.meridiemCache; + } + ); + } + eras(length) { + return listStuff(this, length, eras, () => { + const intl = { era: length }; + if (!this.eraCache[length]) { + this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map( + (dt) => this.extract(dt, intl, "era") + ); + } + return this.eraCache[length]; + }); + } + extract(dt, intlOpts, field) { + const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field); + return matching ? matching.value : null; + } + numberFormatter(opts = {}) { + return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); + } + dtFormatter(dt, intlOpts = {}) { + return new PolyDateFormatter(dt, this.intl, intlOpts); + } + relFormatter(opts = {}) { + return new PolyRelFormatter(this.intl, this.isEnglish(), opts); + } + listFormatter(opts = {}) { + return getCachedLF(this.intl, opts); + } + isEnglish() { + return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); + } + getWeekSettings() { + if (this.weekSettings) { + return this.weekSettings; + } else if (!hasLocaleWeekInfo()) { + return fallbackWeekSettings; + } else { + return getCachedWeekInfo(this.locale); + } + } + getStartOfWeek() { + return this.getWeekSettings().firstDay; + } + getMinDaysInFirstWeek() { + return this.getWeekSettings().minimalDays; + } + getWeekendDays() { + return this.getWeekSettings().weekend; + } + equals(other) { + return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; + } +}; + +// node_modules/luxon/src/zones/fixedOffsetZone.js +var singleton2 = null; +var FixedOffsetZone = class _FixedOffsetZone extends Zone { + /** + * Get a singleton instance of UTC + * @return {FixedOffsetZone} + */ + static get utcInstance() { + if (singleton2 === null) { + singleton2 = new _FixedOffsetZone(0); + } + return singleton2; + } + /** + * Get an instance with a specified offset + * @param {number} offset - The offset in minutes + * @return {FixedOffsetZone} + */ + static instance(offset2) { + return offset2 === 0 ? _FixedOffsetZone.utcInstance : new _FixedOffsetZone(offset2); + } + /** + * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" + * @param {string} s - The offset string to parse + * @example FixedOffsetZone.parseSpecifier("UTC+6") + * @example FixedOffsetZone.parseSpecifier("UTC+06") + * @example FixedOffsetZone.parseSpecifier("UTC-6:00") + * @return {FixedOffsetZone} + */ + static parseSpecifier(s2) { + if (s2) { + const r = s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); + if (r) { + return new _FixedOffsetZone(signedOffset(r[1], r[2])); + } + } + return null; + } + constructor(offset2) { + super(); + this.fixed = offset2; + } + /** @override **/ + get type() { + return "fixed"; + } + /** @override **/ + get name() { + return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; + } + get ianaName() { + if (this.fixed === 0) { + return "Etc/UTC"; + } else { + return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; + } + } + /** @override **/ + offsetName() { + return this.name; + } + /** @override **/ + formatOffset(ts, format) { + return formatOffset(this.fixed, format); + } + /** @override **/ + get isUniversal() { + return true; + } + /** @override **/ + offset() { + return this.fixed; + } + /** @override **/ + equals(otherZone) { + return otherZone.type === "fixed" && otherZone.fixed === this.fixed; + } + /** @override **/ + get isValid() { + return true; + } +}; + +// node_modules/luxon/src/zones/invalidZone.js +var InvalidZone = class extends Zone { + constructor(zoneName) { + super(); + this.zoneName = zoneName; + } + /** @override **/ + get type() { + return "invalid"; + } + /** @override **/ + get name() { + return this.zoneName; + } + /** @override **/ + get isUniversal() { + return false; + } + /** @override **/ + offsetName() { + return null; + } + /** @override **/ + formatOffset() { + return ""; + } + /** @override **/ + offset() { + return NaN; + } + /** @override **/ + equals() { + return false; + } + /** @override **/ + get isValid() { + return false; + } +}; + +// node_modules/luxon/src/impl/zoneUtil.js +function normalizeZone(input, defaultZone2) { + let offset2; + if (isUndefined(input) || input === null) { + return defaultZone2; + } else if (input instanceof Zone) { + return input; + } else if (isString(input)) { + const lowered = input.toLowerCase(); + if (lowered === "default") + return defaultZone2; + else if (lowered === "local" || lowered === "system") + return SystemZone.instance; + else if (lowered === "utc" || lowered === "gmt") + return FixedOffsetZone.utcInstance; + else + return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); + } else if (isNumber(input)) { + return FixedOffsetZone.instance(input); + } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { + return input; + } else { + return new InvalidZone(input); + } +} + +// node_modules/luxon/src/settings.js +var now = () => Date.now(); +var defaultZone = "system"; +var defaultLocale = null; +var defaultNumberingSystem = null; +var defaultOutputCalendar = null; +var twoDigitCutoffYear = 60; +var throwOnInvalid; +var defaultWeekSettings = null; +var Settings = class { + /** + * Get the callback for returning the current timestamp. + * @type {function} + */ + static get now() { + return now; + } + /** + * Set the callback for returning the current timestamp. + * The function should return a number, which will be interpreted as an Epoch millisecond count + * @type {function} + * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future + * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time + */ + static set now(n2) { + now = n2; + } + /** + * Set the default time zone to create DateTimes in. Does not affect existing instances. + * Use the value "system" to reset this value to the system's time zone. + * @type {string} + */ + static set defaultZone(zone) { + defaultZone = zone; + } + /** + * Get the default time zone object currently used to create DateTimes. Does not affect existing instances. + * The default value is the system's time zone (the one set on the machine that runs this code). + * @type {Zone} + */ + static get defaultZone() { + return normalizeZone(defaultZone, SystemZone.instance); + } + /** + * Get the default locale to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultLocale() { + return defaultLocale; + } + /** + * Set the default locale to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultLocale(locale) { + defaultLocale = locale; + } + /** + * Get the default numbering system to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultNumberingSystem() { + return defaultNumberingSystem; + } + /** + * Set the default numbering system to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultNumberingSystem(numberingSystem) { + defaultNumberingSystem = numberingSystem; + } + /** + * Get the default output calendar to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultOutputCalendar() { + return defaultOutputCalendar; + } + /** + * Set the default output calendar to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultOutputCalendar(outputCalendar) { + defaultOutputCalendar = outputCalendar; + } + /** + * @typedef {Object} WeekSettings + * @property {number} firstDay + * @property {number} minimalDays + * @property {number[]} weekend + */ + /** + * @return {WeekSettings|null} + */ + static get defaultWeekSettings() { + return defaultWeekSettings; + } + /** + * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and + * how many days are required in the first week of a year. + * Does not affect existing instances. + * + * @param {WeekSettings|null} weekSettings + */ + static set defaultWeekSettings(weekSettings) { + defaultWeekSettings = validateWeekSettings(weekSettings); + } + /** + * Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. + * @type {number} + */ + static get twoDigitCutoffYear() { + return twoDigitCutoffYear; + } + /** + * Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. + * @type {number} + * @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpreted as current century + * @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050 + * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50 + * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50 + */ + static set twoDigitCutoffYear(cutoffYear) { + twoDigitCutoffYear = cutoffYear % 100; + } + /** + * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals + * @type {boolean} + */ + static get throwOnInvalid() { + return throwOnInvalid; + } + /** + * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals + * @type {boolean} + */ + static set throwOnInvalid(t) { + throwOnInvalid = t; + } + /** + * Reset Luxon's global caches. Should only be necessary in testing scenarios. + * @return {void} + */ + static resetCaches() { + Locale.resetCache(); + IANAZone.resetCache(); + } +}; + +// node_modules/luxon/src/impl/invalid.js +var Invalid = class { + constructor(reason, explanation) { + this.reason = reason; + this.explanation = explanation; + } + toMessage() { + if (this.explanation) { + return `${this.reason}: ${this.explanation}`; + } else { + return this.reason; + } + } +}; + +// node_modules/luxon/src/impl/conversions.js +var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; +var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; +function unitOutOfRange(unit, value) { + return new Invalid( + "unit out of range", + `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid` + ); +} +function dayOfWeek(year, month, day) { + const d = new Date(Date.UTC(year, month - 1, day)); + if (year < 100 && year >= 0) { + d.setUTCFullYear(d.getUTCFullYear() - 1900); + } + const js = d.getUTCDay(); + return js === 0 ? 7 : js; +} +function computeOrdinal(year, month, day) { + return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; +} +function uncomputeOrdinal(year, ordinal) { + const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0]; + return { month: month0 + 1, day }; +} +function isoWeekdayToLocal(isoWeekday, startOfWeek) { + return (isoWeekday - startOfWeek + 7) % 7 + 1; +} +function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) { + const { year, month, day } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek); + let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear; + if (weekNumber < 1) { + weekYear = year - 1; + weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek); + } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) { + weekYear = year + 1; + weekNumber = 1; + } else { + weekYear = year; + } + return { weekYear, weekNumber, weekday, ...timeObject(gregObj) }; +} +function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) { + const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear); + let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, year; + if (ordinal < 1) { + year = weekYear - 1; + ordinal += daysInYear(year); + } else if (ordinal > yearInDays) { + year = weekYear + 1; + ordinal -= daysInYear(weekYear); + } else { + year = weekYear; + } + const { month, day } = uncomputeOrdinal(year, ordinal); + return { year, month, day, ...timeObject(weekData) }; +} +function gregorianToOrdinal(gregData) { + const { year, month, day } = gregData; + const ordinal = computeOrdinal(year, month, day); + return { year, ordinal, ...timeObject(gregData) }; +} +function ordinalToGregorian(ordinalData) { + const { year, ordinal } = ordinalData; + const { month, day } = uncomputeOrdinal(year, ordinal); + return { year, month, day, ...timeObject(ordinalData) }; +} +function usesLocalWeekValues(obj, loc) { + const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear); + if (hasLocaleWeekData) { + const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); + if (hasIsoWeekData) { + throw new ConflictingSpecificationError( + "Cannot mix locale-based week fields with ISO-based week fields" + ); + } + if (!isUndefined(obj.localWeekday)) + obj.weekday = obj.localWeekday; + if (!isUndefined(obj.localWeekNumber)) + obj.weekNumber = obj.localWeekNumber; + if (!isUndefined(obj.localWeekYear)) + obj.weekYear = obj.localWeekYear; + delete obj.localWeekday; + delete obj.localWeekNumber; + delete obj.localWeekYear; + return { + minDaysInFirstWeek: loc.getMinDaysInFirstWeek(), + startOfWeek: loc.getStartOfWeek() + }; + } else { + return { minDaysInFirstWeek: 4, startOfWeek: 1 }; + } +} +function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) { + const validYear = isInteger(obj.weekYear), validWeek = integerBetween( + obj.weekNumber, + 1, + weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek) + ), validWeekday = integerBetween(obj.weekday, 1, 7); + if (!validYear) { + return unitOutOfRange("weekYear", obj.weekYear); + } else if (!validWeek) { + return unitOutOfRange("week", obj.weekNumber); + } else if (!validWeekday) { + return unitOutOfRange("weekday", obj.weekday); + } else + return false; +} +function hasInvalidOrdinalData(obj) { + const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); + if (!validYear) { + return unitOutOfRange("year", obj.year); + } else if (!validOrdinal) { + return unitOutOfRange("ordinal", obj.ordinal); + } else + return false; +} +function hasInvalidGregorianData(obj) { + const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); + if (!validYear) { + return unitOutOfRange("year", obj.year); + } else if (!validMonth) { + return unitOutOfRange("month", obj.month); + } else if (!validDay) { + return unitOutOfRange("day", obj.day); + } else + return false; +} +function hasInvalidTimeData(obj) { + const { hour, minute, second, millisecond } = obj; + const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); + if (!validHour) { + return unitOutOfRange("hour", hour); + } else if (!validMinute) { + return unitOutOfRange("minute", minute); + } else if (!validSecond) { + return unitOutOfRange("second", second); + } else if (!validMillisecond) { + return unitOutOfRange("millisecond", millisecond); + } else + return false; +} + +// node_modules/luxon/src/impl/util.js +function isUndefined(o) { + return typeof o === "undefined"; +} +function isNumber(o) { + return typeof o === "number"; +} +function isInteger(o) { + return typeof o === "number" && o % 1 === 0; +} +function isString(o) { + return typeof o === "string"; +} +function isDate(o) { + return Object.prototype.toString.call(o) === "[object Date]"; +} +function hasRelative() { + try { + return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; + } catch (e) { + return false; + } +} +function hasLocaleWeekInfo() { + try { + return typeof Intl !== "undefined" && !!Intl.Locale && ("weekInfo" in Intl.Locale.prototype || "getWeekInfo" in Intl.Locale.prototype); + } catch (e) { + return false; + } +} +function maybeArray(thing) { + return Array.isArray(thing) ? thing : [thing]; +} +function bestBy(arr, by, compare) { + if (arr.length === 0) { + return void 0; + } + return arr.reduce((best, next) => { + const pair = [by(next), next]; + if (!best) { + return pair; + } else if (compare(best[0], pair[0]) === best[0]) { + return best; + } else { + return pair; + } + }, null)[1]; +} +function pick(obj, keys) { + return keys.reduce((a, k) => { + a[k] = obj[k]; + return a; + }, {}); +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} +function validateWeekSettings(settings) { + if (settings == null) { + return null; + } else if (typeof settings !== "object") { + throw new InvalidArgumentError("Week settings must be an object"); + } else { + if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some((v) => !integerBetween(v, 1, 7))) { + throw new InvalidArgumentError("Invalid week settings"); + } + return { + firstDay: settings.firstDay, + minimalDays: settings.minimalDays, + weekend: Array.from(settings.weekend) + }; + } +} +function integerBetween(thing, bottom, top) { + return isInteger(thing) && thing >= bottom && thing <= top; +} +function floorMod(x, n2) { + return x - n2 * Math.floor(x / n2); +} +function padStart(input, n2 = 2) { + const isNeg = input < 0; + let padded; + if (isNeg) { + padded = "-" + ("" + -input).padStart(n2, "0"); + } else { + padded = ("" + input).padStart(n2, "0"); + } + return padded; +} +function parseInteger(string) { + if (isUndefined(string) || string === null || string === "") { + return void 0; + } else { + return parseInt(string, 10); + } +} +function parseFloating(string) { + if (isUndefined(string) || string === null || string === "") { + return void 0; + } else { + return parseFloat(string); + } +} +function parseMillis(fraction) { + if (isUndefined(fraction) || fraction === null || fraction === "") { + return void 0; + } else { + const f = parseFloat("0." + fraction) * 1e3; + return Math.floor(f); + } +} +function roundTo(number, digits, towardZero = false) { + const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round; + return rounder(number * factor) / factor; +} +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; +} +function daysInMonth(year, month) { + const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; + if (modMonth === 2) { + return isLeapYear(modYear) ? 29 : 28; + } else { + return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; + } +} +function objToLocalTS(obj) { + let d = Date.UTC( + obj.year, + obj.month - 1, + obj.day, + obj.hour, + obj.minute, + obj.second, + obj.millisecond + ); + if (obj.year < 100 && obj.year >= 0) { + d = new Date(d); + d.setUTCFullYear(obj.year, obj.month - 1, obj.day); + } + return +d; +} +function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) { + const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); + return -fwdlw + minDaysInFirstWeek - 1; +} +function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) { + const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); + const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek); + return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7; +} +function untruncateYear(year) { + if (year > 99) { + return year; + } else + return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year; +} +function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) { + const date = new Date(ts), intlOpts = { + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit" + }; + if (timeZone) { + intlOpts.timeZone = timeZone; + } + const modified = { timeZoneName: offsetFormat, ...intlOpts }; + const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename"); + return parsed ? parsed.value : null; +} +function signedOffset(offHourStr, offMinuteStr) { + let offHour = parseInt(offHourStr, 10); + if (Number.isNaN(offHour)) { + offHour = 0; + } + const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; + return offHour * 60 + offMinSigned; +} +function asNumber(value) { + const numericValue = Number(value); + if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) + throw new InvalidArgumentError(`Invalid unit value ${value}`); + return numericValue; +} +function normalizeObject(obj, normalizer) { + const normalized = {}; + for (const u in obj) { + if (hasOwnProperty(obj, u)) { + const v = obj[u]; + if (v === void 0 || v === null) + continue; + normalized[normalizer(u)] = asNumber(v); + } + } + return normalized; +} +function formatOffset(offset2, format) { + const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign = offset2 >= 0 ? "+" : "-"; + switch (format) { + case "short": + return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`; + case "narrow": + return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`; + case "techie": + return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`; + default: + throw new RangeError(`Value format ${format} is out of range for property format`); + } +} +function timeObject(obj) { + return pick(obj, ["hour", "minute", "second", "millisecond"]); +} + +// node_modules/luxon/src/impl/english.js +var monthsLong = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +]; +var monthsShort = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" +]; +var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; +function months(length) { + switch (length) { + case "narrow": + return [...monthsNarrow]; + case "short": + return [...monthsShort]; + case "long": + return [...monthsLong]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; + case "2-digit": + return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; + default: + return null; + } +} +var weekdaysLong = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday" +]; +var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; +var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; +function weekdays(length) { + switch (length) { + case "narrow": + return [...weekdaysNarrow]; + case "short": + return [...weekdaysShort]; + case "long": + return [...weekdaysLong]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7"]; + default: + return null; + } +} +var meridiems = ["AM", "PM"]; +var erasLong = ["Before Christ", "Anno Domini"]; +var erasShort = ["BC", "AD"]; +var erasNarrow = ["B", "A"]; +function eras(length) { + switch (length) { + case "narrow": + return [...erasNarrow]; + case "short": + return [...erasShort]; + case "long": + return [...erasLong]; + default: + return null; + } +} +function meridiemForDateTime(dt) { + return meridiems[dt.hour < 12 ? 0 : 1]; +} +function weekdayForDateTime(dt, length) { + return weekdays(length)[dt.weekday - 1]; +} +function monthForDateTime(dt, length) { + return months(length)[dt.month - 1]; +} +function eraForDateTime(dt, length) { + return eras(length)[dt.year < 0 ? 0 : 1]; +} +function formatRelativeTime(unit, count, numeric = "always", narrow = false) { + const units = { + years: ["year", "yr."], + quarters: ["quarter", "qtr."], + months: ["month", "mo."], + weeks: ["week", "wk."], + days: ["day", "day", "days"], + hours: ["hour", "hr."], + minutes: ["minute", "min."], + seconds: ["second", "sec."] + }; + const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; + if (numeric === "auto" && lastable) { + const isDay = unit === "days"; + switch (count) { + case 1: + return isDay ? "tomorrow" : `next ${units[unit][0]}`; + case -1: + return isDay ? "yesterday" : `last ${units[unit][0]}`; + case 0: + return isDay ? "today" : `this ${units[unit][0]}`; + default: + } + } + const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; + return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; +} + +// node_modules/luxon/src/impl/formatter.js +function stringifyTokens(splits, tokenToString) { + let s2 = ""; + for (const token of splits) { + if (token.literal) { + s2 += token.val; + } else { + s2 += tokenToString(token.val); + } + } + return s2; +} +var macroTokenToFormatOpts = { + D: DATE_SHORT, + DD: DATE_MED, + DDD: DATE_FULL, + DDDD: DATE_HUGE, + t: TIME_SIMPLE, + tt: TIME_WITH_SECONDS, + ttt: TIME_WITH_SHORT_OFFSET, + tttt: TIME_WITH_LONG_OFFSET, + T: TIME_24_SIMPLE, + TT: TIME_24_WITH_SECONDS, + TTT: TIME_24_WITH_SHORT_OFFSET, + TTTT: TIME_24_WITH_LONG_OFFSET, + f: DATETIME_SHORT, + ff: DATETIME_MED, + fff: DATETIME_FULL, + ffff: DATETIME_HUGE, + F: DATETIME_SHORT_WITH_SECONDS, + FF: DATETIME_MED_WITH_SECONDS, + FFF: DATETIME_FULL_WITH_SECONDS, + FFFF: DATETIME_HUGE_WITH_SECONDS +}; +var Formatter = class _Formatter { + static create(locale, opts = {}) { + return new _Formatter(locale, opts); + } + static parseFormat(fmt) { + let current = null, currentFull = "", bracketed = false; + const splits = []; + for (let i = 0; i < fmt.length; i++) { + const c = fmt.charAt(i); + if (c === "'") { + if (currentFull.length > 0) { + splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + } + current = null; + currentFull = ""; + bracketed = !bracketed; + } else if (bracketed) { + currentFull += c; + } else if (c === current) { + currentFull += c; + } else { + if (currentFull.length > 0) { + splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull }); + } + currentFull = c; + current = c; + } + } + if (currentFull.length > 0) { + splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + } + return splits; + } + static macroTokenToFormatOpts(token) { + return macroTokenToFormatOpts[token]; + } + constructor(locale, formatOpts) { + this.opts = formatOpts; + this.loc = locale; + this.systemLoc = null; + } + formatWithSystemDefault(dt, opts) { + if (this.systemLoc === null) { + this.systemLoc = this.loc.redefaultToSystem(); + } + const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts }); + return df.format(); + } + dtFormatter(dt, opts = {}) { + return this.loc.dtFormatter(dt, { ...this.opts, ...opts }); + } + formatDateTime(dt, opts) { + return this.dtFormatter(dt, opts).format(); + } + formatDateTimeParts(dt, opts) { + return this.dtFormatter(dt, opts).formatToParts(); + } + formatInterval(interval, opts) { + const df = this.dtFormatter(interval.start, opts); + return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); + } + resolvedOptions(dt, opts) { + return this.dtFormatter(dt, opts).resolvedOptions(); + } + num(n2, p = 0) { + if (this.opts.forceSimple) { + return padStart(n2, p); + } + const opts = { ...this.opts }; + if (p > 0) { + opts.padTo = p; + } + return this.loc.numberFormatter(opts).format(n2); + } + formatDateTimeFromString(dt, fmt) { + const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => { + if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { + return "Z"; + } + return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; + }, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string( + standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, + "weekday" + ), maybeMacro = (token) => { + const formatOpts = _Formatter.macroTokenToFormatOpts(token); + if (formatOpts) { + return this.formatWithSystemDefault(dt, formatOpts); + } else { + return token; + } + }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"), tokenToString = (token) => { + switch (token) { + case "S": + return this.num(dt.millisecond); + case "u": + case "SSS": + return this.num(dt.millisecond, 3); + case "s": + return this.num(dt.second); + case "ss": + return this.num(dt.second, 2); + case "uu": + return this.num(Math.floor(dt.millisecond / 10), 2); + case "uuu": + return this.num(Math.floor(dt.millisecond / 100)); + case "m": + return this.num(dt.minute); + case "mm": + return this.num(dt.minute, 2); + case "h": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); + case "hh": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); + case "H": + return this.num(dt.hour); + case "HH": + return this.num(dt.hour, 2); + case "Z": + return formatOffset2({ format: "narrow", allowZ: this.opts.allowZ }); + case "ZZ": + return formatOffset2({ format: "short", allowZ: this.opts.allowZ }); + case "ZZZ": + return formatOffset2({ format: "techie", allowZ: this.opts.allowZ }); + case "ZZZZ": + return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale }); + case "ZZZZZ": + return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale }); + case "z": + return dt.zoneName; + case "a": + return meridiem(); + case "d": + return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day); + case "dd": + return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2); + case "c": + return this.num(dt.weekday); + case "ccc": + return weekday("short", true); + case "cccc": + return weekday("long", true); + case "ccccc": + return weekday("narrow", true); + case "E": + return this.num(dt.weekday); + case "EEE": + return weekday("short", false); + case "EEEE": + return weekday("long", false); + case "EEEEE": + return weekday("narrow", false); + case "L": + return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month); + case "LL": + return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2); + case "LLL": + return month("short", true); + case "LLLL": + return month("long", true); + case "LLLLL": + return month("narrow", true); + case "M": + return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month); + case "MM": + return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2); + case "MMM": + return month("short", false); + case "MMMM": + return month("long", false); + case "MMMMM": + return month("narrow", false); + case "y": + return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year); + case "yy": + return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2); + case "yyyy": + return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4); + case "yyyyyy": + return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6); + case "G": + return era("short"); + case "GG": + return era("long"); + case "GGGGG": + return era("narrow"); + case "kk": + return this.num(dt.weekYear.toString().slice(-2), 2); + case "kkkk": + return this.num(dt.weekYear, 4); + case "W": + return this.num(dt.weekNumber); + case "WW": + return this.num(dt.weekNumber, 2); + case "n": + return this.num(dt.localWeekNumber); + case "nn": + return this.num(dt.localWeekNumber, 2); + case "ii": + return this.num(dt.localWeekYear.toString().slice(-2), 2); + case "iiii": + return this.num(dt.localWeekYear, 4); + case "o": + return this.num(dt.ordinal); + case "ooo": + return this.num(dt.ordinal, 3); + case "q": + return this.num(dt.quarter); + case "qq": + return this.num(dt.quarter, 2); + case "X": + return this.num(Math.floor(dt.ts / 1e3)); + case "x": + return this.num(dt.ts); + default: + return maybeMacro(token); + } + }; + return stringifyTokens(_Formatter.parseFormat(fmt), tokenToString); + } + formatDurationFromString(dur, fmt) { + const tokenToField = (token) => { + switch (token[0]) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + return "hour"; + case "d": + return "day"; + case "w": + return "week"; + case "M": + return "month"; + case "y": + return "year"; + default: + return null; + } + }, tokenToString = (lildur) => (token) => { + const mapped = tokenToField(token); + if (mapped) { + return this.num(lildur.get(mapped), token.length); + } else { + return token; + } + }, tokens = _Formatter.parseFormat(fmt), realTokens = tokens.reduce( + (found, { literal, val }) => literal ? found : found.concat(val), + [] + ), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)); + return stringifyTokens(tokens, tokenToString(collapsed)); + } +}; + +// node_modules/luxon/src/impl/regexParser.js +var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; +function combineRegexes(...regexes) { + const full = regexes.reduce((f, r) => f + r.source, ""); + return RegExp(`^${full}$`); +} +function combineExtractors(...extractors) { + return (m) => extractors.reduce( + ([mergedVals, mergedZone, cursor], ex) => { + const [val, zone, next] = ex(m, cursor); + return [{ ...mergedVals, ...val }, zone || mergedZone, next]; + }, + [{}, null, 1] + ).slice(0, 2); +} +function parse(s2, ...patterns) { + if (s2 == null) { + return [null, null]; + } + for (const [regex2, extractor] of patterns) { + const m = regex2.exec(s2); + if (m) { + return extractor(m); + } + } + return [null, null]; +} +function simpleParse(...keys) { + return (match2, cursor) => { + const ret = {}; + let i; + for (i = 0; i < keys.length; i++) { + ret[keys[i]] = parseInteger(match2[cursor + i]); + } + return [ret, null, cursor + i]; + }; +} +var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; +var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; +var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; +var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`); +var isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`); +var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; +var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; +var isoOrdinalRegex = /(\d{4})-?(\d{3})/; +var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); +var extractISOOrdinalData = simpleParse("year", "ordinal"); +var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; +var sqlTimeRegex = RegExp( + `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?` +); +var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); +function int(match2, pos, fallback) { + const m = match2[pos]; + return isUndefined(m) ? fallback : parseInteger(m); +} +function extractISOYmd(match2, cursor) { + const item = { + year: int(match2, cursor), + month: int(match2, cursor + 1, 1), + day: int(match2, cursor + 2, 1) + }; + return [item, null, cursor + 3]; +} +function extractISOTime(match2, cursor) { + const item = { + hours: int(match2, cursor, 0), + minutes: int(match2, cursor + 1, 0), + seconds: int(match2, cursor + 2, 0), + milliseconds: parseMillis(match2[cursor + 3]) + }; + return [item, null, cursor + 4]; +} +function extractISOOffset(match2, cursor) { + const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); + return [{}, zone, cursor + 3]; +} +function extractIANAZone(match2, cursor) { + const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null; + return [{}, zone, cursor + 1]; +} +var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); +var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; +function extractISODuration(match2) { + const [s2, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2; + const hasNegativePrefix = s2[0] === "-"; + const negativeSeconds = secondStr && secondStr[0] === "-"; + const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num; + return [ + { + years: maybeNegate(parseFloating(yearStr)), + months: maybeNegate(parseFloating(monthStr)), + weeks: maybeNegate(parseFloating(weekStr)), + days: maybeNegate(parseFloating(dayStr)), + hours: maybeNegate(parseFloating(hourStr)), + minutes: maybeNegate(parseFloating(minuteStr)), + seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), + milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) + } + ]; +} +var obsOffsets = { + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 +}; +function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + const result = { + year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), + month: monthsShort.indexOf(monthStr) + 1, + day: parseInteger(dayStr), + hour: parseInteger(hourStr), + minute: parseInteger(minuteStr) + }; + if (secondStr) + result.second = parseInteger(secondStr); + if (weekdayStr) { + result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; + } + return result; +} +var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; +function extractRFC2822(match2) { + const [ + , + weekdayStr, + dayStr, + monthStr, + yearStr, + hourStr, + minuteStr, + secondStr, + obsOffset, + milOffset, + offHourStr, + offMinuteStr + ] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + let offset2; + if (obsOffset) { + offset2 = obsOffsets[obsOffset]; + } else if (milOffset) { + offset2 = 0; + } else { + offset2 = signedOffset(offHourStr, offMinuteStr); + } + return [result, new FixedOffsetZone(offset2)]; +} +function preprocessRFC2822(s2) { + return s2.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); +} +var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; +var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; +var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; +function extractRFC1123Or850(match2) { + const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; +} +function extractASCII(match2) { + const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; +} +var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); +var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); +var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); +var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); +var extractISOYmdTimeAndOffset = combineExtractors( + extractISOYmd, + extractISOTime, + extractISOOffset, + extractIANAZone +); +var extractISOWeekTimeAndOffset = combineExtractors( + extractISOWeekData, + extractISOTime, + extractISOOffset, + extractIANAZone +); +var extractISOOrdinalDateAndTime = combineExtractors( + extractISOOrdinalData, + extractISOTime, + extractISOOffset, + extractIANAZone +); +var extractISOTimeAndOffset = combineExtractors( + extractISOTime, + extractISOOffset, + extractIANAZone +); +function parseISODate(s2) { + return parse( + s2, + [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], + [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], + [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], + [isoTimeCombinedRegex, extractISOTimeAndOffset] + ); +} +function parseRFC2822Date(s2) { + return parse(preprocessRFC2822(s2), [rfc2822, extractRFC2822]); +} +function parseHTTPDate(s2) { + return parse( + s2, + [rfc1123, extractRFC1123Or850], + [rfc850, extractRFC1123Or850], + [ascii, extractASCII] + ); +} +function parseISODuration(s2) { + return parse(s2, [isoDuration, extractISODuration]); +} +var extractISOTimeOnly = combineExtractors(extractISOTime); +function parseISOTimeOnly(s2) { + return parse(s2, [isoTimeOnly, extractISOTimeOnly]); +} +var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); +var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); +var extractISOTimeOffsetAndIANAZone = combineExtractors( + extractISOTime, + extractISOOffset, + extractIANAZone +); +function parseSQL(s2) { + return parse( + s2, + [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], + [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone] + ); +} + +// node_modules/luxon/src/duration.js +var INVALID2 = "Invalid Duration"; +var lowOrderMatrix = { + weeks: { + days: 7, + hours: 7 * 24, + minutes: 7 * 24 * 60, + seconds: 7 * 24 * 60 * 60, + milliseconds: 7 * 24 * 60 * 60 * 1e3 + }, + days: { + hours: 24, + minutes: 24 * 60, + seconds: 24 * 60 * 60, + milliseconds: 24 * 60 * 60 * 1e3 + }, + hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 }, + minutes: { seconds: 60, milliseconds: 60 * 1e3 }, + seconds: { milliseconds: 1e3 } +}; +var casualMatrix = { + years: { + quarters: 4, + months: 12, + weeks: 52, + days: 365, + hours: 365 * 24, + minutes: 365 * 24 * 60, + seconds: 365 * 24 * 60 * 60, + milliseconds: 365 * 24 * 60 * 60 * 1e3 + }, + quarters: { + months: 3, + weeks: 13, + days: 91, + hours: 91 * 24, + minutes: 91 * 24 * 60, + seconds: 91 * 24 * 60 * 60, + milliseconds: 91 * 24 * 60 * 60 * 1e3 + }, + months: { + weeks: 4, + days: 30, + hours: 30 * 24, + minutes: 30 * 24 * 60, + seconds: 30 * 24 * 60 * 60, + milliseconds: 30 * 24 * 60 * 60 * 1e3 + }, + ...lowOrderMatrix +}; +var daysInYearAccurate = 146097 / 400; +var daysInMonthAccurate = 146097 / 4800; +var accurateMatrix = { + years: { + quarters: 4, + months: 12, + weeks: daysInYearAccurate / 7, + days: daysInYearAccurate, + hours: daysInYearAccurate * 24, + minutes: daysInYearAccurate * 24 * 60, + seconds: daysInYearAccurate * 24 * 60 * 60, + milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 + }, + quarters: { + months: 3, + weeks: daysInYearAccurate / 28, + days: daysInYearAccurate / 4, + hours: daysInYearAccurate * 24 / 4, + minutes: daysInYearAccurate * 24 * 60 / 4, + seconds: daysInYearAccurate * 24 * 60 * 60 / 4, + milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4 + }, + months: { + weeks: daysInMonthAccurate / 7, + days: daysInMonthAccurate, + hours: daysInMonthAccurate * 24, + minutes: daysInMonthAccurate * 24 * 60, + seconds: daysInMonthAccurate * 24 * 60 * 60, + milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3 + }, + ...lowOrderMatrix +}; +var orderedUnits = [ + "years", + "quarters", + "months", + "weeks", + "days", + "hours", + "minutes", + "seconds", + "milliseconds" +]; +var reverseUnits = orderedUnits.slice(0).reverse(); +function clone(dur, alts, clear = false) { + const conf = { + values: clear ? alts.values : { ...dur.values, ...alts.values || {} }, + loc: dur.loc.clone(alts.loc), + conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, + matrix: alts.matrix || dur.matrix + }; + return new Duration(conf); +} +function durationToMillis(matrix, vals) { + var _a; + let sum = (_a = vals.milliseconds) != null ? _a : 0; + for (const unit of reverseUnits.slice(1)) { + if (vals[unit]) { + sum += vals[unit] * matrix[unit]["milliseconds"]; + } + } + return sum; +} +function normalizeValues(matrix, vals) { + const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; + orderedUnits.reduceRight((previous, current) => { + if (!isUndefined(vals[current])) { + if (previous) { + const previousVal = vals[previous] * factor; + const conv = matrix[current][previous]; + const rollUp = Math.floor(previousVal / conv); + vals[current] += rollUp * factor; + vals[previous] -= rollUp * conv * factor; + } + return current; + } else { + return previous; + } + }, null); + orderedUnits.reduce((previous, current) => { + if (!isUndefined(vals[current])) { + if (previous) { + const fraction = vals[previous] % 1; + vals[previous] -= fraction; + vals[current] += fraction * matrix[previous][current]; + } + return current; + } else { + return previous; + } + }, null); +} +function removeZeroes(vals) { + const newVals = {}; + for (const [key, value] of Object.entries(vals)) { + if (value !== 0) { + newVals[key] = value; + } + } + return newVals; +} +var Duration = class _Duration { + /** + * @private + */ + constructor(config) { + const accurate = config.conversionAccuracy === "longterm" || false; + let matrix = accurate ? accurateMatrix : casualMatrix; + if (config.matrix) { + matrix = config.matrix; + } + this.values = config.values; + this.loc = config.loc || Locale.create(); + this.conversionAccuracy = accurate ? "longterm" : "casual"; + this.invalid = config.invalid || null; + this.matrix = matrix; + this.isLuxonDuration = true; + } + /** + * Create Duration from a number of milliseconds. + * @param {number} count of milliseconds + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @return {Duration} + */ + static fromMillis(count, opts) { + return _Duration.fromObject({ milliseconds: count }, opts); + } + /** + * Create a Duration from a JavaScript object with keys like 'years' and 'hours'. + * If this object is empty then a zero milliseconds duration is returned. + * @param {Object} obj - the object to create the DateTime from + * @param {number} obj.years + * @param {number} obj.quarters + * @param {number} obj.months + * @param {number} obj.weeks + * @param {number} obj.days + * @param {number} obj.hours + * @param {number} obj.minutes + * @param {number} obj.seconds + * @param {number} obj.milliseconds + * @param {Object} [opts=[]] - options for creating this Duration + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the custom conversion system to use + * @return {Duration} + */ + static fromObject(obj, opts = {}) { + if (obj == null || typeof obj !== "object") { + throw new InvalidArgumentError( + `Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}` + ); + } + return new _Duration({ + values: normalizeObject(obj, _Duration.normalizeUnit), + loc: Locale.fromObject(opts), + conversionAccuracy: opts.conversionAccuracy, + matrix: opts.matrix + }); + } + /** + * Create a Duration from DurationLike. + * + * @param {Object | number | Duration} durationLike + * One of: + * - object with keys like 'years' and 'hours'. + * - number representing milliseconds + * - Duration instance + * @return {Duration} + */ + static fromDurationLike(durationLike) { + if (isNumber(durationLike)) { + return _Duration.fromMillis(durationLike); + } else if (_Duration.isDuration(durationLike)) { + return durationLike; + } else if (typeof durationLike === "object") { + return _Duration.fromObject(durationLike); + } else { + throw new InvalidArgumentError( + `Unknown duration argument ${durationLike} of type ${typeof durationLike}` + ); + } + } + /** + * Create a Duration from an ISO 8601 duration string. + * @param {string} text - text to parse + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the preset conversion system to use + * @see https://en.wikipedia.org/wiki/ISO_8601#Durations + * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } + * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } + * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } + * @return {Duration} + */ + static fromISO(text2, opts) { + const [parsed] = parseISODuration(text2); + if (parsed) { + return _Duration.fromObject(parsed, opts); + } else { + return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); + } + } + /** + * Create a Duration from an ISO 8601 time string. + * @param {string} text - text to parse + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the conversion system to use + * @see https://en.wikipedia.org/wiki/ISO_8601#Times + * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } + * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @return {Duration} + */ + static fromISOTime(text2, opts) { + const [parsed] = parseISOTimeOnly(text2); + if (parsed) { + return _Duration.fromObject(parsed, opts); + } else { + return _Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); + } + } + /** + * Create an invalid Duration. + * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {Duration} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); + } + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { + throw new InvalidDurationError(invalid); + } else { + return new _Duration({ invalid }); + } + } + /** + * @private + */ + static normalizeUnit(unit) { + const normalized = { + year: "years", + years: "years", + quarter: "quarters", + quarters: "quarters", + month: "months", + months: "months", + week: "weeks", + weeks: "weeks", + day: "days", + days: "days", + hour: "hours", + hours: "hours", + minute: "minutes", + minutes: "minutes", + second: "seconds", + seconds: "seconds", + millisecond: "milliseconds", + milliseconds: "milliseconds" + }[unit ? unit.toLowerCase() : unit]; + if (!normalized) + throw new InvalidUnitError(unit); + return normalized; + } + /** + * Check if an object is a Duration. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isDuration(o) { + return o && o.isLuxonDuration || false; + } + /** + * Get the locale of a Duration, such 'en-GB' + * @type {string} + */ + get locale() { + return this.isValid ? this.loc.locale : null; + } + /** + * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration + * + * @type {string} + */ + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; + } + /** + * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: + * * `S` for milliseconds + * * `s` for seconds + * * `m` for minutes + * * `h` for hours + * * `d` for days + * * `w` for weeks + * * `M` for months + * * `y` for years + * Notes: + * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits + * * Tokens can be escaped by wrapping with single quotes. + * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting. + * @param {string} fmt - the format string + * @param {Object} opts - options + * @param {boolean} [opts.floor=true] - floor numerical values + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" + * @return {string} + */ + toFormat(fmt, opts = {}) { + const fmtOpts = { + ...opts, + floor: opts.round !== false && opts.floor !== false + }; + return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID2; + } + /** + * Returns a string representation of a Duration with all units included. + * To modify its behavior, use `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options + * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`. + * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor. + * @example + * ```js + * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 }) + * dur.toHuman() //=> '1 day, 5 hours, 6 minutes' + * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes' + * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min' + * ``` + */ + toHuman(opts = {}) { + if (!this.isValid) + return INVALID2; + const l2 = orderedUnits.map((unit) => { + const val = this.values[unit]; + if (isUndefined(val)) { + return null; + } + return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }).format(val); + }).filter((n2) => n2); + return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l2); + } + /** + * Returns a JavaScript object with this Duration's values. + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } + * @return {Object} + */ + toObject() { + if (!this.isValid) + return {}; + return { ...this.values }; + } + /** + * Returns an ISO 8601-compliant string representation of this Duration. + * @see https://en.wikipedia.org/wiki/ISO_8601#Durations + * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' + * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' + * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' + * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' + * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' + * @return {string} + */ + toISO() { + if (!this.isValid) + return null; + let s2 = "P"; + if (this.years !== 0) + s2 += this.years + "Y"; + if (this.months !== 0 || this.quarters !== 0) + s2 += this.months + this.quarters * 3 + "M"; + if (this.weeks !== 0) + s2 += this.weeks + "W"; + if (this.days !== 0) + s2 += this.days + "D"; + if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) + s2 += "T"; + if (this.hours !== 0) + s2 += this.hours + "H"; + if (this.minutes !== 0) + s2 += this.minutes + "M"; + if (this.seconds !== 0 || this.milliseconds !== 0) + s2 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S"; + if (s2 === "P") + s2 += "T0S"; + return s2; + } + /** + * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day. + * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours. + * @see https://en.wikipedia.org/wiki/ISO_8601#Times + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includePrefix=false] - include the `T` prefix + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' + * @return {string} + */ + toISOTime(opts = {}) { + if (!this.isValid) + return null; + const millis = this.toMillis(); + if (millis < 0 || millis >= 864e5) + return null; + opts = { + suppressMilliseconds: false, + suppressSeconds: false, + includePrefix: false, + format: "extended", + ...opts, + includeOffset: false + }; + const dateTime = DateTime.fromMillis(millis, { zone: "UTC" }); + return dateTime.toISOTime(opts); + } + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. + * @return {string} + */ + toJSON() { + return this.toISO(); + } + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. + * @return {string} + */ + toString() { + return this.toISO(); + } + /** + * Returns a string representation of this Duration appropriate for the REPL. + * @return {string} + */ + [Symbol.for("nodejs.util.inspect.custom")]() { + if (this.isValid) { + return `Duration { values: ${JSON.stringify(this.values)} }`; + } else { + return `Duration { Invalid, reason: ${this.invalidReason} }`; + } + } + /** + * Returns an milliseconds value of this Duration. + * @return {number} + */ + toMillis() { + if (!this.isValid) + return NaN; + return durationToMillis(this.matrix, this.values); + } + /** + * Returns an milliseconds value of this Duration. Alias of {@link toMillis} + * @return {number} + */ + valueOf() { + return this.toMillis(); + } + /** + * Make this Duration longer by the specified amount. Return a newly-constructed Duration. + * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @return {Duration} + */ + plus(duration) { + if (!this.isValid) + return this; + const dur = _Duration.fromDurationLike(duration), result = {}; + for (const k of orderedUnits) { + if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { + result[k] = dur.get(k) + this.get(k); + } + } + return clone(this, { values: result }, true); + } + /** + * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. + * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @return {Duration} + */ + minus(duration) { + if (!this.isValid) + return this; + const dur = _Duration.fromDurationLike(duration); + return this.plus(dur.negate()); + } + /** + * Scale this Duration by the specified amount. Return a newly-constructed Duration. + * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. + * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 } + * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 } + * @return {Duration} + */ + mapUnits(fn) { + if (!this.isValid) + return this; + const result = {}; + for (const k of Object.keys(this.values)) { + result[k] = asNumber(fn(this.values[k], k)); + } + return clone(this, { values: result }, true); + } + /** + * Get the value of unit. + * @param {string} unit - a unit such as 'minute' or 'day' + * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2 + * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0 + * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3 + * @return {number} + */ + get(unit) { + return this[_Duration.normalizeUnit(unit)]; + } + /** + * "Set" the values of specified units. Return a newly-constructed Duration. + * @param {Object} values - a mapping of units to numbers + * @example dur.set({ years: 2017 }) + * @example dur.set({ hours: 8, minutes: 30 }) + * @return {Duration} + */ + set(values) { + if (!this.isValid) + return this; + const mixed = { ...this.values, ...normalizeObject(values, _Duration.normalizeUnit) }; + return clone(this, { values: mixed }); + } + /** + * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. + * @example dur.reconfigure({ locale: 'en-GB' }) + * @return {Duration} + */ + reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) { + const loc = this.loc.clone({ locale, numberingSystem }); + const opts = { loc, matrix, conversionAccuracy }; + return clone(this, opts); + } + /** + * Return the length of the duration in the specified unit. + * @param {string} unit - a unit such as 'minutes' or 'days' + * @example Duration.fromObject({years: 1}).as('days') //=> 365 + * @example Duration.fromObject({years: 1}).as('months') //=> 12 + * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 + * @return {number} + */ + as(unit) { + return this.isValid ? this.shiftTo(unit).get(unit) : NaN; + } + /** + * Reduce this Duration to its canonical representation in its current units. + * Assuming the overall value of the Duration is positive, this means: + * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example) + * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise + * the overall value would be negative, see third example) + * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example) + * + * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`. + * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } + * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 } + * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } + * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 } + * @return {Duration} + */ + normalize() { + if (!this.isValid) + return this; + const vals = this.toObject(); + normalizeValues(this.matrix, vals); + return clone(this, { values: vals }, true); + } + /** + * Rescale units to its largest representation + * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 } + * @return {Duration} + */ + rescale() { + if (!this.isValid) + return this; + const vals = removeZeroes(this.normalize().shiftToAll().toObject()); + return clone(this, { values: vals }, true); + } + /** + * Convert this Duration into its representation in a different set of units. + * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } + * @return {Duration} + */ + shiftTo(...units) { + if (!this.isValid) + return this; + if (units.length === 0) { + return this; + } + units = units.map((u) => _Duration.normalizeUnit(u)); + const built = {}, accumulated = {}, vals = this.toObject(); + let lastUnit; + for (const k of orderedUnits) { + if (units.indexOf(k) >= 0) { + lastUnit = k; + let own = 0; + for (const ak in accumulated) { + own += this.matrix[ak][k] * accumulated[ak]; + accumulated[ak] = 0; + } + if (isNumber(vals[k])) { + own += vals[k]; + } + const i = Math.trunc(own); + built[k] = i; + accumulated[k] = (own * 1e3 - i * 1e3) / 1e3; + } else if (isNumber(vals[k])) { + accumulated[k] = vals[k]; + } + } + for (const key in accumulated) { + if (accumulated[key] !== 0) { + built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; + } + } + normalizeValues(this.matrix, built); + return clone(this, { values: built }, true); + } + /** + * Shift this Duration to all available units. + * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds") + * @return {Duration} + */ + shiftToAll() { + if (!this.isValid) + return this; + return this.shiftTo( + "years", + "months", + "weeks", + "days", + "hours", + "minutes", + "seconds", + "milliseconds" + ); + } + /** + * Return the negative of this Duration. + * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } + * @return {Duration} + */ + negate() { + if (!this.isValid) + return this; + const negated = {}; + for (const k of Object.keys(this.values)) { + negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; + } + return clone(this, { values: negated }, true); + } + /** + * Get the years. + * @type {number} + */ + get years() { + return this.isValid ? this.values.years || 0 : NaN; + } + /** + * Get the quarters. + * @type {number} + */ + get quarters() { + return this.isValid ? this.values.quarters || 0 : NaN; + } + /** + * Get the months. + * @type {number} + */ + get months() { + return this.isValid ? this.values.months || 0 : NaN; + } + /** + * Get the weeks + * @type {number} + */ + get weeks() { + return this.isValid ? this.values.weeks || 0 : NaN; + } + /** + * Get the days. + * @type {number} + */ + get days() { + return this.isValid ? this.values.days || 0 : NaN; + } + /** + * Get the hours. + * @type {number} + */ + get hours() { + return this.isValid ? this.values.hours || 0 : NaN; + } + /** + * Get the minutes. + * @type {number} + */ + get minutes() { + return this.isValid ? this.values.minutes || 0 : NaN; + } + /** + * Get the seconds. + * @return {number} + */ + get seconds() { + return this.isValid ? this.values.seconds || 0 : NaN; + } + /** + * Get the milliseconds. + * @return {number} + */ + get milliseconds() { + return this.isValid ? this.values.milliseconds || 0 : NaN; + } + /** + * Returns whether the Duration is invalid. Invalid durations are returned by diff operations + * on invalid DateTimes or Intervals. + * @return {boolean} + */ + get isValid() { + return this.invalid === null; + } + /** + * Returns an error code if this Duration became invalid, or null if the Duration is valid + * @return {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + /** + * Returns an explanation of why this Duration became invalid, or null if the Duration is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + /** + * Equality check + * Two Durations are equal iff they have the same units and the same values for each unit. + * @param {Duration} other + * @return {boolean} + */ + equals(other) { + if (!this.isValid || !other.isValid) { + return false; + } + if (!this.loc.equals(other.loc)) { + return false; + } + function eq(v1, v2) { + if (v1 === void 0 || v1 === 0) + return v2 === void 0 || v2 === 0; + return v1 === v2; + } + for (const u of orderedUnits) { + if (!eq(this.values[u], other.values[u])) { + return false; + } + } + return true; + } +}; + +// node_modules/luxon/src/interval.js +var INVALID3 = "Invalid Interval"; +function validateStartEnd(start, end) { + if (!start || !start.isValid) { + return Interval.invalid("missing or invalid start"); + } else if (!end || !end.isValid) { + return Interval.invalid("missing or invalid end"); + } else if (end < start) { + return Interval.invalid( + "end before start", + `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}` + ); + } else { + return null; + } +} +var Interval = class _Interval { + /** + * @private + */ + constructor(config) { + this.s = config.start; + this.e = config.end; + this.invalid = config.invalid || null; + this.isLuxonInterval = true; + } + /** + * Create an invalid Interval. + * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {Interval} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); + } + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { + throw new InvalidIntervalError(invalid); + } else { + return new _Interval({ invalid }); + } + } + /** + * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. + * @param {DateTime|Date|Object} start + * @param {DateTime|Date|Object} end + * @return {Interval} + */ + static fromDateTimes(start, end) { + const builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); + const validateError = validateStartEnd(builtStart, builtEnd); + if (validateError == null) { + return new _Interval({ + start: builtStart, + end: builtEnd + }); + } else { + return validateError; + } + } + /** + * Create an Interval from a start DateTime and a Duration to extend to. + * @param {DateTime|Date|Object} start + * @param {Duration|Object|number} duration - the length of the Interval. + * @return {Interval} + */ + static after(start, duration) { + const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start); + return _Interval.fromDateTimes(dt, dt.plus(dur)); + } + /** + * Create an Interval from an end DateTime and a Duration to extend backwards to. + * @param {DateTime|Date|Object} end + * @param {Duration|Object|number} duration - the length of the Interval. + * @return {Interval} + */ + static before(end, duration) { + const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end); + return _Interval.fromDateTimes(dt.minus(dur), dt); + } + /** + * Create an Interval from an ISO 8601 string. + * Accepts `/`, `/`, and `/` formats. + * @param {string} text - the ISO string to parse + * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO} + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @return {Interval} + */ + static fromISO(text2, opts) { + const [s2, e] = (text2 || "").split("/", 2); + if (s2 && e) { + let start, startIsValid; + try { + start = DateTime.fromISO(s2, opts); + startIsValid = start.isValid; + } catch (e2) { + startIsValid = false; + } + let end, endIsValid; + try { + end = DateTime.fromISO(e, opts); + endIsValid = end.isValid; + } catch (e2) { + endIsValid = false; + } + if (startIsValid && endIsValid) { + return _Interval.fromDateTimes(start, end); + } + if (startIsValid) { + const dur = Duration.fromISO(e, opts); + if (dur.isValid) { + return _Interval.after(start, dur); + } + } else if (endIsValid) { + const dur = Duration.fromISO(s2, opts); + if (dur.isValid) { + return _Interval.before(end, dur); + } + } + } + return _Interval.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); + } + /** + * Check if an object is an Interval. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isInterval(o) { + return o && o.isLuxonInterval || false; + } + /** + * Returns the start of the Interval + * @type {DateTime} + */ + get start() { + return this.isValid ? this.s : null; + } + /** + * Returns the end of the Interval + * @type {DateTime} + */ + get end() { + return this.isValid ? this.e : null; + } + /** + * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'. + * @type {boolean} + */ + get isValid() { + return this.invalidReason === null; + } + /** + * Returns an error code if this Interval is invalid, or null if the Interval is valid + * @type {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + /** + * Returns an explanation of why this Interval became invalid, or null if the Interval is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + /** + * Returns the length of the Interval in the specified unit. + * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in. + * @return {number} + */ + length(unit = "milliseconds") { + return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; + } + /** + * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. + * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' + * asks 'what dates are included in this interval?', not 'how many days long is this interval?' + * @param {string} [unit='milliseconds'] - the unit of time to count. + * @param {Object} opts - options + * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime + * @return {number} + */ + count(unit = "milliseconds", opts) { + if (!this.isValid) + return NaN; + const start = this.start.startOf(unit, opts); + let end; + if (opts == null ? void 0 : opts.useLocaleWeeks) { + end = this.end.reconfigure({ locale: start.locale }); + } else { + end = this.end; + } + end = end.startOf(unit, opts); + return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf()); + } + /** + * Returns whether this Interval's start and end are both in the same unit of time + * @param {string} unit - the unit of time to check sameness on + * @return {boolean} + */ + hasSame(unit) { + return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; + } + /** + * Return whether this Interval has the same start and end DateTimes. + * @return {boolean} + */ + isEmpty() { + return this.s.valueOf() === this.e.valueOf(); + } + /** + * Return whether this Interval's start is after the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isAfter(dateTime) { + if (!this.isValid) + return false; + return this.s > dateTime; + } + /** + * Return whether this Interval's end is before the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isBefore(dateTime) { + if (!this.isValid) + return false; + return this.e <= dateTime; + } + /** + * Return whether this Interval contains the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + contains(dateTime) { + if (!this.isValid) + return false; + return this.s <= dateTime && this.e > dateTime; + } + /** + * "Sets" the start and/or end dates. Returns a newly-constructed Interval. + * @param {Object} values - the values to set + * @param {DateTime} values.start - the starting DateTime + * @param {DateTime} values.end - the ending DateTime + * @return {Interval} + */ + set({ start, end } = {}) { + if (!this.isValid) + return this; + return _Interval.fromDateTimes(start || this.s, end || this.e); + } + /** + * Split this Interval at each of the specified DateTimes + * @param {...DateTime} dateTimes - the unit of time to count. + * @return {Array} + */ + splitAt(...dateTimes) { + if (!this.isValid) + return []; + const sorted = dateTimes.map(friendlyDateTime).filter((d) => this.contains(d)).sort((a, b) => a.toMillis() - b.toMillis()), results = []; + let { s: s2 } = this, i = 0; + while (s2 < this.e) { + const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; + results.push(_Interval.fromDateTimes(s2, next)); + s2 = next; + i += 1; + } + return results; + } + /** + * Split this Interval into smaller Intervals, each of the specified length. + * Left over time is grouped into a smaller interval + * @param {Duration|Object|number} duration - The length of each resulting interval. + * @return {Array} + */ + splitBy(duration) { + const dur = Duration.fromDurationLike(duration); + if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { + return []; + } + let { s: s2 } = this, idx = 1, next; + const results = []; + while (s2 < this.e) { + const added = this.start.plus(dur.mapUnits((x) => x * idx)); + next = +added > +this.e ? this.e : added; + results.push(_Interval.fromDateTimes(s2, next)); + s2 = next; + idx += 1; + } + return results; + } + /** + * Split this Interval into the specified number of smaller intervals. + * @param {number} numberOfParts - The number of Intervals to divide the Interval into. + * @return {Array} + */ + divideEqually(numberOfParts) { + if (!this.isValid) + return []; + return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); + } + /** + * Return whether this Interval overlaps with the specified Interval + * @param {Interval} other + * @return {boolean} + */ + overlaps(other) { + return this.e > other.s && this.s < other.e; + } + /** + * Return whether this Interval's end is adjacent to the specified Interval's start. + * @param {Interval} other + * @return {boolean} + */ + abutsStart(other) { + if (!this.isValid) + return false; + return +this.e === +other.s; + } + /** + * Return whether this Interval's start is adjacent to the specified Interval's end. + * @param {Interval} other + * @return {boolean} + */ + abutsEnd(other) { + if (!this.isValid) + return false; + return +other.e === +this.s; + } + /** + * Return whether this Interval engulfs the start and end of the specified Interval. + * @param {Interval} other + * @return {boolean} + */ + engulfs(other) { + if (!this.isValid) + return false; + return this.s <= other.s && this.e >= other.e; + } + /** + * Return whether this Interval has the same start and end as the specified Interval. + * @param {Interval} other + * @return {boolean} + */ + equals(other) { + if (!this.isValid || !other.isValid) { + return false; + } + return this.s.equals(other.s) && this.e.equals(other.e); + } + /** + * Return an Interval representing the intersection of this Interval and the specified Interval. + * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. + * Returns null if the intersection is empty, meaning, the intervals don't intersect. + * @param {Interval} other + * @return {Interval} + */ + intersection(other) { + if (!this.isValid) + return this; + const s2 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; + if (s2 >= e) { + return null; + } else { + return _Interval.fromDateTimes(s2, e); + } + } + /** + * Return an Interval representing the union of this Interval and the specified Interval. + * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. + * @param {Interval} other + * @return {Interval} + */ + union(other) { + if (!this.isValid) + return this; + const s2 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; + return _Interval.fromDateTimes(s2, e); + } + /** + * Merge an array of Intervals into a equivalent minimal set of Intervals. + * Combines overlapping and adjacent Intervals. + * @param {Array} intervals + * @return {Array} + */ + static merge(intervals) { + const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce( + ([sofar, current], item) => { + if (!current) { + return [sofar, item]; + } else if (current.overlaps(item) || current.abutsStart(item)) { + return [sofar, current.union(item)]; + } else { + return [sofar.concat([current]), item]; + } + }, + [[], null] + ); + if (final) { + found.push(final); + } + return found; + } + /** + * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. + * @param {Array} intervals + * @return {Array} + */ + static xor(intervals) { + let start = null, currentCount = 0; + const results = [], ends = intervals.map((i) => [ + { time: i.s, type: "s" }, + { time: i.e, type: "e" } + ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time); + for (const i of arr) { + currentCount += i.type === "s" ? 1 : -1; + if (currentCount === 1) { + start = i.time; + } else { + if (start && +start !== +i.time) { + results.push(_Interval.fromDateTimes(start, i.time)); + } + start = null; + } + } + return _Interval.merge(results); + } + /** + * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. + * @param {...Interval} intervals + * @return {Array} + */ + difference(...intervals) { + return _Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty()); + } + /** + * Returns a string representation of this Interval appropriate for debugging. + * @return {string} + */ + toString() { + if (!this.isValid) + return INVALID3; + return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`; + } + /** + * Returns a string representation of this Interval appropriate for the REPL. + * @return {string} + */ + [Symbol.for("nodejs.util.inspect.custom")]() { + if (this.isValid) { + return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`; + } else { + return `Interval { Invalid, reason: ${this.invalidReason} }`; + } + } + /** + * Returns a localized string representing this Interval. Accepts the same options as the + * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as + * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method + * is browser-specific, but in general it will return an appropriate representation of the + * Interval in the assigned locale. Defaults to the system's locale if no locale has been + * specified. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or + * Intl.DateTimeFormat constructor options. + * @param {Object} opts - Options to override the configuration of the start DateTime. + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022 + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022 + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022 + * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM + * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p + * @return {string} + */ + toLocaleString(formatOpts = DATE_SHORT, opts = {}) { + return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID3; + } + /** + * Returns an ISO 8601-compliant string representation of this Interval. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @param {Object} opts - The same options as {@link DateTime#toISO} + * @return {string} + */ + toISO(opts) { + if (!this.isValid) + return INVALID3; + return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; + } + /** + * Returns an ISO 8601-compliant string representation of date of this Interval. + * The time components are ignored. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @return {string} + */ + toISODate() { + if (!this.isValid) + return INVALID3; + return `${this.s.toISODate()}/${this.e.toISODate()}`; + } + /** + * Returns an ISO 8601-compliant string representation of time of this Interval. + * The date components are ignored. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @param {Object} opts - The same options as {@link DateTime#toISO} + * @return {string} + */ + toISOTime(opts) { + if (!this.isValid) + return INVALID3; + return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; + } + /** + * Returns a string representation of this Interval formatted according to the specified format + * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible + * formatting tool. + * @param {string} dateFormat - The format string. This string formats the start and end time. + * See {@link DateTime#toFormat} for details. + * @param {Object} opts - Options. + * @param {string} [opts.separator = ' – '] - A separator to place between the start and end + * representations. + * @return {string} + */ + toFormat(dateFormat, { separator = " \u2013 " } = {}) { + if (!this.isValid) + return INVALID3; + return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; + } + /** + * Return a Duration representing the time spanned by this interval. + * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } + * @return {Duration} + */ + toDuration(unit, opts) { + if (!this.isValid) { + return Duration.invalid(this.invalidReason); + } + return this.e.diff(this.s, unit, opts); + } + /** + * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes + * @param {function} mapFn + * @return {Interval} + * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) + * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) + */ + mapEndpoints(mapFn) { + return _Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); + } +}; + +// node_modules/luxon/src/info.js +var Info = class { + /** + * Return whether the specified zone contains a DST. + * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. + * @return {boolean} + */ + static hasDST(zone = Settings.defaultZone) { + const proto = DateTime.now().setZone(zone).set({ month: 12 }); + return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; + } + /** + * Return whether the specified zone is a valid IANA specifier. + * @param {string} zone - Zone to check + * @return {boolean} + */ + static isValidIANAZone(zone) { + return IANAZone.isValidZone(zone); + } + /** + * Converts the input into a {@link Zone} instance. + * + * * If `input` is already a Zone instance, it is returned unchanged. + * * If `input` is a string containing a valid time zone name, a Zone instance + * with that name is returned. + * * If `input` is a string that doesn't refer to a known time zone, a Zone + * instance with {@link Zone#isValid} == false is returned. + * * If `input is a number, a Zone instance with the specified fixed offset + * in minutes is returned. + * * If `input` is `null` or `undefined`, the default zone is returned. + * @param {string|Zone|number} [input] - the value to be converted + * @return {Zone} + */ + static normalizeZone(input) { + return normalizeZone(input, Settings.defaultZone); + } + /** + * Get the weekday on which the week starts according to the given locale. + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.locObj=null] - an existing locale object to use + * @returns {number} the start of the week, 1 for Monday through 7 for Sunday + */ + static getStartOfWeek({ locale = null, locObj = null } = {}) { + return (locObj || Locale.create(locale)).getStartOfWeek(); + } + /** + * Get the minimum number of days necessary in a week before it is considered part of the next year according + * to the given locale. + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.locObj=null] - an existing locale object to use + * @returns {number} + */ + static getMinimumDaysInFirstWeek({ locale = null, locObj = null } = {}) { + return (locObj || Locale.create(locale)).getMinDaysInFirstWeek(); + } + /** + * Get the weekdays, which are considered the weekend according to the given locale + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.locObj=null] - an existing locale object to use + * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday + */ + static getWeekendWeekdays({ locale = null, locObj = null } = {}) { + return (locObj || Locale.create(locale)).getWeekendDays().slice(); + } + /** + * Return an array of standalone month names. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @param {string} [opts.outputCalendar='gregory'] - the calendar + * @example Info.months()[0] //=> 'January' + * @example Info.months('short')[0] //=> 'Jan' + * @example Info.months('numeric')[0] //=> '1' + * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' + * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' + * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' + * @return {Array} + */ + static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { + return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); + } + /** + * Return an array of format month names. + * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that + * changes the string. + * See {@link Info#months} + * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @param {string} [opts.outputCalendar='gregory'] - the calendar + * @return {Array} + */ + static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { + return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); + } + /** + * Return an array of standalone week names. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @example Info.weekdays()[0] //=> 'Monday' + * @example Info.weekdays('short')[0] //=> 'Mon' + * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' + * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' + * @return {Array} + */ + static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { + return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); + } + /** + * Return an array of format week names. + * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that + * changes the string. + * See {@link Info#weekdays} + * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". + * @param {Object} opts - options + * @param {string} [opts.locale=null] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @return {Array} + */ + static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { + return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); + } + /** + * Return an array of meridiems. + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @example Info.meridiems() //=> [ 'AM', 'PM' ] + * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] + * @return {Array} + */ + static meridiems({ locale = null } = {}) { + return Locale.create(locale).meridiems(); + } + /** + * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. + * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @example Info.eras() //=> [ 'BC', 'AD' ] + * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] + * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] + * @return {Array} + */ + static eras(length = "short", { locale = null } = {}) { + return Locale.create(locale, null, "gregory").eras(length); + } + /** + * Return the set of available features in this environment. + * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case. + * Keys: + * * `relative`: whether this environment supports relative time formatting + * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale + * @example Info.features() //=> { relative: false, localeWeek: true } + * @return {Object} + */ + static features() { + return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() }; + } +}; + +// node_modules/luxon/src/impl/diff.js +function dayDiff(earlier, later) { + const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier); + return Math.floor(Duration.fromMillis(ms).as("days")); +} +function highOrderDiffs(cursor, later, units) { + const differs = [ + ["years", (a, b) => b.year - a.year], + ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], + ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], + [ + "weeks", + (a, b) => { + const days = dayDiff(a, b); + return (days - days % 7) / 7; + } + ], + ["days", dayDiff] + ]; + const results = {}; + const earlier = cursor; + let lowestOrder, highWater; + for (const [unit, differ] of differs) { + if (units.indexOf(unit) >= 0) { + lowestOrder = unit; + results[unit] = differ(cursor, later); + highWater = earlier.plus(results); + if (highWater > later) { + results[unit]--; + cursor = earlier.plus(results); + if (cursor > later) { + highWater = cursor; + results[unit]--; + cursor = earlier.plus(results); + } + } else { + cursor = highWater; + } + } + } + return [cursor, results, highWater, lowestOrder]; +} +function diff_default(earlier, later, units, opts) { + let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units); + const remainingMillis = later - cursor; + const lowerOrderUnits = units.filter( + (u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0 + ); + if (lowerOrderUnits.length === 0) { + if (highWater < later) { + highWater = cursor.plus({ [lowestOrder]: 1 }); + } + if (highWater !== cursor) { + results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); + } + } + const duration = Duration.fromObject(results, opts); + if (lowerOrderUnits.length > 0) { + return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration); + } else { + return duration; + } +} + +// node_modules/luxon/src/impl/digits.js +var numberingSystems = { + arab: "[\u0660-\u0669]", + arabext: "[\u06F0-\u06F9]", + bali: "[\u1B50-\u1B59]", + beng: "[\u09E6-\u09EF]", + deva: "[\u0966-\u096F]", + fullwide: "[\uFF10-\uFF19]", + gujr: "[\u0AE6-\u0AEF]", + hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]", + khmr: "[\u17E0-\u17E9]", + knda: "[\u0CE6-\u0CEF]", + laoo: "[\u0ED0-\u0ED9]", + limb: "[\u1946-\u194F]", + mlym: "[\u0D66-\u0D6F]", + mong: "[\u1810-\u1819]", + mymr: "[\u1040-\u1049]", + orya: "[\u0B66-\u0B6F]", + tamldec: "[\u0BE6-\u0BEF]", + telu: "[\u0C66-\u0C6F]", + thai: "[\u0E50-\u0E59]", + tibt: "[\u0F20-\u0F29]", + latn: "\\d" +}; +var numberingSystemsUTF16 = { + arab: [1632, 1641], + arabext: [1776, 1785], + bali: [6992, 7001], + beng: [2534, 2543], + deva: [2406, 2415], + fullwide: [65296, 65303], + gujr: [2790, 2799], + khmr: [6112, 6121], + knda: [3302, 3311], + laoo: [3792, 3801], + limb: [6470, 6479], + mlym: [3430, 3439], + mong: [6160, 6169], + mymr: [4160, 4169], + orya: [2918, 2927], + tamldec: [3046, 3055], + telu: [3174, 3183], + thai: [3664, 3673], + tibt: [3872, 3881] +}; +var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); +function parseDigits(str) { + let value = parseInt(str, 10); + if (isNaN(value)) { + value = ""; + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + if (str[i].search(numberingSystems.hanidec) !== -1) { + value += hanidecChars.indexOf(str[i]); + } else { + for (const key in numberingSystemsUTF16) { + const [min, max] = numberingSystemsUTF16[key]; + if (code >= min && code <= max) { + value += code - min; + } + } + } + } + return parseInt(value, 10); + } else { + return value; + } +} +function digitRegex({ numberingSystem }, append2 = "") { + return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append2}`); +} + +// node_modules/luxon/src/impl/tokenParser.js +var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; +function intUnit(regex2, post = (i) => i) { + return { regex: regex2, deser: ([s2]) => post(parseDigits(s2)) }; +} +var NBSP = String.fromCharCode(160); +var spaceOrNBSP = `[ ${NBSP}]`; +var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); +function fixListRegex(s2) { + return s2.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); +} +function stripInsensitivities(s2) { + return s2.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); +} +function oneOf(strings, startIndex) { + if (strings === null) { + return null; + } else { + return { + regex: RegExp(strings.map(fixListRegex).join("|")), + deser: ([s2]) => strings.findIndex((i) => stripInsensitivities(s2) === stripInsensitivities(i)) + startIndex + }; + } +} +function offset(regex2, groups) { + return { regex: regex2, deser: ([, h, m]) => signedOffset(h, m), groups }; +} +function simple(regex2) { + return { regex: regex2, deser: ([s2]) => s2 }; +} +function escapeToken(value) { + return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); +} +function unitForToken(token, loc) { + const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s2]) => s2, literal: true }), unitate = (t) => { + if (token.literal) { + return literal(t); + } + switch (t.val) { + case "G": + return oneOf(loc.eras("short"), 0); + case "GG": + return oneOf(loc.eras("long"), 0); + case "y": + return intUnit(oneToSix); + case "yy": + return intUnit(twoToFour, untruncateYear); + case "yyyy": + return intUnit(four); + case "yyyyy": + return intUnit(fourToSix); + case "yyyyyy": + return intUnit(six); + case "M": + return intUnit(oneOrTwo); + case "MM": + return intUnit(two); + case "MMM": + return oneOf(loc.months("short", true), 1); + case "MMMM": + return oneOf(loc.months("long", true), 1); + case "L": + return intUnit(oneOrTwo); + case "LL": + return intUnit(two); + case "LLL": + return oneOf(loc.months("short", false), 1); + case "LLLL": + return oneOf(loc.months("long", false), 1); + case "d": + return intUnit(oneOrTwo); + case "dd": + return intUnit(two); + case "o": + return intUnit(oneToThree); + case "ooo": + return intUnit(three); + case "HH": + return intUnit(two); + case "H": + return intUnit(oneOrTwo); + case "hh": + return intUnit(two); + case "h": + return intUnit(oneOrTwo); + case "mm": + return intUnit(two); + case "m": + return intUnit(oneOrTwo); + case "q": + return intUnit(oneOrTwo); + case "qq": + return intUnit(two); + case "s": + return intUnit(oneOrTwo); + case "ss": + return intUnit(two); + case "S": + return intUnit(oneToThree); + case "SSS": + return intUnit(three); + case "u": + return simple(oneToNine); + case "uu": + return simple(oneOrTwo); + case "uuu": + return intUnit(one); + case "a": + return oneOf(loc.meridiems(), 0); + case "kkkk": + return intUnit(four); + case "kk": + return intUnit(twoToFour, untruncateYear); + case "W": + return intUnit(oneOrTwo); + case "WW": + return intUnit(two); + case "E": + case "c": + return intUnit(one); + case "EEE": + return oneOf(loc.weekdays("short", false), 1); + case "EEEE": + return oneOf(loc.weekdays("long", false), 1); + case "ccc": + return oneOf(loc.weekdays("short", true), 1); + case "cccc": + return oneOf(loc.weekdays("long", true), 1); + case "Z": + case "ZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); + case "ZZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); + case "z": + return simple(/[a-z_+-/]{1,256}?/i); + case " ": + return simple(/[^\S\n\r]/); + default: + return literal(t); + } + }; + const unit = unitate(token) || { + invalidReason: MISSING_FTP + }; + unit.token = token; + return unit; +} +var partTypeStyleToTokenVal = { + year: { + "2-digit": "yy", + numeric: "yyyyy" + }, + month: { + numeric: "M", + "2-digit": "MM", + short: "MMM", + long: "MMMM" + }, + day: { + numeric: "d", + "2-digit": "dd" + }, + weekday: { + short: "EEE", + long: "EEEE" + }, + dayperiod: "a", + dayPeriod: "a", + hour12: { + numeric: "h", + "2-digit": "hh" + }, + hour24: { + numeric: "H", + "2-digit": "HH" + }, + minute: { + numeric: "m", + "2-digit": "mm" + }, + second: { + numeric: "s", + "2-digit": "ss" + }, + timeZoneName: { + long: "ZZZZZ", + short: "ZZZ" + } +}; +function tokenForPart(part, formatOpts, resolvedOpts) { + const { type, value } = part; + if (type === "literal") { + const isSpace = /^\s+$/.test(value); + return { + literal: !isSpace, + val: isSpace ? " " : value + }; + } + const style = formatOpts[type]; + let actualType = type; + if (type === "hour") { + if (formatOpts.hour12 != null) { + actualType = formatOpts.hour12 ? "hour12" : "hour24"; + } else if (formatOpts.hourCycle != null) { + if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") { + actualType = "hour12"; + } else { + actualType = "hour24"; + } + } else { + actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; + } + } + let val = partTypeStyleToTokenVal[actualType]; + if (typeof val === "object") { + val = val[style]; + } + if (val) { + return { + literal: false, + val + }; + } + return void 0; +} +function buildRegex(units) { + const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); + return [`^${re}$`, units]; +} +function match(input, regex2, handlers) { + const matches = input.match(regex2); + if (matches) { + const all = {}; + let matchIndex = 1; + for (const i in handlers) { + if (hasOwnProperty(handlers, i)) { + const h = handlers[i], groups = h.groups ? h.groups + 1 : 1; + if (!h.literal && h.token) { + all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); + } + matchIndex += groups; + } + } + return [matches, all]; + } else { + return [matches, {}]; + } +} +function dateTimeFromMatches(matches) { + const toField = (token) => { + switch (token) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + case "H": + return "hour"; + case "d": + return "day"; + case "o": + return "ordinal"; + case "L": + case "M": + return "month"; + case "y": + return "year"; + case "E": + case "c": + return "weekday"; + case "W": + return "weekNumber"; + case "k": + return "weekYear"; + case "q": + return "quarter"; + default: + return null; + } + }; + let zone = null; + let specificOffset; + if (!isUndefined(matches.z)) { + zone = IANAZone.create(matches.z); + } + if (!isUndefined(matches.Z)) { + if (!zone) { + zone = new FixedOffsetZone(matches.Z); + } + specificOffset = matches.Z; + } + if (!isUndefined(matches.q)) { + matches.M = (matches.q - 1) * 3 + 1; + } + if (!isUndefined(matches.h)) { + if (matches.h < 12 && matches.a === 1) { + matches.h += 12; + } else if (matches.h === 12 && matches.a === 0) { + matches.h = 0; + } + } + if (matches.G === 0 && matches.y) { + matches.y = -matches.y; + } + if (!isUndefined(matches.u)) { + matches.S = parseMillis(matches.u); + } + const vals = Object.keys(matches).reduce((r, k) => { + const f = toField(k); + if (f) { + r[f] = matches[k]; + } + return r; + }, {}); + return [vals, zone, specificOffset]; +} +var dummyDateTimeCache = null; +function getDummyDateTime() { + if (!dummyDateTimeCache) { + dummyDateTimeCache = DateTime.fromMillis(1555555555555); + } + return dummyDateTimeCache; +} +function maybeExpandMacroToken(token, locale) { + if (token.literal) { + return token; + } + const formatOpts = Formatter.macroTokenToFormatOpts(token.val); + const tokens = formatOptsToTokens(formatOpts, locale); + if (tokens == null || tokens.includes(void 0)) { + return token; + } + return tokens; +} +function expandMacroTokens(tokens, locale) { + return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale))); +} +function explainFromTokens(locale, input, format) { + const tokens = expandMacroTokens(Formatter.parseFormat(format), locale), units = tokens.map((t) => unitForToken(t, locale)), disqualifyingUnit = units.find((t) => t.invalidReason); + if (disqualifyingUnit) { + return { input, tokens, invalidReason: disqualifyingUnit.invalidReason }; + } else { + const [regexString, handlers] = buildRegex(units), regex2 = RegExp(regexString, "i"), [rawMatches, matches] = match(input, regex2, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0]; + if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { + throw new ConflictingSpecificationError( + "Can't include meridiem when specifying 24-hour format" + ); + } + return { input, tokens, regex: regex2, rawMatches, matches, result, zone, specificOffset }; + } +} +function parseFromTokens(locale, input, format) { + const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format); + return [result, zone, specificOffset, invalidReason]; +} +function formatOptsToTokens(formatOpts, locale) { + if (!formatOpts) { + return null; + } + const formatter = Formatter.create(locale, formatOpts); + const df = formatter.dtFormatter(getDummyDateTime()); + const parts = df.formatToParts(); + const resolvedOpts = df.resolvedOptions(); + return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts)); +} + +// node_modules/luxon/src/datetime.js +var INVALID4 = "Invalid DateTime"; +var MAX_DATE = 864e13; +function unsupportedZone(zone) { + return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); +} +function possiblyCachedWeekData(dt) { + if (dt.weekData === null) { + dt.weekData = gregorianToWeek(dt.c); + } + return dt.weekData; +} +function possiblyCachedLocalWeekData(dt) { + if (dt.localWeekData === null) { + dt.localWeekData = gregorianToWeek( + dt.c, + dt.loc.getMinDaysInFirstWeek(), + dt.loc.getStartOfWeek() + ); + } + return dt.localWeekData; +} +function clone2(inst, alts) { + const current = { + ts: inst.ts, + zone: inst.zone, + c: inst.c, + o: inst.o, + loc: inst.loc, + invalid: inst.invalid + }; + return new DateTime({ ...current, ...alts, old: current }); +} +function fixOffset(localTS, o, tz) { + let utcGuess = localTS - o * 60 * 1e3; + const o2 = tz.offset(utcGuess); + if (o === o2) { + return [utcGuess, o]; + } + utcGuess -= (o2 - o) * 60 * 1e3; + const o3 = tz.offset(utcGuess); + if (o2 === o3) { + return [utcGuess, o2]; + } + return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)]; +} +function tsToObj(ts, offset2) { + ts += offset2 * 60 * 1e3; + const d = new Date(ts); + return { + year: d.getUTCFullYear(), + month: d.getUTCMonth() + 1, + day: d.getUTCDate(), + hour: d.getUTCHours(), + minute: d.getUTCMinutes(), + second: d.getUTCSeconds(), + millisecond: d.getUTCMilliseconds() + }; +} +function objToTS(obj, offset2, zone) { + return fixOffset(objToLocalTS(obj), offset2, zone); +} +function adjustTime(inst, dur) { + const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = { + ...inst.c, + year, + month, + day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 + }, millisToAdd = Duration.fromObject({ + years: dur.years - Math.trunc(dur.years), + quarters: dur.quarters - Math.trunc(dur.quarters), + months: dur.months - Math.trunc(dur.months), + weeks: dur.weeks - Math.trunc(dur.weeks), + days: dur.days - Math.trunc(dur.days), + hours: dur.hours, + minutes: dur.minutes, + seconds: dur.seconds, + milliseconds: dur.milliseconds + }).as("milliseconds"), localTS = objToLocalTS(c); + let [ts, o] = fixOffset(localTS, oPre, inst.zone); + if (millisToAdd !== 0) { + ts += millisToAdd; + o = inst.zone.offset(ts); + } + return { ts, o }; +} +function parseDataToDateTime(parsed, parsedZone, opts, format, text2, specificOffset) { + const { setZone, zone } = opts; + if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { + const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, { + ...opts, + zone: interpretationZone, + specificOffset + }); + return setZone ? inst : inst.setZone(zone); + } else { + return DateTime.invalid( + new Invalid("unparsable", `the input "${text2}" can't be parsed as ${format}`) + ); + } +} +function toTechFormat(dt, format, allowZ = true) { + return dt.isValid ? Formatter.create(Locale.create("en-US"), { + allowZ, + forceSimple: true + }).formatDateTimeFromString(dt, format) : null; +} +function toISODate(o, extended) { + const longFormat = o.c.year > 9999 || o.c.year < 0; + let c = ""; + if (longFormat && o.c.year >= 0) + c += "+"; + c += padStart(o.c.year, longFormat ? 6 : 4); + if (extended) { + c += "-"; + c += padStart(o.c.month); + c += "-"; + c += padStart(o.c.day); + } else { + c += padStart(o.c.month); + c += padStart(o.c.day); + } + return c; +} +function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) { + let c = padStart(o.c.hour); + if (extended) { + c += ":"; + c += padStart(o.c.minute); + if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { + c += ":"; + } + } else { + c += padStart(o.c.minute); + } + if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { + c += padStart(o.c.second); + if (o.c.millisecond !== 0 || !suppressMilliseconds) { + c += "."; + c += padStart(o.c.millisecond, 3); + } + } + if (includeOffset) { + if (o.isOffsetFixed && o.offset === 0 && !extendedZone) { + c += "Z"; + } else if (o.o < 0) { + c += "-"; + c += padStart(Math.trunc(-o.o / 60)); + c += ":"; + c += padStart(Math.trunc(-o.o % 60)); + } else { + c += "+"; + c += padStart(Math.trunc(o.o / 60)); + c += ":"; + c += padStart(Math.trunc(o.o % 60)); + } + } + if (extendedZone) { + c += "[" + o.zone.ianaName + "]"; + } + return c; +} +var defaultUnitValues = { + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 +}; +var defaultWeekUnitValues = { + weekNumber: 1, + weekday: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 +}; +var defaultOrdinalUnitValues = { + ordinal: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 +}; +var orderedUnits2 = ["year", "month", "day", "hour", "minute", "second", "millisecond"]; +var orderedWeekUnits = [ + "weekYear", + "weekNumber", + "weekday", + "hour", + "minute", + "second", + "millisecond" +]; +var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; +function normalizeUnit(unit) { + const normalized = { + year: "year", + years: "year", + month: "month", + months: "month", + day: "day", + days: "day", + hour: "hour", + hours: "hour", + minute: "minute", + minutes: "minute", + quarter: "quarter", + quarters: "quarter", + second: "second", + seconds: "second", + millisecond: "millisecond", + milliseconds: "millisecond", + weekday: "weekday", + weekdays: "weekday", + weeknumber: "weekNumber", + weeksnumber: "weekNumber", + weeknumbers: "weekNumber", + weekyear: "weekYear", + weekyears: "weekYear", + ordinal: "ordinal" + }[unit.toLowerCase()]; + if (!normalized) + throw new InvalidUnitError(unit); + return normalized; +} +function normalizeUnitWithLocalWeeks(unit) { + switch (unit.toLowerCase()) { + case "localweekday": + case "localweekdays": + return "localWeekday"; + case "localweeknumber": + case "localweeknumbers": + return "localWeekNumber"; + case "localweekyear": + case "localweekyears": + return "localWeekYear"; + default: + return normalizeUnit(unit); + } +} +function quickDT(obj, opts) { + const zone = normalizeZone(opts.zone, Settings.defaultZone), loc = Locale.fromObject(opts), tsNow = Settings.now(); + let ts, o; + if (!isUndefined(obj.year)) { + for (const u of orderedUnits2) { + if (isUndefined(obj[u])) { + obj[u] = defaultUnitValues[u]; + } + } + const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); + if (invalid) { + return DateTime.invalid(invalid); + } + const offsetProvis = zone.offset(tsNow); + [ts, o] = objToTS(obj, offsetProvis, zone); + } else { + ts = tsNow; + } + return new DateTime({ ts, zone, loc, o }); +} +function diffRelative(start, end, opts) { + const round = isUndefined(opts.round) ? true : opts.round, format = (c, unit) => { + c = roundTo(c, round || opts.calendary ? 0 : 2, true); + const formatter = end.loc.clone(opts).relFormatter(opts); + return formatter.format(c, unit); + }, differ = (unit) => { + if (opts.calendary) { + if (!end.hasSame(start, unit)) { + return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); + } else + return 0; + } else { + return end.diff(start, unit).get(unit); + } + }; + if (opts.unit) { + return format(differ(opts.unit), opts.unit); + } + for (const unit of opts.units) { + const count = differ(unit); + if (Math.abs(count) >= 1) { + return format(count, unit); + } + } + return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); +} +function lastOpts(argList) { + let opts = {}, args; + if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { + opts = argList[argList.length - 1]; + args = Array.from(argList).slice(0, argList.length - 1); + } else { + args = Array.from(argList); + } + return [opts, args]; +} +var DateTime = class _DateTime { + /** + * @access private + */ + constructor(config) { + const zone = config.zone || Settings.defaultZone; + let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); + this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; + let c = null, o = null; + if (!invalid) { + const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); + if (unchanged) { + [c, o] = [config.old.c, config.old.o]; + } else { + const ot = zone.offset(this.ts); + c = tsToObj(this.ts, ot); + invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; + c = invalid ? null : c; + o = invalid ? null : ot; + } + } + this._zone = zone; + this.loc = config.loc || Locale.create(); + this.invalid = invalid; + this.weekData = null; + this.localWeekData = null; + this.c = c; + this.o = o; + this.isLuxonDateTime = true; + } + // CONSTRUCT + /** + * Create a DateTime for the current instant, in the system's time zone. + * + * Use Settings to override these default values if needed. + * @example DateTime.now().toISO() //~> now in the ISO format + * @return {DateTime} + */ + static now() { + return new _DateTime({}); + } + /** + * Create a local DateTime + * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used + * @param {number} [month=1] - The month, 1-indexed + * @param {number} [day=1] - The day of the month, 1-indexed + * @param {number} [hour=0] - The hour of the day, in 24-hour time + * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 + * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 + * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 + * @example DateTime.local() //~> now + * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time + * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 + * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 + * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale + * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 + * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC + * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 + * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 + * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 + * @return {DateTime} + */ + static local() { + const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; + return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); + } + /** + * Create a DateTime in UTC + * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used + * @param {number} [month=1] - The month, 1-indexed + * @param {number} [day=1] - The day of the month + * @param {number} [hour=0] - The hour of the day, in 24-hour time + * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 + * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 + * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 + * @param {Object} options - configuration options for the DateTime + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance + * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance + * @example DateTime.utc() //~> now + * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z + * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z + * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z + * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z + * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z + * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale + * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z + * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale + * @return {DateTime} + */ + static utc() { + const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; + opts.zone = FixedOffsetZone.utcInstance; + return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); + } + /** + * Create a DateTime from a JavaScript Date object. Uses the default zone. + * @param {Date} date - a JavaScript Date object + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @return {DateTime} + */ + static fromJSDate(date, options = {}) { + const ts = isDate(date) ? date.valueOf() : NaN; + if (Number.isNaN(ts)) { + return _DateTime.invalid("invalid input"); + } + const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); + if (!zoneToUse.isValid) { + return _DateTime.invalid(unsupportedZone(zoneToUse)); + } + return new _DateTime({ + ts, + zone: zoneToUse, + loc: Locale.fromObject(options) + }); + } + /** + * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. + * @param {number} milliseconds - a number of milliseconds since 1970 UTC + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromMillis(milliseconds, options = {}) { + if (!isNumber(milliseconds)) { + throw new InvalidArgumentError( + `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}` + ); + } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { + return _DateTime.invalid("Timestamp out of range"); + } else { + return new _DateTime({ + ts: milliseconds, + zone: normalizeZone(options.zone, Settings.defaultZone), + loc: Locale.fromObject(options) + }); + } + } + /** + * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. + * @param {number} seconds - a number of seconds since 1970 UTC + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromSeconds(seconds, options = {}) { + if (!isNumber(seconds)) { + throw new InvalidArgumentError("fromSeconds requires a numerical input"); + } else { + return new _DateTime({ + ts: seconds * 1e3, + zone: normalizeZone(options.zone, Settings.defaultZone), + loc: Locale.fromObject(options) + }); + } + } + /** + * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults. + * @param {Object} obj - the object to create the DateTime from + * @param {number} obj.year - a year, such as 1987 + * @param {number} obj.month - a month, 1-12 + * @param {number} obj.day - a day of the month, 1-31, depending on the month + * @param {number} obj.ordinal - day of the year, 1-365 or 366 + * @param {number} obj.weekYear - an ISO week year + * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year + * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday + * @param {number} obj.localWeekYear - a week year, according to the locale + * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale + * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale + * @param {number} obj.hour - hour of the day, 0-23 + * @param {number} obj.minute - minute of the hour, 0-59 + * @param {number} obj.second - second of the minute, 0-59 + * @param {number} obj.millisecond - millisecond of the second, 0-999 + * @param {Object} opts - options for creating this DateTime + * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() + * @param {string} [opts.locale='system\'s locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' + * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }), + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' }) + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' }) + * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' + * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: "en-US" }).toISODate() //=> '2021-12-26' + * @return {DateTime} + */ + static fromObject(obj, opts = {}) { + obj = obj || {}; + const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); + if (!zoneToUse.isValid) { + return _DateTime.invalid(unsupportedZone(zoneToUse)); + } + const loc = Locale.fromObject(opts); + const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks); + const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc); + const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError( + "Can't mix weekYear/weekNumber units with year/month/day or ordinals" + ); + } + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); + } + const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; + let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); + if (useWeekData) { + units = orderedWeekUnits; + defaultValues = defaultWeekUnitValues; + objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek); + } else if (containsOrdinal) { + units = orderedOrdinalUnits; + defaultValues = defaultOrdinalUnitValues; + objNow = gregorianToOrdinal(objNow); + } else { + units = orderedUnits2; + defaultValues = defaultUnitValues; + } + let foundFirst = false; + for (const u of units) { + const v = normalized[u]; + if (!isUndefined(v)) { + foundFirst = true; + } else if (foundFirst) { + normalized[u] = defaultValues[u]; + } else { + normalized[u] = objNow[u]; + } + } + const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); + if (invalid) { + return _DateTime.invalid(invalid); + } + const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new _DateTime({ + ts: tsFinal, + zone: zoneToUse, + o: offsetFinal, + loc + }); + if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { + return _DateTime.invalid( + "mismatched weekday", + `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}` + ); + } + return inst; + } + /** + * Create a DateTime from an ISO 8601 string + * @param {string} text - the ISO string + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance + * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromISO('2016-05-25T09:08:34.123') + * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') + * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) + * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) + * @example DateTime.fromISO('2016-W05-4') + * @return {DateTime} + */ + static fromISO(text2, opts = {}) { + const [vals, parsedZone] = parseISODate(text2); + return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text2); + } + /** + * Create a DateTime from an RFC 2822 string + * @param {string} text - the RFC 2822 string + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. + * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') + * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') + * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') + * @return {DateTime} + */ + static fromRFC2822(text2, opts = {}) { + const [vals, parsedZone] = parseRFC2822Date(text2); + return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text2); + } + /** + * Create a DateTime from an HTTP header date + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 + * @param {string} text - the HTTP header date + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. + * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') + * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') + * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') + * @return {DateTime} + */ + static fromHTTP(text2, opts = {}) { + const [vals, parsedZone] = parseHTTPDate(text2); + return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); + } + /** + * Create a DateTime from an input string and format string. + * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens). + * @param {string} text - the string to parse + * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale + * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromFormat(text2, fmt, opts = {}) { + if (isUndefined(text2) || isUndefined(fmt)) { + throw new InvalidArgumentError("fromFormat requires an input string and a format"); + } + const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({ + locale, + numberingSystem, + defaultToEN: true + }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text2, fmt); + if (invalid) { + return _DateTime.invalid(invalid); + } else { + return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text2, specificOffset); + } + } + /** + * @deprecated use fromFormat instead + */ + static fromString(text2, fmt, opts = {}) { + return _DateTime.fromFormat(text2, fmt, opts); + } + /** + * Create a DateTime from a SQL date, time, or datetime + * Defaults to en-US if no locale has been specified, regardless of the system's locale + * @param {string} text - the string to parse + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale + * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @example DateTime.fromSQL('2017-05-15') + * @example DateTime.fromSQL('2017-05-15 09:12:34') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) + * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) + * @example DateTime.fromSQL('09:12:34.342') + * @return {DateTime} + */ + static fromSQL(text2, opts = {}) { + const [vals, parsedZone] = parseSQL(text2); + return parseDataToDateTime(vals, parsedZone, opts, "SQL", text2); + } + /** + * Create an invalid DateTime. + * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent. + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {DateTime} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); + } + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { + throw new InvalidDateTimeError(invalid); + } else { + return new _DateTime({ invalid }); + } + } + /** + * Check if an object is an instance of DateTime. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isDateTime(o) { + return o && o.isLuxonDateTime || false; + } + /** + * Produce the format string for a set of options + * @param formatOpts + * @param localeOpts + * @returns {string} + */ + static parseFormatForOpts(formatOpts, localeOpts = {}) { + const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); + return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join(""); + } + /** + * Produce the the fully expanded format token for the locale + * Does NOT quote characters, so quoted tokens will not round trip correctly + * @param fmt + * @param localeOpts + * @returns {string} + */ + static expandFormat(fmt, localeOpts = {}) { + const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); + return expanded.map((t) => t.val).join(""); + } + // INFO + /** + * Get the value of unit. + * @param {string} unit - a unit such as 'minute' or 'day' + * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 + * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 + * @return {number} + */ + get(unit) { + return this[unit]; + } + /** + * Returns whether the DateTime is valid. Invalid DateTimes occur when: + * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 + * * The DateTime was created by an operation on another invalid date + * @type {boolean} + */ + get isValid() { + return this.invalid === null; + } + /** + * Returns an error code if this DateTime is invalid, or null if the DateTime is valid + * @type {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + /** + * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + /** + * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime + * + * @type {string} + */ + get locale() { + return this.isValid ? this.loc.locale : null; + } + /** + * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime + * + * @type {string} + */ + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; + } + /** + * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime + * + * @type {string} + */ + get outputCalendar() { + return this.isValid ? this.loc.outputCalendar : null; + } + /** + * Get the time zone associated with this DateTime. + * @type {Zone} + */ + get zone() { + return this._zone; + } + /** + * Get the name of the time zone. + * @type {string} + */ + get zoneName() { + return this.isValid ? this.zone.name : null; + } + /** + * Get the year + * @example DateTime.local(2017, 5, 25).year //=> 2017 + * @type {number} + */ + get year() { + return this.isValid ? this.c.year : NaN; + } + /** + * Get the quarter + * @example DateTime.local(2017, 5, 25).quarter //=> 2 + * @type {number} + */ + get quarter() { + return this.isValid ? Math.ceil(this.c.month / 3) : NaN; + } + /** + * Get the month (1-12). + * @example DateTime.local(2017, 5, 25).month //=> 5 + * @type {number} + */ + get month() { + return this.isValid ? this.c.month : NaN; + } + /** + * Get the day of the month (1-30ish). + * @example DateTime.local(2017, 5, 25).day //=> 25 + * @type {number} + */ + get day() { + return this.isValid ? this.c.day : NaN; + } + /** + * Get the hour of the day (0-23). + * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 + * @type {number} + */ + get hour() { + return this.isValid ? this.c.hour : NaN; + } + /** + * Get the minute of the hour (0-59). + * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 + * @type {number} + */ + get minute() { + return this.isValid ? this.c.minute : NaN; + } + /** + * Get the second of the minute (0-59). + * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 + * @type {number} + */ + get second() { + return this.isValid ? this.c.second : NaN; + } + /** + * Get the millisecond of the second (0-999). + * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 + * @type {number} + */ + get millisecond() { + return this.isValid ? this.c.millisecond : NaN; + } + /** + * Get the week year + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2014, 12, 31).weekYear //=> 2015 + * @type {number} + */ + get weekYear() { + return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; + } + /** + * Get the week number of the week year (1-52ish). + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 + * @type {number} + */ + get weekNumber() { + return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; + } + /** + * Get the day of the week. + * 1 is Monday and 7 is Sunday + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2014, 11, 31).weekday //=> 4 + * @type {number} + */ + get weekday() { + return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; + } + /** + * Returns true if this date is on a weekend according to the locale, false otherwise + * @returns {boolean} + */ + get isWeekend() { + return this.isValid && this.loc.getWeekendDays().includes(this.weekday); + } + /** + * Get the day of the week according to the locale. + * 1 is the first day of the week and 7 is the last day of the week. + * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1, + * @returns {number} + */ + get localWeekday() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN; + } + /** + * Get the week number of the week year according to the locale. Different locales assign week numbers differently, + * because the week can start on different days of the week (see localWeekday) and because a different number of days + * is required for a week to count as the first week of a year. + * @returns {number} + */ + get localWeekNumber() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN; + } + /** + * Get the week year according to the locale. Different locales assign week numbers (and therefor week years) + * differently, see localWeekNumber. + * @returns {number} + */ + get localWeekYear() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN; + } + /** + * Get the ordinal (meaning the day of the year) + * @example DateTime.local(2017, 5, 25).ordinal //=> 145 + * @type {number|DateTime} + */ + get ordinal() { + return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; + } + /** + * Get the human readable short month name, such as 'Oct'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).monthShort //=> Oct + * @type {string} + */ + get monthShort() { + return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null; + } + /** + * Get the human readable long month name, such as 'October'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).monthLong //=> October + * @type {string} + */ + get monthLong() { + return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null; + } + /** + * Get the human readable short weekday, such as 'Mon'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon + * @type {string} + */ + get weekdayShort() { + return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null; + } + /** + * Get the human readable long weekday, such as 'Monday'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday + * @type {string} + */ + get weekdayLong() { + return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null; + } + /** + * Get the UTC offset of this DateTime in minutes + * @example DateTime.now().offset //=> -240 + * @example DateTime.utc().offset //=> 0 + * @type {number} + */ + get offset() { + return this.isValid ? +this.o : NaN; + } + /** + * Get the short human name for the zone's current offset, for example "EST" or "EDT". + * Defaults to the system's locale if no locale has been specified + * @type {string} + */ + get offsetNameShort() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "short", + locale: this.locale + }); + } else { + return null; + } + } + /** + * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". + * Defaults to the system's locale if no locale has been specified + * @type {string} + */ + get offsetNameLong() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "long", + locale: this.locale + }); + } else { + return null; + } + } + /** + * Get whether this zone's offset ever changes, as in a DST. + * @type {boolean} + */ + get isOffsetFixed() { + return this.isValid ? this.zone.isUniversal : null; + } + /** + * Get whether the DateTime is in a DST. + * @type {boolean} + */ + get isInDST() { + if (this.isOffsetFixed) { + return false; + } else { + return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset; + } + } + /** + * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC + * in this DateTime's zone. During DST changes local time can be ambiguous, for example + * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`. + * This method will return both possible DateTimes if this DateTime's local time is ambiguous. + * @returns {DateTime[]} + */ + getPossibleOffsets() { + if (!this.isValid || this.isOffsetFixed) { + return [this]; + } + const dayMs = 864e5; + const minuteMs = 6e4; + const localTS = objToLocalTS(this.c); + const oEarlier = this.zone.offset(localTS - dayMs); + const oLater = this.zone.offset(localTS + dayMs); + const o1 = this.zone.offset(localTS - oEarlier * minuteMs); + const o2 = this.zone.offset(localTS - oLater * minuteMs); + if (o1 === o2) { + return [this]; + } + const ts1 = localTS - o1 * minuteMs; + const ts2 = localTS - o2 * minuteMs; + const c1 = tsToObj(ts1, o1); + const c2 = tsToObj(ts2, o2); + if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) { + return [clone2(this, { ts: ts1 }), clone2(this, { ts: ts2 })]; + } + return [this]; + } + /** + * Returns true if this DateTime is in a leap year, false otherwise + * @example DateTime.local(2016).isInLeapYear //=> true + * @example DateTime.local(2013).isInLeapYear //=> false + * @type {boolean} + */ + get isInLeapYear() { + return isLeapYear(this.year); + } + /** + * Returns the number of days in this DateTime's month + * @example DateTime.local(2016, 2).daysInMonth //=> 29 + * @example DateTime.local(2016, 3).daysInMonth //=> 31 + * @type {number} + */ + get daysInMonth() { + return daysInMonth(this.year, this.month); + } + /** + * Returns the number of days in this DateTime's year + * @example DateTime.local(2016).daysInYear //=> 366 + * @example DateTime.local(2013).daysInYear //=> 365 + * @type {number} + */ + get daysInYear() { + return this.isValid ? daysInYear(this.year) : NaN; + } + /** + * Returns the number of weeks in this DateTime's year + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2004).weeksInWeekYear //=> 53 + * @example DateTime.local(2013).weeksInWeekYear //=> 52 + * @type {number} + */ + get weeksInWeekYear() { + return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; + } + /** + * Returns the number of weeks in this DateTime's local week year + * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52 + * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53 + * @type {number} + */ + get weeksInLocalWeekYear() { + return this.isValid ? weeksInWeekYear( + this.localWeekYear, + this.loc.getMinDaysInFirstWeek(), + this.loc.getStartOfWeek() + ) : NaN; + } + /** + * Returns the resolved Intl options for this DateTime. + * This is useful in understanding the behavior of formatting methods + * @param {Object} opts - the same options as toLocaleString + * @return {Object} + */ + resolvedLocaleOptions(opts = {}) { + const { locale, numberingSystem, calendar } = Formatter.create( + this.loc.clone(opts), + opts + ).resolvedOptions(this); + return { locale, numberingSystem, outputCalendar: calendar }; + } + // TRANSFORM + /** + * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. + * + * Equivalent to {@link DateTime#setZone}('utc') + * @param {number} [offset=0] - optionally, an offset from UTC in minutes + * @param {Object} [opts={}] - options to pass to `setZone()` + * @return {DateTime} + */ + toUTC(offset2 = 0, opts = {}) { + return this.setZone(FixedOffsetZone.instance(offset2), opts); + } + /** + * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. + * + * Equivalent to `setZone('local')` + * @return {DateTime} + */ + toLocal() { + return this.setZone(Settings.defaultZone); + } + /** + * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. + * + * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones. + * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class. + * @param {Object} opts - options + * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. + * @return {DateTime} + */ + setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) { + zone = normalizeZone(zone, Settings.defaultZone); + if (zone.equals(this.zone)) { + return this; + } else if (!zone.isValid) { + return _DateTime.invalid(unsupportedZone(zone)); + } else { + let newTS = this.ts; + if (keepLocalTime || keepCalendarTime) { + const offsetGuess = zone.offset(this.ts); + const asObj = this.toObject(); + [newTS] = objToTS(asObj, offsetGuess, zone); + } + return clone2(this, { ts: newTS, zone }); + } + } + /** + * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. + * @param {Object} properties - the properties to set + * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) + * @return {DateTime} + */ + reconfigure({ locale, numberingSystem, outputCalendar } = {}) { + const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); + return clone2(this, { loc }); + } + /** + * "Set" the locale. Returns a newly-constructed DateTime. + * Just a convenient alias for reconfigure({ locale }) + * @example DateTime.local(2017, 5, 25).setLocale('en-GB') + * @return {DateTime} + */ + setLocale(locale) { + return this.reconfigure({ locale }); + } + /** + * "Set" the values of specified units. Returns a newly-constructed DateTime. + * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}. + * + * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`. + * They cannot be mixed with ISO-week units like `weekday`. + * @param {Object} values - a mapping of units to numbers + * @example dt.set({ year: 2017 }) + * @example dt.set({ hour: 8, minute: 30 }) + * @example dt.set({ weekday: 5 }) + * @example dt.set({ year: 2005, ordinal: 234 }) + * @return {DateTime} + */ + set(values) { + if (!this.isValid) + return this; + const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks); + const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc); + const settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError( + "Can't mix weekYear/weekNumber units with year/month/day or ordinals" + ); + } + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); + } + let mixed; + if (settingWeekStuff) { + mixed = weekToGregorian( + { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized }, + minDaysInFirstWeek, + startOfWeek + ); + } else if (!isUndefined(normalized.ordinal)) { + mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized }); + } else { + mixed = { ...this.toObject(), ...normalized }; + if (isUndefined(normalized.day)) { + mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); + } + } + const [ts, o] = objToTS(mixed, this.o, this.zone); + return clone2(this, { ts, o }); + } + /** + * Add a period of time to this DateTime and return the resulting DateTime + * + * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. + * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @example DateTime.now().plus(123) //~> in 123 milliseconds + * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes + * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow + * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday + * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min + * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min + * @return {DateTime} + */ + plus(duration) { + if (!this.isValid) + return this; + const dur = Duration.fromDurationLike(duration); + return clone2(this, adjustTime(this, dur)); + } + /** + * Subtract a period of time to this DateTime and return the resulting DateTime + * See {@link DateTime#plus} + * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + @return {DateTime} + */ + minus(duration) { + if (!this.isValid) + return this; + const dur = Duration.fromDurationLike(duration).negate(); + return clone2(this, adjustTime(this, dur)); + } + /** + * "Set" this DateTime to the beginning of a unit of time. + * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. + * @param {Object} opts - options + * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week + * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' + * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' + * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays + * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' + * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' + * @return {DateTime} + */ + startOf(unit, { useLocaleWeeks = false } = {}) { + if (!this.isValid) + return this; + const o = {}, normalizedUnit = Duration.normalizeUnit(unit); + switch (normalizedUnit) { + case "years": + o.month = 1; + case "quarters": + case "months": + o.day = 1; + case "weeks": + case "days": + o.hour = 0; + case "hours": + o.minute = 0; + case "minutes": + o.second = 0; + case "seconds": + o.millisecond = 0; + break; + case "milliseconds": + break; + } + if (normalizedUnit === "weeks") { + if (useLocaleWeeks) { + const startOfWeek = this.loc.getStartOfWeek(); + const { weekday } = this; + if (weekday < startOfWeek) { + o.weekNumber = this.weekNumber - 1; + } + o.weekday = startOfWeek; + } else { + o.weekday = 1; + } + } + if (normalizedUnit === "quarters") { + const q = Math.ceil(this.month / 3); + o.month = (q - 1) * 3 + 1; + } + return this.set(o); + } + /** + * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time + * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. + * @param {Object} opts - options + * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week + * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays + * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' + * @return {DateTime} + */ + endOf(unit, opts) { + return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit, opts).minus(1) : this; + } + // OUTPUT + /** + * Returns a string representation of this DateTime formatted according to the specified format string. + * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). + * Defaults to en-US if no locale has been specified, regardless of the system's locale. + * @param {string} fmt - the format string + * @param {Object} opts - opts to override the configuration options on this DateTime + * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' + * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' + * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' + * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' + * @return {string} + */ + toFormat(fmt, opts = {}) { + return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID4; + } + /** + * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. + * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation + * of the DateTime in the assigned locale. + * Defaults to the system's locale if no locale has been specified + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options + * @param {Object} opts - opts to override the configuration options on this DateTime + * @example DateTime.now().toLocaleString(); //=> 4/20/2017 + * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' + * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' + * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022' + * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' + * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' + * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' + * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' + * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' + * @return {string} + */ + toLocaleString(formatOpts = DATE_SHORT, opts = {}) { + return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID4; + } + /** + * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. + * Defaults to the system's locale if no locale has been specified + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts + * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. + * @example DateTime.now().toLocaleParts(); //=> [ + * //=> { type: 'day', value: '25' }, + * //=> { type: 'literal', value: '/' }, + * //=> { type: 'month', value: '05' }, + * //=> { type: 'literal', value: '/' }, + * //=> { type: 'year', value: '1982' } + * //=> ] + */ + toLocaleParts(opts = {}) { + return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.extendedZone=false] - add the time zone format extension + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' + * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' + * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' + * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' + * @return {string} + */ + toISO({ + format = "extended", + suppressSeconds = false, + suppressMilliseconds = false, + includeOffset = true, + extendedZone = false + } = {}) { + if (!this.isValid) { + return null; + } + const ext = format === "extended"; + let c = toISODate(this, ext); + c += "T"; + c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); + return c; + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime's date component + * @param {Object} opts - options + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' + * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' + * @return {string} + */ + toISODate({ format = "extended" } = {}) { + if (!this.isValid) { + return null; + } + return toISODate(this, format === "extended"); + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime's week date + * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' + * @return {string} + */ + toISOWeekDate() { + return toTechFormat(this, "kkkk-'W'WW-c"); + } + /** + * Returns an ISO 8601-compliant string representation of this DateTime's time component + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.extendedZone=true] - add the time zone format extension + * @param {boolean} [opts.includePrefix=false] - include the `T` prefix + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' + * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' + * @return {string} + */ + toISOTime({ + suppressMilliseconds = false, + suppressSeconds = false, + includeOffset = true, + includePrefix = false, + extendedZone = false, + format = "extended" + } = {}) { + if (!this.isValid) { + return null; + } + let c = includePrefix ? "T" : ""; + return c + toISOTime( + this, + format === "extended", + suppressSeconds, + suppressMilliseconds, + includeOffset, + extendedZone + ); + } + /** + * Returns an RFC 2822-compatible string representation of this DateTime + * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' + * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' + * @return {string} + */ + toRFC2822() { + return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); + } + /** + * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT. + * Specifically, the string conforms to RFC 1123. + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 + * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' + * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' + * @return {string} + */ + toHTTP() { + return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); + } + /** + * Returns a string representation of this DateTime appropriate for use in SQL Date + * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' + * @return {string} + */ + toSQLDate() { + if (!this.isValid) { + return null; + } + return toISODate(this, true); + } + /** + * Returns a string representation of this DateTime appropriate for use in SQL Time + * @param {Object} opts - options + * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' + * @example DateTime.utc().toSQL() //=> '05:15:16.345' + * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' + * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' + * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' + * @return {string} + */ + toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { + let fmt = "HH:mm:ss.SSS"; + if (includeZone || includeOffset) { + if (includeOffsetSpace) { + fmt += " "; + } + if (includeZone) { + fmt += "z"; + } else if (includeOffset) { + fmt += "ZZ"; + } + } + return toTechFormat(this, fmt, true); + } + /** + * Returns a string representation of this DateTime appropriate for use in SQL DateTime + * @param {Object} opts - options + * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' + * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' + * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' + * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' + * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' + * @return {string} + */ + toSQL(opts = {}) { + if (!this.isValid) { + return null; + } + return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; + } + /** + * Returns a string representation of this DateTime appropriate for debugging + * @return {string} + */ + toString() { + return this.isValid ? this.toISO() : INVALID4; + } + /** + * Returns a string representation of this DateTime appropriate for the REPL. + * @return {string} + */ + [Symbol.for("nodejs.util.inspect.custom")]() { + if (this.isValid) { + return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`; + } else { + return `DateTime { Invalid, reason: ${this.invalidReason} }`; + } + } + /** + * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis} + * @return {number} + */ + valueOf() { + return this.toMillis(); + } + /** + * Returns the epoch milliseconds of this DateTime. + * @return {number} + */ + toMillis() { + return this.isValid ? this.ts : NaN; + } + /** + * Returns the epoch seconds of this DateTime. + * @return {number} + */ + toSeconds() { + return this.isValid ? this.ts / 1e3 : NaN; + } + /** + * Returns the epoch seconds (as a whole number) of this DateTime. + * @return {number} + */ + toUnixInteger() { + return this.isValid ? Math.floor(this.ts / 1e3) : NaN; + } + /** + * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. + * @return {string} + */ + toJSON() { + return this.toISO(); + } + /** + * Returns a BSON serializable equivalent to this DateTime. + * @return {Date} + */ + toBSON() { + return this.toJSDate(); + } + /** + * Returns a JavaScript object with this DateTime's year, month, day, and so on. + * @param opts - options for generating the object + * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output + * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } + * @return {Object} + */ + toObject(opts = {}) { + if (!this.isValid) + return {}; + const base = { ...this.c }; + if (opts.includeConfig) { + base.outputCalendar = this.outputCalendar; + base.numberingSystem = this.loc.numberingSystem; + base.locale = this.loc.locale; + } + return base; + } + /** + * Returns a JavaScript Date equivalent to this DateTime. + * @return {Date} + */ + toJSDate() { + return new Date(this.isValid ? this.ts : NaN); + } + // COMPARE + /** + * Return the difference between two DateTimes as a Duration. + * @param {DateTime} otherDateTime - the DateTime to compare this one to + * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @example + * var i1 = DateTime.fromISO('1982-05-25T09:45'), + * i2 = DateTime.fromISO('1983-10-14T10:30'); + * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } + * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } + * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } + * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } + * @return {Duration} + */ + diff(otherDateTime, unit = "milliseconds", opts = {}) { + if (!this.isValid || !otherDateTime.isValid) { + return Duration.invalid("created by diffing an invalid DateTime"); + } + const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts }; + const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff_default(earlier, later, units, durOpts); + return otherIsLater ? diffed.negate() : diffed; + } + /** + * Return the difference between this DateTime and right now. + * See {@link DateTime#diff} + * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @return {Duration} + */ + diffNow(unit = "milliseconds", opts = {}) { + return this.diff(_DateTime.now(), unit, opts); + } + /** + * Return an Interval spanning between this DateTime and another DateTime + * @param {DateTime} otherDateTime - the other end point of the Interval + * @return {Interval} + */ + until(otherDateTime) { + return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; + } + /** + * Return whether this DateTime is in the same unit of time as another DateTime. + * Higher-order units must also be identical for this function to return `true`. + * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed. + * @param {DateTime} otherDateTime - the other DateTime + * @param {string} unit - the unit of time to check sameness on + * @param {Object} opts - options + * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used + * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day + * @return {boolean} + */ + hasSame(otherDateTime, unit, opts) { + if (!this.isValid) + return false; + const inputMs = otherDateTime.valueOf(); + const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true }); + return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts); + } + /** + * Equality check + * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid. + * To compare just the millisecond values, use `+dt1 === +dt2`. + * @param {DateTime} other - the other DateTime + * @return {boolean} + */ + equals(other) { + return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); + } + /** + * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your + * platform supports Intl.RelativeTimeFormat. Rounds down by default. + * @param {Object} options - options that affect the output + * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. + * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" + * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" + * @param {boolean} [options.round=true] - whether to round the numbers in the output. + * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. + * @param {string} options.locale - override the locale of this DateTime + * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this + * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" + * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" + * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" + * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" + * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" + * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" + */ + toRelative(options = {}) { + if (!this.isValid) + return null; + const base = options.base || _DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; + let units = ["years", "months", "days", "hours", "minutes", "seconds"]; + let unit = options.unit; + if (Array.isArray(options.unit)) { + units = options.unit; + unit = void 0; + } + return diffRelative(base, this.plus(padding), { + ...options, + numeric: "always", + units, + unit + }); + } + /** + * Returns a string representation of this date relative to today, such as "yesterday" or "next month". + * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. + * @param {Object} options - options that affect the output + * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. + * @param {string} options.locale - override the locale of this DateTime + * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" + * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this + * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" + * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" + * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" + * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" + */ + toRelativeCalendar(options = {}) { + if (!this.isValid) + return null; + return diffRelative(options.base || _DateTime.fromObject({}, { zone: this.zone }), this, { + ...options, + numeric: "auto", + units: ["years", "months", "days"], + calendary: true + }); + } + /** + * Return the min of several date times + * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum + * @return {DateTime} the min DateTime, or undefined if called with no argument + */ + static min(...dateTimes) { + if (!dateTimes.every(_DateTime.isDateTime)) { + throw new InvalidArgumentError("min requires all arguments be DateTimes"); + } + return bestBy(dateTimes, (i) => i.valueOf(), Math.min); + } + /** + * Return the max of several date times + * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum + * @return {DateTime} the max DateTime, or undefined if called with no argument + */ + static max(...dateTimes) { + if (!dateTimes.every(_DateTime.isDateTime)) { + throw new InvalidArgumentError("max requires all arguments be DateTimes"); + } + return bestBy(dateTimes, (i) => i.valueOf(), Math.max); + } + // MISC + /** + * Explain how a string would be parsed by fromFormat() + * @param {string} text - the string to parse + * @param {string} fmt - the format the string is expected to be in (see description) + * @param {Object} options - options taken by fromFormat() + * @return {Object} + */ + static fromFormatExplain(text2, fmt, options = {}) { + const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({ + locale, + numberingSystem, + defaultToEN: true + }); + return explainFromTokens(localeToUse, text2, fmt); + } + /** + * @deprecated use fromFormatExplain instead + */ + static fromStringExplain(text2, fmt, options = {}) { + return _DateTime.fromFormatExplain(text2, fmt, options); + } + // FORMAT PRESETS + /** + * {@link DateTime#toLocaleString} format like 10/14/1983 + * @type {Object} + */ + static get DATE_SHORT() { + return DATE_SHORT; + } + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983' + * @type {Object} + */ + static get DATE_MED() { + return DATE_MED; + } + /** + * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983' + * @type {Object} + */ + static get DATE_MED_WITH_WEEKDAY() { + return DATE_MED_WITH_WEEKDAY; + } + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983' + * @type {Object} + */ + static get DATE_FULL() { + return DATE_FULL; + } + /** + * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983' + * @type {Object} + */ + static get DATE_HUGE() { + return DATE_HUGE; + } + /** + * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_SIMPLE() { + return TIME_SIMPLE; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_SECONDS() { + return TIME_WITH_SECONDS; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_SHORT_OFFSET() { + return TIME_WITH_SHORT_OFFSET; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_LONG_OFFSET() { + return TIME_WITH_LONG_OFFSET; + } + /** + * {@link DateTime#toLocaleString} format like '09:30', always 24-hour. + * @type {Object} + */ + static get TIME_24_SIMPLE() { + return TIME_24_SIMPLE; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_SECONDS() { + return TIME_24_WITH_SECONDS; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_SHORT_OFFSET() { + return TIME_24_WITH_SHORT_OFFSET; + } + /** + * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_LONG_OFFSET() { + return TIME_24_WITH_LONG_OFFSET; + } + /** + * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_SHORT() { + return DATETIME_SHORT; + } + /** + * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_SHORT_WITH_SECONDS() { + return DATETIME_SHORT_WITH_SECONDS; + } + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED() { + return DATETIME_MED; + } + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED_WITH_SECONDS() { + return DATETIME_MED_WITH_SECONDS; + } + /** + * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED_WITH_WEEKDAY() { + return DATETIME_MED_WITH_WEEKDAY; + } + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_FULL() { + return DATETIME_FULL; + } + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_FULL_WITH_SECONDS() { + return DATETIME_FULL_WITH_SECONDS; + } + /** + * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_HUGE() { + return DATETIME_HUGE; + } + /** + * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_HUGE_WITH_SECONDS() { + return DATETIME_HUGE_WITH_SECONDS; + } +}; +function friendlyDateTime(dateTimeish) { + if (DateTime.isDateTime(dateTimeish)) { + return dateTimeish; + } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { + return DateTime.fromJSDate(dateTimeish); + } else if (dateTimeish && typeof dateTimeish === "object") { + return DateTime.fromObject(dateTimeish); + } else { + throw new InvalidArgumentError( + `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}` + ); + } +} + +// src/graph/builders/explicit/date_note.ts +var _add_explicit_edges_date_note = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + const date_note_settings = plugin.settings.explicit_edge_sources.date_note; + if (!date_note_settings.enabled) + return { errors }; + else if (!plugin.settings.edge_fields.find( + (field) => field.label === date_note_settings.default_field + )) { + errors.push({ + code: "invalid_setting_value", + path: "explicit_edge_sources.date_note.default_field", + message: `The default Date Note field "${date_note_settings.default_field}" is not a valid Breadcrumbs Edge field` + }); + return { errors }; + } + const date_notes = []; + (_a = all_files.obsidian) == null ? void 0 : _a.forEach(({ file }) => { + var _a2, _b2; + const date = DateTime.fromFormat( + file.basename, + date_note_settings.date_format + ); + if (!date.isValid) + return; + date_notes.push({ + date, + path: file.path, + ext: file.extension, + basename: file.basename, + // Not sure why would this be undefined? + // I tested and a file in the root of the vault still has a parent + // _it's_ parent is null, but that only happens if "file" is actually a folder + folder: (_b2 = (_a2 = file.parent) == null ? void 0 : _a2.path) != null ? _b2 : "" + }); + }); + (_b = all_files.dataview) == null ? void 0 : _b.forEach(({ file }) => { + const date = DateTime.fromFormat( + file.name, + date_note_settings.date_format + ); + if (!date.isValid) + return; + date_notes.push({ + date, + ext: file.ext, + path: file.path, + folder: file.folder, + basename: file.name + }); + }); + date_notes.sort((a, b) => a.date.toMillis() - b.date.toMillis()).forEach((date_note, i) => { + var _a2, _b2; + const basename_plus_one_day = date_note.date.plus({ days: 1 }).toFormat(date_note_settings.date_format); + const target_basename = date_note_settings.stretch_to_existing ? (_b2 = (_a2 = date_notes.at(i + 1)) == null ? void 0 : _a2.basename) != null ? _b2 : basename_plus_one_day : basename_plus_one_day; + const target_path = Paths.build( + date_note.folder, + target_basename, + date_note.ext + ); + const target_file = plugin.app.vault.getFileByPath(target_path); + if (!target_file) { + graph.safe_add_node(target_path, { resolved: false }); + } + graph.safe_add_directed_edge(date_note.path, target_path, { + explicit: true, + source: "date_note", + field: date_note_settings.default_field + }); + }); + return { errors }; +}; + +// src/graph/builders/explicit/dendron_note.ts +var get_dendron_note_info = (plugin, metadata, path) => { + var _a; + const field = (_a = metadata == null ? void 0 : metadata[META_ALIAS["dendron-note-field"]]) != null ? _a : ( + // Which is why we have a default_field on dendron_note + plugin.settings.explicit_edge_sources.dendron_note.default_field + ); + if (!field) { + return fail(void 0); + } else if (typeof field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `dendron-note-field is not a string: '${field}'` + }); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `dendron-note-field is not a valid field: '${field}'` + }); + } + return succ({ field }); +}; +var handle_dendron_note = (plugin, graph, source_path, source_metadata, errors) => { + const { delimiter } = plugin.settings.explicit_edge_sources.dendron_note; + const source_basename_splits = Paths.basename(source_path).split(delimiter); + if (source_basename_splits.length === 1) + return; + const dendron_note_info = get_dendron_note_info( + plugin, + source_metadata, + source_path + ); + if (!dendron_note_info.ok) { + if (dendron_note_info.error) { + errors.push(dendron_note_info.error); + } + return; + } + const target_path = Paths.build( + // Use the same folder as the source + source_path.split("/").slice(0, -1).join("/"), + // Go one note up + source_basename_splits.slice(0, -1).join(delimiter), + "md" + ); + const { field } = dendron_note_info.data; + const target_file = plugin.app.vault.getFileByPath(target_path); + if (!target_file) { + graph.safe_add_node(target_path, { resolved: false }); + handle_dendron_note( + plugin, + graph, + target_path, + // This is really quite elegant :) + // The unresolved note has no BC-dendron field, by definition + // Passing undefined would just use the settings.default field + // But we can propagate the field from the resolved source note + { [META_ALIAS["dendron-note-field"]]: field }, + errors + ); + } + graph.safe_add_directed_edge(source_path, target_path, { + field, + explicit: true, + source: "dendron_note" + }); +}; +var _add_explicit_edges_dendron_note = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + if (!plugin.settings.explicit_edge_sources.dendron_note.enabled) { + return { errors }; + } + (_a = all_files.obsidian) == null ? void 0 : _a.forEach(({ file, cache }) => { + handle_dendron_note( + plugin, + graph, + file.path, + cache == null ? void 0 : cache.frontmatter, + errors + ); + }); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((page) => { + handle_dendron_note(plugin, graph, page.file.path, page, errors); + }); + return { errors }; +}; + +// src/graph/builders/explicit/folder_note.ts +var get_folder_note_info = (plugin, metadata, path) => { + if (!metadata) + return fail(void 0); + const field = metadata[META_ALIAS["folder-note-field"]]; + if (!field) { + return fail(void 0); + } else if (typeof field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `folder-note-field is not a string: '${field}'` + }); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `folder-note-field is not a valid field: '${field}'` + }); + } + const recurse = Boolean(metadata[META_ALIAS["folder-note-recurse"]]); + return succ({ + field, + recurse + }); +}; +var iterate_folder_files = async (plugin, folder, cb, recurse) => { + const folder_files = await plugin.app.vault.adapter.list(folder); + folder_files.files.forEach((path) => cb(path)); + if (recurse) { + await Promise.all( + folder_files.folders.map( + (folder2) => ( + // When the subfolder is recursed, what does it mean when the callback runs? + // Where will it point up to? The initial folder's files point up to the folder_note + // But the subfolders don't specify a folder_note + // NOTE: For now, the subfiles will point up to the initial folder_note + iterate_folder_files(plugin, folder2, cb, true) + ) + ) + ); + } +}; +var _add_explicit_edges_folder_note = async (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + const folder_notes = []; + (_a = all_files.obsidian) == null ? void 0 : _a.forEach( + ({ file: folder_note_file, cache: folder_note_cache }) => { + var _a2, _b2; + if (!folder_note_cache) + return; + const folder_note_info = get_folder_note_info( + plugin, + folder_note_cache == null ? void 0 : folder_note_cache.frontmatter, + folder_note_file.path + ); + if (!folder_note_info.ok) { + if (folder_note_info.error) + errors.push(folder_note_info.error); + return; + } + folder_notes.push({ + data: folder_note_info.data, + file: { + path: folder_note_file.path, + folder: (_b2 = (_a2 = folder_note_file.parent) == null ? void 0 : _a2.path) != null ? _b2 : "" + } + }); + } + ); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((folder_note_page) => { + const folder_note_info = get_folder_note_info( + plugin, + folder_note_page, + folder_note_page.file.path + ); + if (!folder_note_info.ok) { + if (folder_note_info.error) + errors.push(folder_note_info.error); + return; + } + folder_notes.push({ + data: folder_note_info.data, + file: { + path: folder_note_page.file.path, + folder: folder_note_page.file.folder + } + }); + }); + await Promise.all( + folder_notes.map( + ({ data, file: folder_note }) => iterate_folder_files( + plugin, + folder_note.folder, + (target_path) => { + if (!target_path.endsWith(".md") || target_path === folder_note.path) + return; + graph.safe_add_directed_edge( + folder_note.path, + target_path, + { + explicit: true, + field: data.field, + source: "folder_note" + } + ); + }, + data.recurse + ) + ) + ); + return { errors }; +}; + +// src/graph/builders/explicit/johnny_decimal_note.ts +var get_johnny_decimal_note_info = (plugin, metadata, path) => { + var _a; + const field = (_a = metadata == null ? void 0 : metadata[META_ALIAS["johnny-decimal-note-field"]]) != null ? _a : ( + // Which is why we have a default_field on johnny_decimal_note + plugin.settings.explicit_edge_sources.johnny_decimal_note.default_field + ); + if (!field) { + return fail(void 0); + } else if (typeof field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `johnny-decimal-note-field is not a string: '${field}'` + }); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `johnny-decimal-note-field is not a valid BC field: '${field}'` + }); + } + return succ({ field }); +}; +var handle_johnny_decimal_note = (plugin, graph, source_note, notes, errors) => { + const johnny_decimal_note_info = get_johnny_decimal_note_info( + plugin, + source_note.metadata, + source_note.path + ); + if (!johnny_decimal_note_info.ok) { + if (johnny_decimal_note_info.error) { + errors.push(johnny_decimal_note_info.error); + } + return; + } + const { delimiter } = plugin.settings.explicit_edge_sources.johnny_decimal_note; + const target_decimals = source_note.decimals.split(delimiter).slice(0, -1).join(delimiter); + if (target_decimals === "") + return; + const target_note = notes.find((n2) => n2.decimals === target_decimals); + if (!target_note) + return; + const target_file = plugin.app.vault.getFileByPath(target_note.path); + if (!target_file) { + graph.safe_add_node(target_note.path, { resolved: false }); + } + const { field } = johnny_decimal_note_info.data; + graph.safe_add_directed_edge(source_note.path, target_note.path, { + field, + explicit: true, + source: "johnny_decimal_note" + }); +}; +var _add_explicit_edges_johnny_decimal_note = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + if (!plugin.settings.explicit_edge_sources.johnny_decimal_note.enabled) { + return { errors }; + } + const { delimiter } = plugin.settings.explicit_edge_sources.johnny_decimal_note; + const regex2 = new RegExp(`^([\\w\\d\\${delimiter}]+)(\\s|\\${delimiter}$)`); + const johnny_decimal_notes = []; + (_a = all_files.obsidian) == null ? void 0 : _a.forEach(({ file, cache }) => { + var _a2; + const basename2 = Paths.basename(file.path); + const decimals = (_a2 = basename2.match(regex2)) == null ? void 0 : _a2[1]; + if (!decimals) + return; + johnny_decimal_notes.push({ + basename: basename2, + path: file.path, + metadata: cache == null ? void 0 : cache.frontmatter, + decimals: ensure_not_ends_with(decimals, delimiter) + }); + }); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((page) => { + var _a2; + const basename2 = Paths.basename(page.file.path); + const decimals = (_a2 = basename2.match(regex2)) == null ? void 0 : _a2[1]; + if (!decimals) + return; + johnny_decimal_notes.push({ + basename: basename2, + metadata: page, + path: page.file.path, + decimals: ensure_not_ends_with(decimals, delimiter) + }); + }); + johnny_decimal_notes.forEach((note) => { + handle_johnny_decimal_note( + plugin, + graph, + note, + johnny_decimal_notes, + errors + ); + }); + return { errors }; +}; + +// src/graph/builders/explicit/list_note.ts +var import_obsidian4 = require("obsidian"); + +// src/utils/obsidian.ts +var import_obsidian3 = require("obsidian"); +var resolve_relative_target_path = (app, relative_target_path, source_path) => { + var _a; + const extensioned = Paths.ensure_ext(relative_target_path); + const target_file = app.metadataCache.getFirstLinkpathDest( + extensioned, + source_path + ); + const target_path = (_a = target_file == null ? void 0 : target_file.path) != null ? _a : Links.resolve_to_absolute_path(app, extensioned, source_path); + return [target_path, target_file]; +}; +var copy_to_clipboard = async (text2, options) => { + const resolved = Object.assign({ notify: true, log: true }, options); + if (resolved.log) { + log.feat(text2); + } + await navigator.clipboard.writeText(text2); + if (resolved.notify) { + new import_obsidian3.Notice("Copied to clipboard and logged to console."); + } +}; + +// src/graph/builders/explicit/list_note.ts +var get_list_note_info = (plugin, metadata, path) => { + var _a; + if (!metadata) { + return fail(void 0); + } + const field = metadata[META_ALIAS["list-note-field"]]; + if (!field) { + return fail(void 0); + } else if (typeof field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `list-note-field is not a string: '${field}'` + }); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `list-note-field is not a valid BC field: '${field}'` + }); + } + const neighbour_field = (_a = metadata[META_ALIAS["list-note-neighbour-field"]]) != null ? _a : plugin.settings.explicit_edge_sources.list_note.default_neighbour_field; + if (neighbour_field) { + if (typeof neighbour_field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `list-note-neighbour-field is not a string: '${neighbour_field}'` + }); + } else if (!plugin.settings.edge_fields.find( + (f) => f.label === neighbour_field + )) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `list-note-neighbour-field is not a valid BC field: '${neighbour_field}'` + }); + } + } + const exclude_index = Boolean( + metadata[META_ALIAS["list-note-exclude-index"]] + ); + return succ({ + field, + exclude_index, + neighbour_field: neighbour_field != null ? neighbour_field : void 0 + }); +}; +var FIELD_OVERRIDE_REGEX = /^\s*([-\w\s]+)\b/; +var resolve_field_override = (plugin, list_item, path) => { + var _a; + const field = (_a = list_item.text.match(FIELD_OVERRIDE_REGEX)) == null ? void 0 : _a[1]; + if (!field) { + return succ(void 0); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `Field override is not a valid BC field: ${field}. Line: ${list_item.position.start.line}` + }); + } else { + return succ({ field }); + } +}; +var handle_neighbour_list_item = ({ + graph, + plugin, + source_path, + list_note_page, + list_note_info, + source_list_item_i +}) => { + if (!list_note_info.data.neighbour_field) + return; + const source_list_item = list_note_page.file.lists.values[source_list_item_i]; + let neighbour_list_item; + for (let i = source_list_item_i + 1; i < list_note_page.file.lists.values.length; i++) { + const item = list_note_page.file.lists.values[i]; + if (item.position.start.col < source_list_item.position.start.col) { + break; + } else if (item.position.start.col === source_list_item.position.start.col) { + neighbour_list_item = item; + break; + } + } + if (!neighbour_list_item) + return; + const neighbour_link = neighbour_list_item.outlinks.at(0); + if (!neighbour_link) + return; + const [path, file] = resolve_relative_target_path( + plugin.app, + neighbour_link.path, + list_note_page.file.path + ); + if (!file) { + graph.safe_add_node(path, { resolved: false }); + } + graph.safe_add_directed_edge(source_path, path, { + explicit: true, + source: "list_note", + field: list_note_info.data.neighbour_field + }); +}; +var _add_explicit_edges_list_note = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + (_a = all_files.obsidian) == null ? void 0 : _a.forEach( + ({ file: list_note_file, cache: list_note_cache }) => { + if (!list_note_cache) + return; + const list_note_info = get_list_note_info( + plugin, + list_note_cache == null ? void 0 : list_note_cache.frontmatter, + list_note_file.path + ); + if (!list_note_info.ok) { + if (list_note_info.error) + errors.push(list_note_info.error); + return; + } else { + new import_obsidian4.Notice( + "list-notes are not implemented without Dataview enabled" + ); + } + } + ); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((list_note_page) => { + const list_note_info = get_list_note_info( + plugin, + list_note_page, + list_note_page.file.path + ); + if (!list_note_info.ok) { + if (list_note_info.error) + errors.push(list_note_info.error); + return; + } + list_note_page.file.lists.values.forEach( + (source_list_item, source_list_item_i) => { + var _a2, _b2; + const source_link = source_list_item.outlinks.at(0); + if (!source_link) + return; + const [source_path, source_file] = resolve_relative_target_path( + plugin.app, + source_link.path, + list_note_page.file.path + ); + if (!source_file) { + graph.safe_add_node(source_path, { resolved: false }); + } + if (!list_note_info.data.exclude_index && source_list_item.position.start.col === 0) { + const source_override_field = resolve_field_override( + plugin, + source_list_item, + list_note_page.file.path + ); + if (!source_override_field.ok) { + if (source_override_field.error) { + errors.push(source_override_field.error); + } + return; + } + graph.safe_add_directed_edge( + list_note_page.file.path, + source_path, + { + explicit: true, + source: "list_note", + field: (_b2 = (_a2 = source_override_field.data) == null ? void 0 : _a2.field) != null ? _b2 : list_note_info.data.field + } + ); + } + if (list_note_info.data.neighbour_field) { + handle_neighbour_list_item({ + graph, + plugin, + source_path, + list_note_info, + list_note_page, + source_list_item_i + }); + } + source_list_item.children.forEach((target_list_item) => { + var _a3, _b3; + const target_link = target_list_item.outlinks.at(0); + if (!target_link) + return; + const target_override_field = resolve_field_override( + plugin, + target_list_item, + list_note_page.file.path + ); + if (!target_override_field.ok) { + if (target_override_field.error) { + errors.push(target_override_field.error); + } + return; + } + const [target_path, target_file] = resolve_relative_target_path( + plugin.app, + target_link.path, + list_note_page.file.path + ); + if (!target_file) { + graph.safe_add_node(target_path, { resolved: false }); + } + graph.safe_add_directed_edge(source_path, target_path, { + explicit: true, + source: "list_note", + field: (_b3 = (_a3 = target_override_field.data) == null ? void 0 : _a3.field) != null ? _b3 : list_note_info.data.field + }); + }); + } + ); + }); + return { errors }; +}; + +// src/graph/builders/explicit/regex_note.ts +var get_regex_note_info = (plugin, metadata, path) => { + var _a; + if (!metadata) + return fail(void 0); + const regex_str = metadata[META_ALIAS["regex-note-regex"]]; + if (!regex_str) { + return fail(void 0); + } else if (typeof regex_str !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `regex-note-regex is not a string: '${regex_str}'` + }); + } + const flags = metadata[META_ALIAS["regex-note-flags"]]; + if (flags && typeof flags !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `regex-note-flags is not a string: '${flags}'` + }); + } + let regex2; + try { + regex2 = new RegExp(regex_str, flags || ""); + log.debug(`get_regex_note_info > regex:`, regex2); + } catch (e) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `regex-note-regex is not a valid regex: ${regex_str}` + }); + } + const field = (_a = metadata[META_ALIAS["regex-note-field"]]) != null ? _a : plugin.settings.explicit_edge_sources.regex_note.default_field; + if (!field) { + return fail(void 0); + } else if (typeof field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `regex-note-field is not a string: '${field}'` + }); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `dataview-note-field is not a valid field: '${field}'` + }); + } + return succ({ + field, + regex: regex2 + }); +}; +var _add_explicit_edges_regex_note = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + const regex_note_files = []; + (_a = all_files.obsidian) == null ? void 0 : _a.forEach(({ file, cache }) => { + const info = get_regex_note_info(plugin, cache == null ? void 0 : cache.frontmatter, file.path); + if (!info.ok) { + if (info.error) + errors.push(info.error); + return; + } + regex_note_files.push({ info: info.data, path: file.path }); + }); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((page) => { + const { file } = page; + const info = get_regex_note_info(plugin, page, file.path); + if (!info.ok) { + if (info.error) + errors.push(info.error); + return; + } + regex_note_files.push({ info: info.data, path: file.path }); + }); + if (!regex_note_files) + return { errors }; + const nodes = graph.mapNodes((id) => id); + regex_note_files.forEach((regex_note) => { + nodes.filter((node) => regex_note.info.regex.test(node)).forEach((target_path) => { + graph.safe_add_directed_edge(regex_note.path, target_path, { + explicit: true, + source: "regex_note", + field: regex_note.info.field + }); + }); + }); + return { errors }; +}; + +// src/graph/builders/explicit/tag_note.ts +var get_tag_note_info = (plugin, metadata, path) => { + var _a; + if (!metadata) + return fail(void 0); + let raw_tag = metadata[META_ALIAS["tag-note-tag"]]; + if (!raw_tag) { + raw_tag = metadata["BC-tag-note"]; + if (raw_tag) { + log.warn( + `'BC-tag-note' is deprecated in favor of ${META_ALIAS["tag-note-tag"]}` + ); + } + } + if (!raw_tag) { + return fail(void 0); + } else if (typeof raw_tag !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `tag-note-tag is not a string: '${raw_tag}'` + }); + } + const tag = ensure_starts_with(raw_tag, "#"); + const field = (_a = metadata[META_ALIAS["tag-note-field"]]) != null ? _a : plugin.settings.explicit_edge_sources.tag_note.default_field; + if (!field) { + return fail(void 0); + } else if (typeof field !== "string") { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `tag-note-field is not a string: '${field}'` + }); + } else if (!plugin.settings.edge_fields.find((f) => f.label === field)) { + return graph_build_fail({ + path, + code: "invalid_field_value", + message: `tag-note-field is not a valid BC field: '${field}'` + }); + } + const exact = Boolean(metadata[META_ALIAS["tag-note-exact"]]); + return succ({ tag, field, exact }); +}; +var _add_explicit_edges_tag_note = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + const tag_notes = []; + const tag_paths_map = /* @__PURE__ */ new Map(); + (_a = all_files.obsidian) == null ? void 0 : _a.forEach( + ({ file: tag_note_file, cache: tag_note_cache }) => { + var _a2; + if (!tag_note_cache) + return; + (_a2 = tag_note_cache == null ? void 0 : tag_note_cache.tags) == null ? void 0 : _a2.forEach(({ tag: tag2 }) => { + var _a3; + if (!((_a3 = tag_paths_map.get(tag2)) == null ? void 0 : _a3.push(tag_note_file.path))) { + tag_paths_map.set(tag2, [tag_note_file.path]); + } + }); + const tag_note_info = get_tag_note_info( + plugin, + tag_note_cache == null ? void 0 : tag_note_cache.frontmatter, + tag_note_file.path + ); + if (!tag_note_info.ok) { + if (tag_note_info.error) + errors.push(tag_note_info.error); + return; + } + const { tag, field, exact } = tag_note_info.data; + tag_notes.push({ + tag, + exact, + field, + source_path: tag_note_file.path + }); + } + ); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((page) => { + const tag_note_file = page.file; + tag_note_file.etags.values.forEach((tag2) => { + var _a2; + if (!((_a2 = tag_paths_map.get(tag2)) == null ? void 0 : _a2.push(tag_note_file.path))) { + tag_paths_map.set(tag2, [tag_note_file.path]); + } + }); + const tag_note_info = get_tag_note_info( + plugin, + page, + tag_note_file.path + ); + if (!tag_note_info.ok) { + if (tag_note_info.error) + errors.push(tag_note_info.error); + return; + } + const { tag, field, exact } = tag_note_info.data; + tag_notes.push({ + tag, + exact, + field, + source_path: tag_note_file.path + }); + }); + const all_tags = [...tag_paths_map.keys()]; + tag_notes.forEach((tag_note) => { + const target_paths = tag_note.exact ? tag_paths_map.get(tag_note.tag) : all_tags.filter((tag) => tag.startsWith(tag_note.tag)).flatMap((tag) => tag_paths_map.get(tag)); + target_paths == null ? void 0 : target_paths.forEach((target_path) => { + graph.safe_add_directed_edge(tag_note.source_path, target_path, { + explicit: true, + source: "tag_note", + field: tag_note.field + }); + }); + }); + return { errors }; +}; + +// src/graph/builders/explicit/typed_link.ts +var MARKDOWN_LINK_REGEX = /\[(.+?)\]\((.+?)\)/; +var _add_explicit_edges_typed_link = (graph, plugin, all_files) => { + var _a, _b; + const errors = []; + const field_labels = new Set( + plugin.settings.edge_fields.map((f) => f.label) + ); + (_a = all_files.obsidian) == null ? void 0 : _a.forEach( + ({ file: source_file, cache: source_cache }) => { + var _a2; + (_a2 = source_cache == null ? void 0 : source_cache.frontmatterLinks) == null ? void 0 : _a2.forEach((target_link) => { + const field = target_link.key.split(".")[0]; + if (!field_labels.has(field)) + return; + const [target_path, target_file] = resolve_relative_target_path( + plugin.app, + target_link.link, + source_file.path + ); + if (!target_file) { + graph.safe_add_node(target_path, { resolved: false }); + } + graph.safe_add_directed_edge(source_file.path, target_path, { + field, + explicit: true, + source: "typed_link" + }); + }); + } + ); + (_b = all_files.dataview) == null ? void 0 : _b.forEach((page) => { + const source_file = page.file; + Object.keys(page).forEach((field) => { + if (!field_labels.has(field) || ["file", "aliases"].includes(field)) { + return; + } + ensure_is_array(page[field]).flat().forEach((target_link) => { + var _a2; + let unsafe_target_path; + if (!target_link) + return; + else if (typeof target_link === "string") { + unsafe_target_path = (_a2 = target_link.match(MARKDOWN_LINK_REGEX)) == null ? void 0 : _a2[2]; + } else if (typeof target_link === "object" && (target_link == null ? void 0 : target_link.path)) { + unsafe_target_path = target_link.path; + } else if ( + // @ts-expect-error: instanceof didn't work here? + target_link == null ? void 0 : target_link.isLuxonDateTime + ) { + errors.push({ + path: source_file.path, + code: "invalid_field_value", + message: `Invalid value for field '${field}': '${target_link}'. Dataview DateTime values are not supported, since they don't preserve the original date string.` + }); + } else { + errors.push({ + path: source_file.path, + code: "invalid_field_value", + message: `Invalid value for field '${field}': '${target_link}'. Expected wikilink or markdown link.` + }); + } + if (!unsafe_target_path) + return; + const [target_path, target_file] = resolve_relative_target_path( + plugin.app, + unsafe_target_path, + source_file.path + ); + if (!target_file) { + graph.safe_add_node(target_path, { resolved: false }); + } + graph.safe_add_directed_edge( + source_file.path, + target_path, + { + field, + explicit: true, + source: "typed_link" + } + ); + }); + }); + }); + return { errors }; +}; + +// src/graph/builders/explicit/index.ts +var add_explicit_edges = { + tag_note: _add_explicit_edges_tag_note, + list_note: _add_explicit_edges_list_note, + date_note: _add_explicit_edges_date_note, + typed_link: _add_explicit_edges_typed_link, + regex_note: _add_explicit_edges_regex_note, + folder_note: _add_explicit_edges_folder_note, + dendron_note: _add_explicit_edges_dendron_note, + dataview_note: _add_explicit_edges_dataview_note, + johnny_decimal_note: _add_explicit_edges_johnny_decimal_note +}; + +// src/graph/builders/explicit/files.ts +var get_all_files = (app) => { + var _a; + if (dataview_plugin.is_enabled(app)) { + return { + obsidian: null, + dataview: (_a = dataview_plugin.get_api()) == null ? void 0 : _a.pages().values + }; + } else { + return { + obsidian: app.vault.getMarkdownFiles().map((file) => ({ + file, + cache: app.metadataCache.getFileCache(file) + })), + dataview: null + }; + } +}; + +// src/utils/transitive_rules.ts +var stringify_transitive_relation = (rule) => `[${rule.chain.map((attr2) => url_search_params(attr2, { trim_lone_param: true })).join(", ")}] ${rule.close_reversed ? "<-" : "->"} ${rule.close_field}`; +var regex = /\[(.+)\]\s*(<-|->)\s*(.+)/; +var get_transitive_rule_name = (rule) => rule.name || stringify_transitive_relation(rule); +var parse_transitive_relation = (str) => { + const match2 = str.match(regex); + if (!match2) { + return fail(null); + } else { + return succ({ + close_field: match2[3], + close_reversed: match2[2] === "<-", + chain: split_and_trim(match2[1]).map((field) => ({ field })) + }); + } +}; +var input_transitive_rule_schema = (data) => { + const field_labels = data.fields.map((f) => f.label); + return z.object({ + chain: z.array( + z.object({ field: zod.schema.dynamic_enum(field_labels) }) + ), + close_field: zod.schema.dynamic_enum(field_labels, "close_field"), + close_reversed: z.boolean() + }); +}; +var transitive_rule_to_edges = (rule) => { + const edges = []; + rule.chain.forEach((attr2, i) => { + var _a; + edges.push({ + source_id: i.toString(), + target_id: (i + 1).toString(), + source_attr: { resolved: true }, + target_attr: { resolved: true }, + attr: { + explicit: true, + field: (_a = attr2.field) != null ? _a : "", + source: "typed_link" + } + }); + }); + edges.push({ + source_attr: { resolved: true }, + target_attr: { resolved: true }, + source_id: rule.close_reversed ? rule.chain.length.toString() : "0", + target_id: rule.close_reversed ? "0" : rule.chain.length.toString(), + attr: { + round: 1, + explicit: false, + field: rule.close_field, + implied_kind: `transitive:${get_transitive_rule_name(rule)}` + } + }); + return edges; +}; + +// src/graph/builders/implied/transitive.ts +var _add_implied_edges_transitive = (graph, plugin, rule, round) => { + const results = { edges: [], errors: [] }; + if (rule.rounds < round) { + return results; + } else if (!plugin.settings.edge_fields.find((f) => f.label === rule.close_field)) { + results.errors.push({ + code: "invalid_setting_value", + path: "implied_relations.transitive[].close_field", + message: `close_field is not a valid BC field: '${rule.close_field}'` + }); + return results; + } + const implied_kind = `transitive:${get_transitive_rule_name(rule)}`; + graph.forEachNode((start_node) => { + Traverse.get_transitive_chain_target_ids( + graph, + start_node, + rule.chain, + (item) => item.edge.target_id !== start_node + ).forEach((end_node) => { + const [source_id, target_id] = rule.close_reversed ? [end_node, start_node] : [start_node, end_node]; + results.edges.push({ + source_id, + target_id, + attr: { + round, + implied_kind, + explicit: false, + field: rule.close_field + } + }); + }); + }); + return results; +}; + +// src/graph/builders/index.ts +var add_initial_nodes = (graph, all_files) => { + if (all_files.obsidian) { + all_files.obsidian.forEach(({ file, cache }) => { + var _a, _b, _c; + const node_attr = { + resolved: true + }; + const aliases = (_a = cache == null ? void 0 : cache.frontmatter) == null ? void 0 : _a.aliases; + if (Array.isArray(aliases) && aliases.length > 0) { + node_attr.aliases = aliases; + } + if ((_b = cache == null ? void 0 : cache.frontmatter) == null ? void 0 : _b[META_ALIAS["ignore-in-edges"]]) { + node_attr.ignore_in_edges = true; + } + if ((_c = cache == null ? void 0 : cache.frontmatter) == null ? void 0 : _c[META_ALIAS["ignore-out-edges"]]) { + node_attr.ignore_out_edges = true; + } + graph.addNode(file.path, node_attr); + }); + } else { + all_files.dataview.forEach((page) => { + const node_attr = { + resolved: true + }; + const aliases = page.file.aliases.values; + if (Array.isArray(aliases) && aliases.length > 0) { + node_attr.aliases = aliases; + } + if (page[META_ALIAS["ignore-in-edges"]]) { + node_attr.ignore_in_edges = true; + } + if (page[META_ALIAS["ignore-out-edges"]]) { + node_attr.ignore_out_edges = true; + } + graph.addNode(page.file.path, node_attr); + }); + } +}; +var rebuild_graph = async (plugin) => { + const timer = new Timer(); + const timer2 = new Timer(); + const graph = new BCGraph(); + const all_files = get_all_files(plugin.app); + add_initial_nodes(graph, all_files); + log.debug(timer.elapsedMessage("Adding initial nodes")); + timer.reset(); + const explicit_edge_results = await Promise.all( + EXPLICIT_EDGE_SOURCES.map(async (source) => { + const result = await add_explicit_edges[source]( + graph, + plugin, + all_files + ); + return { source, errors: result.errors }; + }) + ); + log.debug(timer.elapsedMessage("Adding initial edges")); + timer.reset(); + const max_implied_relationship_rounds = Math.max( + ...plugin.settings.implied_relations.transitive.map( + (imp) => imp.rounds + ) + ); + const implied_edge_results = { + transitive: [] + }; + const added_fields = /* @__PURE__ */ new Set(); + for (const edge of graph.edgeEntries()) { + added_fields.add(edge.attributes.field); + } + for (let round = 1; round <= max_implied_relationship_rounds; round++) { + const edges = []; + plugin.settings.implied_relations.transitive.forEach((rule) => { + if (!rule.chain.some((attr2) => added_fields.has(attr2.field))) { + return; + } + const result = _add_implied_edges_transitive( + graph, + plugin, + rule, + round + ); + edges.push(...result.edges); + implied_edge_results.transitive.push(...result.errors); + }); + added_fields.clear(); + if (edges.length === 0) + break; + else { + edges.forEach((edge) => { + graph.safe_add_directed_edge( + edge.source_id, + edge.target_id, + edge.attr + ) && added_fields.add(edge.attr.field); + }); + } + } + log.debug(timer.elapsedMessage("Adding implied edges")); + log.debug(timer2.elapsedMessage("Total Graph building")); + return { graph, explicit_edge_results, implied_edge_results }; +}; + +// src/settings/SettingsTab.ts +var import_obsidian24 = require("obsidian"); + +// node_modules/svelte/src/runtime/internal/utils.js +function noop() { +} +function assign(tar, src) { + for (const k in src) + tar[k] = src[k]; + return ( + /** @type {T & S} */ + tar + ); +} +function run(fn) { + return fn(); +} +function blank_object() { + return /* @__PURE__ */ Object.create(null); +} +function run_all(fns) { + fns.forEach(run); +} +function is_function(thing) { + return typeof thing === "function"; +} +function safe_not_equal(a, b) { + return a != a ? b == b : a !== b || a && typeof a === "object" || typeof a === "function"; +} +function is_empty(obj) { + return Object.keys(obj).length === 0; +} +function subscribe(store2, ...callbacks) { + if (store2 == null) { + for (const callback of callbacks) { + callback(void 0); + } + return noop; + } + const unsub = store2.subscribe(...callbacks); + return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; +} +function get_store_value(store2) { + let value; + subscribe(store2, (_) => value = _)(); + return value; +} +function component_subscribe(component, store2, callback) { + component.$$.on_destroy.push(subscribe(store2, callback)); +} +function create_slot(definition, ctx, $$scope, fn) { + if (definition) { + const slot_ctx = get_slot_context(definition, ctx, $$scope, fn); + return definition[0](slot_ctx); + } +} +function get_slot_context(definition, ctx, $$scope, fn) { + return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx; +} +function get_slot_changes(definition, $$scope, dirty, fn) { + if (definition[2] && fn) { + const lets = definition[2](fn(dirty)); + if ($$scope.dirty === void 0) { + 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 update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) { + if (slot_changes) { + const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn); + slot.p(slot_context, slot_changes); + } +} +function 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 exclude_internal_props(props) { + const result = {}; + for (const k in props) + if (k[0] !== "$") + result[k] = props[k]; + return result; +} +function 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; +} + +// node_modules/svelte/src/runtime/internal/globals.js +var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : ( + // @ts-ignore Node typings have this + global +); + +// node_modules/svelte/src/runtime/internal/ResizeObserverSingleton.js +var ResizeObserverSingleton = class _ResizeObserverSingleton { + /** @param {ResizeObserverOptions} options */ + constructor(options) { + /** + * @private + * @readonly + * @type {WeakMap} + */ + __publicField(this, "_listeners", "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0); + /** + * @private + * @type {ResizeObserver} + */ + __publicField(this, "_observer"); + /** @type {ResizeObserverOptions} */ + __publicField(this, "options"); + this.options = options; + } + /** + * @param {Element} element + * @param {import('./private.js').Listener} listener + * @returns {() => void} + */ + observe(element2, listener) { + this._listeners.set(element2, listener); + this._getObserver().observe(element2, this.options); + return () => { + this._listeners.delete(element2); + this._observer.unobserve(element2); + }; + } + /** + * @private + */ + _getObserver() { + var _a; + return (_a = this._observer) != null ? _a : this._observer = new ResizeObserver((entries) => { + var _a2; + for (const entry of entries) { + _ResizeObserverSingleton.entries.set(entry.target, entry); + (_a2 = this._listeners.get(entry.target)) == null ? void 0 : _a2(entry); + } + }); + } +}; +ResizeObserverSingleton.entries = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0; + +// node_modules/svelte/src/runtime/internal/dom.js +var is_hydrating = false; +function start_hydrating() { + is_hydrating = true; +} +function end_hydrating() { + is_hydrating = false; +} +function append(target, node) { + target.appendChild(node); +} +function append_styles(target, style_sheet_id, styles) { + const append_styles_to = get_root_for_style(target); + if (!append_styles_to.getElementById(style_sheet_id)) { + const style = element("style"); + style.id = style_sheet_id; + style.textContent = styles; + append_stylesheet(append_styles_to, style); + } +} +function get_root_for_style(node) { + if (!node) + return document; + const root = node.getRootNode ? node.getRootNode() : node.ownerDocument; + if (root && /** @type {ShadowRoot} */ + root.host) { + return ( + /** @type {ShadowRoot} */ + root + ); + } + return node.ownerDocument; +} +function append_stylesheet(node, style) { + append( + /** @type {Document} */ + node.head || node, + style + ); + return style.sheet; +} +function insert(target, node, anchor) { + target.insertBefore(node, anchor || null); +} +function detach(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +} +function destroy_each(iterations, detaching) { + for (let i = 0; i < iterations.length; i += 1) { + if (iterations[i]) + iterations[i].d(detaching); + } +} +function element(name) { + return document.createElement(name); +} +function svg_element(name) { + return document.createElementNS("http://www.w3.org/2000/svg", name); +} +function text(data) { + return document.createTextNode(data); +} +function space() { + return text(" "); +} +function empty() { + return text(""); +} +function listen(node, event, handler, options) { + node.addEventListener(event, handler, options); + return () => node.removeEventListener(event, handler, options); +} +function attr(node, attribute, value) { + if (value == null) + node.removeAttribute(attribute); + else if (node.getAttribute(attribute) !== value) + node.setAttribute(attribute, value); +} +function set_svg_attributes(node, attributes) { + for (const key in attributes) { + attr(node, key, attributes[key]); + } +} +function children(element2) { + return Array.from(element2.childNodes); +} +function set_data(text2, data) { + data = "" + data; + if (text2.data === data) + return; + text2.data = /** @type {string} */ + data; +} +function set_input_value(input, value) { + input.value = value == null ? "" : value; +} +function set_style(node, key, value, important) { + if (value == null) { + node.style.removeProperty(key); + } else { + node.style.setProperty(key, value, important ? "important" : ""); + } +} +function 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 !== void 0) { + select.selectedIndex = -1; + } +} +function select_value(select) { + const selected_option = select.querySelector(":checked"); + return selected_option && selected_option.__value; +} +function toggle_class(element2, name, toggle) { + element2.classList.toggle(name, !!toggle); +} +function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) { + return new CustomEvent(type, { detail, bubbles, cancelable }); +} +function get_custom_elements_slots(element2) { + const result = {}; + element2.childNodes.forEach( + /** @param {Element} node */ + (node) => { + result[node.slot || "default"] = true; + } + ); + return result; +} + +// node_modules/svelte/src/runtime/internal/lifecycle.js +var current_component; +function set_current_component(component) { + current_component = component; +} +function get_current_component() { + if (!current_component) + throw new Error("Function called outside component initialization"); + return current_component; +} +function onMount(fn) { + get_current_component().$$.on_mount.push(fn); +} +function createEventDispatcher() { + const component = get_current_component(); + return (type, detail, { cancelable = false } = {}) => { + const callbacks = component.$$.callbacks[type]; + if (callbacks) { + const event = custom_event( + /** @type {string} */ + type, + detail, + { cancelable } + ); + callbacks.slice().forEach((fn) => { + fn.call(component, event); + }); + return !event.defaultPrevented; + } + return true; + }; +} +function bubble(component, event) { + const callbacks = component.$$.callbacks[event.type]; + if (callbacks) { + callbacks.slice().forEach((fn) => fn.call(this, event)); + } +} + +// node_modules/svelte/src/runtime/internal/scheduler.js +var dirty_components = []; +var binding_callbacks = []; +var render_callbacks = []; +var flush_callbacks = []; +var resolved_promise = /* @__PURE__ */ Promise.resolve(); +var update_scheduled = false; +function schedule_update() { + if (!update_scheduled) { + update_scheduled = true; + resolved_promise.then(flush); + } +} +function add_render_callback(fn) { + render_callbacks.push(fn); +} +function add_flush_callback(fn) { + flush_callbacks.push(fn); +} +var seen_callbacks = /* @__PURE__ */ new Set(); +var flushidx = 0; +function flush() { + if (flushidx !== 0) { + return; + } + const saved_component = current_component; + do { + try { + while (flushidx < dirty_components.length) { + const component = dirty_components[flushidx]; + flushidx++; + set_current_component(component); + update(component.$$); + } + } catch (e) { + dirty_components.length = 0; + flushidx = 0; + throw e; + } + set_current_component(null); + dirty_components.length = 0; + flushidx = 0; + while (binding_callbacks.length) + binding_callbacks.pop()(); + for (let i = 0; i < render_callbacks.length; i += 1) { + const callback = render_callbacks[i]; + if (!seen_callbacks.has(callback)) { + seen_callbacks.add(callback); + callback(); + } + } + render_callbacks.length = 0; + } while (dirty_components.length); + while (flush_callbacks.length) { + flush_callbacks.pop()(); + } + update_scheduled = false; + seen_callbacks.clear(); + set_current_component(saved_component); +} +function update($$) { + if ($$.fragment !== null) { + $$.update(); + run_all($$.before_update); + const dirty = $$.dirty; + $$.dirty = [-1]; + $$.fragment && $$.fragment.p($$.ctx, dirty); + $$.after_update.forEach(add_render_callback); + } +} +function flush_render_callbacks(fns) { + const filtered = []; + const targets = []; + render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c)); + targets.forEach((c) => c()); + render_callbacks = filtered; +} + +// node_modules/svelte/src/runtime/internal/transitions.js +var outroing = /* @__PURE__ */ new Set(); +var outros; +function group_outros() { + outros = { + r: 0, + c: [], + p: outros + // parent group + }; +} +function check_outros() { + if (!outros.r) { + run_all(outros.c); + } + outros = outros.p; +} +function transition_in(block, local) { + if (block && block.i) { + outroing.delete(block); + block.i(local); + } +} +function transition_out(block, local, detach2, callback) { + if (block && block.o) { + if (outroing.has(block)) + return; + outroing.add(block); + outros.c.push(() => { + outroing.delete(block); + if (callback) { + if (detach2) + block.d(1); + callback(); + } + }); + block.o(local); + } else if (callback) { + callback(); + } +} + +// node_modules/svelte/src/runtime/internal/each.js +function ensure_array_like(array_like_or_iterator) { + return (array_like_or_iterator == null ? void 0 : array_like_or_iterator.length) !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator); +} +function outro_and_destroy_block(block, lookup) { + transition_out(block, 1, 1, () => { + lookup.delete(block.key); + }); +} +function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list, lookup, node, destroy, create_each_block12, next, get_context) { + let o = old_blocks.length; + let n2 = list.length; + let i = o; + const old_indexes = {}; + while (i--) + old_indexes[old_blocks[i].key] = i; + const new_blocks = []; + const new_lookup = /* @__PURE__ */ new Map(); + const deltas = /* @__PURE__ */ new Map(); + const updates = []; + i = n2; + 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_block12(key, child_ctx); + block.c(); + } else if (dynamic) { + 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 = /* @__PURE__ */ new Set(); + const did_move = /* @__PURE__ */ new Set(); + function insert2(block) { + transition_in(block, 1); + block.m(node, next); + lookup.set(block.key, block); + next = block.first; + n2--; + } + while (o && n2) { + const new_block = new_blocks[n2 - 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) { + next = new_block.first; + o--; + n2--; + } else if (!new_lookup.has(old_key)) { + destroy(old_block, lookup); + o--; + } else if (!lookup.has(new_key) || will_move.has(new_key)) { + insert2(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); + insert2(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 (n2) + insert2(new_blocks[n2 - 1]); + run_all(updates); + return new_blocks; +} + +// node_modules/svelte/src/runtime/internal/spread.js +function get_spread_update(levels, updates) { + const update2 = {}; + const to_null_out = {}; + const accounted_for = { $$scope: 1 }; + let i = levels.length; + while (i--) { + const o = levels[i]; + const n2 = updates[i]; + if (n2) { + for (const key in o) { + if (!(key in n2)) + to_null_out[key] = 1; + } + for (const key in n2) { + if (!accounted_for[key]) { + update2[key] = n2[key]; + accounted_for[key] = 1; + } + } + levels[i] = n2; + } else { + for (const key in o) { + accounted_for[key] = 1; + } + } + } + for (const key in to_null_out) { + if (!(key in update2)) + update2[key] = void 0; + } + return update2; +} +function get_spread_object(spread_props) { + return typeof spread_props === "object" && spread_props !== null ? spread_props : {}; +} + +// node_modules/svelte/src/shared/boolean_attributes.js +var _boolean_attributes = ( + /** @type {const} */ + [ + "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" + ] +); +var boolean_attributes = /* @__PURE__ */ new Set([..._boolean_attributes]); + +// node_modules/svelte/src/runtime/internal/Component.js +function bind(component, name, callback) { + const index = component.$$.props[name]; + if (index !== void 0) { + component.$$.bound[index] = callback; + callback(component.$$.ctx[index]); + } +} +function create_component(block) { + block && block.c(); +} +function mount_component(component, target, anchor) { + const { fragment, after_update } = component.$$; + fragment && fragment.m(target, anchor); + add_render_callback(() => { + const new_on_destroy = component.$$.on_mount.map(run).filter(is_function); + if (component.$$.on_destroy) { + component.$$.on_destroy.push(...new_on_destroy); + } else { + run_all(new_on_destroy); + } + component.$$.on_mount = []; + }); + after_update.forEach(add_render_callback); +} +function destroy_component(component, detaching) { + const $$ = component.$$; + if ($$.fragment !== null) { + flush_render_callbacks($$.after_update); + run_all($$.on_destroy); + $$.fragment && $$.fragment.d(detaching); + $$.on_destroy = $$.fragment = null; + $$.ctx = []; + } +} +function make_dirty(component, i) { + if (component.$$.dirty[0] === -1) { + dirty_components.push(component); + schedule_update(); + component.$$.dirty.fill(0); + } + component.$$.dirty[i / 31 | 0] |= 1 << i % 31; +} +function init(component, options, instance56, create_fragment56, not_equal, props, append_styles2 = null, dirty = [-1]) { + const parent_component = current_component; + set_current_component(component); + const $$ = component.$$ = { + fragment: null, + ctx: [], + // state + props, + update: noop, + not_equal, + bound: 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: blank_object(), + dirty, + skip_bound: false, + root: options.target || parent_component.$$.root + }; + append_styles2 && append_styles2($$.root); + let ready = false; + $$.ctx = instance56 ? instance56(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) + make_dirty(component, i); + } + return ret; + }) : []; + $$.update(); + ready = true; + run_all($$.before_update); + $$.fragment = create_fragment56 ? create_fragment56($$.ctx) : false; + if (options.target) { + if (options.hydrate) { + start_hydrating(); + const nodes = children(options.target); + $$.fragment && $$.fragment.l(nodes); + nodes.forEach(detach); + } else { + $$.fragment && $$.fragment.c(); + } + if (options.intro) + transition_in(component.$$.fragment); + mount_component(component, options.target, options.anchor); + end_hydrating(); + flush(); + } + set_current_component(parent_component); +} +var SvelteElement; +if (typeof HTMLElement === "function") { + SvelteElement = class extends HTMLElement { + constructor($$componentCtor, $$slots, use_shadow_dom) { + super(); + /** The Svelte component constructor */ + __publicField(this, "$$ctor"); + /** Slots */ + __publicField(this, "$$s"); + /** The Svelte component instance */ + __publicField(this, "$$c"); + /** Whether or not the custom element is connected */ + __publicField(this, "$$cn", false); + /** Component props data */ + __publicField(this, "$$d", {}); + /** `true` if currently in the process of reflecting component props back to attributes */ + __publicField(this, "$$r", false); + /** @type {Record} Props definition (name, reflected, type etc) */ + __publicField(this, "$$p_d", {}); + /** @type {Record} Event listeners */ + __publicField(this, "$$l", {}); + /** @type {Map} Event listener unsubscribe functions */ + __publicField(this, "$$l_u", /* @__PURE__ */ new Map()); + this.$$ctor = $$componentCtor; + this.$$s = $$slots; + if (use_shadow_dom) { + this.attachShadow({ mode: "open" }); + } + } + addEventListener(type, listener, options) { + this.$$l[type] = this.$$l[type] || []; + this.$$l[type].push(listener); + if (this.$$c) { + const unsub = this.$$c.$on(type, listener); + this.$$l_u.set(listener, unsub); + } + super.addEventListener(type, listener, options); + } + removeEventListener(type, listener, options) { + super.removeEventListener(type, listener, options); + if (this.$$c) { + const unsub = this.$$l_u.get(listener); + if (unsub) { + unsub(); + this.$$l_u.delete(listener); + } + } + } + async connectedCallback() { + this.$$cn = true; + if (!this.$$c) { + let create_slot2 = function(name) { + return () => { + let node; + const obj = { + c: function create() { + node = element("slot"); + if (name !== "default") { + attr(node, "name", name); + } + }, + /** + * @param {HTMLElement} target + * @param {HTMLElement} [anchor] + */ + m: function mount(target, anchor) { + insert(target, node, anchor); + }, + d: function destroy(detaching) { + if (detaching) { + detach(node); + } + } + }; + return obj; + }; + }; + await Promise.resolve(); + if (!this.$$cn) { + return; + } + const $$slots = {}; + const existing_slots = get_custom_elements_slots(this); + for (const name of this.$$s) { + if (name in existing_slots) { + $$slots[name] = [create_slot2(name)]; + } + } + for (const attribute of this.attributes) { + const name = this.$$g_p(attribute.name); + if (!(name in this.$$d)) { + this.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, "toProp"); + } + } + for (const key in this.$$p_d) { + if (!(key in this.$$d) && this[key] !== void 0) { + this.$$d[key] = this[key]; + delete this[key]; + } + } + this.$$c = new this.$$ctor({ + target: this.shadowRoot || this, + props: { + ...this.$$d, + $$slots, + $$scope: { + ctx: [] + } + } + }); + const reflect_attributes = () => { + this.$$r = true; + for (const key in this.$$p_d) { + this.$$d[key] = this.$$c.$$.ctx[this.$$c.$$.props[key]]; + if (this.$$p_d[key].reflect) { + const attribute_value = get_custom_element_value( + key, + this.$$d[key], + this.$$p_d, + "toAttribute" + ); + if (attribute_value == null) { + this.removeAttribute(this.$$p_d[key].attribute || key); + } else { + this.setAttribute(this.$$p_d[key].attribute || key, attribute_value); + } + } + } + this.$$r = false; + }; + this.$$c.$$.after_update.push(reflect_attributes); + reflect_attributes(); + for (const type in this.$$l) { + for (const listener of this.$$l[type]) { + const unsub = this.$$c.$on(type, listener); + this.$$l_u.set(listener, unsub); + } + } + this.$$l = {}; + } + } + // We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte + // and setting attributes through setAttribute etc, this is helpful + attributeChangedCallback(attr2, _oldValue, newValue) { + var _a; + if (this.$$r) + return; + attr2 = this.$$g_p(attr2); + this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp"); + (_a = this.$$c) == null ? void 0 : _a.$set({ [attr2]: this.$$d[attr2] }); + } + disconnectedCallback() { + this.$$cn = false; + Promise.resolve().then(() => { + if (!this.$$cn) { + this.$$c.$destroy(); + this.$$c = void 0; + } + }); + } + $$g_p(attribute_name) { + return Object.keys(this.$$p_d).find( + (key) => this.$$p_d[key].attribute === attribute_name || !this.$$p_d[key].attribute && key.toLowerCase() === attribute_name + ) || attribute_name; + } + }; +} +function get_custom_element_value(prop, value, props_definition, transform) { + var _a; + const type = (_a = props_definition[prop]) == null ? void 0 : _a.type; + value = type === "Boolean" && typeof value !== "boolean" ? value != null : value; + if (!transform || !props_definition[prop]) { + return value; + } else if (transform === "toAttribute") { + switch (type) { + case "Object": + case "Array": + return value == null ? null : JSON.stringify(value); + case "Boolean": + return value ? "" : null; + case "Number": + return value == null ? null : value; + default: + return value; + } + } else { + switch (type) { + case "Object": + case "Array": + return value && JSON.parse(value); + case "Boolean": + return value; + case "Number": + return value != null ? +value : value; + default: + return value; + } + } +} +var SvelteComponent = class { + constructor() { + /** + * ### PRIVATE API + * + * Do not use, may change at any time + * + * @type {any} + */ + __publicField(this, "$$"); + /** + * ### PRIVATE API + * + * Do not use, may change at any time + * + * @type {any} + */ + __publicField(this, "$$set"); + } + /** @returns {void} */ + $destroy() { + destroy_component(this, 1); + this.$destroy = noop; + } + /** + * @template {Extract} K + * @param {K} type + * @param {((e: Events[K]) => void) | null | undefined} callback + * @returns {() => void} + */ + $on(type, callback) { + if (!is_function(callback)) { + return 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); + }; + } + /** + * @param {Partial} props + * @returns {void} + */ + $set(props) { + if (this.$$set && !is_empty(props)) { + this.$$.skip_bound = true; + this.$$set(props); + this.$$.skip_bound = false; + } + } +}; + +// node_modules/svelte/src/shared/version.js +var PUBLIC_VERSION = "4"; + +// node_modules/svelte/src/runtime/internal/disclose-version/index.js +if (typeof window !== "undefined") + (window.__svelte || (window.__svelte = { v: /* @__PURE__ */ new Set() })).v.add(PUBLIC_VERSION); + +// node_modules/tslib/tslib.es6.mjs +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()); + }); +} + +// node_modules/lucide-svelte/dist/defaultAttributes.js +var defaultAttributes = { + xmlns: "http://www.w3.org/2000/svg", + width: 24, + height: 24, + viewBox: "0 0 24 24", + fill: "none", + stroke: "currentColor", + "stroke-width": 2, + "stroke-linecap": "round", + "stroke-linejoin": "round" +}; +var defaultAttributes_default = defaultAttributes; + +// node_modules/lucide-svelte/dist/Icon.svelte +function get_each_context(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[10] = list[i][0]; + child_ctx[11] = list[i][1]; + return child_ctx; +} +function create_dynamic_element(ctx) { + let svelte_element; + let svelte_element_levels = [ + /*attrs*/ + ctx[11] + ]; + let svelte_element_data = {}; + for (let i = 0; i < svelte_element_levels.length; i += 1) { + svelte_element_data = assign(svelte_element_data, svelte_element_levels[i]); + } + return { + c() { + svelte_element = svg_element( + /*tag*/ + ctx[10] + ); + set_svg_attributes(svelte_element, svelte_element_data); + }, + m(target, anchor) { + insert(target, svelte_element, anchor); + }, + p(ctx2, dirty) { + set_svg_attributes(svelte_element, svelte_element_data = get_spread_update(svelte_element_levels, [dirty & /*iconNode*/ + 32 && /*attrs*/ + ctx2[11]])); + }, + d(detaching) { + if (detaching) { + detach(svelte_element); + } + } + }; +} +function create_each_block(ctx) { + let previous_tag = ( + /*tag*/ + ctx[10] + ); + let svelte_element_anchor; + let svelte_element = ( + /*tag*/ + ctx[10] && create_dynamic_element(ctx) + ); + return { + c() { + if (svelte_element) + svelte_element.c(); + svelte_element_anchor = empty(); + }, + m(target, anchor) { + if (svelte_element) + svelte_element.m(target, anchor); + insert(target, svelte_element_anchor, anchor); + }, + p(ctx2, dirty) { + if ( + /*tag*/ + ctx2[10] + ) { + if (!previous_tag) { + svelte_element = create_dynamic_element(ctx2); + previous_tag = /*tag*/ + ctx2[10]; + svelte_element.c(); + svelte_element.m(svelte_element_anchor.parentNode, svelte_element_anchor); + } else if (safe_not_equal( + previous_tag, + /*tag*/ + ctx2[10] + )) { + svelte_element.d(1); + svelte_element = create_dynamic_element(ctx2); + previous_tag = /*tag*/ + ctx2[10]; + svelte_element.c(); + svelte_element.m(svelte_element_anchor.parentNode, svelte_element_anchor); + } else { + svelte_element.p(ctx2, dirty); + } + } else if (previous_tag) { + svelte_element.d(1); + svelte_element = null; + previous_tag = /*tag*/ + ctx2[10]; + } + }, + d(detaching) { + if (detaching) { + detach(svelte_element_anchor); + } + if (svelte_element) + svelte_element.d(detaching); + } + }; +} +function create_fragment(ctx) { + var _a; + let svg; + let each_1_anchor; + let svg_stroke_width_value; + let svg_class_value; + let current; + let each_value = ensure_array_like( + /*iconNode*/ + ctx[5] + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i)); + } + const default_slot_template = ( + /*#slots*/ + ctx[9].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[8], + null + ); + let svg_levels = [ + defaultAttributes_default, + /*$$restProps*/ + ctx[6], + { width: ( + /*size*/ + ctx[2] + ) }, + { height: ( + /*size*/ + ctx[2] + ) }, + { stroke: ( + /*color*/ + ctx[1] + ) }, + { + "stroke-width": svg_stroke_width_value = /*absoluteStrokeWidth*/ + ctx[4] ? Number( + /*strokeWidth*/ + ctx[3] + ) * 24 / Number( + /*size*/ + ctx[2] + ) : ( + /*strokeWidth*/ + ctx[3] + ) + }, + { + class: svg_class_value = `lucide-icon lucide lucide-${/*name*/ + ctx[0]} ${/*$$props*/ + (_a = ctx[7].class) != null ? _a : ""}` + } + ]; + let svg_data = {}; + for (let i = 0; i < svg_levels.length; i += 1) { + svg_data = assign(svg_data, svg_levels[i]); + } + return { + c() { + svg = svg_element("svg"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + if (default_slot) + default_slot.c(); + set_svg_attributes(svg, svg_data); + }, + m(target, anchor) { + insert(target, svg, anchor); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(svg, null); + } + } + append(svg, each_1_anchor); + if (default_slot) { + default_slot.m(svg, null); + } + current = true; + }, + p(ctx2, [dirty]) { + var _a2; + if (dirty & /*iconNode*/ + 32) { + each_value = ensure_array_like( + /*iconNode*/ + ctx2[5] + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block(child_ctx); + each_blocks[i].c(); + each_blocks[i].m(svg, each_1_anchor); + } + } + for (; i < each_blocks.length; i += 1) { + each_blocks[i].d(1); + } + each_blocks.length = each_value.length; + } + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 256)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[8], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[8] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[8], + dirty, + null + ), + null + ); + } + } + set_svg_attributes(svg, svg_data = get_spread_update(svg_levels, [ + defaultAttributes_default, + dirty & /*$$restProps*/ + 64 && /*$$restProps*/ + ctx2[6], + (!current || dirty & /*size*/ + 4) && { width: ( + /*size*/ + ctx2[2] + ) }, + (!current || dirty & /*size*/ + 4) && { height: ( + /*size*/ + ctx2[2] + ) }, + (!current || dirty & /*color*/ + 2) && { stroke: ( + /*color*/ + ctx2[1] + ) }, + (!current || dirty & /*absoluteStrokeWidth, strokeWidth, size*/ + 28 && svg_stroke_width_value !== (svg_stroke_width_value = /*absoluteStrokeWidth*/ + ctx2[4] ? Number( + /*strokeWidth*/ + ctx2[3] + ) * 24 / Number( + /*size*/ + ctx2[2] + ) : ( + /*strokeWidth*/ + ctx2[3] + ))) && { "stroke-width": svg_stroke_width_value }, + (!current || dirty & /*name, $$props*/ + 129 && svg_class_value !== (svg_class_value = `lucide-icon lucide lucide-${/*name*/ + ctx2[0]} ${/*$$props*/ + (_a2 = ctx2[7].class) != null ? _a2 : ""}`)) && { class: svg_class_value } + ])); + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(svg); + } + destroy_each(each_blocks, detaching); + if (default_slot) + default_slot.d(detaching); + } + }; +} +function instance($$self, $$props, $$invalidate) { + const omit_props_names = ["name", "color", "size", "strokeWidth", "absoluteStrokeWidth", "iconNode"]; + let $$restProps = compute_rest_props($$props, omit_props_names); + let { $$slots: slots = {}, $$scope } = $$props; + let { name } = $$props; + let { color = "currentColor" } = $$props; + let { size = 24 } = $$props; + let { strokeWidth = 2 } = $$props; + let { absoluteStrokeWidth = false } = $$props; + let { iconNode } = $$props; + $$self.$$set = ($$new_props) => { + $$invalidate(7, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + $$invalidate(6, $$restProps = compute_rest_props($$props, omit_props_names)); + if ("name" in $$new_props) + $$invalidate(0, name = $$new_props.name); + if ("color" in $$new_props) + $$invalidate(1, color = $$new_props.color); + if ("size" in $$new_props) + $$invalidate(2, size = $$new_props.size); + if ("strokeWidth" in $$new_props) + $$invalidate(3, strokeWidth = $$new_props.strokeWidth); + if ("absoluteStrokeWidth" in $$new_props) + $$invalidate(4, absoluteStrokeWidth = $$new_props.absoluteStrokeWidth); + if ("iconNode" in $$new_props) + $$invalidate(5, iconNode = $$new_props.iconNode); + if ("$$scope" in $$new_props) + $$invalidate(8, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [ + name, + color, + size, + strokeWidth, + absoluteStrokeWidth, + iconNode, + $$restProps, + $$props, + $$scope, + slots + ]; +} +var Icon = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance, create_fragment, safe_not_equal, { + name: 0, + color: 1, + size: 2, + strokeWidth: 3, + absoluteStrokeWidth: 4, + iconNode: 5 + }); + } +}; +var Icon_default = Icon; + +// node_modules/lucide-svelte/dist/icons/arrow-down-wide-narrow.svelte +function create_default_slot(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment2(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "arrow-down-wide-narrow" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance2($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + ["path", { "d": "m3 16 4 4 4-4" }], + ["path", { "d": "M7 20V4" }], + ["path", { "d": "M11 4h10" }], + ["path", { "d": "M11 8h7" }], + ["path", { "d": "M11 12h4" }] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Arrow_down_wide_narrow = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance2, create_fragment2, safe_not_equal, {}); + } +}; +var arrow_down_wide_narrow_default = Arrow_down_wide_narrow; + +// node_modules/lucide-svelte/dist/icons/arrow-down.svelte +function create_default_slot2(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment3(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "arrow-down" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot2] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance3($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "M12 5v14" }], ["path", { "d": "m19 12-7 7-7-7" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Arrow_down = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance3, create_fragment3, safe_not_equal, {}); + } +}; +var arrow_down_default = Arrow_down; + +// node_modules/lucide-svelte/dist/icons/arrow-up-narrow-wide.svelte +function create_default_slot3(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment4(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "arrow-up-narrow-wide" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot3] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance4($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + ["path", { "d": "m3 8 4-4 4 4" }], + ["path", { "d": "M7 4v16" }], + ["path", { "d": "M11 12h4" }], + ["path", { "d": "M11 16h7" }], + ["path", { "d": "M11 20h10" }] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Arrow_up_narrow_wide = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance4, create_fragment4, safe_not_equal, {}); + } +}; +var arrow_up_narrow_wide_default = Arrow_up_narrow_wide; + +// node_modules/lucide-svelte/dist/icons/arrow-up.svelte +function create_default_slot4(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment5(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "arrow-up" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot4] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance5($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "m5 12 7-7 7 7" }], ["path", { "d": "M12 19V5" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Arrow_up = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance5, create_fragment5, safe_not_equal, {}); + } +}; +var arrow_up_default = Arrow_up; + +// node_modules/lucide-svelte/dist/icons/check.svelte +function create_default_slot5(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment6(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "check" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot5] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance6($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "M20 6 9 17l-5-5" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Check = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance6, create_fragment6, safe_not_equal, {}); + } +}; +var check_default = Check; + +// node_modules/lucide-svelte/dist/icons/chevron-down.svelte +function create_default_slot6(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment7(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "chevron-down" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot6] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance7($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "m6 9 6 6 6-6" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Chevron_down = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance7, create_fragment7, safe_not_equal, {}); + } +}; +var chevron_down_default = Chevron_down; + +// node_modules/lucide-svelte/dist/icons/chevron-right.svelte +function create_default_slot7(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment8(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "chevron-right" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot7] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance8($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "m9 18 6-6-6-6" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Chevron_right = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance8, create_fragment8, safe_not_equal, {}); + } +}; +var chevron_right_default = Chevron_right; + +// node_modules/lucide-svelte/dist/icons/chevrons-down-up.svelte +function create_default_slot8(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment9(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "chevrons-down-up" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot8] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance9($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "m7 20 5-5 5 5" }], ["path", { "d": "m7 4 5 5 5-5" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Chevrons_down_up = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance9, create_fragment9, safe_not_equal, {}); + } +}; +var chevrons_down_up_default = Chevrons_down_up; + +// node_modules/lucide-svelte/dist/icons/chevrons-up-down.svelte +function create_default_slot9(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment10(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "chevrons-up-down" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot9] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance10($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "m7 15 5 5 5-5" }], ["path", { "d": "m7 9 5-5 5 5" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Chevrons_up_down = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance10, create_fragment10, safe_not_equal, {}); + } +}; +var chevrons_up_down_default = Chevrons_up_down; + +// node_modules/lucide-svelte/dist/icons/clipboard.svelte +function create_default_slot10(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment11(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "clipboard" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot10] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance11($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + [ + "rect", + { + "width": "8", + "height": "4", + "x": "8", + "y": "2", + "rx": "1", + "ry": "1" + } + ], + [ + "path", + { + "d": "M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" + } + ] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Clipboard = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance11, create_fragment11, safe_not_equal, {}); + } +}; +var clipboard_default = Clipboard; + +// node_modules/lucide-svelte/dist/icons/file-json.svelte +function create_default_slot11(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment12(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "file-json" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot11] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance12($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + [ + "path", + { + "d": "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" + } + ], + ["path", { "d": "M14 2v4a2 2 0 0 0 2 2h4" }], + [ + "path", + { + "d": "M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1" + } + ], + [ + "path", + { + "d": "M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1" + } + ] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var File_json = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance12, create_fragment12, safe_not_equal, {}); + } +}; +var file_json_default = File_json; + +// node_modules/lucide-svelte/dist/icons/group.svelte +function create_default_slot12(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment13(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "group" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot12] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance13($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + ["path", { "d": "M3 7V5c0-1.1.9-2 2-2h2" }], + ["path", { "d": "M17 3h2c1.1 0 2 .9 2 2v2" }], + ["path", { "d": "M21 17v2c0 1.1-.9 2-2 2h-2" }], + ["path", { "d": "M7 21H5c-1.1 0-2-.9-2-2v-2" }], + [ + "rect", + { + "width": "7", + "height": "5", + "x": "7", + "y": "7", + "rx": "1" + } + ], + [ + "rect", + { + "width": "7", + "height": "5", + "x": "10", + "y": "12", + "rx": "1" + } + ] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Group = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance13, create_fragment13, safe_not_equal, {}); + } +}; +var group_default = Group; + +// node_modules/lucide-svelte/dist/icons/image.svelte +function create_default_slot13(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment14(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "image" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot13] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance14($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + [ + "rect", + { + "width": "18", + "height": "18", + "x": "3", + "y": "3", + "rx": "2", + "ry": "2" + } + ], + ["circle", { "cx": "9", "cy": "9", "r": "2" }], + [ + "path", + { + "d": "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" + } + ] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Image = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance14, create_fragment14, safe_not_equal, {}); + } +}; +var image_default = Image; + +// node_modules/lucide-svelte/dist/icons/merge.svelte +function create_default_slot14(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment15(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "merge" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot14] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance15($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + ["path", { "d": "m8 6 4-4 4 4" }], + [ + "path", + { + "d": "M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22" + } + ], + ["path", { "d": "m20 22-5-5" }] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Merge = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance15, create_fragment15, safe_not_equal, {}); + } +}; +var merge_default = Merge; + +// node_modules/lucide-svelte/dist/icons/pencil.svelte +function create_default_slot15(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment16(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "pencil" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot15] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance16($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + [ + "path", + { + "d": "M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" + } + ], + ["path", { "d": "m15 5 4 4" }] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Pencil = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance16, create_fragment16, safe_not_equal, {}); + } +}; +var pencil_default = Pencil; + +// node_modules/lucide-svelte/dist/icons/plus.svelte +function create_default_slot16(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment17(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "plus" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot16] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance17($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [["path", { "d": "M5 12h14" }], ["path", { "d": "M12 5v14" }]]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Plus = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance17, create_fragment17, safe_not_equal, {}); + } +}; +var plus_default = Plus; + +// node_modules/lucide-svelte/dist/icons/rotate-ccw.svelte +function create_default_slot17(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment18(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "rotate-ccw" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot17] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance18($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + [ + "path", + { + "d": "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" + } + ], + ["path", { "d": "M3 3v5h5" }] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Rotate_ccw = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance18, create_fragment18, safe_not_equal, {}); + } +}; +var rotate_ccw_default = Rotate_ccw; + +// node_modules/lucide-svelte/dist/icons/save.svelte +function create_default_slot18(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment19(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "save" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot18] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance19($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + [ + "path", + { + "d": "M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" + } + ], + ["polyline", { "points": "17 21 17 13 7 13 7 21" }], + ["polyline", { "points": "7 3 7 8 15 8" }] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Save = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance19, create_fragment19, safe_not_equal, {}); + } +}; +var save_default = Save; + +// node_modules/lucide-svelte/dist/icons/split.svelte +function create_default_slot19(ctx) { + let current; + const default_slot_template = ( + /*#slots*/ + ctx[2].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[3], + null + ); + return { + c() { + if (default_slot) + default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + current = true; + }, + p(ctx2, dirty) { + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 8)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[3], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[3] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[3], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) + default_slot.d(detaching); + } + }; +} +function create_fragment20(ctx) { + let icon; + let current; + const icon_spread_levels = [ + { name: "split" }, + /*$$props*/ + ctx[1], + { iconNode: ( + /*iconNode*/ + ctx[0] + ) } + ]; + let icon_props = { + $$slots: { default: [create_default_slot19] }, + $$scope: { ctx } + }; + for (let i = 0; i < icon_spread_levels.length; i += 1) { + icon_props = assign(icon_props, icon_spread_levels[i]); + } + icon = new Icon_default({ props: icon_props }); + return { + c() { + create_component(icon.$$.fragment); + }, + m(target, anchor) { + mount_component(icon, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const icon_changes = dirty & /*$$props, iconNode*/ + 3 ? get_spread_update(icon_spread_levels, [ + icon_spread_levels[0], + dirty & /*$$props*/ + 2 && get_spread_object( + /*$$props*/ + ctx2[1] + ), + dirty & /*iconNode*/ + 1 && { iconNode: ( + /*iconNode*/ + ctx2[0] + ) } + ]) : {}; + if (dirty & /*$$scope*/ + 8) { + icon_changes.$$scope = { dirty, ctx: ctx2 }; + } + icon.$set(icon_changes); + }, + i(local) { + if (current) + return; + transition_in(icon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(icon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(icon, detaching); + } + }; +} +function instance20($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + const iconNode = [ + ["path", { "d": "M16 3h5v5" }], + ["path", { "d": "M8 3H3v5" }], + [ + "path", + { + "d": "M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3" + } + ], + ["path", { "d": "m15 9 6-6" }] + ]; + $$self.$$set = ($$new_props) => { + $$invalidate(1, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props))); + if ("$$scope" in $$new_props) + $$invalidate(3, $$scope = $$new_props.$$scope); + }; + $$props = exclude_internal_props($$props); + return [iconNode, $$props, slots, $$scope]; +} +var Split = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance20, create_fragment20, safe_not_equal, {}); + } +}; +var split_default = Split; + +// src/components/settings/EdgeFieldSettings.svelte +var import_obsidian7 = require("obsidian"); + +// src/const/index.ts +var ICON_SIZE = 20; + +// src/components/obsidian/tag.svelte +function create_else_block(ctx) { + let a; + let t; + let mounted; + let dispose; + return { + c() { + a = element("a"); + t = text( + /*tag*/ + ctx[0] + ); + attr( + a, + "title", + /*title*/ + ctx[2] + ); + attr(a, "class", "tag"); + attr(a, "tabindex", "0"); + attr(a, "role", "button"); + }, + m(target, anchor) { + insert(target, a, anchor); + append(a, t); + if (!mounted) { + dispose = [ + listen( + a, + "click", + /*click_handler_1*/ + ctx[5] + ), + listen( + a, + "keydown", + /*keydown_handler*/ + ctx[6] + ), + listen( + a, + "contextmenu", + /*contextmenu_handler_1*/ + ctx[7] + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & /*tag*/ + 1) + set_data( + t, + /*tag*/ + ctx2[0] + ); + if (dirty & /*title*/ + 4) { + attr( + a, + "title", + /*title*/ + ctx2[2] + ); + } + }, + d(detaching) { + if (detaching) { + detach(a); + } + mounted = false; + run_all(dispose); + } + }; +} +function create_if_block(ctx) { + let a; + let t; + let mounted; + let dispose; + return { + c() { + a = element("a"); + t = text( + /*tag*/ + ctx[0] + ); + attr( + a, + "href", + /*href*/ + ctx[1] + ); + attr( + a, + "title", + /*title*/ + ctx[2] + ); + attr(a, "class", "tag"); + }, + m(target, anchor) { + insert(target, a, anchor); + append(a, t); + if (!mounted) { + dispose = [ + listen( + a, + "click", + /*click_handler*/ + ctx[3] + ), + listen( + a, + "contextmenu", + /*contextmenu_handler*/ + ctx[4] + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & /*tag*/ + 1) + set_data( + t, + /*tag*/ + ctx2[0] + ); + if (dirty & /*href*/ + 2) { + attr( + a, + "href", + /*href*/ + ctx2[1] + ); + } + if (dirty & /*title*/ + 4) { + attr( + a, + "title", + /*title*/ + ctx2[2] + ); + } + }, + d(detaching) { + if (detaching) { + detach(a); + } + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment21(ctx) { + let if_block_anchor; + function select_block_type(ctx2, dirty) { + if ( + /*href*/ + ctx2[1] !== void 0 + ) + return create_if_block; + return create_else_block; + } + let current_block_type = select_block_type(ctx, -1); + let if_block = current_block_type(ctx); + return { + c() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + }, + p(ctx2, [dirty]) { + if (current_block_type === (current_block_type = select_block_type(ctx2, dirty)) && if_block) { + if_block.p(ctx2, dirty); + } else { + if_block.d(1); + if_block = current_block_type(ctx2); + if (if_block) { + if_block.c(); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if_block.d(detaching); + } + }; +} +function instance21($$self, $$props, $$invalidate) { + let { tag } = $$props; + let { href = void 0 } = $$props; + let { title = void 0 } = $$props; + function click_handler(event) { + bubble.call(this, $$self, event); + } + function contextmenu_handler(event) { + bubble.call(this, $$self, event); + } + function click_handler_1(event) { + bubble.call(this, $$self, event); + } + function keydown_handler(event) { + bubble.call(this, $$self, event); + } + function contextmenu_handler_1(event) { + bubble.call(this, $$self, event); + } + $$self.$$set = ($$props2) => { + if ("tag" in $$props2) + $$invalidate(0, tag = $$props2.tag); + if ("href" in $$props2) + $$invalidate(1, href = $$props2.href); + if ("title" in $$props2) + $$invalidate(2, title = $$props2.title); + }; + return [ + tag, + href, + title, + click_handler, + contextmenu_handler, + click_handler_1, + keydown_handler, + contextmenu_handler_1 + ]; +} +var Tag = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance21, create_fragment21, safe_not_equal, { tag: 0, href: 1, title: 2 }); + } +}; +var tag_default = Tag; + +// src/components/settings/EdgeFieldSettings.svelte +function get_each_context2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[22] = list[i]; + return child_ctx; +} +function get_each_context_1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[25] = list[i]; + return child_ctx; +} +function get_each_context_2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[28] = list[i]; + return child_ctx; +} +function get_each_context_3(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[31] = list[i]; + const constants_0 = ( + /*settings*/ + child_ctx[0].edge_field_groups.filter(function func_1(...args) { + return ( + /*func_1*/ + ctx[13]( + /*field*/ + child_ctx[31], + ...args + ) + ); + }).map((g) => g.label) + ); + child_ctx[32] = constants_0; + return child_ctx; +} +function get_each_context_4(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[22] = list[i]; + return child_ctx; +} +function get_each_context_5(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[37] = list[i]; + return child_ctx; +} +function create_if_block_6(ctx) { + let span; + return { + c() { + span = element("span"); + span.textContent = "Unsaved changes"; + attr(span, "class", "text-warning"); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + d(detaching) { + if (detaching) { + detach(span); + } + } + }; +} +function create_if_block_5(ctx) { + let button; + let arrowdown; + let current; + let mounted; + let dispose; + arrowdown = new arrow_down_default({ props: { size: ICON_SIZE } }); + return { + c() { + button = element("button"); + create_component(arrowdown.$$.fragment); + attr(button, "class", "w-10"); + attr(button, "aria-label", "Jump to bottom"); + }, + m(target, anchor) { + insert(target, button, anchor); + mount_component(arrowdown, button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler_1*/ + ctx[7] + ); + mounted = true; + } + }, + p: noop, + i(local) { + if (current) + return; + transition_in(arrowdown.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(arrowdown.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + destroy_component(arrowdown); + mounted = false; + dispose(); + } + }; +} +function create_each_block_5(ctx) { + let div; + let tag; + let current; + function click_handler_3() { + return ( + /*click_handler_3*/ + ctx[11]( + /*group_label*/ + ctx[37] + ) + ); + } + tag = new tag_default({ + props: { + tag: ( + /*group_label*/ + ctx[37] + ), + title: "Jump to group. Right click for more actions." + } + }); + tag.$on("click", click_handler_3); + tag.$on("contextmenu", function() { + if (is_function( + /*context_menus*/ + ctx[3].field_group( + /*field*/ + ctx[31], + /*group_label*/ + ctx[37] + ) + )) + ctx[3].field_group( + /*field*/ + ctx[31], + /*group_label*/ + ctx[37] + ).apply(this, arguments); + }); + return { + c() { + div = element("div"); + create_component(tag.$$.fragment); + attr(div, "class", "flex items-center gap-0.5"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(tag, div, null); + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + const tag_changes = {}; + if (dirty[0] & /*settings, filters*/ + 3) + tag_changes.tag = /*group_label*/ + ctx[37]; + tag.$set(tag_changes); + }, + i(local) { + if (current) + return; + transition_in(tag.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(tag.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(tag); + } + }; +} +function create_if_block_4(ctx) { + let span; + return { + c() { + span = element("span"); + span.textContent = `${""}`; + attr(span, "class", "search-empty-state my-0"); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + d(detaching) { + if (detaching) { + detach(span); + } + } + }; +} +function create_if_block_3(ctx) { + let option; + let t_value = ( + /*group*/ + ctx[22].label + "" + ); + let t; + let option_value_value; + return { + c() { + option = element("option"); + t = text(t_value); + option.__value = option_value_value = /*group*/ + ctx[22].label; + set_input_value(option, option.__value); + }, + m(target, anchor) { + insert(target, option, anchor); + append(option, t); + }, + p(ctx2, dirty) { + if (dirty[0] & /*settings*/ + 1 && t_value !== (t_value = /*group*/ + ctx2[22].label + "")) + set_data(t, t_value); + if (dirty[0] & /*settings*/ + 1 && option_value_value !== (option_value_value = /*group*/ + ctx2[22].label)) { + option.__value = option_value_value; + set_input_value(option, option.__value); + } + }, + d(detaching) { + if (detaching) { + detach(option); + } + } + }; +} +function create_each_block_4(ctx) { + let show_if = !/*group*/ + ctx[22].fields.includes( + /*field*/ + ctx[31].label + ); + let if_block_anchor; + let if_block = show_if && create_if_block_3(ctx); + return { + c() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (if_block) + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + }, + p(ctx2, dirty) { + if (dirty[0] & /*settings, filters*/ + 3) + show_if = !/*group*/ + ctx2[22].fields.includes( + /*field*/ + ctx2[31].label + ); + if (show_if) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block_3(ctx2); + 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 (detaching) { + detach(if_block_anchor); + } + if (if_block) + if_block.d(detaching); + } + }; +} +function create_key_block(ctx) { + let div; + let span; + let t1; + let t2; + let t3; + let select; + let option; + let current; + let mounted; + let dispose; + let each_value_5 = ensure_array_like( + /*group_labels*/ + ctx[32] + ); + let each_blocks_1 = []; + for (let i = 0; i < each_value_5.length; i += 1) { + each_blocks_1[i] = create_each_block_5(get_each_context_5(ctx, each_value_5, i)); + } + const out = (i) => transition_out(each_blocks_1[i], 1, 1, () => { + each_blocks_1[i] = null; + }); + let if_block = !/*group_labels*/ + ctx[32].length && create_if_block_4(ctx); + let each_value_4 = ensure_array_like( + /*settings*/ + ctx[0].edge_field_groups + ); + let each_blocks = []; + for (let i = 0; i < each_value_4.length; i += 1) { + each_blocks[i] = create_each_block_4(get_each_context_4(ctx, each_value_4, i)); + } + function change_handler(...args) { + return ( + /*change_handler*/ + ctx[12]( + /*field*/ + ctx[31], + ...args + ) + ); + } + return { + c() { + div = element("div"); + span = element("span"); + span.textContent = "Groups"; + t1 = space(); + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].c(); + } + t2 = space(); + if (if_block) + if_block.c(); + t3 = space(); + select = element("select"); + option = element("option"); + option.textContent = "Add to Group"; + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + option.__value = ""; + set_input_value(option, option.__value); + option.disabled = true; + attr(select, "class", "dropdown"); + attr(div, "class", "flex flex-wrap items-center gap-1.5"); + }, + m(target, anchor) { + insert(target, div, anchor); + append(div, span); + append(div, t1); + for (let i = 0; i < each_blocks_1.length; i += 1) { + if (each_blocks_1[i]) { + each_blocks_1[i].m(div, null); + } + } + append(div, t2); + if (if_block) + if_block.m(div, null); + append(div, t3); + append(div, select); + append(select, option); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(select, null); + } + } + select_option(select, ""); + current = true; + if (!mounted) { + dispose = listen(select, "change", change_handler); + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (dirty[0] & /*settings, filters, actions, context_menus*/ + 15) { + each_value_5 = ensure_array_like( + /*group_labels*/ + ctx[32] + ); + let i; + for (i = 0; i < each_value_5.length; i += 1) { + const child_ctx = get_each_context_5(ctx, each_value_5, i); + if (each_blocks_1[i]) { + each_blocks_1[i].p(child_ctx, dirty); + transition_in(each_blocks_1[i], 1); + } else { + each_blocks_1[i] = create_each_block_5(child_ctx); + each_blocks_1[i].c(); + transition_in(each_blocks_1[i], 1); + each_blocks_1[i].m(div, t2); + } + } + group_outros(); + for (i = each_value_5.length; i < each_blocks_1.length; i += 1) { + out(i); + } + check_outros(); + } + if (!/*group_labels*/ + ctx[32].length) { + if (if_block) { + } else { + if_block = create_if_block_4(ctx); + if_block.c(); + if_block.m(div, t3); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + if (dirty[0] & /*settings, filters*/ + 3) { + each_value_4 = ensure_array_like( + /*settings*/ + ctx[0].edge_field_groups + ); + let i; + for (i = 0; i < each_value_4.length; i += 1) { + const child_ctx = get_each_context_4(ctx, each_value_4, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block_4(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_4.length; + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_5.length; i += 1) { + transition_in(each_blocks_1[i]); + } + current = true; + }, + o(local) { + each_blocks_1 = each_blocks_1.filter(Boolean); + for (let i = 0; i < each_blocks_1.length; i += 1) { + transition_out(each_blocks_1[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_each(each_blocks_1, detaching); + if (if_block) + if_block.d(); + destroy_each(each_blocks, detaching); + mounted = false; + dispose(); + } + }; +} +function create_each_block_3(ctx) { + let div1; + let div0; + let input; + let input_id_value; + let input_value_value; + let t0; + let button; + let t2; + let previous_key = ( + /*settings*/ + ctx[0].edge_field_groups + ); + let current; + let mounted; + let dispose; + function blur_handler(...args) { + return ( + /*blur_handler*/ + ctx[9]( + /*field*/ + ctx[31], + ...args + ) + ); + } + function click_handler_2() { + return ( + /*click_handler_2*/ + ctx[10]( + /*field*/ + ctx[31] + ) + ); + } + let key_block = create_key_block(ctx); + return { + c() { + div1 = element("div"); + div0 = element("div"); + input = element("input"); + t0 = space(); + button = element("button"); + button.textContent = "X"; + t2 = space(); + key_block.c(); + attr(input, "id", input_id_value = /*actions*/ + ctx[2].fields.make_id( + /*field*/ + ctx[31].label + )); + attr(input, "type", "text"); + attr(input, "class", "w-48 scroll-mt-40"); + attr(input, "placeholder", "Field Label"); + input.value = input_value_value = /*field*/ + ctx[31].label; + attr(button, "class", "w-8"); + attr(button, "title", "Remove Field"); + attr(div0, "class", "flex flex-wrap items-center gap-1"); + attr(div1, "class", "flex flex-col gap-2"); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, div0); + append(div0, input); + append(div0, t0); + append(div0, button); + append(div1, t2); + key_block.m(div1, null); + current = true; + if (!mounted) { + dispose = [ + listen(input, "blur", blur_handler), + listen(button, "click", click_handler_2) + ]; + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (!current || dirty[0] & /*settings, filters*/ + 3 && input_id_value !== (input_id_value = /*actions*/ + ctx[2].fields.make_id( + /*field*/ + ctx[31].label + ))) { + attr(input, "id", input_id_value); + } + if (!current || dirty[0] & /*settings, filters*/ + 3 && input_value_value !== (input_value_value = /*field*/ + ctx[31].label) && input.value !== input_value_value) { + input.value = input_value_value; + } + if (dirty[0] & /*settings*/ + 1 && safe_not_equal(previous_key, previous_key = /*settings*/ + ctx[0].edge_field_groups)) { + group_outros(); + transition_out(key_block, 1, 1, noop); + check_outros(); + key_block = create_key_block(ctx); + key_block.c(); + transition_in(key_block, 1); + key_block.m(div1, null); + } else { + key_block.p(ctx, dirty); + } + }, + i(local) { + if (current) + return; + transition_in(key_block); + current = true; + }, + o(local) { + transition_out(key_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div1); + } + key_block.d(detaching); + mounted = false; + run_all(dispose); + } + }; +} +function create_if_block_2(ctx) { + let button; + let arrowdown; + let current; + let mounted; + let dispose; + arrowdown = new arrow_down_default({ props: { size: ICON_SIZE } }); + return { + c() { + button = element("button"); + create_component(arrowdown.$$.fragment); + attr(button, "class", "w-10"); + attr(button, "aria-label", "Jump to bottom"); + }, + m(target, anchor) { + insert(target, button, anchor); + mount_component(arrowdown, button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler_5*/ + ctx[16] + ); + mounted = true; + } + }, + p: noop, + i(local) { + if (current) + return; + transition_in(arrowdown.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(arrowdown.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + destroy_component(arrowdown); + mounted = false; + dispose(); + } + }; +} +function create_each_block_2(ctx) { + let div; + let tag; + let current; + function click_handler_7() { + return ( + /*click_handler_7*/ + ctx[20]( + /*field_label*/ + ctx[28] + ) + ); + } + tag = new tag_default({ + props: { + tag: ( + /*field_label*/ + ctx[28] + ), + title: "Jump to field. Right click for more actions." + } + }); + tag.$on("click", click_handler_7); + tag.$on("contextmenu", function() { + if (is_function( + /*context_menus*/ + ctx[3].group_field( + /*group*/ + ctx[22], + /*field_label*/ + ctx[28] + ) + )) + ctx[3].group_field( + /*group*/ + ctx[22], + /*field_label*/ + ctx[28] + ).apply(this, arguments); + }); + return { + c() { + div = element("div"); + create_component(tag.$$.fragment); + attr(div, "class", "flex items-center gap-0.5"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(tag, div, null); + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + const tag_changes = {}; + if (dirty[0] & /*settings, filters*/ + 3) + tag_changes.tag = /*field_label*/ + ctx[28]; + tag.$set(tag_changes); + }, + i(local) { + if (current) + return; + transition_in(tag.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(tag.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(tag); + } + }; +} +function create_if_block_1(ctx) { + let span; + return { + c() { + span = element("span"); + span.textContent = `${""}`; + attr(span, "class", "search-empty-state my-0"); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + d(detaching) { + if (detaching) { + detach(span); + } + } + }; +} +function create_if_block2(ctx) { + let option; + let t_value = ( + /*edge_field*/ + ctx[25].label + "" + ); + let t; + let option_value_value; + return { + c() { + option = element("option"); + t = text(t_value); + option.__value = option_value_value = /*edge_field*/ + ctx[25].label; + set_input_value(option, option.__value); + }, + m(target, anchor) { + insert(target, option, anchor); + append(option, t); + }, + p(ctx2, dirty) { + if (dirty[0] & /*settings*/ + 1 && t_value !== (t_value = /*edge_field*/ + ctx2[25].label + "")) + set_data(t, t_value); + if (dirty[0] & /*settings*/ + 1 && option_value_value !== (option_value_value = /*edge_field*/ + ctx2[25].label)) { + option.__value = option_value_value; + set_input_value(option, option.__value); + } + }, + d(detaching) { + if (detaching) { + detach(option); + } + } + }; +} +function create_each_block_1(ctx) { + let show_if = !/*group*/ + ctx[22].fields.includes( + /*edge_field*/ + ctx[25].label + ); + let if_block_anchor; + let if_block = show_if && create_if_block2(ctx); + return { + c() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (if_block) + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + }, + p(ctx2, dirty) { + if (dirty[0] & /*settings, filters*/ + 3) + show_if = !/*group*/ + ctx2[22].fields.includes( + /*edge_field*/ + ctx2[25].label + ); + if (show_if) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block2(ctx2); + 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 (detaching) { + detach(if_block_anchor); + } + if (if_block) + if_block.d(detaching); + } + }; +} +function create_each_block2(ctx) { + let div2; + let div0; + let input; + let input_id_value; + let input_value_value; + let t0; + let button; + let t2; + let div1; + let span; + let t4; + let t5; + let t6; + let select; + let option; + let current; + let mounted; + let dispose; + function blur_handler_1(...args) { + return ( + /*blur_handler_1*/ + ctx[18]( + /*group*/ + ctx[22], + ...args + ) + ); + } + function click_handler_6() { + return ( + /*click_handler_6*/ + ctx[19]( + /*group*/ + ctx[22] + ) + ); + } + let each_value_2 = ensure_array_like( + /*group*/ + ctx[22].fields + ); + let each_blocks_1 = []; + for (let i = 0; i < each_value_2.length; i += 1) { + each_blocks_1[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i)); + } + const out = (i) => transition_out(each_blocks_1[i], 1, 1, () => { + each_blocks_1[i] = null; + }); + let if_block = !/*group*/ + ctx[22].fields.length && create_if_block_1(ctx); + let each_value_1 = ensure_array_like( + /*settings*/ + ctx[0].edge_fields + ); + let each_blocks = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i)); + } + function change_handler_1(...args) { + return ( + /*change_handler_1*/ + ctx[21]( + /*group*/ + ctx[22], + ...args + ) + ); + } + return { + c() { + div2 = element("div"); + div0 = element("div"); + input = element("input"); + t0 = space(); + button = element("button"); + button.textContent = "X"; + t2 = space(); + div1 = element("div"); + span = element("span"); + span.textContent = "Fields"; + t4 = space(); + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].c(); + } + t5 = space(); + if (if_block) + if_block.c(); + t6 = space(); + select = element("select"); + option = element("option"); + option.textContent = "Add Field"; + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(input, "id", input_id_value = /*actions*/ + ctx[2].groups.make_id( + /*group*/ + ctx[22].label + )); + attr(input, "type", "text"); + attr(input, "class", "w-48 scroll-mt-40"); + attr(input, "placeholder", "Group Label"); + input.value = input_value_value = /*group*/ + ctx[22].label; + attr(button, "class", "w-8"); + attr(button, "title", "Remove Group"); + attr(div0, "class", "flex flex-wrap items-center gap-1"); + option.__value = ""; + set_input_value(option, option.__value); + option.disabled = true; + attr(select, "class", "dropdown"); + attr(div1, "class", "flex flex-wrap items-center gap-1.5"); + attr(div2, "class", "flex flex-col gap-2"); + }, + m(target, anchor) { + insert(target, div2, anchor); + append(div2, div0); + append(div0, input); + append(div0, t0); + append(div0, button); + append(div2, t2); + append(div2, div1); + append(div1, span); + append(div1, t4); + for (let i = 0; i < each_blocks_1.length; i += 1) { + if (each_blocks_1[i]) { + each_blocks_1[i].m(div1, null); + } + } + append(div1, t5); + if (if_block) + if_block.m(div1, null); + append(div1, t6); + append(div1, select); + append(select, option); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(select, null); + } + } + select_option(select, ""); + current = true; + if (!mounted) { + dispose = [ + listen(input, "blur", blur_handler_1), + listen(button, "click", click_handler_6), + listen(select, "change", change_handler_1) + ]; + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (!current || dirty[0] & /*settings, filters*/ + 3 && input_id_value !== (input_id_value = /*actions*/ + ctx[2].groups.make_id( + /*group*/ + ctx[22].label + ))) { + attr(input, "id", input_id_value); + } + if (!current || dirty[0] & /*settings, filters*/ + 3 && input_value_value !== (input_value_value = /*group*/ + ctx[22].label) && input.value !== input_value_value) { + input.value = input_value_value; + } + if (dirty[0] & /*settings, filters, actions, context_menus*/ + 15) { + each_value_2 = ensure_array_like( + /*group*/ + ctx[22].fields + ); + let i; + for (i = 0; i < each_value_2.length; i += 1) { + const child_ctx = get_each_context_2(ctx, each_value_2, i); + if (each_blocks_1[i]) { + each_blocks_1[i].p(child_ctx, dirty); + transition_in(each_blocks_1[i], 1); + } else { + each_blocks_1[i] = create_each_block_2(child_ctx); + each_blocks_1[i].c(); + transition_in(each_blocks_1[i], 1); + each_blocks_1[i].m(div1, t5); + } + } + group_outros(); + for (i = each_value_2.length; i < each_blocks_1.length; i += 1) { + out(i); + } + check_outros(); + } + if (!/*group*/ + ctx[22].fields.length) { + if (if_block) { + } else { + if_block = create_if_block_1(ctx); + if_block.c(); + if_block.m(div1, t6); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + if (dirty[0] & /*settings, filters*/ + 3) { + each_value_1 = ensure_array_like( + /*settings*/ + ctx[0].edge_fields + ); + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_1(ctx, each_value_1, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block_1(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_1.length; + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_2.length; i += 1) { + transition_in(each_blocks_1[i]); + } + current = true; + }, + o(local) { + each_blocks_1 = each_blocks_1.filter(Boolean); + for (let i = 0; i < each_blocks_1.length; i += 1) { + transition_out(each_blocks_1[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div2); + } + destroy_each(each_blocks_1, detaching); + if (if_block) + if_block.d(); + destroy_each(each_blocks, detaching); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment22(ctx) { + let div7; + let div0; + let button0; + let saveicon; + let t0; + let t1; + let t2; + let div2; + let h40; + let t4; + let div1; + let input0; + let t5; + let button1; + let t6; + let button1_disabled_value; + let t7; + let t8; + let div3; + let t9; + let button2; + let plusicon0; + let t10; + let t11; + let hr; + let t12; + let div5; + let h41; + let t14; + let div4; + let input1; + let t15; + let button3; + let t16; + let button3_disabled_value; + let t17; + let t18; + let div6; + let t19; + let button4; + let plusicon1; + let t20; + let current; + let mounted; + let dispose; + saveicon = new save_default({ props: { size: ICON_SIZE } }); + let if_block0 = ( + /*settings*/ + ctx[0].is_dirty && create_if_block_6(ctx) + ); + let if_block1 = ( + /*settings*/ + ctx[0].edge_fields.length > 3 && create_if_block_5(ctx) + ); + let each_value_3 = ensure_array_like( + /*settings*/ + ctx[0].edge_fields.filter( + /*func*/ + ctx[8] + ) + ); + let each_blocks_1 = []; + for (let i = 0; i < each_value_3.length; i += 1) { + each_blocks_1[i] = create_each_block_3(get_each_context_3(ctx, each_value_3, i)); + } + const out = (i) => transition_out(each_blocks_1[i], 1, 1, () => { + each_blocks_1[i] = null; + }); + plusicon0 = new plus_default({ props: { size: ICON_SIZE } }); + let if_block2 = ( + /*settings*/ + ctx[0].edge_field_groups.length > 3 && create_if_block_2(ctx) + ); + let each_value = ensure_array_like( + /*settings*/ + ctx[0].edge_field_groups.filter( + /*func_3*/ + ctx[17] + ) + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i)); + } + const out_1 = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + plusicon1 = new plus_default({ props: { size: ICON_SIZE } }); + return { + c() { + div7 = element("div"); + div0 = element("div"); + button0 = element("button"); + create_component(saveicon.$$.fragment); + t0 = text("\n Save"); + t1 = space(); + if (if_block0) + if_block0.c(); + t2 = space(); + div2 = element("div"); + h40 = element("h4"); + h40.textContent = "Fields"; + t4 = space(); + div1 = element("div"); + input0 = element("input"); + t5 = space(); + button1 = element("button"); + t6 = text("X"); + t7 = space(); + if (if_block1) + if_block1.c(); + t8 = space(); + div3 = element("div"); + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].c(); + } + t9 = space(); + button2 = element("button"); + create_component(plusicon0.$$.fragment); + t10 = text("\n New Edge Field"); + t11 = space(); + hr = element("hr"); + t12 = space(); + div5 = element("div"); + h41 = element("h4"); + h41.textContent = "Groups"; + t14 = space(); + div4 = element("div"); + input1 = element("input"); + t15 = space(); + button3 = element("button"); + t16 = text("X"); + t17 = space(); + if (if_block2) + if_block2.c(); + t18 = space(); + div6 = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + t19 = space(); + button4 = element("button"); + create_component(plusicon1.$$.fragment); + t20 = text("\n New Group"); + attr(button0, "class", "flex items-center gap-1"); + attr(div0, "class", "my-2 flex items-center gap-2"); + attr(input0, "type", "text"); + attr(input0, "placeholder", "Filter Fields by Name"); + attr(button1, "class", "w-8"); + attr(button1, "aria-label", "Clear Filter"); + button1.disabled = button1_disabled_value = /*filters*/ + ctx[1].fields === ""; + attr(div1, "class", "flex gap-1"); + attr(div2, "class", "flex items-center gap-4"); + attr(button2, "class", "flex items-center gap-1"); + attr(div3, "class", "flex flex-col gap-7"); + attr(input1, "type", "text"); + attr(input1, "placeholder", "Filter Groups by Name"); + attr(button3, "class", "w-8"); + attr(button3, "aria-label", "Clear Filter"); + button3.disabled = button3_disabled_value = /*filters*/ + ctx[1].groups === ""; + attr(div4, "class", "flex gap-1"); + attr(div5, "class", "flex items-center gap-4"); + attr(button4, "class", "flex items-center gap-1"); + attr(div6, "class", "flex flex-col gap-7"); + attr(div7, "class", "flex flex-col"); + }, + m(target, anchor) { + insert(target, div7, anchor); + append(div7, div0); + append(div0, button0); + mount_component(saveicon, button0, null); + append(button0, t0); + append(div0, t1); + if (if_block0) + if_block0.m(div0, null); + append(div7, t2); + append(div7, div2); + append(div2, h40); + append(div2, t4); + append(div2, div1); + append(div1, input0); + set_input_value( + input0, + /*filters*/ + ctx[1].fields + ); + append(div1, t5); + append(div1, button1); + append(button1, t6); + append(div2, t7); + if (if_block1) + if_block1.m(div2, null); + append(div7, t8); + append(div7, div3); + for (let i = 0; i < each_blocks_1.length; i += 1) { + if (each_blocks_1[i]) { + each_blocks_1[i].m(div3, null); + } + } + append(div3, t9); + append(div3, button2); + mount_component(plusicon0, button2, null); + append(button2, t10); + append(div7, t11); + append(div7, hr); + append(div7, t12); + append(div7, div5); + append(div5, h41); + append(div5, t14); + append(div5, div4); + append(div4, input1); + set_input_value( + input1, + /*filters*/ + ctx[1].groups + ); + append(div4, t15); + append(div4, button3); + append(button3, t16); + append(div5, t17); + if (if_block2) + if_block2.m(div5, null); + append(div7, t18); + append(div7, div6); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(div6, null); + } + } + append(div6, t19); + append(div6, button4); + mount_component(plusicon1, button4, null); + append(button4, t20); + current = true; + if (!mounted) { + dispose = [ + listen( + button0, + "click", + /*actions*/ + ctx[2].save + ), + listen( + input0, + "input", + /*input0_input_handler*/ + ctx[5] + ), + listen( + button1, + "click", + /*click_handler*/ + ctx[6] + ), + listen( + button2, + "click", + /*actions*/ + ctx[2].fields.add + ), + listen( + input1, + "input", + /*input1_input_handler*/ + ctx[14] + ), + listen( + button3, + "click", + /*click_handler_4*/ + ctx[15] + ), + listen( + button4, + "click", + /*actions*/ + ctx[2].groups.add + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if ( + /*settings*/ + ctx2[0].is_dirty + ) { + if (if_block0) { + } else { + if_block0 = create_if_block_6(ctx2); + if_block0.c(); + if_block0.m(div0, null); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + if (dirty[0] & /*filters*/ + 2 && input0.value !== /*filters*/ + ctx2[1].fields) { + set_input_value( + input0, + /*filters*/ + ctx2[1].fields + ); + } + if (!current || dirty[0] & /*filters*/ + 2 && button1_disabled_value !== (button1_disabled_value = /*filters*/ + ctx2[1].fields === "")) { + button1.disabled = button1_disabled_value; + } + if ( + /*settings*/ + ctx2[0].edge_fields.length > 3 + ) { + if (if_block1) { + if_block1.p(ctx2, dirty); + if (dirty[0] & /*settings*/ + 1) { + transition_in(if_block1, 1); + } + } else { + if_block1 = create_if_block_5(ctx2); + if_block1.c(); + transition_in(if_block1, 1); + if_block1.m(div2, null); + } + } else if (if_block1) { + group_outros(); + transition_out(if_block1, 1, 1, () => { + if_block1 = null; + }); + check_outros(); + } + if (dirty[0] & /*settings, actions, filters, context_menus*/ + 15) { + each_value_3 = ensure_array_like( + /*settings*/ + ctx2[0].edge_fields.filter( + /*func*/ + ctx2[8] + ) + ); + let i; + for (i = 0; i < each_value_3.length; i += 1) { + const child_ctx = get_each_context_3(ctx2, each_value_3, i); + if (each_blocks_1[i]) { + each_blocks_1[i].p(child_ctx, dirty); + transition_in(each_blocks_1[i], 1); + } else { + each_blocks_1[i] = create_each_block_3(child_ctx); + each_blocks_1[i].c(); + transition_in(each_blocks_1[i], 1); + each_blocks_1[i].m(div3, t9); + } + } + group_outros(); + for (i = each_value_3.length; i < each_blocks_1.length; i += 1) { + out(i); + } + check_outros(); + } + if (dirty[0] & /*filters*/ + 2 && input1.value !== /*filters*/ + ctx2[1].groups) { + set_input_value( + input1, + /*filters*/ + ctx2[1].groups + ); + } + if (!current || dirty[0] & /*filters*/ + 2 && button3_disabled_value !== (button3_disabled_value = /*filters*/ + ctx2[1].groups === "")) { + button3.disabled = button3_disabled_value; + } + if ( + /*settings*/ + ctx2[0].edge_field_groups.length > 3 + ) { + if (if_block2) { + if_block2.p(ctx2, dirty); + if (dirty[0] & /*settings*/ + 1) { + transition_in(if_block2, 1); + } + } else { + if_block2 = create_if_block_2(ctx2); + if_block2.c(); + transition_in(if_block2, 1); + if_block2.m(div5, null); + } + } else if (if_block2) { + group_outros(); + transition_out(if_block2, 1, 1, () => { + if_block2 = null; + }); + check_outros(); + } + if (dirty[0] & /*actions, settings, filters, context_menus*/ + 15) { + each_value = ensure_array_like( + /*settings*/ + ctx2[0].edge_field_groups.filter( + /*func_3*/ + ctx2[17] + ) + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context2(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block2(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div6, t19); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out_1(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(saveicon.$$.fragment, local); + transition_in(if_block1); + for (let i = 0; i < each_value_3.length; i += 1) { + transition_in(each_blocks_1[i]); + } + transition_in(plusicon0.$$.fragment, local); + transition_in(if_block2); + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + transition_in(plusicon1.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(saveicon.$$.fragment, local); + transition_out(if_block1); + each_blocks_1 = each_blocks_1.filter(Boolean); + for (let i = 0; i < each_blocks_1.length; i += 1) { + transition_out(each_blocks_1[i]); + } + transition_out(plusicon0.$$.fragment, local); + transition_out(if_block2); + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + transition_out(plusicon1.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div7); + } + destroy_component(saveicon); + if (if_block0) + if_block0.d(); + if (if_block1) + if_block1.d(); + destroy_each(each_blocks_1, detaching); + destroy_component(plusicon0); + if (if_block2) + if_block2.d(); + destroy_each(each_blocks, detaching); + destroy_component(plusicon1); + mounted = false; + run_all(dispose); + } + }; +} +function instance22($$self, $$props, $$invalidate) { + let { plugin } = $$props; + const settings = plugin.settings; + let filters = { fields: "", groups: "" }; + const actions = { + save: () => __awaiter(void 0, void 0, void 0, function* () { + yield Promise.all([plugin.saveSettings(), plugin.refresh({ redraw_side_views: true })]); + $$invalidate(4, plugin); + }), + fields: { + make_id: (label) => `BC-edge-field-${label}`, + scroll_to: (label) => { + const el = document.getElementById(actions.fields.make_id(label)); + if (el) { + el.scrollIntoView({ behavior: "smooth", block: "center" }); + el.focus(); + } + }, + add: () => { + const field = { + label: `Edge Field ${settings.edge_fields.length + 1}` + }; + settings.edge_fields.push(field); + setTimeout(() => actions.fields.scroll_to(field.label), 0); + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + }, + remove: (edge_field) => { + $$invalidate(0, settings.edge_fields = settings.edge_fields.filter((f) => f.label !== edge_field.label), settings); + settings.edge_field_groups.forEach((group) => { + group.fields = group.fields.filter((f) => f !== edge_field.label); + }); + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + }, + rename: (edge_field, new_label) => { + if (edge_field.label === new_label) { + return; + } else if (new_label === "") { + return new import_obsidian7.Notice("Field label cannot be empty."); + } else if (settings.edge_fields.some((f) => f.label === new_label)) { + return new import_obsidian7.Notice("Field label must be unique."); + } + settings.edge_field_groups.forEach((group) => { + const index = group.fields.indexOf(edge_field.label); + if (index === -1) + return; + group.fields[index] = new_label; + }); + settings.implied_relations.transitive.forEach((rule) => { + rule.chain = rule.chain.map((attr2) => attr2.field === edge_field.label ? Object.assign(Object.assign({}, attr2), { field: new_label }) : attr2); + rule.close_field = rule.close_field === edge_field.label ? new_label : rule.close_field; + }); + $$invalidate( + 0, + settings.explicit_edge_sources.tag_note.default_field = settings.explicit_edge_sources.tag_note.default_field === edge_field.label ? new_label : settings.explicit_edge_sources.tag_note.default_field, + settings + ); + $$invalidate( + 0, + settings.explicit_edge_sources.list_note.default_neighbour_field = settings.explicit_edge_sources.list_note.default_neighbour_field === edge_field.label ? new_label : settings.explicit_edge_sources.list_note.default_neighbour_field, + settings + ); + $$invalidate( + 0, + settings.explicit_edge_sources.dendron_note.default_field = settings.explicit_edge_sources.dendron_note.default_field === edge_field.label ? new_label : settings.explicit_edge_sources.dendron_note.default_field, + settings + ); + $$invalidate( + 0, + settings.explicit_edge_sources.johnny_decimal_note.default_field = settings.explicit_edge_sources.johnny_decimal_note.default_field === edge_field.label ? new_label : settings.explicit_edge_sources.johnny_decimal_note.default_field, + settings + ); + $$invalidate( + 0, + settings.explicit_edge_sources.date_note.default_field = settings.explicit_edge_sources.date_note.default_field === edge_field.label ? new_label : settings.explicit_edge_sources.date_note.default_field, + settings + ); + $$invalidate( + 0, + settings.explicit_edge_sources.regex_note.default_field = settings.explicit_edge_sources.regex_note.default_field === edge_field.label ? new_label : settings.explicit_edge_sources.regex_note.default_field, + settings + ); + edge_field.label = new_label; + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + } + }, + groups: { + make_id: (label) => `BC-edge-group-${label}`, + scroll_to: (label) => { + const el = document.getElementById(actions.groups.make_id(label)); + if (el) { + el.scrollIntoView({ behavior: "smooth", block: "center" }); + el.focus(); + } + }, + add: () => { + const group = { + label: `Group ${settings.edge_field_groups.length + 1}`, + fields: [] + }; + settings.edge_field_groups.push(group); + setTimeout(() => actions.groups.scroll_to(group.label), 0); + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + }, + remove: (group) => { + $$invalidate(0, settings.edge_field_groups = settings.edge_field_groups.filter((g) => g.label !== group.label), settings); + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + }, + rename: (group, new_label) => { + if (group.label === new_label) + return; + $$invalidate(0, settings.views.page.trail.field_group_labels = settings.views.page.trail.field_group_labels.map((label) => label === group.label ? new_label : label), settings); + $$invalidate(0, settings.views.page.prev_next.field_group_labels.prev = settings.views.page.prev_next.field_group_labels.prev.map((label) => label === group.label ? new_label : label), settings); + $$invalidate(0, settings.views.page.prev_next.field_group_labels.next = settings.views.page.prev_next.field_group_labels.next.map((label) => label === group.label ? new_label : label), settings); + $$invalidate(0, settings.views.side.matrix.field_group_labels = settings.views.side.matrix.field_group_labels.map((label) => label === group.label ? new_label : label), settings); + $$invalidate(0, settings.views.side.matrix.field_group_labels = settings.views.side.matrix.field_group_labels.map((label) => label === group.label ? new_label : label), settings); + group.label = new_label; + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + }, + add_field: (group, field_label) => { + if (!group) + return; + group.fields.push(field_label); + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + }, + remove_field: (group, field_label) => { + if (!group) + return; + group.fields = group.fields.filter((f) => f !== field_label); + $$invalidate(0, settings.is_dirty = true, settings); + $$invalidate(4, plugin); + } + } + }; + const context_menus = { + field_group: (edge_field, group_label) => (e) => { + const menu = new import_obsidian7.Menu(); + menu.addItem((item) => item.setTitle("Remove from Group").setIcon("x").onClick(() => actions.groups.remove_field(settings.edge_field_groups.find((g) => g.label === group_label), edge_field.label))); + menu.showAtMouseEvent(e); + }, + group_field: (group, field_label) => (e) => { + const menu = new import_obsidian7.Menu(); + menu.addItem((item) => item.setTitle("Remove Field").setIcon("x").onClick(() => actions.groups.remove_field(group, field_label))); + menu.showAtMouseEvent(e); + } + }; + function input0_input_handler() { + filters.fields = this.value; + $$invalidate(1, filters); + } + const click_handler = () => $$invalidate(1, filters.fields = "", filters); + const click_handler_1 = () => { + var _a, _b; + return actions.fields.scroll_to((_b = (_a = settings.edge_fields.last()) == null ? void 0 : _a.label) != null ? _b : ""); + }; + const func = (f) => f.label.includes(filters.fields.toLowerCase()); + const blur_handler = (field, e) => actions.fields.rename(field, e.currentTarget.value); + const click_handler_2 = (field) => actions.fields.remove(field); + const click_handler_3 = (group_label) => actions.groups.scroll_to(group_label); + const change_handler = (field, e) => { + if (e.currentTarget.value) { + actions.groups.add_field(settings.edge_field_groups.find((g) => g.label === e.currentTarget.value), field.label); + e.currentTarget.value = ""; + } + }; + const func_1 = (field, group) => group.fields.includes(field.label); + function input1_input_handler() { + filters.groups = this.value; + $$invalidate(1, filters); + } + const click_handler_4 = () => $$invalidate(1, filters.groups = "", filters); + const click_handler_5 = () => { + var _a, _b; + return actions.groups.scroll_to((_b = (_a = settings.edge_field_groups.last()) == null ? void 0 : _a.label) != null ? _b : ""); + }; + const func_3 = (group) => group.label.includes(filters.groups.toLowerCase()); + const blur_handler_1 = (group, e) => actions.groups.rename(group, e.currentTarget.value); + const click_handler_6 = (group) => actions.groups.remove(group); + const click_handler_7 = (field_label) => actions.fields.scroll_to(field_label); + const change_handler_1 = (group, e) => { + if (e.currentTarget.value) { + actions.groups.add_field(group, e.currentTarget.value); + e.currentTarget.value = ""; + } + }; + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(4, plugin = $$props2.plugin); + }; + return [ + settings, + filters, + actions, + context_menus, + plugin, + input0_input_handler, + click_handler, + click_handler_1, + func, + blur_handler, + click_handler_2, + click_handler_3, + change_handler, + func_1, + input1_input_handler, + click_handler_4, + click_handler_5, + func_3, + blur_handler_1, + click_handler_6, + click_handler_7, + change_handler_1 + ]; +} +var EdgeFieldSettings = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance22, create_fragment22, safe_not_equal, { plugin: 4 }, null, [-1, -1]); + } +}; +var EdgeFieldSettings_default = EdgeFieldSettings; + +// src/components/settings/TransitiveImpliedRelations.svelte +var import_obsidian10 = require("obsidian"); + +// src/components/button/ChevronOpener.svelte +function create_else_block2(ctx) { + let chevronright; + let current; + chevronright = new chevron_right_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(chevronright.$$.fragment); + }, + m(target, anchor) { + mount_component(chevronright, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(chevronright.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(chevronright.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(chevronright, detaching); + } + }; +} +function create_if_block3(ctx) { + let chevrondown; + let current; + chevrondown = new chevron_down_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(chevrondown.$$.fragment); + }, + m(target, anchor) { + mount_component(chevrondown, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(chevrondown.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(chevrondown.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(chevrondown, detaching); + } + }; +} +function create_fragment23(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block3, create_else_block2]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*open*/ + ctx2[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() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_blocks[current_block_type_index].m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, [dirty]) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index !== previous_block_index) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + 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](ctx2); + if_block.c(); + } else { + } + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if_blocks[current_block_type_index].d(detaching); + } + }; +} +function instance23($$self, $$props, $$invalidate) { + let { open } = $$props; + $$self.$$set = ($$props2) => { + if ("open" in $$props2) + $$invalidate(0, open = $$props2.open); + }; + return [open]; +} +var ChevronOpener = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance23, create_fragment23, safe_not_equal, { open: 0 }); + } +}; +var ChevronOpener_default = ChevronOpener; + +// src/components/obsidian/RenderMarkdown.svelte +var import_obsidian9 = require("obsidian"); + +// src/stores/active_file.ts +var import_obsidian8 = require("obsidian"); + +// node_modules/svelte/src/runtime/store/index.js +var subscriber_queue = []; +function writable(value, start = noop) { + let stop; + const subscribers = /* @__PURE__ */ new Set(); + function set(new_value) { + if (safe_not_equal(value, new_value)) { + value = new_value; + if (stop) { + const run_queue = !subscriber_queue.length; + for (const subscriber of subscribers) { + subscriber[1](); + subscriber_queue.push(subscriber, value); + } + if (run_queue) { + for (let i = 0; i < subscriber_queue.length; i += 2) { + subscriber_queue[i][0](subscriber_queue[i + 1]); + } + subscriber_queue.length = 0; + } + } + } + } + function update2(fn) { + set(fn(value)); + } + function subscribe2(run2, invalidate = noop) { + const subscriber = [run2, invalidate]; + subscribers.add(subscriber); + if (subscribers.size === 1) { + stop = start(set, update2) || noop; + } + run2(value); + return () => { + subscribers.delete(subscriber); + if (subscribers.size === 0 && stop) { + stop(); + stop = null; + } + }; + } + return { set, update: update2, subscribe: subscribe2 }; +} + +// src/stores/active_file.ts +var store = writable(null); +var active_file_store = { + ...store, + refresh: (app) => store.set(app.workspace.getActiveFile()) +}; + +// src/components/obsidian/RenderMarkdown.svelte +function create_fragment24(ctx) { + let div; + let div_class_value; + return { + c() { + div = element("div"); + attr(div, "class", div_class_value = "markdown-rendered " + /*cls*/ + ctx[0]); + }, + m(target, anchor) { + insert(target, div, anchor); + ctx[5](div); + }, + p(ctx2, [dirty]) { + if (dirty & /*cls*/ + 1 && div_class_value !== (div_class_value = "markdown-rendered " + /*cls*/ + ctx2[0])) { + attr(div, "class", div_class_value); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(div); + } + ctx[5](null); + } + }; +} +function instance24($$self, $$props, $$invalidate) { + let $active_file_store; + component_subscribe($$self, active_file_store, ($$value) => $$invalidate(6, $active_file_store = $$value)); + let { cls = "" } = $$props; + let { markdown } = $$props; + let { plugin } = $$props; + let { source_path = void 0 } = $$props; + let el; + const render = (markdown2, el2) => { + var _a; + if (!el2) + return; + log.debug("rendering markdown"); + el2.empty(); + import_obsidian9.MarkdownRenderer.render( + plugin.app, + markdown2, + el2, + (_a = source_path !== null && source_path !== void 0 ? source_path : $active_file_store === null || $active_file_store === void 0 ? void 0 : $active_file_store.path) !== null && _a !== void 0 ? _a : "", + plugin + ); + }; + function div_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + el = $$value; + $$invalidate(1, el); + }); + } + $$self.$$set = ($$props2) => { + if ("cls" in $$props2) + $$invalidate(0, cls = $$props2.cls); + if ("markdown" in $$props2) + $$invalidate(2, markdown = $$props2.markdown); + if ("plugin" in $$props2) + $$invalidate(3, plugin = $$props2.plugin); + if ("source_path" in $$props2) + $$invalidate(4, source_path = $$props2.source_path); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*markdown, el*/ + 6) { + $: + render(markdown, el); + } + }; + return [cls, el, markdown, plugin, source_path, div_binding]; +} +var RenderMarkdown = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance24, create_fragment24, safe_not_equal, { + cls: 0, + markdown: 2, + plugin: 3, + source_path: 4 + }); + } +}; +var RenderMarkdown_default = RenderMarkdown; + +// src/components/obsidian/RenderExternalCodeblock.svelte +function create_fragment25(ctx) { + let rendermarkdown; + let updating_plugin; + let current; + function rendermarkdown_plugin_binding(value) { + ctx[4](value); + } + let rendermarkdown_props = { + source_path: ( + /*source_path*/ + ctx[3] + ), + markdown: wrap_in_codeblock( + /*code*/ + ctx[1], + /*type*/ + ctx[2] + ) + }; + if ( + /*plugin*/ + ctx[0] !== void 0 + ) { + rendermarkdown_props.plugin = /*plugin*/ + ctx[0]; + } + rendermarkdown = new RenderMarkdown_default({ props: rendermarkdown_props }); + binding_callbacks.push(() => bind(rendermarkdown, "plugin", rendermarkdown_plugin_binding)); + return { + c() { + create_component(rendermarkdown.$$.fragment); + }, + m(target, anchor) { + mount_component(rendermarkdown, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const rendermarkdown_changes = {}; + if (dirty & /*source_path*/ + 8) + rendermarkdown_changes.source_path = /*source_path*/ + ctx2[3]; + if (dirty & /*code, type*/ + 6) + rendermarkdown_changes.markdown = wrap_in_codeblock( + /*code*/ + ctx2[1], + /*type*/ + ctx2[2] + ); + if (!updating_plugin && dirty & /*plugin*/ + 1) { + updating_plugin = true; + rendermarkdown_changes.plugin = /*plugin*/ + ctx2[0]; + add_flush_callback(() => updating_plugin = false); + } + rendermarkdown.$set(rendermarkdown_changes); + }, + i(local) { + if (current) + return; + transition_in(rendermarkdown.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(rendermarkdown.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(rendermarkdown, detaching); + } + }; +} +function instance25($$self, $$props, $$invalidate) { + let { code } = $$props; + let { type } = $$props; + let { plugin } = $$props; + let { source_path = void 0 } = $$props; + function rendermarkdown_plugin_binding(value) { + plugin = value; + $$invalidate(0, plugin); + } + $$self.$$set = ($$props2) => { + if ("code" in $$props2) + $$invalidate(1, code = $$props2.code); + if ("type" in $$props2) + $$invalidate(2, type = $$props2.type); + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("source_path" in $$props2) + $$invalidate(3, source_path = $$props2.source_path); + }; + return [plugin, code, type, source_path, rendermarkdown_plugin_binding]; +} +var RenderExternalCodeblock = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance25, create_fragment25, safe_not_equal, { + code: 1, + type: 2, + plugin: 0, + source_path: 3 + }); + } +}; +var RenderExternalCodeblock_default = RenderExternalCodeblock; + +// src/components/selector/EdgeFieldSelector.svelte +function get_each_context3(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[5] = list[i].label; + return child_ctx; +} +function create_each_block3(ctx) { + let option; + let t_value = ( + /*label*/ + ctx[5] + "" + ); + let t; + let option_value_value; + return { + c() { + option = element("option"); + t = text(t_value); + option.__value = option_value_value = /*label*/ + ctx[5]; + set_input_value(option, option.__value); + }, + m(target, anchor) { + insert(target, option, anchor); + append(option, t); + }, + p(ctx2, dirty) { + if (dirty & /*fields*/ + 2 && t_value !== (t_value = /*label*/ + ctx2[5] + "")) + set_data(t, t_value); + if (dirty & /*fields*/ + 2 && option_value_value !== (option_value_value = /*label*/ + ctx2[5])) { + option.__value = option_value_value; + set_input_value(option, option.__value); + } + }, + d(detaching) { + if (detaching) { + detach(option); + } + } + }; +} +function create_fragment26(ctx) { + let select; + let option; + let t; + let select_value_value; + let mounted; + let dispose; + let each_value = ensure_array_like( + /*fields*/ + ctx[1] + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block3(get_each_context3(ctx, each_value, i)); + } + return { + c() { + select = element("select"); + option = element("option"); + t = text("Select Field"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + option.__value = void 0; + set_input_value(option, option.__value); + option.disabled = true; + attr(select, "class", "dropdown"); + }, + m(target, anchor) { + var _a; + insert(target, select, anchor); + append(select, option); + append(option, t); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(select, null); + } + } + select_option( + select, + /*field*/ + (_a = ctx[0]) == null ? void 0 : _a.label + ); + if (!mounted) { + dispose = listen( + select, + "change", + /*change_handler*/ + ctx[4] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + var _a, _b; + if (dirty & /*fields*/ + 2) { + each_value = ensure_array_like( + /*fields*/ + ctx2[1] + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context3(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block3(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 & /*field, fields, undefined*/ + 3 && select_value_value !== (select_value_value = /*field*/ + (_a = ctx2[0]) == null ? void 0 : _a.label)) { + select_option( + select, + /*field*/ + (_b = ctx2[0]) == null ? void 0 : _b.label + ); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(select); + } + destroy_each(each_blocks, detaching); + mounted = false; + dispose(); + } + }; +} +function instance26($$self, $$props, $$invalidate) { + let { fields } = $$props; + let { undefine_on_change = true } = $$props; + let { field = void 0 } = $$props; + const dispatch = createEventDispatcher(); + const change_handler = (e) => { + $$invalidate(0, field = fields.find((field2) => field2.label === e.currentTarget.value)); + dispatch("select", field); + if (undefine_on_change) + $$invalidate(0, field = void 0); + }; + $$self.$$set = ($$props2) => { + if ("fields" in $$props2) + $$invalidate(1, fields = $$props2.fields); + if ("undefine_on_change" in $$props2) + $$invalidate(2, undefine_on_change = $$props2.undefine_on_change); + if ("field" in $$props2) + $$invalidate(0, field = $$props2.field); + }; + return [field, fields, undefine_on_change, dispatch, change_handler]; +} +var EdgeFieldSelector = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance26, create_fragment26, safe_not_equal, { + fields: 1, + undefine_on_change: 2, + field: 0 + }); + } +}; +var EdgeFieldSelector_default = EdgeFieldSelector; + +// src/components/settings/TransitiveImpliedRelations.svelte +function add_css(target) { + append_styles(target, "svelte-91sdw2", ".border.svelte-91sdw2{border-radius:var(--radius-m);border:var(--modal-border-width) solid\n var(--background-modifier-border)}"); +} +function get_each_context4(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[25] = list[i].rule; + child_ctx[26] = list[i].rule_i; + child_ctx[27] = list[i].name; + child_ctx[28] = list; + child_ctx[29] = i; + return child_ctx; +} +function get_each_context_12(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[30] = list[i]; + child_ctx[32] = i; + return child_ctx; +} +function create_if_block_32(ctx) { + let button; + let arrowdown; + let current; + let mounted; + let dispose; + arrowdown = new arrow_down_default({ props: { size: ICON_SIZE } }); + return { + c() { + button = element("button"); + create_component(arrowdown.$$.fragment); + attr(button, "class", "w-10"); + attr(button, "aria-label", "Jump to bottom"); + }, + m(target, anchor) { + insert(target, button, anchor); + mount_component(arrowdown, button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler_1*/ + ctx[9] + ); + mounted = true; + } + }, + p: noop, + i(local) { + if (current) + return; + transition_in(arrowdown.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(arrowdown.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + destroy_component(arrowdown); + mounted = false; + dispose(); + } + }; +} +function create_if_block_22(ctx) { + let span; + return { + c() { + span = element("span"); + span.textContent = "Unsaved changes"; + attr(span, "class", "text-warning"); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + d(detaching) { + if (detaching) { + detach(span); + } + } + }; +} +function create_else_block3(ctx) { + let span; + return { + c() { + span = element("span"); + span.textContent = "No fields in the chain."; + attr(span, "class", "search-empty-state my-0"); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + p: noop, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(span); + } + } + }; +} +function create_if_block_12(ctx) { + let div; + let each_blocks = []; + let each_1_lookup = /* @__PURE__ */ new Map(); + let current; + let each_value_1 = ensure_array_like( + /*rule*/ + ctx[25].chain + ); + const get_key = (ctx2) => { + var _a; + return ( + /*attr_i*/ + ctx2[32] + /*attr*/ + ((_a = ctx2[30].field) != null ? _a : "") + ); + }; + for (let i = 0; i < each_value_1.length; i += 1) { + let child_ctx = get_each_context_12(ctx, each_value_1, i); + let key = get_key(child_ctx); + each_1_lookup.set(key, each_blocks[i] = create_each_block_12(key, child_ctx)); + } + return { + c() { + div = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(div, "class", "flex flex-wrap gap-3"); + }, + m(target, anchor) { + 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(ctx2, dirty) { + if (dirty[0] & /*transitives, filter, context_menus*/ + 76) { + each_value_1 = ensure_array_like( + /*rule*/ + ctx2[25].chain + ); + group_outros(); + each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_1, each_1_lookup, div, outro_and_destroy_block, create_each_block_12, null, get_each_context_12); + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_1.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].d(); + } + } + }; +} +function create_each_block_12(key_1, ctx) { + var _a; + let first; + let tag; + let current; + tag = new tag_default({ + props: { + tag: ( + /*attr*/ + (_a = ctx[30].field) != null ? _a : "" + ), + title: "Right click for more actions." + } + }); + tag.$on("contextmenu", function() { + if (is_function( + /*context_menus*/ + ctx[6].chain_field( + /*rule_i*/ + ctx[26], + /*attr_i*/ + ctx[32] + ) + )) + ctx[6].chain_field( + /*rule_i*/ + ctx[26], + /*attr_i*/ + ctx[32] + ).apply(this, arguments); + }); + return { + key: key_1, + first: null, + c() { + first = empty(); + create_component(tag.$$.fragment); + this.first = first; + }, + m(target, anchor) { + insert(target, first, anchor); + mount_component(tag, target, anchor); + current = true; + }, + p(new_ctx, dirty) { + var _a2; + ctx = new_ctx; + const tag_changes = {}; + if (dirty[0] & /*transitives, filter*/ + 12) + tag_changes.tag = /*attr*/ + (_a2 = ctx[30].field) != null ? _a2 : ""; + tag.$set(tag_changes); + }, + i(local) { + if (current) + return; + transition_in(tag.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(tag.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(first); + } + destroy_component(tag, detaching); + } + }; +} +function create_if_block4(ctx) { + let renderexternalcodeblock; + let current; + renderexternalcodeblock = new RenderExternalCodeblock_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + type: "mermaid", + code: Mermaid.from_edges(transitive_rule_to_edges( + /*rule*/ + ctx[25] + ), { + show_attributes: ["field"], + collapse_opposing_edges: false + }) + } + }); + return { + c() { + create_component(renderexternalcodeblock.$$.fragment); + }, + m(target, anchor) { + mount_component(renderexternalcodeblock, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const renderexternalcodeblock_changes = {}; + if (dirty[0] & /*plugin*/ + 1) + renderexternalcodeblock_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty[0] & /*transitives, filter*/ + 12) + renderexternalcodeblock_changes.code = Mermaid.from_edges(transitive_rule_to_edges( + /*rule*/ + ctx2[25] + ), { + show_attributes: ["field"], + collapse_opposing_edges: false + }); + renderexternalcodeblock.$set(renderexternalcodeblock_changes); + }, + i(local) { + if (current) + return; + transition_in(renderexternalcodeblock.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(renderexternalcodeblock.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(renderexternalcodeblock, detaching); + } + }; +} +function create_key_block2(ctx) { + let div6; + let div0; + let span0; + let t1; + let current_block_type_index; + let if_block0; + let t2; + let edgefieldselector0; + let t3; + let div1; + let span1; + let t5; + let edgefieldselector1; + let t6; + let div2; + let span2; + let t8; + let input0; + let t9; + let div3; + let span3; + let t11; + let input1; + let input1_min_value; + let input1_max_value; + let input1_value_value; + let t12; + let div5; + let span4; + let t14; + let div4; + let input2; + let input2_value_value; + let t15; + let button; + let t17; + let current; + let mounted; + let dispose; + const if_block_creators = [create_if_block_12, create_else_block3]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*rule*/ + ctx2[25].chain.length + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, [-1, -1]); + if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + function select_handler(...args) { + return ( + /*select_handler*/ + ctx[16]( + /*rule_i*/ + ctx[26], + ...args + ) + ); + } + edgefieldselector0 = new EdgeFieldSelector_default({ + props: { fields: ( + /*settings*/ + ctx[1].edge_fields + ) } + }); + edgefieldselector0.$on("select", select_handler); + function func_2(...args) { + return ( + /*func_2*/ + ctx[17]( + /*rule*/ + ctx[25], + ...args + ) + ); + } + function select_handler_1(...args) { + return ( + /*select_handler_1*/ + ctx[18]( + /*rule_i*/ + ctx[26], + ...args + ) + ); + } + edgefieldselector1 = new EdgeFieldSelector_default({ + props: { + undefine_on_change: false, + fields: ( + /*settings*/ + ctx[1].edge_fields + ), + field: ( + /*settings*/ + ctx[1].edge_fields.find(func_2) + ) + } + }); + edgefieldselector1.$on("select", select_handler_1); + function input0_change_handler() { + ctx[19].call( + input0, + /*each_value*/ + ctx[28], + /*each_index*/ + ctx[29] + ); + } + function click_handler_6(...args) { + return ( + /*click_handler_6*/ + ctx[20]( + /*rule_i*/ + ctx[26], + ...args + ) + ); + } + function blur_handler(...args) { + return ( + /*blur_handler*/ + ctx[21]( + /*rule_i*/ + ctx[26], + ...args + ) + ); + } + function blur_handler_1(...args) { + return ( + /*blur_handler_1*/ + ctx[22]( + /*rule_i*/ + ctx[26], + ...args + ) + ); + } + function click_handler_7() { + return ( + /*click_handler_7*/ + ctx[23]( + /*rule_i*/ + ctx[26] + ) + ); + } + let if_block1 = ( + /*opens*/ + ctx[4][ + /*rule_i*/ + ctx[26] + ] && create_if_block4(ctx) + ); + return { + c() { + div6 = element("div"); + div0 = element("div"); + span0 = element("span"); + span0.textContent = "Edge Chain:"; + t1 = space(); + if_block0.c(); + t2 = space(); + create_component(edgefieldselector0.$$.fragment); + t3 = space(); + div1 = element("div"); + span1 = element("span"); + span1.textContent = "Closing Field:"; + t5 = space(); + create_component(edgefieldselector1.$$.fragment); + t6 = space(); + div2 = element("div"); + span2 = element("span"); + span2.textContent = "Close Reversed:"; + t8 = space(); + input0 = element("input"); + t9 = space(); + div3 = element("div"); + span3 = element("span"); + span3.textContent = "Rounds:"; + t11 = space(); + input1 = element("input"); + t12 = space(); + div5 = element("div"); + span4 = element("span"); + span4.textContent = "Name (optional):"; + t14 = space(); + div4 = element("div"); + input2 = element("input"); + t15 = space(); + button = element("button"); + button.textContent = "X"; + t17 = space(); + if (if_block1) + if_block1.c(); + attr(span0, "class", "font-semibold"); + attr(div0, "class", "flex flex-wrap items-center gap-3"); + attr(span1, "class", "font-semibold"); + attr(span2, "class", "font-semibold"); + attr(input0, "type", "checkbox"); + attr(div2, "class", "flex items-center gap-2"); + attr(span3, "class", "font-semibold"); + attr(input1, "type", "number"); + attr(input1, "min", input1_min_value = 0); + attr(input1, "max", input1_max_value = 100); + input1.value = input1_value_value = /*rule*/ + ctx[25].rounds; + attr(span4, "class", "font-semibold"); + attr(input2, "type", "text"); + input2.value = input2_value_value = /*rule*/ + ctx[25].name; + attr(input2, "placeholder", "Rule Name"); + attr(button, "aria-label", "Reset Name"); + attr(div4, "class", "flex gap-1"); + attr(div5, "class", "flex flex-wrap items-center gap-3"); + attr(div6, "class", "my-2 flex flex-col gap-3 px-4 py-2"); + }, + m(target, anchor) { + insert(target, div6, anchor); + append(div6, div0); + append(div0, span0); + append(div0, t1); + if_blocks[current_block_type_index].m(div0, null); + append(div0, t2); + mount_component(edgefieldselector0, div0, null); + append(div6, t3); + append(div6, div1); + append(div1, span1); + append(div1, t5); + mount_component(edgefieldselector1, div1, null); + append(div6, t6); + append(div6, div2); + append(div2, span2); + append(div2, t8); + append(div2, input0); + input0.checked = /*rule*/ + ctx[25].close_reversed; + append(div6, t9); + append(div6, div3); + append(div3, span3); + append(div3, t11); + append(div3, input1); + append(div6, t12); + append(div6, div5); + append(div5, span4); + append(div5, t14); + append(div5, div4); + append(div4, input2); + append(div4, t15); + append(div4, button); + append(div6, t17); + if (if_block1) + if_block1.m(div6, null); + current = true; + if (!mounted) { + dispose = [ + listen(input0, "change", input0_change_handler), + listen(input0, "click", click_handler_6), + listen(input1, "blur", blur_handler), + listen(input2, "blur", blur_handler_1), + listen(button, "click", click_handler_7) + ]; + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + 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 { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block0 = if_blocks[current_block_type_index]; + if (!if_block0) { + if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + if_block0.c(); + } else { + if_block0.p(ctx, dirty); + } + transition_in(if_block0, 1); + if_block0.m(div0, t2); + } + const edgefieldselector0_changes = {}; + if (dirty[0] & /*settings*/ + 2) + edgefieldselector0_changes.fields = /*settings*/ + ctx[1].edge_fields; + edgefieldselector0.$set(edgefieldselector0_changes); + const edgefieldselector1_changes = {}; + if (dirty[0] & /*settings*/ + 2) + edgefieldselector1_changes.fields = /*settings*/ + ctx[1].edge_fields; + if (dirty[0] & /*settings, transitives, filter*/ + 14) + edgefieldselector1_changes.field = /*settings*/ + ctx[1].edge_fields.find(func_2); + edgefieldselector1.$set(edgefieldselector1_changes); + if (dirty[0] & /*transitives, filter*/ + 12) { + input0.checked = /*rule*/ + ctx[25].close_reversed; + } + if (!current || dirty[0] & /*transitives, filter*/ + 12 && input1_value_value !== (input1_value_value = /*rule*/ + ctx[25].rounds) && input1.value !== input1_value_value) { + input1.value = input1_value_value; + } + if (!current || dirty[0] & /*transitives, filter*/ + 12 && input2_value_value !== (input2_value_value = /*rule*/ + ctx[25].name) && input2.value !== input2_value_value) { + input2.value = input2_value_value; + } + if ( + /*opens*/ + ctx[4][ + /*rule_i*/ + ctx[26] + ] + ) { + if (if_block1) { + if_block1.p(ctx, dirty); + if (dirty[0] & /*opens, transitives, filter*/ + 28) { + transition_in(if_block1, 1); + } + } else { + if_block1 = create_if_block4(ctx); + if_block1.c(); + transition_in(if_block1, 1); + if_block1.m(div6, null); + } + } else if (if_block1) { + group_outros(); + transition_out(if_block1, 1, 1, () => { + if_block1 = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block0); + transition_in(edgefieldselector0.$$.fragment, local); + transition_in(edgefieldselector1.$$.fragment, local); + transition_in(if_block1); + current = true; + }, + o(local) { + transition_out(if_block0); + transition_out(edgefieldselector0.$$.fragment, local); + transition_out(edgefieldselector1.$$.fragment, local); + transition_out(if_block1); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div6); + } + if_blocks[current_block_type_index].d(); + destroy_component(edgefieldselector0); + destroy_component(edgefieldselector1); + if (if_block1) + if_block1.d(); + mounted = false; + run_all(dispose); + } + }; +} +function create_each_block4(key_1, ctx) { + let details; + let summary; + let div0; + let chevronopener; + let t0; + let code; + let t1_value = ( + /*name*/ + ctx[27] + "" + ); + let t1; + let t2; + let div1; + let button0; + let arrowup; + let button0_disabled_value; + let t3; + let button1; + let arrowdown; + let button1_disabled_value; + let t4; + let button2; + let clipboardicon; + let t5; + let button3; + let t7; + let previous_key = ( + /*rule*/ + ctx[25] + ); + let details_id_value; + let current; + let mounted; + let dispose; + chevronopener = new ChevronOpener_default({ + props: { + open: ( + /*opens*/ + ctx[4][ + /*rule_i*/ + ctx[26] + ] + ) + } + }); + arrowup = new arrow_up_default({ props: { size: ICON_SIZE } }); + function click_handler_2() { + return ( + /*click_handler_2*/ + ctx[12]( + /*rule_i*/ + ctx[26] + ) + ); + } + arrowdown = new arrow_down_default({ props: { size: ICON_SIZE } }); + function click_handler_3() { + return ( + /*click_handler_3*/ + ctx[13]( + /*rule_i*/ + ctx[26] + ) + ); + } + clipboardicon = new clipboard_default({ props: { size: ICON_SIZE } }); + function click_handler_4() { + return ( + /*click_handler_4*/ + ctx[14]( + /*rule_i*/ + ctx[26] + ) + ); + } + function click_handler_5() { + return ( + /*click_handler_5*/ + ctx[15]( + /*rule_i*/ + ctx[26] + ) + ); + } + let key_block = create_key_block2(ctx); + function details_toggle_handler() { + ctx[24].call( + details, + /*rule_i*/ + ctx[26] + ); + } + return { + key: key_1, + first: null, + c() { + details = element("details"); + summary = element("summary"); + div0 = element("div"); + create_component(chevronopener.$$.fragment); + t0 = space(); + code = element("code"); + t1 = text(t1_value); + t2 = space(); + div1 = element("div"); + button0 = element("button"); + create_component(arrowup.$$.fragment); + t3 = space(); + button1 = element("button"); + create_component(arrowdown.$$.fragment); + t4 = space(); + button2 = element("button"); + create_component(clipboardicon.$$.fragment); + t5 = space(); + button3 = element("button"); + button3.textContent = "X"; + t7 = space(); + key_block.c(); + attr(div0, "class", "flex items-center gap-2"); + button0.disabled = button0_disabled_value = /*rule_i*/ + ctx[26] === 0; + button1.disabled = button1_disabled_value = /*rule_i*/ + ctx[26] === /*transitives*/ + ctx[3].length - 1; + attr(button2, "aria-label", "Copy Transitive Implied Relation"); + attr(button3, "aria-label", "Delete Transitive Implied Relation"); + attr(div1, "class", "flex gap-1"); + attr(summary, "class", "flex items-center justify-between gap-2"); + attr(details, "id", details_id_value = /*actions*/ + ctx[5].make_id( + /*rule_i*/ + ctx[26] + )); + attr(details, "class", "scroll-mt-40 border p-2 svelte-91sdw2"); + this.first = details; + }, + m(target, anchor) { + insert(target, details, anchor); + append(details, summary); + append(summary, div0); + mount_component(chevronopener, div0, null); + append(div0, t0); + append(div0, code); + append(code, t1); + append(summary, t2); + append(summary, div1); + append(div1, button0); + mount_component(arrowup, button0, null); + append(div1, t3); + append(div1, button1); + mount_component(arrowdown, button1, null); + append(div1, t4); + append(div1, button2); + mount_component(clipboardicon, button2, null); + append(div1, t5); + append(div1, button3); + append(details, t7); + key_block.m(details, null); + details.open = /*opens*/ + ctx[4][ + /*rule_i*/ + ctx[26] + ]; + current = true; + if (!mounted) { + dispose = [ + listen(button0, "click", click_handler_2), + listen(button1, "click", click_handler_3), + listen(button2, "click", click_handler_4), + listen(button3, "click", click_handler_5), + listen(details, "toggle", details_toggle_handler) + ]; + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + const chevronopener_changes = {}; + if (dirty[0] & /*opens, transitives, filter*/ + 28) + chevronopener_changes.open = /*opens*/ + ctx[4][ + /*rule_i*/ + ctx[26] + ]; + chevronopener.$set(chevronopener_changes); + if ((!current || dirty[0] & /*transitives, filter*/ + 12) && t1_value !== (t1_value = /*name*/ + ctx[27] + "")) + set_data(t1, t1_value); + if (!current || dirty[0] & /*transitives, filter*/ + 12 && button0_disabled_value !== (button0_disabled_value = /*rule_i*/ + ctx[26] === 0)) { + button0.disabled = button0_disabled_value; + } + if (!current || dirty[0] & /*transitives, filter*/ + 12 && button1_disabled_value !== (button1_disabled_value = /*rule_i*/ + ctx[26] === /*transitives*/ + ctx[3].length - 1)) { + button1.disabled = button1_disabled_value; + } + if (dirty[0] & /*transitives, filter*/ + 12 && safe_not_equal(previous_key, previous_key = /*rule*/ + ctx[25])) { + group_outros(); + transition_out(key_block, 1, 1, noop); + check_outros(); + key_block = create_key_block2(ctx); + key_block.c(); + transition_in(key_block, 1); + key_block.m(details, null); + } else { + key_block.p(ctx, dirty); + } + if (!current || dirty[0] & /*transitives, filter*/ + 12 && details_id_value !== (details_id_value = /*actions*/ + ctx[5].make_id( + /*rule_i*/ + ctx[26] + ))) { + attr(details, "id", details_id_value); + } + if (dirty[0] & /*opens, transitives, filter*/ + 28) { + details.open = /*opens*/ + ctx[4][ + /*rule_i*/ + ctx[26] + ]; + } + }, + i(local) { + if (current) + return; + transition_in(chevronopener.$$.fragment, local); + transition_in(arrowup.$$.fragment, local); + transition_in(arrowdown.$$.fragment, local); + transition_in(clipboardicon.$$.fragment, local); + transition_in(key_block); + current = true; + }, + o(local) { + transition_out(chevronopener.$$.fragment, local); + transition_out(arrowup.$$.fragment, local); + transition_out(arrowdown.$$.fragment, local); + transition_out(clipboardicon.$$.fragment, local); + transition_out(key_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(details); + } + destroy_component(chevronopener); + destroy_component(arrowup); + destroy_component(arrowdown); + destroy_component(clipboardicon); + key_block.d(detaching); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment27(ctx) { + let div4; + let p0; + let t0; + let em; + let t2; + let code0; + let t5; + let t6; + let div1; + let button0; + let saveicon; + let t7; + let t8; + let div0; + let input; + let t9; + let button1; + let t10; + let button1_disabled_value; + let t11; + let t12; + let t13; + let div3; + let each_blocks = []; + let each_1_lookup = /* @__PURE__ */ new Map(); + let t14; + let button2; + let plusicon; + let t15; + let t16; + let details; + let summary; + let t18; + let div2; + let p1; + let t22; + let textarea; + let t23; + let button3; + let current; + let mounted; + let dispose; + saveicon = new save_default({ props: { size: ICON_SIZE } }); + let if_block0 = ( + /*transitives*/ + ctx[3].length > 3 && create_if_block_32(ctx) + ); + let if_block1 = ( + /*settings*/ + ctx[1].is_dirty && create_if_block_22(ctx) + ); + let each_value = ensure_array_like( + /*transitives*/ + ctx[3].map( + /*func*/ + ctx[10] + ).filter( + /*func_1*/ + ctx[11] + ) + ); + const get_key = (ctx2) => ( + /*name*/ + ctx2[27] + /*rule_i*/ + ctx2[26] + ); + for (let i = 0; i < each_value.length; i += 1) { + let child_ctx = get_each_context4(ctx, each_value, i); + let key = get_key(child_ctx); + each_1_lookup.set(key, each_blocks[i] = create_each_block4(key, child_ctx)); + } + plusicon = new plus_default({ props: { size: ICON_SIZE } }); + return { + c() { + div4 = element("div"); + p0 = element("p"); + t0 = text("Transitive implied relations represent "); + em = element("em"); + em.textContent = "chains"; + t2 = text(' of your\n Breadcrumbs fields that collapse into a single field. For example, if\n you have the fields: "spouse", "sibling", and "sibling-in-law", you can\n add the transitive chain\n '); + code0 = element("code"); + code0.textContent = `${stringify_transitive_relation({ + close_reversed: false, + close_field: "sibling-in-law", + chain: [{ field: "spouse" }, { field: "sibling" }] + })} `; + t5 = text(". In other words, your spouse's sibling is your sibling-in-law."); + t6 = space(); + div1 = element("div"); + button0 = element("button"); + create_component(saveicon.$$.fragment); + t7 = text("\n Save"); + t8 = space(); + div0 = element("div"); + input = element("input"); + t9 = space(); + button1 = element("button"); + t10 = text("X"); + t11 = space(); + if (if_block0) + if_block0.c(); + t12 = space(); + if (if_block1) + if_block1.c(); + t13 = space(); + div3 = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + t14 = space(); + button2 = element("button"); + create_component(plusicon.$$.fragment); + t15 = text("\n Add New Transitive Implied Relation"); + t16 = space(); + details = element("details"); + summary = element("summary"); + summary.textContent = "Bulk Add Rules (Advanced)"; + t18 = space(); + div2 = element("div"); + p1 = element("p"); + p1.innerHTML = `Quickly add multiple rules using the shorthand syntax: [field-one, field-two] -> close-field + . Each rule should be on a new line.`; + t22 = space(); + textarea = element("textarea"); + t23 = space(); + button3 = element("button"); + button3.textContent = "Bulk Add"; + attr(button0, "class", "flex items-center gap-1"); + attr(input, "type", "text"); + attr(input, "placeholder", "Filter Rules by Name"); + attr(button1, "class", "w-8"); + attr(button1, "aria-label", "Clear Filter"); + button1.disabled = button1_disabled_value = /*filter*/ + ctx[2] === ""; + attr(div0, "class", "flex gap-1"); + attr(div1, "class", "my-2 flex items-center gap-2"); + attr(button2, "class", "flex items-center gap-1"); + attr(textarea, "id", "BC-transitive-bulk-str"); + attr(textarea, "class", "h-32 w-60"); + attr(textarea, "placeholder", "[up] <- down"); + attr(button3, "class", "w-60"); + attr(div2, "class", "flex flex-col gap-1"); + attr(div3, "class", "flex flex-col gap-3"); + attr(div4, "class", "BC-custom-transitive-implied-relations"); + }, + m(target, anchor) { + insert(target, div4, anchor); + append(div4, p0); + append(p0, t0); + append(p0, em); + append(p0, t2); + append(p0, code0); + append(p0, t5); + append(div4, t6); + append(div4, div1); + append(div1, button0); + mount_component(saveicon, button0, null); + append(button0, t7); + append(div1, t8); + append(div1, div0); + append(div0, input); + set_input_value( + input, + /*filter*/ + ctx[2] + ); + append(div0, t9); + append(div0, button1); + append(button1, t10); + append(div1, t11); + if (if_block0) + if_block0.m(div1, null); + append(div1, t12); + if (if_block1) + if_block1.m(div1, null); + append(div4, t13); + append(div4, div3); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(div3, null); + } + } + append(div3, t14); + append(div3, button2); + mount_component(plusicon, button2, null); + append(button2, t15); + append(div3, t16); + append(div3, details); + append(details, summary); + append(details, t18); + append(details, div2); + append(div2, p1); + append(div2, t22); + append(div2, textarea); + append(div2, t23); + append(div2, button3); + current = true; + if (!mounted) { + dispose = [ + listen( + button0, + "click", + /*actions*/ + ctx[5].save + ), + listen( + input, + "input", + /*input_input_handler*/ + ctx[7] + ), + listen( + button1, + "click", + /*click_handler*/ + ctx[8] + ), + listen( + button2, + "click", + /*actions*/ + ctx[5].add_transitive + ), + listen( + button3, + "click", + /*actions*/ + ctx[5].add_bulk + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty[0] & /*filter*/ + 4 && input.value !== /*filter*/ + ctx2[2]) { + set_input_value( + input, + /*filter*/ + ctx2[2] + ); + } + if (!current || dirty[0] & /*filter*/ + 4 && button1_disabled_value !== (button1_disabled_value = /*filter*/ + ctx2[2] === "")) { + button1.disabled = button1_disabled_value; + } + if ( + /*transitives*/ + ctx2[3].length > 3 + ) { + if (if_block0) { + if_block0.p(ctx2, dirty); + if (dirty[0] & /*transitives*/ + 8) { + transition_in(if_block0, 1); + } + } else { + if_block0 = create_if_block_32(ctx2); + if_block0.c(); + transition_in(if_block0, 1); + if_block0.m(div1, t12); + } + } else if (if_block0) { + group_outros(); + transition_out(if_block0, 1, 1, () => { + if_block0 = null; + }); + check_outros(); + } + if ( + /*settings*/ + ctx2[1].is_dirty + ) { + if (if_block1) { + } else { + if_block1 = create_if_block_22(ctx2); + if_block1.c(); + if_block1.m(div1, null); + } + } else if (if_block1) { + if_block1.d(1); + if_block1 = null; + } + if (dirty[0] & /*actions, transitives, filter, opens, plugin, settings, context_menus*/ + 127) { + each_value = ensure_array_like( + /*transitives*/ + ctx2[3].map( + /*func*/ + ctx2[10] + ).filter( + /*func_1*/ + ctx2[11] + ) + ); + group_outros(); + each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, div3, outro_and_destroy_block, create_each_block4, t14, get_each_context4); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(saveicon.$$.fragment, local); + transition_in(if_block0); + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + transition_in(plusicon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(saveicon.$$.fragment, local); + transition_out(if_block0); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + transition_out(plusicon.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div4); + } + destroy_component(saveicon); + if (if_block0) + if_block0.d(); + if (if_block1) + if_block1.d(); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].d(); + } + destroy_component(plusicon); + mounted = false; + run_all(dispose); + } + }; +} +function instance27($$self, $$props, $$invalidate) { + let { plugin } = $$props; + const settings = plugin.settings; + let filter = ""; + let transitives = [...settings.implied_relations.transitive]; + const opens = transitives.map(() => false); + const actions = { + save: () => __awaiter(void 0, void 0, void 0, function* () { + for (const { close_field } of transitives) { + if (!close_field) { + return new import_obsidian10.Notice("Closing field cannot be empty."); + } + } + $$invalidate(1, settings.implied_relations.transitive = transitives, settings); + yield Promise.all([plugin.saveSettings(), plugin.refresh({ redraw_side_views: true })]); + $$invalidate(0, plugin); + }), + make_id: (rule_i) => `BC-transitive-rule-${rule_i}`, + scroll_to: (rule_i) => { + var _a; + return (_a = document.getElementById(actions.make_id(rule_i))) === null || _a === void 0 ? void 0 : _a.scrollIntoView({ behavior: "smooth" }); + }, + add_transitive: () => { + const new_length = transitives.push({ + name: "", + chain: [], + // NOTE: Max by default, users can lower if needed + // It seems to fit with intuition that the implied relations just keep going + rounds: 10, + close_reversed: false, + close_field: settings.edge_fields[0].label + }); + $$invalidate(4, opens[new_length - 1] = true, opens); + setTimeout(() => actions.scroll_to(new_length - 1), 0); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + add_bulk: () => { + const textarea = document.getElementById("BC-transitive-bulk-str"); + if (!textarea) + return new import_obsidian10.Notice("Could not find textarea."); + const value = textarea.value.trim(); + if (!value) + return new import_obsidian10.Notice("No rules to parse."); + const lines = split_and_trim(value, "\n").filter(Boolean); + const parsed = lines.map(parse_transitive_relation).filter((r) => r.ok); + if (parsed.length !== lines.length) { + return new import_obsidian10.Notice("Some rules could not be parsed. Ensure you're using the correct syntax of `[field-one, field-two] -> close-field`, with each rule of a new line."); + } + const validated = parsed.map((r) => input_transitive_rule_schema({ fields: plugin.settings.edge_fields }).safeParse(r.data)); + const validation_errors = validated.filter((r) => !r.success); + if (validation_errors.length) { + log.error("Bulk-add transitive rule errors >", validation_errors.map((r) => { + var _a; + return r.success ? null : (_a = r.error) === null || _a === void 0 ? void 0 : _a.issues; + })); + return new import_obsidian10.Notice("Some rules could not be parsed. Check the logs for more information."); + } + validated.forEach((r) => { + if (r.success) { + transitives.push(Object.assign(Object.assign({}, r.data), { name: "", rounds: 10 })); + } + }); + new import_obsidian10.Notice(`Bulk added ${validated.length} rules \u2705`); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + copy_transitive: (i) => { + const new_length = transitives.push(Object.assign(Object.assign({}, transitives[i]), { + name: `${get_transitive_rule_name(transitives[i])} (copy)` + })); + $$invalidate(4, opens[new_length - 1] = true, opens); + setTimeout(() => actions.scroll_to(new_length - 1), 0); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + remove_transitive: (i) => { + $$invalidate(3, transitives = transitives.filter((_, j) => j !== i)); + $$invalidate(1, settings.is_dirty = true, settings); + }, + rename_transitive: (i, new_name) => { + if (transitives[i].name === new_name) + return; + $$invalidate(3, transitives[i].name = new_name, transitives); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + reorder_transitive: (i, j) => { + const temp = transitives[i]; + $$invalidate(3, transitives[i] = transitives[j], transitives); + $$invalidate(3, transitives[j] = temp, transitives); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + add_chain_field: (i, field) => { + if (!field) + return; + transitives[i].chain.push({ field: field.label }); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + remove_chain_field: (i, j) => { + $$invalidate(3, transitives[i].chain = transitives[i].chain.filter((_, k) => k !== j), transitives); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + set_close_field: (i, field) => { + if (!field) + return; + $$invalidate(3, transitives[i].close_field = field.label, transitives); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + set_rounds: (i, rounds) => { + if (isNaN(rounds) || rounds < 0) + return; + $$invalidate(3, transitives[i].rounds = rounds, transitives); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + }, + set_close_reversed: (i, reversed) => { + $$invalidate(3, transitives[i].close_reversed = reversed, transitives); + $$invalidate(3, transitives); + $$invalidate(1, settings.is_dirty = true, settings); + } + }; + const context_menus = { + chain_field: (rule_i, attr_i) => (e) => { + const menu = new import_obsidian10.Menu(); + menu.addItem((item) => item.setTitle("Remove Field").setIcon("x").onClick(() => actions.remove_chain_field(rule_i, attr_i))); + menu.showAtMouseEvent(e); + } + }; + function input_input_handler() { + filter = this.value; + $$invalidate(2, filter); + } + const click_handler = () => $$invalidate(2, filter = ""); + const click_handler_1 = () => actions.scroll_to(transitives.length - 1); + const func = (rule, rule_i) => ({ + rule, + rule_i, + name: get_transitive_rule_name(rule) + }); + const func_1 = (r) => r.name.includes(filter.toLowerCase()); + const click_handler_2 = (rule_i) => actions.reorder_transitive(rule_i, rule_i - 1); + const click_handler_3 = (rule_i) => actions.reorder_transitive(rule_i, rule_i + 1); + const click_handler_4 = (rule_i) => actions.copy_transitive(rule_i); + const click_handler_5 = (rule_i) => actions.remove_transitive(rule_i); + const select_handler = (rule_i, e) => actions.add_chain_field(rule_i, e.detail); + const func_2 = (rule, f) => f.label === rule.close_field; + const select_handler_1 = (rule_i, e) => actions.set_close_field(rule_i, e.detail); + function input0_change_handler(each_value, each_index) { + each_value[each_index].rule.close_reversed = this.checked; + $$invalidate(3, transitives); + $$invalidate(2, filter); + } + const click_handler_6 = (rule_i, e) => actions.set_close_reversed(rule_i, e.currentTarget.checked); + const blur_handler = (rule_i, e) => actions.set_rounds(rule_i, +e.currentTarget.value); + const blur_handler_1 = (rule_i, e) => actions.rename_transitive(rule_i, e.currentTarget.value); + const click_handler_7 = (rule_i) => actions.rename_transitive(rule_i, ""); + function details_toggle_handler(rule_i) { + opens[rule_i] = this.open; + $$invalidate(4, opens); + } + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + }; + return [ + plugin, + settings, + filter, + transitives, + opens, + actions, + context_menus, + input_input_handler, + click_handler, + click_handler_1, + func, + func_1, + click_handler_2, + click_handler_3, + click_handler_4, + click_handler_5, + select_handler, + func_2, + select_handler_1, + input0_change_handler, + click_handler_6, + blur_handler, + blur_handler_1, + click_handler_7, + details_toggle_handler + ]; +} +var TransitiveImpliedRelations = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance27, create_fragment27, safe_not_equal, { plugin: 0 }, add_css, [-1, -1]); + } +}; +var TransitiveImpliedRelations_default = TransitiveImpliedRelations; + +// src/settings/ShowNodeOptions.ts +var import_obsidian11 = require("obsidian"); +var _add_settings_show_node_options = (plugin, containerEl, cb, options) => { + let show_node_options = cb.get(); + const setting = new import_obsidian11.Setting(containerEl).setName("Note display options").setDesc("How to display note links"); + setting.controlEl.addClasses(["flex", "flex-wrap", "gap-2"]); + setting.addToggle((toggle) => { + toggle.toggleEl.before("Folder"); + toggle.setTooltip("Folder path").setValue(show_node_options.folder).onChange(async (value) => { + show_node_options.folder = value; + cb.set(show_node_options); + if ((options == null ? void 0 : options.save_and_refresh) !== false) { + await Promise.all([plugin.saveSettings()]); + plugin.refresh({ rebuild_graph: false }); + } + }); + }); + setting.addToggle((toggle) => { + toggle.toggleEl.before("Extension"); + toggle.setTooltip("File extension").setValue(show_node_options.ext).onChange(async (value) => { + show_node_options.ext = value; + cb.set(show_node_options); + if ((options == null ? void 0 : options.save_and_refresh) !== false) { + await Promise.all([plugin.saveSettings()]); + plugin.refresh({ rebuild_graph: false }); + } + }); + }); + setting.addToggle((toggle) => { + toggle.toggleEl.before("Alias"); + toggle.setTooltip("Alias (first alias, if available)").setValue(show_node_options.alias).onChange(async (value) => { + show_node_options.alias = value; + cb.set(show_node_options); + if ((options == null ? void 0 : options.save_and_refresh) !== false) { + await Promise.all([plugin.saveSettings()]); + plugin.refresh({ rebuild_graph: false }); + } + }); + }); + return setting; +}; + +// src/settings/CodeblockSettings.ts +var _add_settings_codeblocks = (plugin, containerEl) => { + _add_settings_show_node_options(plugin, containerEl, { + get: () => plugin.settings.views.codeblocks.show_node_options, + set: (value) => plugin.settings.views.codeblocks.show_node_options = value + }); +}; + +// src/settings/DateNoteSettings.ts +var import_obsidian13 = require("obsidian"); + +// src/utils/settings.ts +var import_obsidian12 = require("obsidian"); +var new_setting = (container_el, config) => { + const setting = new import_obsidian12.Setting(container_el); + if (config.name) + setting.setName(config.name); + if (config.desc) + setting.setDesc(config.desc); + if (config.toggle) { + setting.addToggle((toggle) => { + toggle.setValue(config.toggle.value).onChange(config.toggle.cb); + }); + } else if (config.input) { + setting.addText((text2) => { + var _a; + if ((_a = config.input) == null ? void 0 : _a.placeholder) { + text2.setPlaceholder(config.input.placeholder); + } + text2.setValue(config.input.value); + text2.inputEl.onblur = () => { + config.input.cb(text2.getValue()); + }; + }); + } else if (config.select) { + setting.addDropdown((dropdown) => { + const options = Array.isArray(config.select.options) ? config.select.options.reduce( + (acc, option) => { + acc[option] = option; + return acc; + }, + {} + ) : config.select.options; + dropdown.addOptions(options).setValue(config.select.value).onChange(config.select.cb); + }); + } else if (config.checklist) { + const checklist_el = setting.controlEl.createEl("div", { + attr: { class: "flex flex-wrap gap-3" } + }); + let state = { ...config.checklist.options }; + Object.keys(config.checklist.options).forEach((key) => { + const attr2 = { type: "checkbox" }; + if (config.checklist.options[key]) + attr2.checked = true; + checklist_el.createEl("label", { + text: key, + cls: "flex items-center gap-1.5 grow" + }).createEl("input", { attr: attr2 }, (el) => { + el.classList.add("shrink"); + el.onchange = (e) => { + if (!(e.target instanceof HTMLInputElement)) + return; + state[key] = e.target.checked; + config.checklist.cb(state); + }; + }); + }); + } + return setting; +}; + +// src/settings/DateNoteSettings.ts +var _add_settings_date_note = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Enabled", + desc: "Look for date notes to use as edge sources", + toggle: { + value: plugin.settings.explicit_edge_sources.date_note.enabled, + cb: async (value) => { + plugin.settings.explicit_edge_sources.date_note.enabled = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); + new_setting(containerEl, { + name: "Default Field", + desc: "Field used to join date notes together. Breadcrumbs takes the current note's date, adds one day, and joins the two notes with this field.", + select: { + value: plugin.settings.explicit_edge_sources.date_note.default_field, + options: plugin.settings.edge_fields.map((f) => f.label), + cb: async (value) => { + plugin.settings.explicit_edge_sources.date_note.default_field = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); + const date_format_fragment = new DocumentFragment(); + date_format_fragment.createEl( + "span", + {}, + (el) => el.innerHTML = `Luxon date format to use` + ); + new_setting(containerEl, { + name: "Date Format", + desc: date_format_fragment, + input: { + value: plugin.settings.explicit_edge_sources.date_note.date_format, + cb: async (value) => { + if (!value) + new import_obsidian13.Notice("Date format cannot be empty"); + else { + plugin.settings.explicit_edge_sources.date_note.date_format = value; + await Promise.all([ + plugin.refresh(), + plugin.saveSettings() + ]); + } + } + } + }); + new_setting(containerEl, { + name: "Stretch to Existing", + desc: "If there is a gap from one day to another, should the next note be the unresolved one in one day or should it 'stretch' to the next resolved (existing) note?", + toggle: { + value: plugin.settings.explicit_edge_sources.date_note.stretch_to_existing, + cb: async (value) => { + plugin.settings.explicit_edge_sources.date_note.stretch_to_existing = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); +}; + +// src/settings/DebugSettings.ts +var _add_settings_debug = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Debug Level", + desc: "Set the level of debug logging", + select: { + options: LOG_LEVELS, + value: plugin.settings.debug.level, + cb: async (value) => { + log.set_level(value); + plugin.settings.debug.level = value; + await plugin.saveSettings(); + } + } + }); +}; + +// src/settings/DendronNoteSettings.ts +var import_obsidian14 = require("obsidian"); +var _add_settings_dendron_note = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Enabled", + desc: "Look for dendron notes to use as edge sources", + toggle: { + value: plugin.settings.explicit_edge_sources.dendron_note.enabled, + cb: async (value) => { + plugin.settings.explicit_edge_sources.dendron_note.enabled = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); + new_setting(containerEl, { + name: "Delimiter", + desc: "Delimiter to use to split the note name", + input: { + value: plugin.settings.explicit_edge_sources.dendron_note.delimiter, + cb: async (value) => { + if (!value) + new import_obsidian14.Notice("Delimiter cannot be empty"); + else { + plugin.settings.explicit_edge_sources.dendron_note.delimiter = value; + await Promise.all([ + plugin.refresh(), + plugin.saveSettings() + ]); + } + } + } + }); + new_setting(containerEl, { + name: "Default Field", + desc: "Field to use if the BC-dendron-note-field is not specified", + select: { + value: plugin.settings.explicit_edge_sources.dendron_note.default_field, + options: plugin.settings.edge_fields.map((f) => f.label), + cb: async (value) => { + plugin.settings.explicit_edge_sources.dendron_note.default_field = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); + new_setting(containerEl, { + name: "Display Trimmed", + desc: "Display Dendron note names as the right-most split of the delimiter. e.g. `a.b.c` -> `c`", + toggle: { + value: plugin.settings.explicit_edge_sources.dendron_note.display_trimmed, + cb: async (value) => { + plugin.settings.explicit_edge_sources.dendron_note.display_trimmed = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); +}; + +// src/settings/EdgeFieldSuggestorSettings.ts +var import_obsidian15 = require("obsidian"); +var _add_settings_edge_field_suggestor = (plugin, contentEl) => { + const { settings } = plugin; + new_setting(contentEl, { + name: "Enabled", + desc: "Whether to enable the edge field suggestor", + toggle: { + value: settings.suggestors.edge_field.enabled, + cb: async (value) => { + settings.suggestors.edge_field.enabled = value; + if (value) { + new import_obsidian15.Notice( + "Please restart Obsidian for the changes to take effect" + ); + } + await plugin.saveSettings(); + } + } + }); + new_setting(contentEl, { + name: "Trigger String", + desc: "The string that triggers the suggestor (when entered at the start of a line)", + input: { + value: settings.suggestors.edge_field.trigger, + cb: async (value) => { + if (!value) { + new import_obsidian15.Notice("Trigger string cannot be empty"); + return; + } + settings.suggestors.edge_field.trigger = value; + await plugin.saveSettings(); + } + } + }); +}; + +// src/settings/FreezeImpliedEdgesSettings.ts +var _add_settings_freeze_implied_edges = (plugin, contentEl) => { + const { settings } = plugin; + new_setting(contentEl, { + name: "Destination", + desc: "Where to write the frozen edges to", + select: { + options: ["frontmatter", "dataview-inline"], + value: settings.commands.freeze_implied_edges.default_options.destination, + cb: async (value) => { + settings.commands.freeze_implied_edges.default_options.destination = value; + await plugin.saveSettings(); + } + } + }); +}; + +// src/settings/GridSettings.ts +var import_obsidian17 = require("obsidian"); + +// src/menus/FieldGroupsSelector.ts +var import_obsidian16 = require("obsidian"); +var FieldGroupsSelectorMenu = ({ + cb, + value, + edge_field_groups +}) => { + const menu = new import_obsidian16.Menu(); + const checks = edge_field_groups.map( + (group) => value.includes(group.label) + ); + const all_checked = checks.every((check) => check); + menu.addItem( + (item) => item.setTitle(all_checked ? "None" : "All").onClick(() => { + value = all_checked ? [] : edge_field_groups.map((group) => group.label); + cb(value); + }) + ); + menu.addSeparator(); + edge_field_groups.forEach((group, group_i) => { + const checked = checks[group_i]; + menu.addItem( + (item) => item.setTitle(group.label).setChecked(checked).onClick(() => { + if (checked) { + value = value.filter((label) => label !== group.label); + } else { + value.push(group.label); + } + cb(value); + }) + ); + }); + return menu; +}; + +// src/components/selector/FieldGroupLabelsSelector.svelte +function create_fragment28(ctx) { + let button; + let groupicon; + let current; + let mounted; + let dispose; + groupicon = new group_default({ props: { size: ICON_SIZE } }); + return { + c() { + button = element("button"); + create_component(groupicon.$$.fragment); + attr( + button, + "class", + /*cls*/ + ctx[1] + ); + attr(button, "aria-label", "Choose edge field groups"); + }, + m(target, anchor) { + insert(target, button, anchor); + mount_component(groupicon, button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler*/ + ctx[3] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (!current || dirty & /*cls*/ + 2) { + attr( + button, + "class", + /*cls*/ + ctx2[1] + ); + } + }, + i(local) { + if (current) + return; + transition_in(groupicon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(groupicon.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + destroy_component(groupicon); + mounted = false; + dispose(); + } + }; +} +function instance28($$self, $$props, $$invalidate) { + let { cls = "" } = $$props; + let { field_group_labels } = $$props; + let { edge_field_groups } = $$props; + const click_handler = (e) => { + FieldGroupsSelectorMenu({ + edge_field_groups, + value: field_group_labels, + cb: (value) => $$invalidate(0, field_group_labels = value) + }).showAtMouseEvent(e); + }; + $$self.$$set = ($$props2) => { + if ("cls" in $$props2) + $$invalidate(1, cls = $$props2.cls); + if ("field_group_labels" in $$props2) + $$invalidate(0, field_group_labels = $$props2.field_group_labels); + if ("edge_field_groups" in $$props2) + $$invalidate(2, edge_field_groups = $$props2.edge_field_groups); + }; + return [field_group_labels, cls, edge_field_groups, click_handler]; +} +var FieldGroupLabelsSelector = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance28, create_fragment28, safe_not_equal, { + cls: 1, + field_group_labels: 0, + edge_field_groups: 2 + }); + } +}; +var FieldGroupLabelsSelector_default = FieldGroupLabelsSelector; + +// src/components/settings/SettingItem.svelte +function create_fragment29(ctx) { + let div4; + let div2; + let div0; + let t0; + let t1; + let div1; + let t2; + let t3; + let div3; + let current; + const default_slot_template = ( + /*#slots*/ + ctx[3].default + ); + const default_slot = create_slot( + default_slot_template, + ctx, + /*$$scope*/ + ctx[2], + null + ); + return { + c() { + div4 = element("div"); + div2 = element("div"); + div0 = element("div"); + t0 = text( + /*name*/ + ctx[0] + ); + t1 = space(); + div1 = element("div"); + t2 = text( + /*description*/ + ctx[1] + ); + t3 = space(); + div3 = element("div"); + if (default_slot) + default_slot.c(); + attr(div0, "class", "setting-item-name"); + attr(div1, "class", "setting-item-description"); + attr(div2, "class", "setting-item-info"); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + }, + m(target, anchor) { + insert(target, div4, anchor); + append(div4, div2); + append(div2, div0); + append(div0, t0); + append(div2, t1); + append(div2, div1); + append(div1, t2); + append(div4, t3); + append(div4, div3); + if (default_slot) { + default_slot.m(div3, null); + } + current = true; + }, + p(ctx2, [dirty]) { + if (!current || dirty & /*name*/ + 1) + set_data( + t0, + /*name*/ + ctx2[0] + ); + if (!current || dirty & /*description*/ + 2) + set_data( + t2, + /*description*/ + ctx2[1] + ); + if (default_slot) { + if (default_slot.p && (!current || dirty & /*$$scope*/ + 4)) { + update_slot_base( + default_slot, + default_slot_template, + ctx2, + /*$$scope*/ + ctx2[2], + !current ? get_all_dirty_from_scope( + /*$$scope*/ + ctx2[2] + ) : get_slot_changes( + default_slot_template, + /*$$scope*/ + ctx2[2], + dirty, + null + ), + null + ); + } + } + }, + i(local) { + if (current) + return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div4); + } + if (default_slot) + default_slot.d(detaching); + } + }; +} +function instance29($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + let { name } = $$props; + let { description } = $$props; + $$self.$$set = ($$props2) => { + if ("name" in $$props2) + $$invalidate(0, name = $$props2.name); + if ("description" in $$props2) + $$invalidate(1, description = $$props2.description); + if ("$$scope" in $$props2) + $$invalidate(2, $$scope = $$props2.$$scope); + }; + return [name, description, $$scope, slots]; +} +var SettingItem = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance29, create_fragment29, safe_not_equal, { name: 0, description: 1 }); + } +}; +var SettingItem_default = SettingItem; + +// src/components/settings/FieldGroupLabelsSettingItem.svelte +function create_default_slot20(ctx) { + let fieldgrouplabelsselector; + let updating_field_group_labels; + let current; + function fieldgrouplabelsselector_field_group_labels_binding(value) { + ctx[4](value); + } + let fieldgrouplabelsselector_props = { + edge_field_groups: ( + /*edge_field_groups*/ + ctx[3] + ) + }; + if ( + /*field_group_labels*/ + ctx[0] !== void 0 + ) { + fieldgrouplabelsselector_props.field_group_labels = /*field_group_labels*/ + ctx[0]; + } + fieldgrouplabelsselector = new FieldGroupLabelsSelector_default({ props: fieldgrouplabelsselector_props }); + binding_callbacks.push(() => bind(fieldgrouplabelsselector, "field_group_labels", fieldgrouplabelsselector_field_group_labels_binding)); + return { + c() { + create_component(fieldgrouplabelsselector.$$.fragment); + }, + m(target, anchor) { + mount_component(fieldgrouplabelsselector, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const fieldgrouplabelsselector_changes = {}; + if (dirty & /*edge_field_groups*/ + 8) + fieldgrouplabelsselector_changes.edge_field_groups = /*edge_field_groups*/ + ctx2[3]; + if (!updating_field_group_labels && dirty & /*field_group_labels*/ + 1) { + updating_field_group_labels = true; + fieldgrouplabelsselector_changes.field_group_labels = /*field_group_labels*/ + ctx2[0]; + add_flush_callback(() => updating_field_group_labels = false); + } + fieldgrouplabelsselector.$set(fieldgrouplabelsselector_changes); + }, + i(local) { + if (current) + return; + transition_in(fieldgrouplabelsselector.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(fieldgrouplabelsselector.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(fieldgrouplabelsselector, detaching); + } + }; +} +function create_fragment30(ctx) { + let settingitem; + let current; + settingitem = new SettingItem_default({ + props: { + name: ( + /*name*/ + ctx[1] + ), + description: ( + /*description*/ + ctx[2] + ), + $$slots: { default: [create_default_slot20] }, + $$scope: { ctx } + } + }); + return { + c() { + create_component(settingitem.$$.fragment); + }, + m(target, anchor) { + mount_component(settingitem, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const settingitem_changes = {}; + if (dirty & /*name*/ + 2) + settingitem_changes.name = /*name*/ + ctx2[1]; + if (dirty & /*description*/ + 4) + settingitem_changes.description = /*description*/ + ctx2[2]; + if (dirty & /*$$scope, edge_field_groups, field_group_labels*/ + 73) { + settingitem_changes.$$scope = { dirty, ctx: ctx2 }; + } + settingitem.$set(settingitem_changes); + }, + i(local) { + if (current) + return; + transition_in(settingitem.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(settingitem.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(settingitem, detaching); + } + }; +} +function instance30($$self, $$props, $$invalidate) { + let { name = "Field Groups" } = $$props; + let { description = "Select the field groups to use for this traversal." } = $$props; + let { field_group_labels } = $$props; + let { edge_field_groups } = $$props; + const dispatch = createEventDispatcher(); + function fieldgrouplabelsselector_field_group_labels_binding(value) { + field_group_labels = value; + $$invalidate(0, field_group_labels); + } + $$self.$$set = ($$props2) => { + if ("name" in $$props2) + $$invalidate(1, name = $$props2.name); + if ("description" in $$props2) + $$invalidate(2, description = $$props2.description); + if ("field_group_labels" in $$props2) + $$invalidate(0, field_group_labels = $$props2.field_group_labels); + if ("edge_field_groups" in $$props2) + $$invalidate(3, edge_field_groups = $$props2.edge_field_groups); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*field_group_labels*/ + 1) { + $: + if (field_group_labels) { + dispatch("select", field_group_labels); + } + } + }; + return [ + field_group_labels, + name, + description, + edge_field_groups, + fieldgrouplabelsselector_field_group_labels_binding + ]; +} +var FieldGroupLabelsSettingItem = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance30, create_fragment30, safe_not_equal, { + name: 1, + description: 2, + field_group_labels: 0, + edge_field_groups: 3 + }); + } +}; +var FieldGroupLabelsSettingItem_default = FieldGroupLabelsSettingItem; + +// src/settings/GridSettings.ts +var _add_settings_trail_view = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Enable trail view", + desc: "Show the trail view at the top of the page", + toggle: { + value: plugin.settings.views.page.trail.enabled, + cb: async (value) => { + plugin.settings.views.page.trail.enabled = value; + await Promise.all([plugin.saveSettings()]); + plugin.refresh({ rebuild_graph: false }); + } + } + }); + new_setting(containerEl, { + name: "Format", + desc: "Format of the trail view", + select: { + value: plugin.settings.views.page.trail.format, + options: ["grid", "path"], + cb: async (value) => { + plugin.settings.views.page.trail.format = value; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + } + } + }); + new_setting(containerEl, { + name: "Path Selection", + desc: "How to select the path(s) to display in the trail view", + select: { + value: plugin.settings.views.page.trail.selection, + options: ["all", "shortest", "longest"], + cb: async (value) => { + plugin.settings.views.page.trail.selection = value; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + } + } + }); + new_setting(containerEl, { + name: "Default depth", + desc: "Default depth of the trail view", + input: { + value: plugin.settings.views.page.trail.default_depth.toString(), + cb: async (value) => { + const int2 = parseInt(value); + if (isNaN(int2)) { + return new import_obsidian17.Notice("Depth must be a number"); + } else if (int2 < 0) { + return new import_obsidian17.Notice("Depth must be a non-negative number"); + } + plugin.settings.views.page.trail.default_depth = int2; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + } + } + }); + new FieldGroupLabelsSettingItem_default({ + target: containerEl, + props: { + edge_field_groups: plugin.settings.edge_field_groups, + field_group_labels: plugin.settings.views.page.trail.field_group_labels + } + }).$on("select", async (e) => { + plugin.settings.views.page.trail.field_group_labels = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + }); + new_setting(containerEl, { + name: "Merge Fields", + desc: "Merge fields in the traversal, instead of keeping their paths separate", + toggle: { + value: plugin.settings.views.page.trail.merge_fields, + cb: async (value) => { + plugin.settings.views.page.trail.merge_fields = value; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + } + } + }); + new_setting(containerEl, { + name: "Show controls", + desc: "Show controls to change the depth/format/path-selection of the trail view", + toggle: { + value: plugin.settings.views.page.trail.show_controls, + cb: async (value) => { + plugin.settings.views.page.trail.show_controls = value; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + } + } + }); + new_setting(containerEl, { + name: "No path message", + desc: "Message to display when there is no path to display. Leave blank to hide the trail view when there is no path.", + input: { + value: plugin.settings.views.page.trail.no_path_message, + cb: async (value) => { + plugin.settings.views.page.trail.no_path_message = value; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + } + } + }); + _add_settings_show_node_options(plugin, containerEl, { + get: () => plugin.settings.views.page.trail.show_node_options, + set: (value) => plugin.settings.views.page.trail.show_node_options = value + }); +}; + +// src/settings/JohnnyDecimalSettings.ts +var import_obsidian18 = require("obsidian"); +var _add_settings_johnny_decimal_note = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Enabled", + desc: "Look for Johnny Decimal notes to use as edge sources", + toggle: { + value: plugin.settings.explicit_edge_sources.johnny_decimal_note.enabled, + cb: async (value) => { + plugin.settings.explicit_edge_sources.johnny_decimal_note.enabled = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); + new_setting(containerEl, { + name: "Delimiter", + desc: "Delimiter to use to split the note name", + input: { + value: plugin.settings.explicit_edge_sources.johnny_decimal_note.delimiter, + cb: async (value) => { + if (!value) + new import_obsidian18.Notice("Delimiter cannot be empty"); + else { + plugin.settings.explicit_edge_sources.johnny_decimal_note.delimiter = value; + await Promise.all([ + plugin.refresh(), + plugin.saveSettings() + ]); + } + } + } + }); + new_setting(containerEl, { + name: "Default Field", + desc: "Field to use to point to next note in the Johnny Decimal system", + select: { + value: plugin.settings.explicit_edge_sources.johnny_decimal_note.default_field, + options: plugin.settings.edge_fields.map((f) => f.label), + cb: async (value) => { + plugin.settings.explicit_edge_sources.johnny_decimal_note.default_field = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); +}; + +// src/menus/EdgeSortIdMenu.ts +var import_obsidian19 = require("obsidian"); +var ORDERS = [1, -1]; +var EdgeSortIdMenu = ({ + cb, + value, + exclude_fields +}) => { + const menu = new import_obsidian19.Menu(); + ORDERS.forEach((order) => { + menu.addItem( + (item) => item.setTitle(`Order: ${order === 1 ? "asc" : "desc"}`).setChecked(value.order === order).onClick(() => { + value.order = order; + cb(value); + }) + ); + }); + menu.addSeparator(); + SIMPLE_EDGE_SORT_FIELDS.filter((f) => !(exclude_fields == null ? void 0 : exclude_fields.includes(f))).forEach( + (field) => { + menu.addItem( + (item) => item.setTitle("Field: " + field).setChecked(value.field === field).onClick(() => { + value.field = field; + cb(value); + }) + ); + } + ); + return menu; +}; + +// src/components/selector/EdgeSortIdSelector.svelte +function create_else_block4(ctx) { + let arrowdownwidenarrow; + let current; + arrowdownwidenarrow = new arrow_down_wide_narrow_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(arrowdownwidenarrow.$$.fragment); + }, + m(target, anchor) { + mount_component(arrowdownwidenarrow, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(arrowdownwidenarrow.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(arrowdownwidenarrow.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(arrowdownwidenarrow, detaching); + } + }; +} +function create_if_block5(ctx) { + let arrowupnarrowwide; + let current; + arrowupnarrowwide = new arrow_up_narrow_wide_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(arrowupnarrowwide.$$.fragment); + }, + m(target, anchor) { + mount_component(arrowupnarrowwide, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(arrowupnarrowwide.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(arrowupnarrowwide.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(arrowupnarrowwide, detaching); + } + }; +} +function create_fragment31(ctx) { + let button; + let current_block_type_index; + let if_block; + let button_class_value; + let current; + let mounted; + let dispose; + const if_block_creators = [create_if_block5, create_else_block4]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*edge_sort_id*/ + ctx2[0].order === 1 + ) + 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() { + button = element("button"); + if_block.c(); + attr(button, "class", button_class_value = "flex gap-1 " + /*cls*/ + ctx[2]); + attr(button, "aria-label", "Change sort field/order"); + }, + m(target, anchor) { + insert(target, button, anchor); + if_blocks[current_block_type_index].m(button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler*/ + ctx[3] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index !== previous_block_index) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + 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](ctx2); + if_block.c(); + } else { + } + transition_in(if_block, 1); + if_block.m(button, null); + } + if (!current || dirty & /*cls*/ + 4 && button_class_value !== (button_class_value = "flex gap-1 " + /*cls*/ + ctx2[2])) { + attr(button, "class", button_class_value); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + if_blocks[current_block_type_index].d(); + mounted = false; + dispose(); + } + }; +} +function instance31($$self, $$props, $$invalidate) { + let { edge_sort_id } = $$props; + let { exclude_fields = [] } = $$props; + let { cls = "" } = $$props; + const click_handler = (e) => { + EdgeSortIdMenu({ + exclude_fields, + value: edge_sort_id, + cb: (value) => $$invalidate(0, edge_sort_id = value) + }).showAtMouseEvent(e); + }; + $$self.$$set = ($$props2) => { + if ("edge_sort_id" in $$props2) + $$invalidate(0, edge_sort_id = $$props2.edge_sort_id); + if ("exclude_fields" in $$props2) + $$invalidate(1, exclude_fields = $$props2.exclude_fields); + if ("cls" in $$props2) + $$invalidate(2, cls = $$props2.cls); + }; + return [edge_sort_id, exclude_fields, cls, click_handler]; +} +var EdgeSortIdSelector = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance31, create_fragment31, safe_not_equal, { + edge_sort_id: 0, + exclude_fields: 1, + cls: 2 + }); + } +}; +var EdgeSortIdSelector_default = EdgeSortIdSelector; + +// src/components/settings/EdgeSortIdSettingItem.svelte +function create_default_slot21(ctx) { + let edgesortidselector; + let updating_edge_sort_id; + let current; + function edgesortidselector_edge_sort_id_binding(value) { + ctx[1](value); + } + let edgesortidselector_props = {}; + if ( + /*edge_sort_id*/ + ctx[0] !== void 0 + ) { + edgesortidselector_props.edge_sort_id = /*edge_sort_id*/ + ctx[0]; + } + edgesortidselector = new EdgeSortIdSelector_default({ props: edgesortidselector_props }); + binding_callbacks.push(() => bind(edgesortidselector, "edge_sort_id", edgesortidselector_edge_sort_id_binding)); + return { + c() { + create_component(edgesortidselector.$$.fragment); + }, + m(target, anchor) { + mount_component(edgesortidselector, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const edgesortidselector_changes = {}; + if (!updating_edge_sort_id && dirty & /*edge_sort_id*/ + 1) { + updating_edge_sort_id = true; + edgesortidselector_changes.edge_sort_id = /*edge_sort_id*/ + ctx2[0]; + add_flush_callback(() => updating_edge_sort_id = false); + } + edgesortidselector.$set(edgesortidselector_changes); + }, + i(local) { + if (current) + return; + transition_in(edgesortidselector.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(edgesortidselector.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(edgesortidselector, detaching); + } + }; +} +function create_fragment32(ctx) { + let settingitem; + let current; + settingitem = new SettingItem_default({ + props: { + name: "Edge Sort", + description: "Select the sorting method for the edges in the graph.", + $$slots: { default: [create_default_slot21] }, + $$scope: { ctx } + } + }); + return { + c() { + create_component(settingitem.$$.fragment); + }, + m(target, anchor) { + mount_component(settingitem, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const settingitem_changes = {}; + if (dirty & /*$$scope, edge_sort_id*/ + 9) { + settingitem_changes.$$scope = { dirty, ctx: ctx2 }; + } + settingitem.$set(settingitem_changes); + }, + i(local) { + if (current) + return; + transition_in(settingitem.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(settingitem.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(settingitem, detaching); + } + }; +} +function instance32($$self, $$props, $$invalidate) { + let { edge_sort_id } = $$props; + const dispatch = createEventDispatcher(); + function edgesortidselector_edge_sort_id_binding(value) { + edge_sort_id = value; + $$invalidate(0, edge_sort_id); + } + $$self.$$set = ($$props2) => { + if ("edge_sort_id" in $$props2) + $$invalidate(0, edge_sort_id = $$props2.edge_sort_id); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*edge_sort_id*/ + 1) { + $: + if (edge_sort_id) { + dispatch("select", edge_sort_id); + } + } + }; + return [edge_sort_id, edgesortidselector_edge_sort_id_binding]; +} +var EdgeSortIdSettingItem = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance32, create_fragment32, safe_not_equal, { edge_sort_id: 0 }); + } +}; +var EdgeSortIdSettingItem_default = EdgeSortIdSettingItem; + +// src/menus/ShowAttributesMenu.ts +var import_obsidian20 = require("obsidian"); +var ShowAttributesSelectorMenu = ({ + cb, + value, + exclude_attributes +}) => { + const menu = new import_obsidian20.Menu(); + const possible = EDGE_ATTRIBUTES.filter( + (attr2) => !(exclude_attributes == null ? void 0 : exclude_attributes.includes(attr2)) + ); + const all = possible.length === value.length; + menu.addItem( + (item) => item.setTitle(all ? "None" : "All").onClick(() => { + cb(all ? [] : possible); + }) + ); + menu.addSeparator(); + const add_item = (attr2) => { + const included = value.includes(attr2); + menu.addItem( + (item) => item.setTitle(attr2).setChecked(included).onClick(() => { + if (included) { + cb(value.filter((v) => v !== attr2)); + } else { + cb([...value, attr2]); + } + }) + ); + }; + ["field", "explicit"].filter((attr2) => !(exclude_attributes == null ? void 0 : exclude_attributes.includes(attr2))).forEach(add_item); + menu.addSeparator(); + ["source"].filter((attr2) => !(exclude_attributes == null ? void 0 : exclude_attributes.includes(attr2))).forEach(add_item); + menu.addSeparator(); + ["implied_kind", "round"].filter((attr2) => !(exclude_attributes == null ? void 0 : exclude_attributes.includes(attr2))).forEach(add_item); + return menu; +}; + +// src/components/selector/ShowAttributesSelectorMenu.svelte +function create_fragment33(ctx) { + let button; + let filejson; + let current; + let mounted; + let dispose; + filejson = new file_json_default({ props: { size: ICON_SIZE } }); + return { + c() { + button = element("button"); + create_component(filejson.$$.fragment); + attr( + button, + "class", + /*cls*/ + ctx[2] + ); + attr(button, "aria-label", "Change which edge attributes show"); + }, + m(target, anchor) { + insert(target, button, anchor); + mount_component(filejson, button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler*/ + ctx[3] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (!current || dirty & /*cls*/ + 4) { + attr( + button, + "class", + /*cls*/ + ctx2[2] + ); + } + }, + i(local) { + if (current) + return; + transition_in(filejson.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(filejson.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + destroy_component(filejson); + mounted = false; + dispose(); + } + }; +} +function instance33($$self, $$props, $$invalidate) { + let { show_attributes } = $$props; + let { exclude_attributes = [] } = $$props; + let { cls = "" } = $$props; + if (exclude_attributes === null || exclude_attributes === void 0 ? void 0 : exclude_attributes.length) { + show_attributes = show_attributes.filter((v) => !(exclude_attributes === null || exclude_attributes === void 0 ? void 0 : exclude_attributes.includes(v))); + } + const click_handler = (e) => { + ShowAttributesSelectorMenu({ + exclude_attributes, + value: show_attributes, + cb: (value) => $$invalidate(0, show_attributes = value) + }).showAtMouseEvent(e); + }; + $$self.$$set = ($$props2) => { + if ("show_attributes" in $$props2) + $$invalidate(0, show_attributes = $$props2.show_attributes); + if ("exclude_attributes" in $$props2) + $$invalidate(1, exclude_attributes = $$props2.exclude_attributes); + if ("cls" in $$props2) + $$invalidate(2, cls = $$props2.cls); + }; + return [show_attributes, exclude_attributes, cls, click_handler]; +} +var ShowAttributesSelectorMenu_1 = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance33, create_fragment33, safe_not_equal, { + show_attributes: 0, + exclude_attributes: 1, + cls: 2 + }); + } +}; +var ShowAttributesSelectorMenu_default = ShowAttributesSelectorMenu_1; + +// src/components/settings/ShowAttributesSettingItem.svelte +function create_default_slot22(ctx) { + let showattributesselectormenu; + let updating_show_attributes; + let current; + function showattributesselectormenu_show_attributes_binding(value) { + ctx[2](value); + } + let showattributesselectormenu_props = { + exclude_attributes: ( + /*exclude_attributes*/ + ctx[1] + ) + }; + if ( + /*show_attributes*/ + ctx[0] !== void 0 + ) { + showattributesselectormenu_props.show_attributes = /*show_attributes*/ + ctx[0]; + } + showattributesselectormenu = new ShowAttributesSelectorMenu_default({ props: showattributesselectormenu_props }); + binding_callbacks.push(() => bind(showattributesselectormenu, "show_attributes", showattributesselectormenu_show_attributes_binding)); + return { + c() { + create_component(showattributesselectormenu.$$.fragment); + }, + m(target, anchor) { + mount_component(showattributesselectormenu, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const showattributesselectormenu_changes = {}; + if (dirty & /*exclude_attributes*/ + 2) + showattributesselectormenu_changes.exclude_attributes = /*exclude_attributes*/ + ctx2[1]; + if (!updating_show_attributes && dirty & /*show_attributes*/ + 1) { + updating_show_attributes = true; + showattributesselectormenu_changes.show_attributes = /*show_attributes*/ + ctx2[0]; + add_flush_callback(() => updating_show_attributes = false); + } + showattributesselectormenu.$set(showattributesselectormenu_changes); + }, + i(local) { + if (current) + return; + transition_in(showattributesselectormenu.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(showattributesselectormenu.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(showattributesselectormenu, detaching); + } + }; +} +function create_fragment34(ctx) { + let settingitem; + let current; + settingitem = new SettingItem_default({ + props: { + name: "Show Attributes", + description: "Select the edge attributes to show.", + $$slots: { default: [create_default_slot22] }, + $$scope: { ctx } + } + }); + return { + c() { + create_component(settingitem.$$.fragment); + }, + m(target, anchor) { + mount_component(settingitem, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const settingitem_changes = {}; + if (dirty & /*$$scope, exclude_attributes, show_attributes*/ + 19) { + settingitem_changes.$$scope = { dirty, ctx: ctx2 }; + } + settingitem.$set(settingitem_changes); + }, + i(local) { + if (current) + return; + transition_in(settingitem.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(settingitem.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(settingitem, detaching); + } + }; +} +function instance34($$self, $$props, $$invalidate) { + let { show_attributes } = $$props; + let { exclude_attributes = [] } = $$props; + const dispatch = createEventDispatcher(); + function showattributesselectormenu_show_attributes_binding(value) { + show_attributes = value; + $$invalidate(0, show_attributes); + } + $$self.$$set = ($$props2) => { + if ("show_attributes" in $$props2) + $$invalidate(0, show_attributes = $$props2.show_attributes); + if ("exclude_attributes" in $$props2) + $$invalidate(1, exclude_attributes = $$props2.exclude_attributes); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*show_attributes*/ + 1) { + $: + if (show_attributes) { + dispatch("select", show_attributes); + } + } + }; + return [ + show_attributes, + exclude_attributes, + showattributesselectormenu_show_attributes_binding + ]; +} +var ShowAttributesSettingItem = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance34, create_fragment34, safe_not_equal, { + show_attributes: 0, + exclude_attributes: 1 + }); + } +}; +var ShowAttributesSettingItem_default = ShowAttributesSettingItem; + +// src/const/links.ts +var LINK_KINDS = ["none", "wiki", "markdown"]; + +// src/settings/ListIndexSettings.ts +var _add_settings_list_index = (plugin, contentEl) => { + const { settings } = plugin; + new FieldGroupLabelsSettingItem_default({ + target: contentEl, + props: { + edge_field_groups: plugin.settings.edge_field_groups, + field_group_labels: settings.commands.list_index.default_options.field_group_labels + } + }).$on("select", async (e) => { + settings.commands.list_index.default_options.field_group_labels = e.detail; + settings.commands.list_index.default_options.fields = resolve_field_group_labels( + plugin.settings.edge_field_groups, + settings.commands.list_index.default_options.field_group_labels + ); + await plugin.saveSettings(); + }); + new_setting(contentEl, { + name: "Link Kind", + desc: "Format to use for links", + select: { + options: LINK_KINDS, + value: settings.commands.list_index.default_options.link_kind, + cb: async (value) => { + settings.commands.list_index.default_options.link_kind = value; + await plugin.saveSettings(); + } + } + }); + new_setting(contentEl, { + name: "Indent", + desc: "Indentation to use for each level", + input: { + value: settings.commands.list_index.default_options.indent, + cb: async (value) => { + settings.commands.list_index.default_options.indent = value; + await plugin.saveSettings(); + } + } + }); + new EdgeSortIdSettingItem_default({ + target: contentEl, + props: { + edge_sort_id: settings.commands.list_index.default_options.edge_sort_id + } + }).$on("select", async (e) => { + settings.commands.list_index.default_options.edge_sort_id = e.detail; + await plugin.saveSettings(); + }); + new ShowAttributesSettingItem_default({ + target: contentEl, + props: { + show_attributes: settings.commands.list_index.default_options.show_attributes + } + }).$on("select", async (e) => { + settings.commands.list_index.default_options.show_attributes = e.detail; + await plugin.saveSettings(); + }); + _add_settings_show_node_options(plugin, contentEl, { + get: () => settings.commands.list_index.default_options.show_node_options, + set: (value) => settings.commands.list_index.default_options.show_node_options = value + }); +}; + +// src/settings/ListNoteSettings.ts +var _add_settings_list_note = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Default Neighbour Field", + desc: "Field to use to join neighbouring list items.", + select: { + value: plugin.settings.explicit_edge_sources.list_note.default_neighbour_field, + options: [""].concat( + plugin.settings.edge_fields.map((f) => f.label) + ), + cb: async (value) => { + plugin.settings.explicit_edge_sources.list_note.default_neighbour_field = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); +}; + +// src/settings/MatrixSettings.ts +var _add_settings_matrix = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Collapse", + desc: "Collapse the matrix by default", + toggle: { + value: plugin.settings.views.side.matrix.collapse, + cb: async (checked) => { + plugin.settings.views.side.matrix.collapse = checked; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ + redraw_side_views: true, + rebuild_graph: false + }) + ]); + } + } + }); + new EdgeSortIdSettingItem_default({ + target: containerEl, + props: { edge_sort_id: plugin.settings.views.side.matrix.edge_sort_id } + }).$on("select", async (e) => { + plugin.settings.views.side.matrix.edge_sort_id = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ redraw_side_views: true, rebuild_graph: false }) + ]); + }); + new ShowAttributesSettingItem_default({ + target: containerEl, + props: { + exclude_attributes: ["field", "explicit"], + show_attributes: plugin.settings.views.side.matrix.show_attributes + } + }).$on("select", async (e) => { + plugin.settings.views.side.matrix.show_attributes = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ redraw_side_views: true, rebuild_graph: false }) + ]); + }); + new FieldGroupLabelsSettingItem_default({ + target: containerEl, + props: { + edge_field_groups: plugin.settings.edge_field_groups, + field_group_labels: plugin.settings.views.side.matrix.field_group_labels + } + }).$on("select", async (e) => { + plugin.settings.views.side.matrix.field_group_labels = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ redraw_side_views: true, rebuild_graph: false }) + ]); + }); + _add_settings_show_node_options(plugin, containerEl, { + get: () => plugin.settings.views.side.matrix.show_node_options, + set: (value) => plugin.settings.views.side.matrix.show_node_options = value + }); +}; + +// src/views/page.ts +var import_obsidian22 = require("obsidian"); + +// src/components/ObsidianLink.svelte +var import_obsidian21 = require("obsidian"); +function create_fragment35(ctx) { + let span; + let t; + let span_class_value; + let span_aria_label_value; + let mounted; + let dispose; + return { + c() { + var _a; + span = element("span"); + t = text( + /*display*/ + ctx[1] + ); + attr(span, "role", "link"); + attr(span, "class", span_class_value = "internal-link cursor-pointer " + /*cls*/ + ctx[4]); + attr( + span, + "data-href", + /*path*/ + ctx[0] + ); + attr(span, "aria-label", span_aria_label_value = /*no_ext*/ + ctx[6] === /*display*/ + ctx[1] ? "" : ( + /*path*/ + ctx[0] + )); + toggle_class(span, "is-unresolved", !/*resolved*/ + ctx[2]); + toggle_class( + span, + "BC-active-note", + /*$active_file_store*/ + ((_a = ctx[5]) == null ? void 0 : _a.path) === /*path*/ + ctx[0] + ); + }, + m(target, anchor) { + insert(target, span, anchor); + append(span, t); + if (!mounted) { + dispose = [ + listen( + span, + "mouseover", + /*mouseover_handler*/ + ctx[7] + ), + listen( + span, + "contextmenu", + /*contextmenu_handler*/ + ctx[8] + ), + listen( + span, + "auxclick", + /*auxclick_handler*/ + ctx[9] + ), + listen( + span, + "click", + /*click_handler*/ + ctx[10] + ) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + var _a; + if (dirty & /*display*/ + 2) + set_data( + t, + /*display*/ + ctx2[1] + ); + if (dirty & /*cls*/ + 16 && span_class_value !== (span_class_value = "internal-link cursor-pointer " + /*cls*/ + ctx2[4])) { + attr(span, "class", span_class_value); + } + if (dirty & /*path*/ + 1) { + attr( + span, + "data-href", + /*path*/ + ctx2[0] + ); + } + if (dirty & /*display, path*/ + 3 && span_aria_label_value !== (span_aria_label_value = /*no_ext*/ + ctx2[6] === /*display*/ + ctx2[1] ? "" : ( + /*path*/ + ctx2[0] + ))) { + attr(span, "aria-label", span_aria_label_value); + } + if (dirty & /*cls, resolved*/ + 20) { + toggle_class(span, "is-unresolved", !/*resolved*/ + ctx2[2]); + } + if (dirty & /*cls, $active_file_store, path*/ + 49) { + toggle_class( + span, + "BC-active-note", + /*$active_file_store*/ + ((_a = ctx2[5]) == null ? void 0 : _a.path) === /*path*/ + ctx2[0] + ); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(span); + } + mounted = false; + run_all(dispose); + } + }; +} +function instance35($$self, $$props, $$invalidate) { + let $active_file_store; + component_subscribe($$self, active_file_store, ($$value) => $$invalidate(5, $active_file_store = $$value)); + let { path } = $$props; + let { display } = $$props; + let { resolved } = $$props; + let { plugin } = $$props; + let { cls = "" } = $$props; + const no_ext = Paths.drop_ext(path); + const mouseover_handler = (event) => { + plugin.app.workspace.trigger("hover-link", { + event, + linktext: path, + // Must match `plugin.registerHoverSource` source (in `main.ts`) + source: "breadcrumbs", + targetEl: event.currentTarget, + hoverParent: event.currentTarget.parentElement + }); + }; + const contextmenu_handler = (e) => { + const menu = new import_obsidian21.Menu(); + plugin.app.workspace.handleLinkContextMenu(menu, display, path); + menu.showAtMouseEvent(e); + }; + const auxclick_handler = (e) => { + log.debug("on:auxclick e.button", e.button); + if (e.button === 1) { + plugin.app.workspace.openLinkText(path, "", "tab"); + } + }; + const click_handler = (e) => { + plugin.app.workspace.openLinkText(path, "", import_obsidian21.Keymap.isModEvent(e)); + }; + $$self.$$set = ($$props2) => { + if ("path" in $$props2) + $$invalidate(0, path = $$props2.path); + if ("display" in $$props2) + $$invalidate(1, display = $$props2.display); + if ("resolved" in $$props2) + $$invalidate(2, resolved = $$props2.resolved); + if ("plugin" in $$props2) + $$invalidate(3, plugin = $$props2.plugin); + if ("cls" in $$props2) + $$invalidate(4, cls = $$props2.cls); + }; + return [ + path, + display, + resolved, + plugin, + cls, + $active_file_store, + no_ext, + mouseover_handler, + contextmenu_handler, + auxclick_handler, + click_handler + ]; +} +var ObsidianLink = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance35, create_fragment35, safe_not_equal, { + path: 0, + display: 1, + resolved: 2, + plugin: 3, + cls: 4 + }); + } +}; +var ObsidianLink_default = ObsidianLink; + +// src/components/EdgeLink.svelte +function create_fragment36(ctx) { + let obsidianlink; + let current; + obsidianlink = new ObsidianLink_default({ + props: { + plugin: ( + /*plugin*/ + ctx[1] + ), + display: ( + /*display*/ + ctx[3] + ), + path: ( + /*edge*/ + ctx[0].target_id + ), + resolved: ( + /*edge*/ + ctx[0].target_attr.resolved + ), + cls: ( + /*cls*/ + ctx[2] + " BC-edge " + /*edge*/ + (ctx[0].attr.explicit ? "BC-edge-explicit" : `BC-edge-implied BC-edge-implied-${/*edge*/ + ctx[0].attr.implied_kind}`) + ) + } + }); + return { + c() { + create_component(obsidianlink.$$.fragment); + }, + m(target, anchor) { + mount_component(obsidianlink, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const obsidianlink_changes = {}; + if (dirty & /*plugin*/ + 2) + obsidianlink_changes.plugin = /*plugin*/ + ctx2[1]; + if (dirty & /*edge*/ + 1) + obsidianlink_changes.path = /*edge*/ + ctx2[0].target_id; + if (dirty & /*edge*/ + 1) + obsidianlink_changes.resolved = /*edge*/ + ctx2[0].target_attr.resolved; + if (dirty & /*cls, edge*/ + 5) + obsidianlink_changes.cls = /*cls*/ + ctx2[2] + " BC-edge " + /*edge*/ + (ctx2[0].attr.explicit ? "BC-edge-explicit" : `BC-edge-implied BC-edge-implied-${/*edge*/ + ctx2[0].attr.implied_kind}`); + obsidianlink.$set(obsidianlink_changes); + }, + i(local) { + if (current) + return; + transition_in(obsidianlink.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(obsidianlink.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(obsidianlink, detaching); + } + }; +} +function instance36($$self, $$props, $$invalidate) { + let { edge } = $$props; + let { plugin } = $$props; + let { show_node_options } = $$props; + let { cls = "" } = $$props; + const { dendron_note } = plugin.settings.explicit_edge_sources; + const display = stringify_node(edge.target_id, edge.target_attr, { + show_node_options, + trim_basename_delimiter: dendron_note.enabled && dendron_note.display_trimmed ? dendron_note.delimiter : void 0 + }); + $$self.$$set = ($$props2) => { + if ("edge" in $$props2) + $$invalidate(0, edge = $$props2.edge); + if ("plugin" in $$props2) + $$invalidate(1, plugin = $$props2.plugin); + if ("show_node_options" in $$props2) + $$invalidate(4, show_node_options = $$props2.show_node_options); + if ("cls" in $$props2) + $$invalidate(2, cls = $$props2.cls); + }; + return [edge, plugin, cls, display, show_node_options]; +} +var EdgeLink = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance36, create_fragment36, safe_not_equal, { + edge: 0, + plugin: 1, + show_node_options: 4, + cls: 2 + }); + } +}; +var EdgeLink_default = EdgeLink; + +// src/components/page_views/PrevNextView.svelte +function add_css2(target) { + append_styles(target, "svelte-deyewb", ".BC-prev-next-view.svelte-deyewb>div.svelte-deyewb{border:1px solid var(--background-modifier-border)}"); +} +function get_each_context5(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[7] = list[i]; + return child_ctx; +} +function get_each_context_13(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[7] = list[i]; + return child_ctx; +} +function create_if_block6(ctx) { + var _a, _b, _c, _d; + let div0; + let t; + let div1; + let current; + let each_value_1 = ensure_array_like( + /*grouped_out_edges*/ + (_b = (_a = ctx[2]) == null ? void 0 : _a.prev) != null ? _b : [] + ); + let each_blocks_1 = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks_1[i] = create_each_block_13(get_each_context_13(ctx, each_value_1, i)); + } + const out = (i) => transition_out(each_blocks_1[i], 1, 1, () => { + each_blocks_1[i] = null; + }); + let each_value = ensure_array_like( + /*grouped_out_edges*/ + (_d = (_c = ctx[2]) == null ? void 0 : _c.next) != null ? _d : [] + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block5(get_each_context5(ctx, each_value, i)); + } + const out_1 = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + div0 = element("div"); + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].c(); + } + t = space(); + div1 = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(div0, "class", "flex w-full flex-col svelte-deyewb"); + set_style(div0, "border-radius", "var(--radius-m) 0 0 var(--radius-m)"); + attr(div1, "class", "flex w-full flex-col svelte-deyewb"); + set_style(div1, "border-radius", "0 var(--radius-m) var(--radius-m) 0"); + }, + m(target, anchor) { + insert(target, div0, anchor); + for (let i = 0; i < each_blocks_1.length; i += 1) { + if (each_blocks_1[i]) { + each_blocks_1[i].m(div0, null); + } + } + insert(target, t, anchor); + insert(target, div1, anchor); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(div1, null); + } + } + current = true; + }, + p(ctx2, dirty) { + var _a2, _b2, _c2, _d2; + if (dirty & /*grouped_out_edges, plugin, show_node_options*/ + 7) { + each_value_1 = ensure_array_like( + /*grouped_out_edges*/ + (_b2 = (_a2 = ctx2[2]) == null ? void 0 : _a2.prev) != null ? _b2 : [] + ); + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_13(ctx2, each_value_1, i); + if (each_blocks_1[i]) { + each_blocks_1[i].p(child_ctx, dirty); + transition_in(each_blocks_1[i], 1); + } else { + each_blocks_1[i] = create_each_block_13(child_ctx); + each_blocks_1[i].c(); + transition_in(each_blocks_1[i], 1); + each_blocks_1[i].m(div0, null); + } + } + group_outros(); + for (i = each_value_1.length; i < each_blocks_1.length; i += 1) { + out(i); + } + check_outros(); + } + if (dirty & /*grouped_out_edges, plugin, show_node_options*/ + 7) { + each_value = ensure_array_like( + /*grouped_out_edges*/ + (_d2 = (_c2 = ctx2[2]) == null ? void 0 : _c2.next) != null ? _d2 : [] + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context5(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block5(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div1, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out_1(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_1.length; i += 1) { + transition_in(each_blocks_1[i]); + } + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks_1 = each_blocks_1.filter(Boolean); + for (let i = 0; i < each_blocks_1.length; i += 1) { + transition_out(each_blocks_1[i]); + } + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div0); + detach(t); + detach(div1); + } + destroy_each(each_blocks_1, detaching); + destroy_each(each_blocks, detaching); + } + }; +} +function create_each_block_13(ctx) { + let div; + let span; + let t1; + let edgelink; + let t2; + let current; + edgelink = new EdgeLink_default({ + props: { + cls: "grow", + edge: ( + /*edge*/ + ctx[7] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + show_node_options: ( + /*show_node_options*/ + ctx[1] + ) + } + }); + return { + c() { + div = element("div"); + span = element("span"); + span.textContent = `${/*edge*/ + ctx[7].attr.field}`; + t1 = space(); + create_component(edgelink.$$.fragment); + t2 = space(); + attr(span, "class", "BC-field pl-2"); + attr(div, "class", "BC-next-prev-item flex gap-3 p-1 text-left"); + }, + m(target, anchor) { + insert(target, div, anchor); + append(div, span); + append(div, t1); + mount_component(edgelink, div, null); + append(div, t2); + current = true; + }, + p(ctx2, dirty) { + const edgelink_changes = {}; + if (dirty & /*plugin*/ + 1) + edgelink_changes.plugin = /*plugin*/ + ctx2[0]; + edgelink.$set(edgelink_changes); + }, + i(local) { + if (current) + return; + transition_in(edgelink.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(edgelink.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(edgelink); + } + }; +} +function create_each_block5(ctx) { + let div; + let edgelink; + let t0; + let span; + let t2; + let current; + edgelink = new EdgeLink_default({ + props: { + cls: "grow", + edge: ( + /*edge*/ + ctx[7] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + show_node_options: ( + /*show_node_options*/ + ctx[1] + ) + } + }); + return { + c() { + div = element("div"); + create_component(edgelink.$$.fragment); + t0 = space(); + span = element("span"); + span.textContent = `${/*edge*/ + ctx[7].attr.field}`; + t2 = space(); + attr(span, "class", "BC-field pr-2"); + attr(div, "class", "BC-next-prev-item flex gap-3 p-1 text-right"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(edgelink, div, null); + append(div, t0); + append(div, span); + append(div, t2); + current = true; + }, + p(ctx2, dirty) { + const edgelink_changes = {}; + if (dirty & /*plugin*/ + 1) + edgelink_changes.plugin = /*plugin*/ + ctx2[0]; + edgelink.$set(edgelink_changes); + }, + i(local) { + if (current) + return; + transition_in(edgelink.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(edgelink.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(edgelink); + } + }; +} +function create_fragment37(ctx) { + var _a, _b, _c, _d; + let div; + let current; + let if_block = ( + /*grouped_out_edges*/ + (((_b = (_a = ctx[2]) == null ? void 0 : _a.prev) == null ? void 0 : _b.length) || /*grouped_out_edges*/ + ((_d = (_c = ctx[2]) == null ? void 0 : _c.next) == null ? void 0 : _d.length)) && create_if_block6(ctx) + ); + return { + c() { + div = element("div"); + if (if_block) + if_block.c(); + attr(div, "class", "BC-prev-next-view flex svelte-deyewb"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (if_block) + if_block.m(div, null); + current = true; + }, + p(ctx2, [dirty]) { + var _a2, _b2, _c2, _d2; + if ( + /*grouped_out_edges*/ + ((_b2 = (_a2 = ctx2[2]) == null ? void 0 : _a2.prev) == null ? void 0 : _b2.length) || /*grouped_out_edges*/ + ((_d2 = (_c2 = ctx2[2]) == null ? void 0 : _c2.next) == null ? void 0 : _d2.length) + ) + if_block.p(ctx2, dirty); + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if (if_block) + if_block.d(); + } + }; +} +function instance37($$self, $$props, $$invalidate) { + let { file_path } = $$props; + let { plugin } = $$props; + const { field_group_labels, show_node_options } = plugin.settings.views.page.prev_next; + const edge_field_labels = { + prev: resolve_field_group_labels(plugin.settings.edge_field_groups, field_group_labels.prev), + next: resolve_field_group_labels(plugin.settings.edge_field_groups, field_group_labels.next) + }; + const merged_field_labels = remove_duplicates([...edge_field_labels.prev, ...edge_field_labels.next]); + const grouped_out_edges = plugin.graph.hasNode(file_path) ? group_by(plugin.graph.get_out_edges(file_path).filter((e) => has_edge_attrs(e, { $or_fields: merged_field_labels })), (e) => edge_field_labels.prev.includes(e.attr.field) ? "prev" : "next") : null; + $$self.$$set = ($$props2) => { + if ("file_path" in $$props2) + $$invalidate(3, file_path = $$props2.file_path); + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + }; + return [plugin, show_node_options, grouped_out_edges, file_path]; +} +var PrevNextView = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance37, create_fragment37, safe_not_equal, { file_path: 3, plugin: 0 }, add_css2); + } +}; +var PrevNextView_default = PrevNextView; + +// src/components/button/MergeFieldsButton.svelte +function create_else_block5(ctx) { + let spliticon; + let current; + spliticon = new split_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(spliticon.$$.fragment); + }, + m(target, anchor) { + mount_component(spliticon, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(spliticon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(spliticon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(spliticon, detaching); + } + }; +} +function create_if_block7(ctx) { + let mergeicon; + let current; + mergeicon = new merge_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(mergeicon.$$.fragment); + }, + m(target, anchor) { + mount_component(mergeicon, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(mergeicon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(mergeicon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(mergeicon, detaching); + } + }; +} +function create_fragment38(ctx) { + let button; + let current_block_type_index; + let if_block; + let button_aria_label_value; + let current; + let mounted; + let dispose; + const if_block_creators = [create_if_block7, create_else_block5]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*merge_fields*/ + ctx2[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() { + button = element("button"); + if_block.c(); + attr( + button, + "class", + /*cls*/ + ctx[1] + ); + attr(button, "aria-label", button_aria_label_value = /*merge_fields*/ + ctx[0] ? "Separate Fields" : "Merge Fields"); + }, + m(target, anchor) { + insert(target, button, anchor); + if_blocks[current_block_type_index].m(button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler*/ + ctx[2] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index !== previous_block_index) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + 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](ctx2); + if_block.c(); + } else { + } + transition_in(if_block, 1); + if_block.m(button, null); + } + if (!current || dirty & /*cls*/ + 2) { + attr( + button, + "class", + /*cls*/ + ctx2[1] + ); + } + if (!current || dirty & /*merge_fields*/ + 1 && button_aria_label_value !== (button_aria_label_value = /*merge_fields*/ + ctx2[0] ? "Separate Fields" : "Merge Fields")) { + attr(button, "aria-label", button_aria_label_value); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + if_blocks[current_block_type_index].d(); + mounted = false; + dispose(); + } + }; +} +function instance38($$self, $$props, $$invalidate) { + let { cls = "" } = $$props; + let { merge_fields } = $$props; + const click_handler = () => $$invalidate(0, merge_fields = !merge_fields); + $$self.$$set = ($$props2) => { + if ("cls" in $$props2) + $$invalidate(1, cls = $$props2.cls); + if ("merge_fields" in $$props2) + $$invalidate(0, merge_fields = $$props2.merge_fields); + }; + return [merge_fields, cls, click_handler]; +} +var MergeFieldsButton = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance38, create_fragment38, safe_not_equal, { cls: 1, merge_fields: 0 }); + } +}; +var MergeFieldsButton_default = MergeFieldsButton; + +// src/components/page_views/TrailViewGrid.svelte +function add_css3(target) { + append_styles(target, "svelte-fynvrm", ".BC-trail-view.svelte-fynvrm{overflow:hidden;border-radius:var(--radius-m);border:1px solid var(--background-modifier-border)}.BC-trail-view-item.svelte-fynvrm{margin:-1px -1px 0 0;border-right:1px solid var(--background-modifier-border);border-top:1px solid var(--background-modifier-border)}"); +} +function get_each_context6(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[5] = list[i]; + child_ctx[7] = i; + return child_ctx; +} +function get_each_context_14(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[8] = list[i].first; + child_ctx[9] = list[i].last; + const constants_0 = ( + /*square*/ + child_ctx[1][ + /*first*/ + child_ctx[8] + ][ + /*j*/ + child_ctx[7] + ] + ); + child_ctx[10] = constants_0; + return child_ctx; +} +function create_if_block8(ctx) { + let edgelink; + let current; + edgelink = new EdgeLink_default({ + props: { + edge: ( + /*edge*/ + ctx[10] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + cls: "p-1 grow flex justify-center items-center", + show_node_options: ( + /*plugin*/ + ctx[0].settings.views.page.trail.show_node_options + ) + } + }); + return { + c() { + create_component(edgelink.$$.fragment); + }, + m(target, anchor) { + mount_component(edgelink, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const edgelink_changes = {}; + if (dirty & /*plugin*/ + 1) + edgelink_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*plugin*/ + 1) + edgelink_changes.show_node_options = /*plugin*/ + ctx2[0].settings.views.page.trail.show_node_options; + edgelink.$set(edgelink_changes); + }, + i(local) { + if (current) + return; + transition_in(edgelink.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(edgelink.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(edgelink, detaching); + } + }; +} +function create_each_block_14(ctx) { + let div; + let t; + let current; + let if_block = ( + /*edge*/ + ctx[10] && create_if_block8(ctx) + ); + return { + c() { + div = element("div"); + if (if_block) + if_block.c(); + t = space(); + attr(div, "class", "BC-trail-view-item flex svelte-fynvrm"); + set_style( + div, + "grid-area", + /*first*/ + ctx[8] + 1 + " / " + /*j*/ + (ctx[7] + 1) + " / " + /*last*/ + (ctx[9] + 2) + " / " + /*j*/ + (ctx[7] + 2) + ); + }, + m(target, anchor) { + insert(target, div, anchor); + if (if_block) + if_block.m(div, null); + append(div, t); + current = true; + }, + p(ctx2, dirty) { + if ( + /*edge*/ + ctx2[10] + ) + if_block.p(ctx2, dirty); + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if (if_block) + if_block.d(); + } + }; +} +function create_each_block6(ctx) { + let each_1_anchor; + let current; + let each_value_1 = ensure_array_like( + /*col*/ + ctx[5] + ); + let each_blocks = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks[i] = create_each_block_14(get_each_context_14(ctx, each_value_1, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(target, anchor); + } + } + insert(target, each_1_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + if (dirty & /*col_runs, square, plugin*/ + 7) { + each_value_1 = ensure_array_like( + /*col*/ + ctx2[5] + ); + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_14(ctx2, each_value_1, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block_14(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + group_outros(); + for (i = each_value_1.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_1.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(each_1_anchor); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_fragment39(ctx) { + let div; + let current; + let each_value = ensure_array_like( + /*col_runs*/ + ctx[2] + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block6(get_each_context6(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + var _a, _b; + div = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(div, "class", "BC-trail-view grid svelte-fynvrm"); + set_style(div, "grid-template-rows", "min-content"); + set_style(div, "grid-template-columns", "1fr ".repeat( + /*square*/ + (_b = (_a = ctx[1].at(0)) == null ? void 0 : _a.length) != null ? _b : 0 + )); + }, + m(target, anchor) { + 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(ctx2, [dirty]) { + if (dirty & /*col_runs, square, plugin*/ + 7) { + each_value = ensure_array_like( + /*col_runs*/ + ctx2[2] + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context6(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block6(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_each(each_blocks, detaching); + } + }; +} +function instance39($$self, $$props, $$invalidate) { + let { plugin } = $$props; + let { all_paths } = $$props; + const reversed = all_paths.map((path) => [...path].reverse()); + const square = ensure_square_array(reversed, null, true); + const col_runs = transpose(square).map((col) => gather_by_runs(col, (e) => e ? e.target_id : null)); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("all_paths" in $$props2) + $$invalidate(3, all_paths = $$props2.all_paths); + }; + return [plugin, square, col_runs, all_paths]; +} +var TrailViewGrid = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance39, create_fragment39, safe_not_equal, { plugin: 0, all_paths: 3 }, add_css3); + } +}; +var TrailViewGrid_default = TrailViewGrid; + +// src/components/page_views/TrailViewPath.svelte +function add_css4(target) { + append_styles(target, "svelte-4v6yoh", '.BC-trail-view.svelte-4v6yoh{overflow:hidden;border-radius:var(--radius-m);border:1px solid var(--background-modifier-border)}.BC-trail-view-item-separator.svelte-4v6yoh::before{content:">"}'); +} +function get_each_context7(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[3] = list[i]; + return child_ctx; +} +function get_each_context_15(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[6] = list[i]; + child_ctx[8] = i; + return child_ctx; +} +function create_if_block9(ctx) { + let span; + let span_aria_label_value; + return { + c() { + span = element("span"); + attr(span, "class", "BC-trail-view-item-separator svelte-4v6yoh"); + attr(span, "aria-label", span_aria_label_value = url_search_params(untyped_pick( + /*edge*/ + ctx[6].attr, + ["source", "implied_kind", "round"] + ))); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + p: noop, + d(detaching) { + if (detaching) { + detach(span); + } + } + }; +} +function create_each_block_15(ctx) { + let div; + let t; + let edgelink; + let current; + let if_block = ( + /*j*/ + ctx[8] !== 0 && create_if_block9(ctx) + ); + edgelink = new EdgeLink_default({ + props: { + edge: ( + /*edge*/ + ctx[6] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + show_node_options: ( + /*plugin*/ + ctx[0].settings.views.page.trail.show_node_options + ) + } + }); + return { + c() { + div = element("div"); + if (if_block) + if_block.c(); + t = space(); + create_component(edgelink.$$.fragment); + attr(div, "class", "BC-trail-view-item"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (if_block) + if_block.m(div, null); + append(div, t); + mount_component(edgelink, div, null); + current = true; + }, + p(ctx2, dirty) { + if ( + /*j*/ + ctx2[8] !== 0 + ) + if_block.p(ctx2, dirty); + const edgelink_changes = {}; + if (dirty & /*plugin*/ + 1) + edgelink_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*plugin*/ + 1) + edgelink_changes.show_node_options = /*plugin*/ + ctx2[0].settings.views.page.trail.show_node_options; + edgelink.$set(edgelink_changes); + }, + i(local) { + if (current) + return; + transition_in(edgelink.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(edgelink.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if (if_block) + if_block.d(); + destroy_component(edgelink); + } + }; +} +function create_each_block7(ctx) { + let div; + let t; + let current; + let each_value_1 = ensure_array_like( + /*path*/ + ctx[3] + ); + let each_blocks = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks[i] = create_each_block_15(get_each_context_15(ctx, each_value_1, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + div = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + t = space(); + attr(div, "class", "BC-trail-view-path flex gap-1.5"); + }, + m(target, anchor) { + insert(target, div, anchor); + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(div, null); + } + } + append(div, t); + current = true; + }, + p(ctx2, dirty) { + if (dirty & /*reversed, plugin*/ + 3) { + each_value_1 = ensure_array_like( + /*path*/ + ctx2[3] + ); + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_15(ctx2, each_value_1, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block_15(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div, t); + } + } + group_outros(); + for (i = each_value_1.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value_1.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_fragment40(ctx) { + let div; + let current; + let each_value = ensure_array_like( + /*reversed*/ + ctx[1] + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block7(get_each_context7(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + div = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(div, "class", "BC-trail-view flex flex-col gap-1 px-3 py-2 svelte-4v6yoh"); + }, + m(target, anchor) { + 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(ctx2, [dirty]) { + if (dirty & /*reversed, plugin*/ + 3) { + each_value = ensure_array_like( + /*reversed*/ + ctx2[1] + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context7(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block7(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_each(each_blocks, detaching); + } + }; +} +function instance40($$self, $$props, $$invalidate) { + let { plugin } = $$props; + let { all_paths } = $$props; + const reversed = all_paths.map((path) => [...path].reverse()); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("all_paths" in $$props2) + $$invalidate(2, all_paths = $$props2.all_paths); + }; + return [plugin, reversed, all_paths]; +} +var TrailViewPath = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance40, create_fragment40, safe_not_equal, { plugin: 0, all_paths: 2 }, add_css4); + } +}; +var TrailViewPath_default = TrailViewPath; + +// src/components/page_views/TrailView.svelte +function get_each_context8(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[18] = list[i]; + return child_ctx; +} +function get_each_context_16(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[21] = list[i]; + return child_ctx; +} +function create_if_block_33(ctx) { + let p; + let t_value = ( + /*plugin*/ + ctx[0].settings.views.page.trail.no_path_message + "" + ); + let t; + return { + c() { + p = element("p"); + t = text(t_value); + attr(p, "class", "BC-trail-view-no-path search-empty-state"); + }, + m(target, anchor) { + insert(target, p, anchor); + append(p, t); + }, + p(ctx2, dirty) { + if (dirty & /*plugin*/ + 1 && t_value !== (t_value = /*plugin*/ + ctx2[0].settings.views.page.trail.no_path_message + "")) + set_data(t, t_value); + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(p); + } + } + }; +} +function create_if_block10(ctx) { + let div1; + let select0; + let t0; + let select1; + let t1; + let mergefieldsbutton; + let updating_merge_fields; + let t2; + let div0; + let button0; + let t3; + let button0_disabled_value; + let t4; + let span; + let t5; + let t6; + let t7; + let t8; + let button1; + let t9; + let button1_disabled_value; + let t10; + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + let mounted; + let dispose; + let each_value_1 = ensure_array_like(["grid", "path"]); + let each_blocks_1 = []; + for (let i = 0; i < 2; i += 1) { + each_blocks_1[i] = create_each_block_16(get_each_context_16(ctx, each_value_1, i)); + } + let each_value = ensure_array_like(["all", "shortest", "longest"]); + let each_blocks = []; + for (let i = 0; i < 3; i += 1) { + each_blocks[i] = create_each_block8(get_each_context8(ctx, each_value, i)); + } + function mergefieldsbutton_merge_fields_binding(value) { + ctx[14](value); + } + let mergefieldsbutton_props = {}; + if ( + /*plugin*/ + ctx[0].settings.views.page.trail.merge_fields !== void 0 + ) { + mergefieldsbutton_props.merge_fields = /*plugin*/ + ctx[0].settings.views.page.trail.merge_fields; + } + mergefieldsbutton = new MergeFieldsButton_default({ props: mergefieldsbutton_props }); + binding_callbacks.push(() => bind(mergefieldsbutton, "merge_fields", mergefieldsbutton_merge_fields_binding)); + const if_block_creators = [create_if_block_13, create_if_block_23]; + const if_blocks = []; + function select_block_type_1(ctx2, dirty) { + if ( + /*plugin*/ + ctx2[0].settings.views.page.trail.format === "grid" + ) + return 0; + if ( + /*plugin*/ + ctx2[0].settings.views.page.trail.format === "path" + ) + return 1; + return -1; + } + if (~(current_block_type_index = select_block_type_1(ctx, -1))) { + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + } + return { + c() { + div1 = element("div"); + select0 = element("select"); + for (let i = 0; i < 2; i += 1) { + each_blocks_1[i].c(); + } + t0 = space(); + select1 = element("select"); + for (let i = 0; i < 3; i += 1) { + each_blocks[i].c(); + } + t1 = space(); + create_component(mergefieldsbutton.$$.fragment); + t2 = space(); + div0 = element("div"); + button0 = element("button"); + t3 = text("-"); + t4 = space(); + span = element("span"); + t5 = text( + /*depth*/ + ctx[2] + ); + t6 = text("/"); + t7 = text( + /*MAX_DEPTH*/ + ctx[1] + ); + t8 = space(); + button1 = element("button"); + t9 = text("+"); + t10 = space(); + if (if_block) + if_block.c(); + if_block_anchor = empty(); + attr(select0, "class", "dropdown"); + if ( + /*plugin*/ + ctx[0].settings.views.page.trail.format === void 0 + ) + add_render_callback(() => ( + /*select0_change_handler*/ + ctx[10].call(select0) + )); + attr(select1, "class", "dropdown"); + if ( + /*plugin*/ + ctx[0].settings.views.page.trail.selection === void 0 + ) + add_render_callback(() => ( + /*select1_change_handler*/ + ctx[12].call(select1) + )); + attr(button0, "class", "aspect-square text-lg"); + attr(button0, "aria-label", "Decrease max depth"); + button0.disabled = button0_disabled_value = /*depth*/ + ctx[2] <= 1; + attr(span, "class", "font-mono"); + attr(span, "aria-label", "Max depth"); + attr(button1, "class", "aspect-square text-lg"); + attr(button1, "aria-label", "Increase max depth"); + button1.disabled = button1_disabled_value = /*depth*/ + ctx[2] >= /*MAX_DEPTH*/ + ctx[1]; + attr(div0, "class", "flex items-center gap-1"); + attr(div1, "class", "mb-1 flex flex-wrap justify-between gap-3"); + toggle_class(div1, "hidden", !/*plugin*/ + ctx[0].settings.views.page.trail.show_controls); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, select0); + for (let i = 0; i < 2; i += 1) { + if (each_blocks_1[i]) { + each_blocks_1[i].m(select0, null); + } + } + select_option( + select0, + /*plugin*/ + ctx[0].settings.views.page.trail.format, + true + ); + append(div1, t0); + append(div1, select1); + for (let i = 0; i < 3; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(select1, null); + } + } + select_option( + select1, + /*plugin*/ + ctx[0].settings.views.page.trail.selection, + true + ); + append(div1, t1); + mount_component(mergefieldsbutton, div1, null); + append(div1, t2); + append(div1, div0); + append(div0, button0); + append(button0, t3); + append(div0, t4); + append(div0, span); + append(span, t5); + append(span, t6); + append(span, t7); + append(div0, t8); + append(div0, button1); + append(button1, t9); + insert(target, t10, anchor); + if (~current_block_type_index) { + if_blocks[current_block_type_index].m(target, anchor); + } + insert(target, if_block_anchor, anchor); + current = true; + if (!mounted) { + dispose = [ + listen( + select0, + "change", + /*select0_change_handler*/ + ctx[10] + ), + listen( + select0, + "change", + /*change_handler*/ + ctx[11] + ), + listen( + select1, + "change", + /*select1_change_handler*/ + ctx[12] + ), + listen( + select1, + "change", + /*change_handler_1*/ + ctx[13] + ), + listen( + button0, + "click", + /*click_handler*/ + ctx[15] + ), + listen( + button1, + "click", + /*click_handler_1*/ + ctx[16] + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & /*plugin*/ + 1) { + select_option( + select0, + /*plugin*/ + ctx2[0].settings.views.page.trail.format + ); + } + if (dirty & /*plugin*/ + 1) { + select_option( + select1, + /*plugin*/ + ctx2[0].settings.views.page.trail.selection + ); + } + const mergefieldsbutton_changes = {}; + if (!updating_merge_fields && dirty & /*plugin*/ + 1) { + updating_merge_fields = true; + mergefieldsbutton_changes.merge_fields = /*plugin*/ + ctx2[0].settings.views.page.trail.merge_fields; + add_flush_callback(() => updating_merge_fields = false); + } + mergefieldsbutton.$set(mergefieldsbutton_changes); + if (!current || dirty & /*depth*/ + 4 && button0_disabled_value !== (button0_disabled_value = /*depth*/ + ctx2[2] <= 1)) { + button0.disabled = button0_disabled_value; + } + if (!current || dirty & /*depth*/ + 4) + set_data( + t5, + /*depth*/ + ctx2[2] + ); + if (!current || dirty & /*MAX_DEPTH*/ + 2) + set_data( + t7, + /*MAX_DEPTH*/ + ctx2[1] + ); + if (!current || dirty & /*depth, MAX_DEPTH*/ + 6 && button1_disabled_value !== (button1_disabled_value = /*depth*/ + ctx2[2] >= /*MAX_DEPTH*/ + ctx2[1])) { + button1.disabled = button1_disabled_value; + } + if (!current || dirty & /*plugin*/ + 1) { + toggle_class(div1, "hidden", !/*plugin*/ + ctx2[0].settings.views.page.trail.show_controls); + } + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type_1(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if (~current_block_type_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } + } else { + if (if_block) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + } + if (~current_block_type_index) { + 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](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } else { + if_block = null; + } + } + }, + i(local) { + if (current) + return; + transition_in(mergefieldsbutton.$$.fragment, local); + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(mergefieldsbutton.$$.fragment, local); + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div1); + detach(t10); + detach(if_block_anchor); + } + destroy_each(each_blocks_1, detaching); + destroy_each(each_blocks, detaching); + destroy_component(mergefieldsbutton); + if (~current_block_type_index) { + if_blocks[current_block_type_index].d(detaching); + } + mounted = false; + run_all(dispose); + } + }; +} +function create_each_block_16(ctx) { + let option; + let option_value_value; + return { + c() { + option = element("option"); + option.textContent = `${/*format*/ + ctx[21]} `; + option.__value = option_value_value = /*format*/ + ctx[21]; + set_input_value(option, option.__value); + }, + m(target, anchor) { + insert(target, option, anchor); + }, + p: noop, + d(detaching) { + if (detaching) { + detach(option); + } + } + }; +} +function create_each_block8(ctx) { + let option; + let option_value_value; + return { + c() { + option = element("option"); + option.textContent = `${/*s*/ + ctx[18]} `; + option.__value = option_value_value = /*s*/ + ctx[18]; + set_input_value(option, option.__value); + }, + m(target, anchor) { + insert(target, option, anchor); + }, + p: noop, + d(detaching) { + if (detaching) { + detach(option); + } + } + }; +} +function create_if_block_23(ctx) { + let trailviewpath; + let current; + trailviewpath = new TrailViewPath_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + all_paths: ( + /*sorted_paths*/ + ctx[3] + ) + } + }); + return { + c() { + create_component(trailviewpath.$$.fragment); + }, + m(target, anchor) { + mount_component(trailviewpath, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const trailviewpath_changes = {}; + if (dirty & /*plugin*/ + 1) + trailviewpath_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*sorted_paths*/ + 8) + trailviewpath_changes.all_paths = /*sorted_paths*/ + ctx2[3]; + trailviewpath.$set(trailviewpath_changes); + }, + i(local) { + if (current) + return; + transition_in(trailviewpath.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(trailviewpath.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(trailviewpath, detaching); + } + }; +} +function create_if_block_13(ctx) { + let trailviewgrid; + let current; + trailviewgrid = new TrailViewGrid_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + all_paths: ( + /*sorted_paths*/ + ctx[3] + ) + } + }); + return { + c() { + create_component(trailviewgrid.$$.fragment); + }, + m(target, anchor) { + mount_component(trailviewgrid, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const trailviewgrid_changes = {}; + if (dirty & /*plugin*/ + 1) + trailviewgrid_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*sorted_paths*/ + 8) + trailviewgrid_changes.all_paths = /*sorted_paths*/ + ctx2[3]; + trailviewgrid.$set(trailviewgrid_changes); + }, + i(local) { + if (current) + return; + transition_in(trailviewgrid.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(trailviewgrid.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(trailviewgrid, detaching); + } + }; +} +function create_key_block3(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block10, create_if_block_33]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*sorted_paths*/ + ctx2[3].length + ) + return 0; + if ( + /*plugin*/ + ctx2[0].settings.views.page.trail.no_path_message + ) + return 1; + return -1; + } + if (~(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() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (~current_block_type_index) { + if_blocks[current_block_type_index].m(target, anchor); + } + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if (~current_block_type_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } + } else { + if (if_block) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + } + if (~current_block_type_index) { + 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](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } else { + if_block = null; + } + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if (~current_block_type_index) { + if_blocks[current_block_type_index].d(detaching); + } + } + }; +} +function create_fragment41(ctx) { + let div; + let previous_key = ( + /*sorted_paths*/ + ctx[3] + ); + let current; + let key_block = create_key_block3(ctx); + return { + c() { + div = element("div"); + key_block.c(); + }, + m(target, anchor) { + insert(target, div, anchor); + key_block.m(div, null); + current = true; + }, + p(ctx2, [dirty]) { + if (dirty & /*sorted_paths*/ + 8 && safe_not_equal(previous_key, previous_key = /*sorted_paths*/ + ctx2[3])) { + group_outros(); + transition_out(key_block, 1, 1, noop); + check_outros(); + key_block = create_key_block3(ctx2); + key_block.c(); + transition_in(key_block, 1); + key_block.m(div, null); + } else { + key_block.p(ctx2, dirty); + } + }, + i(local) { + if (current) + return; + transition_in(key_block); + current = true; + }, + o(local) { + transition_out(key_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + key_block.d(detaching); + } + }; +} +function instance41($$self, $$props, $$invalidate) { + let edge_field_labels; + let all_paths; + let selected_paths; + let MAX_DEPTH2; + let depth; + let sliced_paths; + let deduped_paths; + let sorted_paths; + let { plugin } = $$props; + let { file_path } = $$props; + const base_traversal = (attr2) => Traverse.tree_to_all_paths(Traverse.build_tree(plugin.graph, file_path, {}, (e) => has_edge_attrs(e, attr2))); + function select0_change_handler() { + plugin.settings.views.page.trail.format = select_value(this); + $$invalidate(0, plugin); + } + const change_handler = async () => await plugin.saveSettings(); + function select1_change_handler() { + plugin.settings.views.page.trail.selection = select_value(this); + $$invalidate(0, plugin); + } + const change_handler_1 = async () => await plugin.saveSettings(); + function mergefieldsbutton_merge_fields_binding(value) { + if ($$self.$$.not_equal(plugin.settings.views.page.trail.merge_fields, value)) { + plugin.settings.views.page.trail.merge_fields = value; + $$invalidate(0, plugin); + } + } + const click_handler = () => $$invalidate(2, depth = Math.max(1, depth - 1)); + const click_handler_1 = () => $$invalidate(2, depth = Math.min(MAX_DEPTH2, depth + 1)); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("file_path" in $$props2) + $$invalidate(4, file_path = $$props2.file_path); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*plugin*/ + 1) { + $: + $$invalidate(9, edge_field_labels = resolve_field_group_labels(plugin.settings.edge_field_groups, plugin.settings.views.page.trail.field_group_labels)); + } + if ($$self.$$.dirty & /*plugin, file_path, edge_field_labels*/ + 529) { + $: + $$invalidate(8, all_paths = plugin.graph.hasNode(file_path) ? plugin.settings.views.page.trail.merge_fields ? base_traversal({ $or_fields: edge_field_labels }) : edge_field_labels.flatMap((field) => base_traversal({ field })) : []); + } + if ($$self.$$.dirty & /*plugin, all_paths*/ + 257) { + $: + $$invalidate(7, selected_paths = plugin.settings.views.page.trail.selection === "all" ? all_paths : plugin.settings.views.page.trail.selection === "shortest" ? all_paths.slice(-1) : plugin.settings.views.page.trail.selection === "longest" ? all_paths.slice(0, 1) : [[]]); + } + if ($$self.$$.dirty & /*selected_paths*/ + 128) { + $: + $$invalidate(1, MAX_DEPTH2 = Math.max(0, ...selected_paths.map((p) => p.length))); + } + if ($$self.$$.dirty & /*MAX_DEPTH, plugin*/ + 3) { + $: + $$invalidate(2, depth = Math.min(MAX_DEPTH2, plugin.settings.views.page.trail.default_depth)); + } + if ($$self.$$.dirty & /*selected_paths, depth*/ + 132) { + $: + $$invalidate(6, sliced_paths = selected_paths.map((path) => path.slice(0, depth))); + } + if ($$self.$$.dirty & /*depth, MAX_DEPTH, sliced_paths*/ + 70) { + $: + $$invalidate(5, deduped_paths = // There are no duplicates if the depth is the max depth. + // The traversal wouldn't add them in the first place. + depth === MAX_DEPTH2 ? sliced_paths : remove_duplicates_by(sliced_paths, (path) => path.map((p) => p.target_id).join("/"))); + } + if ($$self.$$.dirty & /*deduped_paths*/ + 32) { + $: + $$invalidate(3, sorted_paths = deduped_paths.sort((a, b) => { + const len_diff = b.length - a.length; + if (len_diff !== 0) + return len_diff; + else + return a[0].target_id.localeCompare(b[0].target_id); + })); + } + }; + return [ + plugin, + MAX_DEPTH2, + depth, + sorted_paths, + file_path, + deduped_paths, + sliced_paths, + selected_paths, + all_paths, + edge_field_labels, + select0_change_handler, + change_handler, + select1_change_handler, + change_handler_1, + mergefieldsbutton_merge_fields_binding, + click_handler, + click_handler_1 + ]; +} +var TrailView = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance41, create_fragment41, safe_not_equal, { plugin: 0, file_path: 4 }); + } +}; +var TrailView_default = TrailView; + +// src/components/page_views/index.svelte +function create_if_block11(ctx) { + let div; + let t; + let current; + let if_block0 = ( + /*enabled_views*/ + ctx[2].grid && create_if_block_24(ctx) + ); + let if_block1 = ( + /*enabled_views*/ + ctx[2].prev_next && create_if_block_14(ctx) + ); + return { + c() { + div = element("div"); + if (if_block0) + if_block0.c(); + t = space(); + if (if_block1) + if_block1.c(); + attr(div, "class", "markdown-rendered mb-4 flex flex-col gap-2"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (if_block0) + if_block0.m(div, null); + append(div, t); + if (if_block1) + if_block1.m(div, null); + current = true; + }, + p(ctx2, dirty) { + if ( + /*enabled_views*/ + ctx2[2].grid + ) + if_block0.p(ctx2, dirty); + if ( + /*enabled_views*/ + ctx2[2].prev_next + ) + if_block1.p(ctx2, dirty); + }, + i(local) { + if (current) + return; + transition_in(if_block0); + transition_in(if_block1); + current = true; + }, + o(local) { + transition_out(if_block0); + transition_out(if_block1); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + if (if_block0) + if_block0.d(); + if (if_block1) + if_block1.d(); + } + }; +} +function create_if_block_24(ctx) { + let trailview; + let current; + trailview = new TrailView_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + file_path: ( + /*file_path*/ + ctx[1] + ) + } + }); + return { + c() { + create_component(trailview.$$.fragment); + }, + m(target, anchor) { + mount_component(trailview, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const trailview_changes = {}; + if (dirty & /*plugin*/ + 1) + trailview_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*file_path*/ + 2) + trailview_changes.file_path = /*file_path*/ + ctx2[1]; + trailview.$set(trailview_changes); + }, + i(local) { + if (current) + return; + transition_in(trailview.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(trailview.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(trailview, detaching); + } + }; +} +function create_if_block_14(ctx) { + let prevnextview; + let current; + prevnextview = new PrevNextView_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + file_path: ( + /*file_path*/ + ctx[1] + ) + } + }); + return { + c() { + create_component(prevnextview.$$.fragment); + }, + m(target, anchor) { + mount_component(prevnextview, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const prevnextview_changes = {}; + if (dirty & /*plugin*/ + 1) + prevnextview_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*file_path*/ + 2) + prevnextview_changes.file_path = /*file_path*/ + ctx2[1]; + prevnextview.$set(prevnextview_changes); + }, + i(local) { + if (current) + return; + transition_in(prevnextview.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(prevnextview.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(prevnextview, detaching); + } + }; +} +function create_fragment42(ctx) { + let show_if = Object.values( + /*enabled_views*/ + ctx[2] + ).some(Boolean); + let if_block_anchor; + let current; + let if_block = show_if && create_if_block11(ctx); + return { + c() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (if_block) + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, [dirty]) { + if (show_if) + if_block.p(ctx2, dirty); + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if (if_block) + if_block.d(detaching); + } + }; +} +function instance42($$self, $$props, $$invalidate) { + let { plugin } = $$props; + let { file_path } = $$props; + const enabled_views = { + grid: plugin.settings.views.page.trail.enabled, + prev_next: plugin.settings.views.page.prev_next.enabled + }; + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("file_path" in $$props2) + $$invalidate(1, file_path = $$props2.file_path); + }; + return [plugin, file_path, enabled_views]; +} +var Page_views = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance42, create_fragment42, safe_not_equal, { plugin: 0, file_path: 1 }); + } +}; +var page_views_default = Page_views; + +// src/views/page.ts +var redraw_page_views = (plugin) => { + const markdown_views = plugin.app.workspace.getLeavesOfType("markdown"); + if (!markdown_views.length) { + log.info("redraw_page_views > No markdown views found"); + return; + } + markdown_views.forEach((leaf) => { + var _a, _b, _c; + if (!(leaf.view instanceof import_obsidian22.MarkdownView)) + return; + const markdown_view = leaf.view; + const mode = markdown_view.getMode(); + const page_views_el = (_a = markdown_view.containerEl.querySelector(".BC-page-views")) != null ? _a : markdown_view.containerEl.createDiv({ + cls: "BC-page-views w-full mx-auto" + }); + const max_width = plugin.settings.views.page.all.readable_line_width ? "var(--file-line-width)" : "none"; + page_views_el.setAttribute("style", `max-width: ${max_width};`); + page_views_el.classList.toggle( + "BC-page-views-sticky", + plugin.settings.views.page.all.sticky + ); + page_views_el.empty(); + if (mode === "preview") { + const view_parent = markdown_view.containerEl.querySelector( + ".markdown-reading-view > .markdown-preview-view" + ); + if (!view_parent) { + return log.info( + "redraw_page_views > No view_parent (mode=preview)" + ); + } + view_parent.insertBefore(page_views_el, view_parent.firstChild); + } else { + const view_parent = markdown_view.containerEl.querySelector(".cm-scroller"); + if (!view_parent) { + return log.info( + "redraw_page_views > No view_parent (mode=source)" + ); + } + view_parent.addClass("flex-col"); + view_parent.insertBefore(page_views_el, view_parent.firstChild); + } + new page_views_default({ + target: page_views_el, + props: { plugin, file_path: (_c = (_b = markdown_view.file) == null ? void 0 : _b.path) != null ? _c : "" } + }); + }); +}; + +// src/settings/PageViewSettings.ts +var _add_settings_page_views = (plugin, container_el) => { + new_setting(container_el, { + name: "Sticky", + desc: "Keep the page views pinned to the top of the note as you scroll", + toggle: { + value: plugin.settings.views.page.all.sticky, + cb: async (value) => { + plugin.settings.views.page.all.sticky = value; + await plugin.saveSettings(); + redraw_page_views(plugin); + } + } + }); + new_setting(container_el, { + name: "Readable line width", + desc: "Limit to the width of the text in the editor", + toggle: { + value: plugin.settings.views.page.all.readable_line_width, + cb: async (value) => { + plugin.settings.views.page.all.readable_line_width = value; + await plugin.saveSettings(); + redraw_page_views(plugin); + } + } + }); +}; + +// src/settings/PrevNextSettings.ts +var import_obsidian23 = require("obsidian"); +var _add_settings_prev_next_view = (plugin, containerEl) => { + new import_obsidian23.Setting(containerEl).setName("Enable Previous/Next view").setDesc("Show the Previous/Next view at the top of the page").addToggle((toggle) => { + toggle.setValue(plugin.settings.views.page.prev_next.enabled).onChange(async (value) => { + plugin.settings.views.page.prev_next.enabled = value; + await Promise.all([plugin.saveSettings()]); + plugin.refresh({ + rebuild_graph: false, + active_file_store: false + }); + }); + }); + new FieldGroupLabelsSettingItem_default({ + target: containerEl, + props: { + name: "Field Groups for Left", + description: "Select the field groups to show in the left side of this view", + edge_field_groups: plugin.settings.edge_field_groups, + field_group_labels: plugin.settings.views.page.prev_next.field_group_labels.prev + } + }).$on("select", async (e) => { + plugin.settings.views.page.prev_next.field_group_labels.prev = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + }); + new FieldGroupLabelsSettingItem_default({ + target: containerEl, + props: { + name: "Field Groups for Right", + description: "Select the field groups to show in the right side of this view", + edge_field_groups: plugin.settings.edge_field_groups, + field_group_labels: plugin.settings.views.page.prev_next.field_group_labels.next + } + }).$on("select", async (e) => { + plugin.settings.views.page.prev_next.field_group_labels.next = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ rebuild_graph: false }) + ]); + }); + _add_settings_show_node_options(plugin, containerEl, { + get: () => plugin.settings.views.page.prev_next.show_node_options, + set: (value) => plugin.settings.views.page.prev_next.show_node_options = value + }); +}; + +// src/settings/RebuildGraphSettings.ts +var _add_settings_rebuild_graph = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Notify on refresh", + desc: "Show a notification when the graph is rebuilt", + toggle: { + value: plugin.settings.commands.rebuild_graph.notify, + cb: async (value) => { + plugin.settings.commands.rebuild_graph.notify = value; + await Promise.all([plugin.saveSettings(), plugin.refresh({})]); + } + } + }); + new_setting(containerEl, { + name: "Triggers", + desc: "When to rebuild the graph", + checklist: { + options: { + note_save: plugin.settings.commands.rebuild_graph.trigger.note_save, + layout_change: plugin.settings.commands.rebuild_graph.trigger.layout_change + }, + cb: async (value) => { + plugin.settings.commands.rebuild_graph.trigger = value; + await Promise.all([plugin.saveSettings(), plugin.refresh({})]); + } + } + }); +}; + +// src/settings/RegexNoteSettings.ts +var _add_settings_regex_note = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Default Field", + desc: "Field to use if the BC-regex-note-field is not specified", + select: { + value: plugin.settings.explicit_edge_sources.regex_note.default_field, + options: plugin.settings.edge_fields.map((f) => f.label), + cb: async (value) => { + plugin.settings.explicit_edge_sources.regex_note.default_field = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); +}; + +// src/settings/TagNoteSettings.ts +var _add_settings_tag_note = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Default Field", + desc: "Field to use if the BC-tag-note-field is not specified", + select: { + value: plugin.settings.explicit_edge_sources.tag_note.default_field, + options: plugin.settings.edge_fields.map((f) => f.label), + cb: async (value) => { + plugin.settings.explicit_edge_sources.tag_note.default_field = value; + await Promise.all([plugin.refresh(), plugin.saveSettings()]); + } + } + }); +}; + +// src/settings/ThreadSettings.ts +var _add_settings_thread = (plugin, contentEl) => { + const { settings } = plugin; + new_setting(contentEl, { + name: "Destination", + desc: "Where to write the new edge to", + select: { + options: ["frontmatter", "dataview-inline", "none"], + value: settings.commands.thread.default_options.destination, + cb: async (value) => { + settings.commands.thread.default_options.destination = value; + await plugin.saveSettings(); + } + } + }); + new_setting(contentEl, { + name: "Target Path Template", + desc: "The template to use for the target path. You don't need to add the .md extension.", + input: { + value: settings.commands.thread.default_options.target_path_template, + cb: async (value) => { + settings.commands.thread.default_options.target_path_template = value; + await plugin.saveSettings(); + } + } + }); +}; + +// src/settings/TreeViewSettings.ts +var _add_settings_tree_view = (plugin, containerEl) => { + new_setting(containerEl, { + name: "Collapse", + desc: "Collapse the tree by default", + toggle: { + value: plugin.settings.views.side.tree.collapse, + cb: async (checked) => { + plugin.settings.views.side.tree.collapse = checked; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ + redraw_side_views: true, + rebuild_graph: false + }) + ]); + } + } + }); + new EdgeSortIdSettingItem_default({ + target: containerEl, + props: { edge_sort_id: plugin.settings.views.side.tree.edge_sort_id } + }).$on("select", async (e) => { + plugin.settings.views.side.tree.edge_sort_id = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ + redraw_side_views: true, + rebuild_graph: false + }) + ]); + }); + new ShowAttributesSettingItem_default({ + target: containerEl, + props: { + show_attributes: plugin.settings.views.side.tree.show_attributes + } + }).$on("select", async (e) => { + plugin.settings.views.side.tree.show_attributes = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ + redraw_side_views: true, + rebuild_graph: false + }) + ]); + }); + new FieldGroupLabelsSettingItem_default({ + target: containerEl, + props: { + edge_field_groups: plugin.settings.edge_field_groups, + field_group_labels: plugin.settings.views.side.tree.field_group_labels + } + }).$on("select", async (e) => { + plugin.settings.views.side.tree.field_group_labels = e.detail; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ + redraw_side_views: true, + rebuild_graph: false + }) + ]); + }); + new_setting(containerEl, { + name: "Merge Fields", + desc: "Merge fields in the traversal, instead of keeping their paths separate", + toggle: { + value: plugin.settings.views.side.tree.merge_fields, + cb: async (value) => { + plugin.settings.views.side.tree.merge_fields = value; + await Promise.all([ + plugin.saveSettings(), + plugin.refresh({ + redraw_side_views: true, + rebuild_graph: false + }) + ]); + } + } + }); + _add_settings_show_node_options(plugin, containerEl, { + get: () => plugin.settings.views.side.tree.show_node_options, + set: (value) => plugin.settings.views.side.tree.show_node_options = value + }); +}; + +// src/settings/SettingsTab.ts +var make_details_el = (parent, o) => { + let details; + let summary; + let children2; + details = parent.createEl("details", { + cls: "tree-item", + ...o == null ? void 0 : o.d + }); + summary = details.createEl("summary", { + cls: "text-xl p-1 tree-item-self is-clickable", + ...o == null ? void 0 : o.s + }); + children2 = details.createEl("div", { cls: "tree-item-children pl-4" }); + return { + details, + summary, + children: children2 + }; +}; +var BreadcrumbsSettingTab = class extends import_obsidian24.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.components = []; + this.plugin = plugin; + } + display() { + const { containerEl, plugin } = this; + containerEl.empty(); + containerEl.addClass("BC-settings-tab"); + this.components.push( + new EdgeFieldSettings_default({ + props: { plugin }, + target: make_details_el(containerEl, { + s: { text: "> Edge Fields" } + }).children + }) + ); + containerEl.createEl("hr"); + containerEl.createEl("h3", { text: "Implied Relations" }); + this.components.push( + new TransitiveImpliedRelations_default({ + props: { plugin }, + target: make_details_el(containerEl, { + s: { text: "> Transitive" } + }).children + }) + ); + containerEl.createEl("hr"); + containerEl.createEl("h3", { text: "Edge Sources" }); + _add_settings_tag_note( + plugin, + make_details_el(containerEl, { s: { text: "> Tag Notes" } }).children + ); + _add_settings_list_note( + plugin, + make_details_el(containerEl, { s: { text: "> List Notes" } }).children + ); + _add_settings_date_note( + plugin, + make_details_el(containerEl, { s: { text: "> Date Notes" } }).children + ); + _add_settings_regex_note( + plugin, + make_details_el(containerEl, { s: { text: "> Regex Notes" } }).children + ); + _add_settings_dendron_note( + plugin, + make_details_el(containerEl, { s: { text: "> Dendron Notes" } }).children + ); + _add_settings_johnny_decimal_note( + plugin, + make_details_el(containerEl, { + s: { text: "> Johnny Decimal Notes" } + }).children + ); + containerEl.createEl("hr"); + containerEl.createEl("h3", { text: "Views" }); + _add_settings_matrix( + plugin, + make_details_el(containerEl, { s: { text: "> Matrix" } }).children + ); + const page_details = make_details_el(containerEl, { + s: { text: "> Page" } + }).children; + page_details.createEl("h5", { text: "General" }); + _add_settings_page_views(plugin, page_details); + page_details.createEl("h5", { text: "Trail" }); + _add_settings_trail_view(plugin, page_details); + page_details.createEl("h5", { text: "Previous/Next" }); + _add_settings_prev_next_view(plugin, page_details); + _add_settings_tree_view( + plugin, + make_details_el(containerEl, { s: { text: "> Tree" } }).children + ); + _add_settings_codeblocks( + plugin, + make_details_el(containerEl, { s: { text: "> Codeblocks" } }).children + ); + containerEl.createEl("hr"); + containerEl.createEl("h3", { text: "Commands" }); + _add_settings_rebuild_graph( + plugin, + make_details_el(containerEl, { s: { text: "> Rebuild Graph" } }).children + ); + _add_settings_list_index( + plugin, + make_details_el(containerEl, { s: { text: "> List Index" } }).children + ); + _add_settings_freeze_implied_edges( + plugin, + make_details_el(containerEl, { + s: { text: "> Freeze Implied Edges" } + }).children + ); + _add_settings_thread( + plugin, + make_details_el(containerEl, { s: { text: "> Thread" } }).children + ); + containerEl.createEl("hr"); + containerEl.createEl("h3", { text: "Suggestors" }); + _add_settings_edge_field_suggestor( + plugin, + make_details_el(containerEl, { + s: { text: "> Edge Field Suggestor" } + }).children + ); + containerEl.createEl("hr"); + _add_settings_debug( + plugin, + make_details_el(containerEl, { s: { text: "> Debug" } }).children + ); + } + hide() { + if (this.plugin.settings.is_dirty) { + new import_obsidian24.Notice( + "\u26A0\uFE0F Exited without saving settings. Your changes are still in effect, but were not saved. Go back and click 'Save' if you want them to persist. Otherwise, reload Obsidian to revert to the last saved settings." + ); + } + this.components.forEach((c) => c.$destroy()); + } +}; + +// src/views/matrix.ts +var import_obsidian25 = require("obsidian"); + +// src/components/button/ChevronCollapseButton.svelte +function create_else_block6(ctx) { + let chevronsupdown; + let current; + chevronsupdown = new chevrons_up_down_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(chevronsupdown.$$.fragment); + }, + m(target, anchor) { + mount_component(chevronsupdown, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(chevronsupdown.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(chevronsupdown.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(chevronsupdown, detaching); + } + }; +} +function create_if_block12(ctx) { + let chevronsdownup; + let current; + chevronsdownup = new chevrons_down_up_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(chevronsdownup.$$.fragment); + }, + m(target, anchor) { + mount_component(chevronsdownup, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(chevronsdownup.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(chevronsdownup.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(chevronsdownup, detaching); + } + }; +} +function create_fragment43(ctx) { + let button; + let current_block_type_index; + let if_block; + let button_aria_label_value; + let current; + let mounted; + let dispose; + const if_block_creators = [create_if_block12, create_else_block6]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*collapse*/ + ctx2[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() { + button = element("button"); + if_block.c(); + attr( + button, + "class", + /*cls*/ + ctx[1] + ); + attr(button, "aria-label", button_aria_label_value = /*collapse*/ + ctx[0] ? "Expand" : "Collapse"); + }, + m(target, anchor) { + insert(target, button, anchor); + if_blocks[current_block_type_index].m(button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler*/ + ctx[2] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index !== previous_block_index) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + 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](ctx2); + if_block.c(); + } else { + } + transition_in(if_block, 1); + if_block.m(button, null); + } + if (!current || dirty & /*cls*/ + 2) { + attr( + button, + "class", + /*cls*/ + ctx2[1] + ); + } + if (!current || dirty & /*collapse*/ + 1 && button_aria_label_value !== (button_aria_label_value = /*collapse*/ + ctx2[0] ? "Expand" : "Collapse")) { + attr(button, "aria-label", button_aria_label_value); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + if_blocks[current_block_type_index].d(); + mounted = false; + dispose(); + } + }; +} +function instance43($$self, $$props, $$invalidate) { + let { cls = "" } = $$props; + let { collapse } = $$props; + const click_handler = () => $$invalidate(0, collapse = !collapse); + $$self.$$set = ($$props2) => { + if ("cls" in $$props2) + $$invalidate(1, cls = $$props2.cls); + if ("collapse" in $$props2) + $$invalidate(0, collapse = $$props2.collapse); + }; + return [collapse, cls, click_handler]; +} +var ChevronCollapseButton = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance43, create_fragment43, safe_not_equal, { cls: 1, collapse: 0 }); + } +}; +var ChevronCollapseButton_default = ChevronCollapseButton; + +// src/components/button/RebuildGraphButton.svelte +function create_fragment44(ctx) { + let button; + let rotateccw; + let current; + let mounted; + let dispose; + rotateccw = new rotate_ccw_default({ props: { size: ICON_SIZE } }); + return { + c() { + button = element("button"); + create_component(rotateccw.$$.fragment); + attr( + button, + "class", + /*cls*/ + ctx[0] + ); + attr(button, "aria-label", "Rebuild Graph"); + }, + m(target, anchor) { + insert(target, button, anchor); + mount_component(rotateccw, button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler*/ + ctx[2] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (!current || dirty & /*cls*/ + 1) { + attr( + button, + "class", + /*cls*/ + ctx2[0] + ); + } + }, + i(local) { + if (current) + return; + transition_in(rotateccw.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(rotateccw.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + destroy_component(rotateccw); + mounted = false; + dispose(); + } + }; +} +function instance44($$self, $$props, $$invalidate) { + let { cls = "" } = $$props; + let { plugin } = $$props; + const click_handler = () => plugin.refresh(); + $$self.$$set = ($$props2) => { + if ("cls" in $$props2) + $$invalidate(0, cls = $$props2.cls); + if ("plugin" in $$props2) + $$invalidate(1, plugin = $$props2.plugin); + }; + return [cls, plugin, click_handler]; +} +var RebuildGraphButton = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance44, create_fragment44, safe_not_equal, { cls: 0, plugin: 1 }); + } +}; +var RebuildGraphButton_default = RebuildGraphButton; + +// src/components/obsidian/TreeItemFlair.svelte +function create_fragment45(ctx) { + let div; + let span; + let t; + let span_class_value; + return { + c() { + div = element("div"); + span = element("span"); + t = text( + /*label*/ + ctx[1] + ); + attr(span, "class", span_class_value = /*cls*/ + ctx[0] + " tree-item-flair"); + attr( + span, + "aria-label", + /*aria_label*/ + ctx[2] + ); + attr(div, "class", "tree-item-flair-outer"); + }, + m(target, anchor) { + insert(target, div, anchor); + append(div, span); + append(span, t); + }, + p(ctx2, [dirty]) { + if (dirty & /*label*/ + 2) + set_data( + t, + /*label*/ + ctx2[1] + ); + if (dirty & /*cls*/ + 1 && span_class_value !== (span_class_value = /*cls*/ + ctx2[0] + " tree-item-flair")) { + attr(span, "class", span_class_value); + } + if (dirty & /*aria_label*/ + 4) { + attr( + span, + "aria-label", + /*aria_label*/ + ctx2[2] + ); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(div); + } + } + }; +} +function instance45($$self, $$props, $$invalidate) { + let { cls = "" } = $$props; + let { label = "" } = $$props; + let { aria_label = "" } = $$props; + $$self.$$set = ($$props2) => { + if ("cls" in $$props2) + $$invalidate(0, cls = $$props2.cls); + if ("label" in $$props2) + $$invalidate(1, label = $$props2.label); + if ("aria_label" in $$props2) + $$invalidate(2, aria_label = $$props2.aria_label); + }; + return [cls, label, aria_label]; +} +var TreeItemFlair = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance45, create_fragment45, safe_not_equal, { cls: 0, label: 1, aria_label: 2 }); + } +}; +var TreeItemFlair_default = TreeItemFlair; + +// src/components/side_views/MatrixEdgeField.svelte +function get_each_context9(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[8] = list[i]; + return child_ctx; +} +function create_each_block9(ctx) { + let div2; + let div1; + let div0; + let edgelink; + let t0; + let treeitemflair; + let t1; + let current; + edgelink = new EdgeLink_default({ + props: { + edge: ( + /*edge*/ + ctx[8] + ), + plugin: ( + /*plugin*/ + ctx[3] + ), + show_node_options: ( + /*show_node_options*/ + ctx[6] + ), + cls: "grow tree-item-inner-text" + } + }); + treeitemflair = new TreeItemFlair_default({ + props: { + cls: "font-mono", + label: ( + /*edge*/ + ctx[8].attr.explicit ? "x" : "i" + ), + aria_label: url_search_params(untyped_pick( + /*edge*/ + ctx[8].attr, + /*show_attributes*/ + ctx[4] + ), { trim_lone_param: true }) + } + }); + return { + c() { + div2 = element("div"); + div1 = element("div"); + div0 = element("div"); + create_component(edgelink.$$.fragment); + t0 = space(); + create_component(treeitemflair.$$.fragment); + t1 = space(); + attr(div0, "class", "tree-item-inner flex grow"); + attr(div1, "class", "tree-item-self is-clickable"); + attr(div2, "class", "tree-item"); + }, + m(target, anchor) { + insert(target, div2, anchor); + append(div2, div1); + append(div1, div0); + mount_component(edgelink, div0, null); + append(div1, t0); + mount_component(treeitemflair, div1, null); + append(div2, t1); + current = true; + }, + p(ctx2, dirty) { + const edgelink_changes = {}; + if (dirty & /*edges, sort*/ + 34) + edgelink_changes.edge = /*edge*/ + ctx2[8]; + if (dirty & /*plugin*/ + 8) + edgelink_changes.plugin = /*plugin*/ + ctx2[3]; + edgelink.$set(edgelink_changes); + const treeitemflair_changes = {}; + if (dirty & /*edges, sort*/ + 34) + treeitemflair_changes.label = /*edge*/ + ctx2[8].attr.explicit ? "x" : "i"; + if (dirty & /*edges, sort, show_attributes*/ + 50) + treeitemflair_changes.aria_label = url_search_params(untyped_pick( + /*edge*/ + ctx2[8].attr, + /*show_attributes*/ + ctx2[4] + ), { trim_lone_param: true }); + treeitemflair.$set(treeitemflair_changes); + }, + i(local) { + if (current) + return; + transition_in(edgelink.$$.fragment, local); + transition_in(treeitemflair.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(edgelink.$$.fragment, local); + transition_out(treeitemflair.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div2); + } + destroy_component(edgelink); + destroy_component(treeitemflair); + } + }; +} +function create_key_block4(ctx) { + let each_1_anchor; + let current; + let each_value = ensure_array_like( + /*edges*/ + ctx[1].sort( + /*sort*/ + ctx[5] + ) + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block9(get_each_context9(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(target, anchor); + } + } + insert(target, each_1_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + if (dirty & /*edges, sort, show_attributes, plugin, show_node_options*/ + 122) { + each_value = ensure_array_like( + /*edges*/ + ctx2[1].sort( + /*sort*/ + ctx2[5] + ) + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context9(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block9(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(each_1_anchor); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_fragment46(ctx) { + let details; + let summary; + let div0; + let chevronopener; + let t0; + let div1; + let span0; + let t1_value = ( + /*field*/ + ctx[2].label + "" + ); + let t1; + let t2; + let div2; + let span1; + let t3_value = ( + /*edges*/ + ctx[1].length + "" + ); + let t3; + let t4; + let div3; + let previous_key = ( + /*sort*/ + ctx[5] + ); + let details_class_value; + let current; + let mounted; + let dispose; + chevronopener = new ChevronOpener_default({ props: { open: ( + /*open*/ + ctx[0] + ) } }); + let key_block = create_key_block4(ctx); + return { + c() { + details = element("details"); + summary = element("summary"); + div0 = element("div"); + create_component(chevronopener.$$.fragment); + t0 = space(); + div1 = element("div"); + span0 = element("span"); + t1 = text(t1_value); + t2 = space(); + div2 = element("div"); + span1 = element("span"); + t3 = text(t3_value); + t4 = space(); + div3 = element("div"); + key_block.c(); + attr(div0, "class", "tree-item-icon collapse-icon"); + attr(span0, "class", "tree-item-inner-text"); + attr(div1, "class", "tree-item-inner"); + attr(span1, "class", "tree-item-flair font-mono text-lg"); + attr(div2, "class", "tree-item-flair-outer"); + attr(summary, "class", "tree-item-self is-clickable mod-collapsible text-lg"); + attr(div3, "class", "tree-item-children flex flex-col"); + attr(details, "class", details_class_value = "BC-matrix-view-field BC-matrix-view-field-" + /*field*/ + ctx[2].label + " tree-item"); + }, + m(target, anchor) { + insert(target, details, anchor); + append(details, summary); + append(summary, div0); + mount_component(chevronopener, div0, null); + append(summary, t0); + append(summary, div1); + append(div1, span0); + append(span0, t1); + append(summary, t2); + append(summary, div2); + append(div2, span1); + append(span1, t3); + append(details, t4); + append(details, div3); + key_block.m(div3, null); + details.open = /*open*/ + ctx[0]; + current = true; + if (!mounted) { + dispose = listen( + details, + "toggle", + /*details_toggle_handler*/ + ctx[7] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + const chevronopener_changes = {}; + if (dirty & /*open*/ + 1) + chevronopener_changes.open = /*open*/ + ctx2[0]; + chevronopener.$set(chevronopener_changes); + if ((!current || dirty & /*field*/ + 4) && t1_value !== (t1_value = /*field*/ + ctx2[2].label + "")) + set_data(t1, t1_value); + if ((!current || dirty & /*edges*/ + 2) && t3_value !== (t3_value = /*edges*/ + ctx2[1].length + "")) + set_data(t3, t3_value); + if (dirty & /*sort*/ + 32 && safe_not_equal(previous_key, previous_key = /*sort*/ + ctx2[5])) { + group_outros(); + transition_out(key_block, 1, 1, noop); + check_outros(); + key_block = create_key_block4(ctx2); + key_block.c(); + transition_in(key_block, 1); + key_block.m(div3, null); + } else { + key_block.p(ctx2, dirty); + } + if (!current || dirty & /*field*/ + 4 && details_class_value !== (details_class_value = "BC-matrix-view-field BC-matrix-view-field-" + /*field*/ + ctx2[2].label + " tree-item")) { + attr(details, "class", details_class_value); + } + if (dirty & /*open*/ + 1) { + details.open = /*open*/ + ctx2[0]; + } + }, + i(local) { + if (current) + return; + transition_in(chevronopener.$$.fragment, local); + transition_in(key_block); + current = true; + }, + o(local) { + transition_out(chevronopener.$$.fragment, local); + transition_out(key_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(details); + } + destroy_component(chevronopener); + key_block.d(detaching); + mounted = false; + dispose(); + } + }; +} +function instance46($$self, $$props, $$invalidate) { + let { open } = $$props; + let { edges } = $$props; + let { field } = $$props; + let { plugin } = $$props; + let { show_attributes } = $$props; + let { show_node_options } = plugin.settings.views.side.matrix; + let { sort } = $$props; + function details_toggle_handler() { + open = this.open; + $$invalidate(0, open); + } + $$self.$$set = ($$props2) => { + if ("open" in $$props2) + $$invalidate(0, open = $$props2.open); + if ("edges" in $$props2) + $$invalidate(1, edges = $$props2.edges); + if ("field" in $$props2) + $$invalidate(2, field = $$props2.field); + if ("plugin" in $$props2) + $$invalidate(3, plugin = $$props2.plugin); + if ("show_attributes" in $$props2) + $$invalidate(4, show_attributes = $$props2.show_attributes); + if ("sort" in $$props2) + $$invalidate(5, sort = $$props2.sort); + }; + return [ + open, + edges, + field, + plugin, + show_attributes, + sort, + show_node_options, + details_toggle_handler + ]; +} +var MatrixEdgeField = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance46, create_fragment46, safe_not_equal, { + open: 0, + edges: 1, + field: 2, + plugin: 3, + show_attributes: 4, + sort: 5 + }); + } +}; +var MatrixEdgeField_default = MatrixEdgeField; + +// src/components/side_views/Matrix.svelte +function get_each_context10(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[13] = list[i]; + const constants_0 = ( + /*grouped_out_edges*/ + child_ctx[6][ + /*field*/ + child_ctx[13].label + ] + ); + child_ctx[14] = constants_0; + return child_ctx; +} +function create_else_block7(ctx) { + let p; + return { + c() { + p = element("p"); + p.textContent = "No outgoings edges"; + attr(p, "class", "search-empty-state"); + }, + m(target, anchor) { + insert(target, p, anchor); + }, + p: noop, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(p); + } + } + }; +} +function create_if_block13(ctx) { + let div; + let current; + let each_value = ensure_array_like( + /*plugin*/ + ctx[0].settings.edge_fields + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block10(get_each_context10(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + div = element("div"); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + }, + m(target, anchor) { + 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(ctx2, dirty) { + if (dirty & /*sort, grouped_out_edges, plugin, show_attributes, collapse*/ + 121) { + each_value = ensure_array_like( + /*plugin*/ + ctx2[0].settings.edge_fields + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context10(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block10(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_each(each_blocks, detaching); + } + }; +} +function create_if_block_15(ctx) { + let matrixedgefield; + let current; + matrixedgefield = new MatrixEdgeField_default({ + props: { + sort: ( + /*sort*/ + ctx[5] + ), + edges: ( + /*edges*/ + ctx[14] + ), + field: ( + /*field*/ + ctx[13] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + show_attributes: ( + /*show_attributes*/ + ctx[3] + ), + open: !/*collapse*/ + ctx[4] + } + }); + return { + c() { + create_component(matrixedgefield.$$.fragment); + }, + m(target, anchor) { + mount_component(matrixedgefield, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const matrixedgefield_changes = {}; + if (dirty & /*sort*/ + 32) + matrixedgefield_changes.sort = /*sort*/ + ctx2[5]; + if (dirty & /*grouped_out_edges, plugin*/ + 65) + matrixedgefield_changes.edges = /*edges*/ + ctx2[14]; + if (dirty & /*plugin*/ + 1) + matrixedgefield_changes.field = /*field*/ + ctx2[13]; + if (dirty & /*plugin*/ + 1) + matrixedgefield_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*show_attributes*/ + 8) + matrixedgefield_changes.show_attributes = /*show_attributes*/ + ctx2[3]; + if (dirty & /*collapse*/ + 16) + matrixedgefield_changes.open = !/*collapse*/ + ctx2[4]; + matrixedgefield.$set(matrixedgefield_changes); + }, + i(local) { + if (current) + return; + transition_in(matrixedgefield.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(matrixedgefield.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(matrixedgefield, detaching); + } + }; +} +function create_each_block10(ctx) { + var _a; + let if_block_anchor; + let current; + let if_block = ( + /*edges*/ + ((_a = ctx[14]) == null ? void 0 : _a.length) && create_if_block_15(ctx) + ); + return { + c() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (if_block) + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + var _a2; + if ( + /*edges*/ + (_a2 = ctx2[14]) == null ? void 0 : _a2.length + ) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & /*grouped_out_edges, plugin*/ + 65) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block_15(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if (if_block) + if_block.d(detaching); + } + }; +} +function create_key_block5(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block13, create_else_block7]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*grouped_out_edges*/ + ctx2[6] + ) + 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() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_blocks[current_block_type_index].m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + 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](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if_blocks[current_block_type_index].d(detaching); + } + }; +} +function create_fragment47(ctx) { + let div2; + let div1; + let div0; + let rebuildgraphbutton; + let t0; + let edgesortidselector; + let updating_edge_sort_id; + let t1; + let chevroncollapsebutton; + let updating_collapse; + let t2; + let showattributesselectormenu; + let updating_show_attributes; + let t3; + let fieldgroupselector; + let updating_field_group_labels; + let t4; + let previous_key = ( + /*grouped_out_edges*/ + ctx[6] + ); + let current; + rebuildgraphbutton = new RebuildGraphButton_default({ + props: { + cls: "clickable-icon nav-action-button", + plugin: ( + /*plugin*/ + ctx[0] + ) + } + }); + function edgesortidselector_edge_sort_id_binding(value) { + ctx[9](value); + } + let edgesortidselector_props = { + cls: "clickable-icon nav-action-button", + exclude_fields: ["field", "neighbour-field:"] + }; + if ( + /*edge_sort_id*/ + ctx[1] !== void 0 + ) { + edgesortidselector_props.edge_sort_id = /*edge_sort_id*/ + ctx[1]; + } + edgesortidselector = new EdgeSortIdSelector_default({ props: edgesortidselector_props }); + binding_callbacks.push(() => bind(edgesortidselector, "edge_sort_id", edgesortidselector_edge_sort_id_binding)); + function chevroncollapsebutton_collapse_binding(value) { + ctx[10](value); + } + let chevroncollapsebutton_props = { cls: "clickable-icon nav-action-button" }; + if ( + /*collapse*/ + ctx[4] !== void 0 + ) { + chevroncollapsebutton_props.collapse = /*collapse*/ + ctx[4]; + } + chevroncollapsebutton = new ChevronCollapseButton_default({ props: chevroncollapsebutton_props }); + binding_callbacks.push(() => bind(chevroncollapsebutton, "collapse", chevroncollapsebutton_collapse_binding)); + function showattributesselectormenu_show_attributes_binding(value) { + ctx[11](value); + } + let showattributesselectormenu_props = { + cls: "clickable-icon nav-action-button", + exclude_attributes: ["field", "explicit"] + }; + if ( + /*show_attributes*/ + ctx[3] !== void 0 + ) { + showattributesselectormenu_props.show_attributes = /*show_attributes*/ + ctx[3]; + } + showattributesselectormenu = new ShowAttributesSelectorMenu_default({ props: showattributesselectormenu_props }); + binding_callbacks.push(() => bind(showattributesselectormenu, "show_attributes", showattributesselectormenu_show_attributes_binding)); + function fieldgroupselector_field_group_labels_binding(value) { + ctx[12](value); + } + let fieldgroupselector_props = { + cls: "clickable-icon nav-action-button", + edge_field_groups: ( + /*plugin*/ + ctx[0].settings.edge_field_groups + ) + }; + if ( + /*field_group_labels*/ + ctx[2] !== void 0 + ) { + fieldgroupselector_props.field_group_labels = /*field_group_labels*/ + ctx[2]; + } + fieldgroupselector = new FieldGroupLabelsSelector_default({ props: fieldgroupselector_props }); + binding_callbacks.push(() => bind(fieldgroupselector, "field_group_labels", fieldgroupselector_field_group_labels_binding)); + let key_block = create_key_block5(ctx); + return { + c() { + div2 = element("div"); + div1 = element("div"); + div0 = element("div"); + create_component(rebuildgraphbutton.$$.fragment); + t0 = space(); + create_component(edgesortidselector.$$.fragment); + t1 = space(); + create_component(chevroncollapsebutton.$$.fragment); + t2 = space(); + create_component(showattributesselectormenu.$$.fragment); + t3 = space(); + create_component(fieldgroupselector.$$.fragment); + t4 = space(); + key_block.c(); + attr(div0, "class", "nav-buttons-container"); + attr(div1, "class", "nav-header"); + attr(div2, "class", "markdown-rendered BC-matrix-view"); + }, + m(target, anchor) { + insert(target, div2, anchor); + append(div2, div1); + append(div1, div0); + mount_component(rebuildgraphbutton, div0, null); + append(div0, t0); + mount_component(edgesortidselector, div0, null); + append(div0, t1); + mount_component(chevroncollapsebutton, div0, null); + append(div0, t2); + mount_component(showattributesselectormenu, div0, null); + append(div0, t3); + mount_component(fieldgroupselector, div0, null); + append(div2, t4); + key_block.m(div2, null); + current = true; + }, + p(ctx2, [dirty]) { + const rebuildgraphbutton_changes = {}; + if (dirty & /*plugin*/ + 1) + rebuildgraphbutton_changes.plugin = /*plugin*/ + ctx2[0]; + rebuildgraphbutton.$set(rebuildgraphbutton_changes); + const edgesortidselector_changes = {}; + if (!updating_edge_sort_id && dirty & /*edge_sort_id*/ + 2) { + updating_edge_sort_id = true; + edgesortidselector_changes.edge_sort_id = /*edge_sort_id*/ + ctx2[1]; + add_flush_callback(() => updating_edge_sort_id = false); + } + edgesortidselector.$set(edgesortidselector_changes); + const chevroncollapsebutton_changes = {}; + if (!updating_collapse && dirty & /*collapse*/ + 16) { + updating_collapse = true; + chevroncollapsebutton_changes.collapse = /*collapse*/ + ctx2[4]; + add_flush_callback(() => updating_collapse = false); + } + chevroncollapsebutton.$set(chevroncollapsebutton_changes); + const showattributesselectormenu_changes = {}; + if (!updating_show_attributes && dirty & /*show_attributes*/ + 8) { + updating_show_attributes = true; + showattributesselectormenu_changes.show_attributes = /*show_attributes*/ + ctx2[3]; + add_flush_callback(() => updating_show_attributes = false); + } + showattributesselectormenu.$set(showattributesselectormenu_changes); + const fieldgroupselector_changes = {}; + if (dirty & /*plugin*/ + 1) + fieldgroupselector_changes.edge_field_groups = /*plugin*/ + ctx2[0].settings.edge_field_groups; + if (!updating_field_group_labels && dirty & /*field_group_labels*/ + 4) { + updating_field_group_labels = true; + fieldgroupselector_changes.field_group_labels = /*field_group_labels*/ + ctx2[2]; + add_flush_callback(() => updating_field_group_labels = false); + } + fieldgroupselector.$set(fieldgroupselector_changes); + if (dirty & /*grouped_out_edges*/ + 64 && safe_not_equal(previous_key, previous_key = /*grouped_out_edges*/ + ctx2[6])) { + group_outros(); + transition_out(key_block, 1, 1, noop); + check_outros(); + key_block = create_key_block5(ctx2); + key_block.c(); + transition_in(key_block, 1); + key_block.m(div2, null); + } else { + key_block.p(ctx2, dirty); + } + }, + i(local) { + if (current) + return; + transition_in(rebuildgraphbutton.$$.fragment, local); + transition_in(edgesortidselector.$$.fragment, local); + transition_in(chevroncollapsebutton.$$.fragment, local); + transition_in(showattributesselectormenu.$$.fragment, local); + transition_in(fieldgroupselector.$$.fragment, local); + transition_in(key_block); + current = true; + }, + o(local) { + transition_out(rebuildgraphbutton.$$.fragment, local); + transition_out(edgesortidselector.$$.fragment, local); + transition_out(chevroncollapsebutton.$$.fragment, local); + transition_out(showattributesselectormenu.$$.fragment, local); + transition_out(fieldgroupselector.$$.fragment, local); + transition_out(key_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div2); + } + destroy_component(rebuildgraphbutton); + destroy_component(edgesortidselector); + destroy_component(chevroncollapsebutton); + destroy_component(showattributesselectormenu); + destroy_component(fieldgroupselector); + key_block.d(detaching); + } + }; +} +function instance47($$self, $$props, $$invalidate) { + let edge_field_labels; + let grouped_out_edges; + let sort; + let $active_file_store; + component_subscribe($$self, active_file_store, ($$value) => $$invalidate(8, $active_file_store = $$value)); + let { plugin } = $$props; + let { edge_sort_id, field_group_labels, show_attributes, collapse } = plugin.settings.views.side.matrix; + function edgesortidselector_edge_sort_id_binding(value) { + edge_sort_id = value; + $$invalidate(1, edge_sort_id); + } + function chevroncollapsebutton_collapse_binding(value) { + collapse = value; + $$invalidate(4, collapse); + } + function showattributesselectormenu_show_attributes_binding(value) { + show_attributes = value; + $$invalidate(3, show_attributes); + } + function fieldgroupselector_field_group_labels_binding(value) { + field_group_labels = value; + $$invalidate(2, field_group_labels); + } + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*plugin, field_group_labels*/ + 5) { + $: + $$invalidate(7, edge_field_labels = resolve_field_group_labels(plugin.settings.edge_field_groups, field_group_labels)); + } + if ($$self.$$.dirty & /*$active_file_store, plugin, edge_field_labels*/ + 385) { + $: + $$invalidate(6, grouped_out_edges = $active_file_store && // Even tho we ensure the graph is built before the views are registered, + // Existing views still try render before the graph is built. + plugin.graph.hasNode($active_file_store.path) ? group_by(plugin.graph.get_out_edges($active_file_store.path).filter((e) => has_edge_attrs(e, { $or_fields: edge_field_labels })), (e) => e.attr.field) : null); + } + if ($$self.$$.dirty & /*edge_sort_id, plugin*/ + 3) { + $: + $$invalidate(5, sort = get_edge_sorter(edge_sort_id, plugin.graph)); + } + }; + return [ + plugin, + edge_sort_id, + field_group_labels, + show_attributes, + collapse, + sort, + grouped_out_edges, + edge_field_labels, + $active_file_store, + edgesortidselector_edge_sort_id_binding, + chevroncollapsebutton_collapse_binding, + showattributesselectormenu_show_attributes_binding, + fieldgroupselector_field_group_labels_binding + ]; +} +var Matrix = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance47, create_fragment47, safe_not_equal, { plugin: 0 }); + } +}; +var Matrix_default = Matrix; + +// src/views/matrix.ts +var MatrixView = class extends import_obsidian25.ItemView { + constructor(leaf, plugin) { + super(leaf); + this.icon = "blinds"; + this.plugin = plugin; + } + getViewType() { + return VIEW_IDS.matrix; + } + getDisplayText() { + return "Matrix view"; + } + async onOpen() { + const container = this.containerEl.children[1]; + container.empty(); + this.component = new Matrix_default({ + target: this.contentEl, + props: { plugin: this.plugin } + }); + } + async onClose() { + var _a; + (_a = this.component) == null ? void 0 : _a.$destroy(); + } +}; + +// src/api/index.ts +var BCAPI = class { + constructor(plugin) { + this.refresh = () => this.plugin.refresh(); + /** @deprecated Use refresh */ + this.refreshIndex = this.refresh; + /** @deprecated Filter edges of plugin.graph instead */ + this.getSubForFields = (fields, g = this.plugin.graph) => { + }; + this.build_tree = Traverse.build_tree; + this.breadth_first_traversal = Traverse.breadth_first; + this.create_list_index = (start_node = ((_a) => (_a = get_store_value(active_file_store)) == null ? void 0 : _a.path)(), options) => { + if (!start_node) + throw new Error("No active file"); + return ListIndex.build( + this.plugin.graph, + start_node, + Object.assign({ ...ListIndex.DEFAULT_OPTIONS }, options) + ); + }; + // BREAKING + /** @deprecated Use flatten_all_paths and flat_paths_to_index_list instead. Or, create_list_index */ + this.createIndex = () => { + }; + this.get_neighbours = (source = ((_b) => (_b = get_store_value(active_file_store)) == null ? void 0 : _b.path)()) => source && this.plugin.graph.hasNode(source) ? this.plugin.graph.get_out_edges(source) : []; + /** @deprecated Use get_neighbours instead */ + this.getMatrixNeighbours = this.get_neighbours; + this.plugin = plugin; + } + get fields() { + return this.plugin.settings.edge_fields; + } + get field_groups() { + return this.plugin.settings.edge_field_groups; + } +}; + +// src/codeblocks/MDRC.ts +var import_obsidian27 = require("obsidian"); + +// src/components/codeblocks/CodeblockErrors.svelte +function create_if_block14(ctx) { + let p0; + let t1; + let p1; + let t3; + let div; + let rendermarkdown; + let t4; + let hr; + let t5; + let p2; + let t9; + let p3; + let t10; + let code; + let t11_value = ( + /*plugin*/ + ctx[0].manifest.version + "" + ); + let t11; + let current; + rendermarkdown = new RenderMarkdown_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + markdown: ( + /*markdown*/ + ctx[2] + ) + } + }); + return { + c() { + p0 = element("p"); + p0.textContent = "Breadcrumbs Codeblock Errors"; + t1 = space(); + p1 = element("p"); + p1.textContent = "The codeblock YAML has errors in the following keys/properties:"; + t3 = space(); + div = element("div"); + create_component(rendermarkdown.$$.fragment); + t4 = space(); + hr = element("hr"); + t5 = space(); + p2 = element("p"); + p2.innerHTML = `See the codeblock docs for more info`; + t9 = space(); + p3 = element("p"); + t10 = text("Version: "); + code = element("code"); + t11 = text(t11_value); + attr(p0, "class", "text-warning text-lg font-semibold"); + attr(div, "class", "BC-codeblock-errors"); + }, + m(target, anchor) { + insert(target, p0, anchor); + insert(target, t1, anchor); + insert(target, p1, anchor); + insert(target, t3, anchor); + insert(target, div, anchor); + mount_component(rendermarkdown, div, null); + insert(target, t4, anchor); + insert(target, hr, anchor); + insert(target, t5, anchor); + insert(target, p2, anchor); + insert(target, t9, anchor); + insert(target, p3, anchor); + append(p3, t10); + append(p3, code); + append(code, t11); + current = true; + }, + p(ctx2, dirty) { + const rendermarkdown_changes = {}; + if (dirty & /*plugin*/ + 1) + rendermarkdown_changes.plugin = /*plugin*/ + ctx2[0]; + rendermarkdown.$set(rendermarkdown_changes); + if ((!current || dirty & /*plugin*/ + 1) && t11_value !== (t11_value = /*plugin*/ + ctx2[0].manifest.version + "")) + set_data(t11, t11_value); + }, + i(local) { + if (current) + return; + transition_in(rendermarkdown.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(rendermarkdown.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(p0); + detach(t1); + detach(p1); + detach(t3); + detach(div); + detach(t4); + detach(hr); + detach(t5); + detach(p2); + detach(t9); + detach(p3); + } + destroy_component(rendermarkdown); + } + }; +} +function create_fragment48(ctx) { + let if_block_anchor; + let current; + let if_block = ( + /*errors*/ + ctx[1].length && create_if_block14(ctx) + ); + return { + c() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (if_block) + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, [dirty]) { + if ( + /*errors*/ + ctx2[1].length + ) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & /*errors*/ + 2) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block14(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if (if_block) + if_block.d(detaching); + } + }; +} +function instance48($$self, $$props, $$invalidate) { + let { plugin } = $$props; + let { errors } = $$props; + const markdown = errors.map((e) => `- **\`${e.path}\`**: ${e.message}`).join("\n"); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("errors" in $$props2) + $$invalidate(1, errors = $$props2.errors); + }; + return [plugin, errors, markdown]; +} +var CodeblockErrors = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance48, create_fragment48, safe_not_equal, { plugin: 0, errors: 1 }); + } +}; +var CodeblockErrors_default = CodeblockErrors; + +// src/components/button/CopyToClipboardButton.svelte +function create_else_block8(ctx) { + let clipboardicon; + let current; + clipboardicon = new clipboard_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(clipboardicon.$$.fragment); + }, + m(target, anchor) { + mount_component(clipboardicon, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(clipboardicon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(clipboardicon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(clipboardicon, detaching); + } + }; +} +function create_if_block15(ctx) { + let checkicon; + let current; + checkicon = new check_default({ props: { size: ICON_SIZE } }); + return { + c() { + create_component(checkicon.$$.fragment); + }, + m(target, anchor) { + mount_component(checkicon, target, anchor); + current = true; + }, + i(local) { + if (current) + return; + transition_in(checkicon.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(checkicon.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(checkicon, detaching); + } + }; +} +function create_fragment49(ctx) { + let button; + let current_block_type_index; + let if_block; + let button_aria_label_value; + let current; + let mounted; + let dispose; + const if_block_creators = [create_if_block15, create_else_block8]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*copied*/ + ctx2[4] + ) + 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() { + button = element("button"); + if_block.c(); + attr( + button, + "class", + /*cls*/ + ctx[0] + ); + attr(button, "aria-label", button_aria_label_value = /*copied*/ + ctx[4] ? "Copied!" : ( + /*aria_label*/ + ctx[2] + )); + }, + m(target, anchor) { + insert(target, button, anchor); + if_blocks[current_block_type_index].m(button, null); + current = true; + if (!mounted) { + dispose = listen( + button, + "click", + /*click_handler*/ + ctx[5] + ); + mounted = true; + } + }, + p(ctx2, [dirty]) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index !== previous_block_index) { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + 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](ctx2); + if_block.c(); + } else { + } + transition_in(if_block, 1); + if_block.m(button, null); + } + if (!current || dirty & /*cls*/ + 1) { + attr( + button, + "class", + /*cls*/ + ctx2[0] + ); + } + if (!current || dirty & /*copied, aria_label*/ + 20 && button_aria_label_value !== (button_aria_label_value = /*copied*/ + ctx2[4] ? "Copied!" : ( + /*aria_label*/ + ctx2[2] + ))) { + attr(button, "aria-label", button_aria_label_value); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(button); + } + if_blocks[current_block_type_index].d(); + mounted = false; + dispose(); + } + }; +} +function instance49($$self, $$props, $$invalidate) { + let { cls = "" } = $$props; + let { text: text2 } = $$props; + let { aria_label = "Copy to Clipboard" } = $$props; + let { options = {} } = $$props; + let copied = false; + const click_handler = () => { + $$invalidate(4, copied = true); + copy_to_clipboard(text2, options); + setTimeout(() => $$invalidate(4, copied = false), 2500); + }; + $$self.$$set = ($$props2) => { + if ("cls" in $$props2) + $$invalidate(0, cls = $$props2.cls); + if ("text" in $$props2) + $$invalidate(1, text2 = $$props2.text); + if ("aria_label" in $$props2) + $$invalidate(2, aria_label = $$props2.aria_label); + if ("options" in $$props2) + $$invalidate(3, options = $$props2.options); + }; + return [cls, text2, aria_label, options, copied, click_handler]; +} +var CopyToClipboardButton = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance49, create_fragment49, safe_not_equal, { + cls: 0, + text: 1, + aria_label: 2, + options: 3 + }); + } +}; +var CopyToClipboardButton_default = CopyToClipboardButton; + +// src/components/codeblocks/CodeblockMarkmap.svelte +function create_if_block_16(ctx) { + let h3; + let t_value = ( + /*options*/ + ctx[1].title + "" + ); + let t; + return { + c() { + h3 = element("h3"); + t = text(t_value); + attr(h3, "class", "BC-codeblock-markmap-title"); + }, + m(target, anchor) { + insert(target, h3, anchor); + append(h3, t); + }, + p(ctx2, dirty) { + if (dirty & /*options*/ + 2 && t_value !== (t_value = /*options*/ + ctx2[1].title + "")) + set_data(t, t_value); + }, + d(detaching) { + if (detaching) { + detach(h3); + } + } + }; +} +function create_else_block9(ctx) { + let p; + return { + c() { + p = element("p"); + p.textContent = "No paths found."; + attr(p, "class", "search-empty-state"); + }, + m(target, anchor) { + insert(target, p, anchor); + }, + p: noop, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(p); + } + } + }; +} +function create_if_block16(ctx) { + let div1; + let div0; + let copytoclipboardbutton; + let t; + let renderexternalcodeblock; + let current; + copytoclipboardbutton = new CopyToClipboardButton_default({ + props: { + text: ( + /*code*/ + ctx[4] + ), + cls: "clickable-icon nav-action-button" + } + }); + renderexternalcodeblock = new RenderExternalCodeblock_default({ + props: { + code: ( + /*code*/ + ctx[4] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + source_path: ( + /*source_path*/ + ctx[5] + ), + type: "markmap" + } + }); + return { + c() { + div1 = element("div"); + div0 = element("div"); + create_component(copytoclipboardbutton.$$.fragment); + t = space(); + create_component(renderexternalcodeblock.$$.fragment); + attr(div0, "class", "absolute left-2 top-2 flex"); + attr(div1, "class", "relative"); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, div0); + mount_component(copytoclipboardbutton, div0, null); + append(div1, t); + mount_component(renderexternalcodeblock, div1, null); + current = true; + }, + p(ctx2, dirty) { + const copytoclipboardbutton_changes = {}; + if (dirty & /*code*/ + 16) + copytoclipboardbutton_changes.text = /*code*/ + ctx2[4]; + copytoclipboardbutton.$set(copytoclipboardbutton_changes); + const renderexternalcodeblock_changes = {}; + if (dirty & /*code*/ + 16) + renderexternalcodeblock_changes.code = /*code*/ + ctx2[4]; + if (dirty & /*plugin*/ + 1) + renderexternalcodeblock_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*source_path*/ + 32) + renderexternalcodeblock_changes.source_path = /*source_path*/ + ctx2[5]; + renderexternalcodeblock.$set(renderexternalcodeblock_changes); + }, + i(local) { + if (current) + return; + transition_in(copytoclipboardbutton.$$.fragment, local); + transition_in(renderexternalcodeblock.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(copytoclipboardbutton.$$.fragment, local); + transition_out(renderexternalcodeblock.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div1); + } + destroy_component(copytoclipboardbutton); + destroy_component(renderexternalcodeblock); + } + }; +} +function create_fragment50(ctx) { + let div; + let codeblockerrors; + let t0; + let t1; + let current_block_type_index; + let if_block1; + let current; + codeblockerrors = new CodeblockErrors_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + errors: ( + /*errors*/ + ctx[2] + ) + } + }); + let if_block0 = ( + /*options*/ + ctx[1].title && create_if_block_16(ctx) + ); + const if_block_creators = [create_if_block16, create_else_block9]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*tree*/ + ctx2[3].length + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, -1); + if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + div = element("div"); + create_component(codeblockerrors.$$.fragment); + t0 = space(); + if (if_block0) + if_block0.c(); + t1 = space(); + if_block1.c(); + attr(div, "class", "BC-codeblock-markmap"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(codeblockerrors, div, null); + append(div, t0); + if (if_block0) + if_block0.m(div, null); + append(div, t1); + if_blocks[current_block_type_index].m(div, null); + current = true; + }, + p(ctx2, [dirty]) { + const codeblockerrors_changes = {}; + if (dirty & /*plugin*/ + 1) + codeblockerrors_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*errors*/ + 4) + codeblockerrors_changes.errors = /*errors*/ + ctx2[2]; + codeblockerrors.$set(codeblockerrors_changes); + if ( + /*options*/ + ctx2[1].title + ) { + if (if_block0) { + if_block0.p(ctx2, dirty); + } else { + if_block0 = create_if_block_16(ctx2); + if_block0.c(); + if_block0.m(div, t1); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block1 = if_blocks[current_block_type_index]; + if (!if_block1) { + if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block1.c(); + } else { + if_block1.p(ctx2, dirty); + } + transition_in(if_block1, 1); + if_block1.m(div, null); + } + }, + i(local) { + if (current) + return; + transition_in(codeblockerrors.$$.fragment, local); + transition_in(if_block1); + current = true; + }, + o(local) { + transition_out(codeblockerrors.$$.fragment, local); + transition_out(if_block1); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(codeblockerrors); + if (if_block0) + if_block0.d(); + if_blocks[current_block_type_index].d(); + } + }; +} +function instance50($$self, $$props, $$invalidate) { + let source_path; + let code; + let $active_file_store; + component_subscribe($$self, active_file_store, ($$value) => $$invalidate(9, $active_file_store = $$value)); + var _a, _b; + let { plugin } = $$props; + let { options } = $$props; + let { errors } = $$props; + let { file_path } = $$props; + const sort = get_edge_sorter( + // @ts-expect-error: ts(2345) + options.sort, + plugin.graph + ); + const { show_node_options } = plugin.settings.views.codeblocks; + let tree = []; + const update2 = () => { + $$invalidate(3, tree = Traverse.sort_edge_tree(get_tree(), sort)); + }; + const base_traversal = (attr2) => Traverse.build_tree(plugin.graph, source_path, { max_depth: options.depth[1] }, (e) => has_edge_attrs(e, Object.assign(Object.assign({}, attr2), { + $or_target_ids: options["dataview-from-paths"] + }))); + const edge_field_labels = (_a = options.fields) !== null && _a !== void 0 ? _a : plugin.settings.edge_fields.map((f) => f.label); + const get_tree = () => { + if (source_path && plugin.graph.hasNode(source_path)) { + const traversal = options["merge-fields"] ? base_traversal({ $or_fields: options.fields }) : edge_field_labels.flatMap((field) => base_traversal({ field })); + return options.flat ? Traverse.flatten_tree(traversal).map((item) => ({ depth: 0, children: [], edge: item.edge })) : traversal; + } else { + return []; + } + }; + onMount(update2); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("options" in $$props2) + $$invalidate(1, options = $$props2.options); + if ("errors" in $$props2) + $$invalidate(2, errors = $$props2.errors); + if ("file_path" in $$props2) + $$invalidate(6, file_path = $$props2.file_path); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*file_path, $active_file_store*/ + 576) { + $: + $$invalidate(5, source_path = file_path ? file_path : $active_file_store ? $active_file_store.path : ""); + } + if ($$self.$$.dirty & /*tree, plugin, options, _b*/ + 267) { + $: + $$invalidate(4, code = ListIndex.edge_tree_to_list_index(tree, Object.assign(Object.assign({}, plugin.settings.commands.list_index.default_options), { + show_node_options, + show_attributes: $$invalidate(8, _b = options["show-attributes"]) !== null && _b !== void 0 ? _b : [] + }))); + } + }; + return [ + plugin, + options, + errors, + tree, + code, + source_path, + file_path, + update2, + _b, + $active_file_store + ]; +} +var CodeblockMarkmap = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance50, create_fragment50, safe_not_equal, { + plugin: 0, + options: 1, + errors: 2, + file_path: 6, + update: 7 + }); + } + get update() { + return this.$$.ctx[7]; + } +}; +var CodeblockMarkmap_default = CodeblockMarkmap; + +// src/graph/distance.ts +var from_traversal_items = (items) => { + const distances = /* @__PURE__ */ new Map(); + items.forEach((item) => { + var _a; + distances.set( + item.edge.target_id, + Math.min( + (_a = distances.get(item.edge.target_id)) != null ? _a : Infinity, + item.depth + 1 + ) + ); + }); + return distances; +}; +var Distance = { + from_traversal_items +}; + +// src/utils/numbers.ts +var is_between = (value, min, max) => value >= min && value <= max; + +// src/components/codeblocks/CodeblockMermaid.svelte +function create_if_block_17(ctx) { + let h3; + let t_value = ( + /*options*/ + ctx[1].title + "" + ); + let t; + return { + c() { + h3 = element("h3"); + t = text(t_value); + attr(h3, "class", "BC-codeblock-mermaid-title"); + }, + m(target, anchor) { + insert(target, h3, anchor); + append(h3, t); + }, + p(ctx2, dirty) { + if (dirty & /*options*/ + 2 && t_value !== (t_value = /*options*/ + ctx2[1].title + "")) + set_data(t, t_value); + }, + d(detaching) { + if (detaching) { + detach(h3); + } + } + }; +} +function create_else_block10(ctx) { + let p; + return { + c() { + p = element("p"); + p.textContent = "No paths found."; + attr(p, "class", "search-empty-state"); + }, + m(target, anchor) { + insert(target, p, anchor); + }, + p: noop, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(p); + } + } + }; +} +function create_if_block17(ctx) { + let div1; + let div0; + let copytoclipboardbutton; + let t0; + let button0; + let imageicon; + let t1; + let button1; + let pencilicon; + let t2; + let renderexternalcodeblock; + let current; + let mounted; + let dispose; + copytoclipboardbutton = new CopyToClipboardButton_default({ + props: { + text: ( + /*code*/ + ctx[4] + ), + cls: "clickable-icon nav-action-button" + } + }); + imageicon = new image_default({ props: { size: ICON_SIZE } }); + pencilicon = new pencil_default({ props: { size: ICON_SIZE } }); + renderexternalcodeblock = new RenderExternalCodeblock_default({ + props: { + code: ( + /*code*/ + ctx[4] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + source_path: ( + /*source_path*/ + ctx[5] + ), + type: "mermaid" + } + }); + return { + c() { + div1 = element("div"); + div0 = element("div"); + create_component(copytoclipboardbutton.$$.fragment); + t0 = space(); + button0 = element("button"); + create_component(imageicon.$$.fragment); + t1 = space(); + button1 = element("button"); + create_component(pencilicon.$$.fragment); + t2 = space(); + create_component(renderexternalcodeblock.$$.fragment); + attr(button0, "role", "link"); + attr(button0, "aria-label", "View Image on mermaid.ink"); + attr(button0, "class", "clickable-icon nav-action-button"); + attr(button1, "role", "link"); + attr(button1, "aria-label", "Live Edit on mermaid.live"); + attr(button1, "class", "clickable-icon nav-action-button"); + attr(div0, "class", "absolute left-2 top-2 flex"); + attr(div1, "class", "relative"); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, div0); + mount_component(copytoclipboardbutton, div0, null); + append(div0, t0); + append(div0, button0); + mount_component(imageicon, button0, null); + append(div0, t1); + append(div0, button1); + mount_component(pencilicon, button1, null); + append(div1, t2); + mount_component(renderexternalcodeblock, div1, null); + current = true; + if (!mounted) { + dispose = [ + listen( + button0, + "click", + /*click_handler*/ + ctx[12] + ), + listen( + button1, + "click", + /*click_handler_1*/ + ctx[13] + ) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + const copytoclipboardbutton_changes = {}; + if (dirty & /*code*/ + 16) + copytoclipboardbutton_changes.text = /*code*/ + ctx2[4]; + copytoclipboardbutton.$set(copytoclipboardbutton_changes); + const renderexternalcodeblock_changes = {}; + if (dirty & /*code*/ + 16) + renderexternalcodeblock_changes.code = /*code*/ + ctx2[4]; + if (dirty & /*plugin*/ + 1) + renderexternalcodeblock_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*source_path*/ + 32) + renderexternalcodeblock_changes.source_path = /*source_path*/ + ctx2[5]; + renderexternalcodeblock.$set(renderexternalcodeblock_changes); + }, + i(local) { + if (current) + return; + transition_in(copytoclipboardbutton.$$.fragment, local); + transition_in(imageicon.$$.fragment, local); + transition_in(pencilicon.$$.fragment, local); + transition_in(renderexternalcodeblock.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(copytoclipboardbutton.$$.fragment, local); + transition_out(imageicon.$$.fragment, local); + transition_out(pencilicon.$$.fragment, local); + transition_out(renderexternalcodeblock.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div1); + } + destroy_component(copytoclipboardbutton); + destroy_component(imageicon); + destroy_component(pencilicon); + destroy_component(renderexternalcodeblock); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment51(ctx) { + let div; + let codeblockerrors; + let t0; + let t1; + let current_block_type_index; + let if_block1; + let current; + codeblockerrors = new CodeblockErrors_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + errors: ( + /*errors*/ + ctx[2] + ) + } + }); + let if_block0 = ( + /*options*/ + ctx[1].title && create_if_block_17(ctx) + ); + const if_block_creators = [create_if_block17, create_else_block10]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*traversal_items*/ + ctx2[3].length + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, -1); + if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + div = element("div"); + create_component(codeblockerrors.$$.fragment); + t0 = space(); + if (if_block0) + if_block0.c(); + t1 = space(); + if_block1.c(); + attr(div, "class", "BC-codeblock-mermaid"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(codeblockerrors, div, null); + append(div, t0); + if (if_block0) + if_block0.m(div, null); + append(div, t1); + if_blocks[current_block_type_index].m(div, null); + current = true; + }, + p(ctx2, [dirty]) { + const codeblockerrors_changes = {}; + if (dirty & /*plugin*/ + 1) + codeblockerrors_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*errors*/ + 4) + codeblockerrors_changes.errors = /*errors*/ + ctx2[2]; + codeblockerrors.$set(codeblockerrors_changes); + if ( + /*options*/ + ctx2[1].title + ) { + if (if_block0) { + if_block0.p(ctx2, dirty); + } else { + if_block0 = create_if_block_17(ctx2); + if_block0.c(); + if_block0.m(div, t1); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block1 = if_blocks[current_block_type_index]; + if (!if_block1) { + if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block1.c(); + } else { + if_block1.p(ctx2, dirty); + } + transition_in(if_block1, 1); + if_block1.m(div, null); + } + }, + i(local) { + if (current) + return; + transition_in(codeblockerrors.$$.fragment, local); + transition_in(if_block1); + current = true; + }, + o(local) { + transition_out(codeblockerrors.$$.fragment, local); + transition_out(if_block1); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(codeblockerrors); + if (if_block0) + if_block0.d(); + if_blocks[current_block_type_index].d(); + } + }; +} +function instance51($$self, $$props, $$invalidate) { + let source_path; + let edges; + let code; + let $active_file_store; + component_subscribe($$self, active_file_store, ($$value) => $$invalidate(11, $active_file_store = $$value)); + var _a; + let { plugin } = $$props; + let { options } = $$props; + let { errors } = $$props; + let { file_path } = $$props; + const sort = get_edge_sorter( + // @ts-expect-error: ts(2345) + options.sort, + plugin.graph + ); + let traversal_items = []; + let distances = /* @__PURE__ */ new Map(); + const update2 = () => { + $$invalidate(3, traversal_items = get_traversal_items()); + $$invalidate(9, distances = Distance.from_traversal_items(traversal_items)); + }; + const base_traversal = (attr2) => Traverse.gather_items(plugin.graph, source_path, (item) => has_edge_attrs(item.edge, Object.assign(Object.assign({}, attr2), { + $or_target_ids: options["dataview-from-paths"] + }))); + const edge_field_labels = (_a = options.fields) !== null && _a !== void 0 ? _a : plugin.settings.edge_fields.map((f) => f.label); + const get_traversal_items = () => { + if (source_path && plugin.graph.hasNode(source_path)) { + return options["merge-fields"] ? base_traversal({ $or_fields: options.fields }) : edge_field_labels.flatMap((field) => base_traversal({ field })); + } else { + return []; + } + }; + onMount(update2); + const click_handler = () => { + window.open(Mermaid.to_image_link(code), "_blank"); + }; + const click_handler_1 = () => { + window.open(Mermaid.to_live_edit_link(code), "_blank"); + }; + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("options" in $$props2) + $$invalidate(1, options = $$props2.options); + if ("errors" in $$props2) + $$invalidate(2, errors = $$props2.errors); + if ("file_path" in $$props2) + $$invalidate(6, file_path = $$props2.file_path); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*file_path, $active_file_store*/ + 2112) { + $: + $$invalidate(5, source_path = file_path ? file_path : $active_file_store ? $active_file_store.path : ""); + } + if ($$self.$$.dirty & /*traversal_items, distances, options*/ + 522) { + $: + $$invalidate(10, edges = traversal_items.filter((item) => { + var _a2; + return is_between( + (_a2 = distances.get(item.edge.target_id)) !== null && _a2 !== void 0 ? _a2 : 0, + options.depth[0] + 1, + options.depth[1] + ); + }).map((item) => item.edge).sort(sort)); + } + if ($$self.$$.dirty & /*edges, source_path, options, plugin*/ + 1059) { + $: + $$invalidate(4, code = Mermaid.from_edges(edges, { + kind: "graph", + click: { method: "class" }, + active_node_id: source_path, + renderer: options["mermaid-renderer"], + curve_style: options["mermaid-curve"], + direction: options["mermaid-direction"], + show_attributes: options["show-attributes"], + get_node_label: (node_id, _attr) => { + const file = plugin.app.vault.getFileByPath(node_id); + return file ? plugin.app.fileManager.generateMarkdownLink(file, source_path).slice(2, -2) : Paths.drop_ext(Links.resolve_to_absolute_path(plugin.app, node_id, source_path)); + } + })); + } + if ($$self.$$.dirty & /*code*/ + 16) { + $: + log.debug(code); + } + }; + return [ + plugin, + options, + errors, + traversal_items, + code, + source_path, + file_path, + update2, + _a, + distances, + edges, + $active_file_store, + click_handler, + click_handler_1 + ]; +} +var CodeblockMermaid = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance51, create_fragment51, safe_not_equal, { + plugin: 0, + options: 1, + errors: 2, + file_path: 6, + update: 7 + }); + } + get update() { + return this.$$.ctx[7]; + } +}; +var CodeblockMermaid_default = CodeblockMermaid; + +// src/components/NestedEdgeList.svelte +function get_each_context11(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[9] = list[i]; + child_ctx[10] = list; + child_ctx[11] = i; + return child_ctx; +} +function create_if_block_25(ctx) { + let div; + let chevronopener; + let current; + chevronopener = new ChevronOpener_default({ + props: { open: ( + /*opens*/ + ctx[5][ + /*i*/ + ctx[11] + ] + ) } + }); + return { + c() { + div = element("div"); + create_component(chevronopener.$$.fragment); + attr(div, "class", "tree-item-icon collapse-icon mod-collapsible"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(chevronopener, div, null); + current = true; + }, + p(ctx2, dirty) { + const chevronopener_changes = {}; + if (dirty & /*opens*/ + 32) + chevronopener_changes.open = /*opens*/ + ctx2[5][ + /*i*/ + ctx2[11] + ]; + chevronopener.$set(chevronopener_changes); + }, + i(local) { + if (current) + return; + transition_in(chevronopener.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(chevronopener.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(chevronopener); + } + }; +} +function create_if_block_18(ctx) { + let treeitemflair; + let current; + treeitemflair = new TreeItemFlair_default({ + props: { + label: url_search_params(untyped_pick( + /*item*/ + ctx[9].edge.attr, + /*show_attributes*/ + ctx[3] + ), { trim_lone_param: true }) + } + }); + return { + c() { + create_component(treeitemflair.$$.fragment); + }, + m(target, anchor) { + mount_component(treeitemflair, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const treeitemflair_changes = {}; + if (dirty & /*tree, sort, show_attributes*/ + 26) + treeitemflair_changes.label = url_search_params(untyped_pick( + /*item*/ + ctx2[9].edge.attr, + /*show_attributes*/ + ctx2[3] + ), { trim_lone_param: true }); + treeitemflair.$set(treeitemflair_changes); + }, + i(local) { + if (current) + return; + transition_in(treeitemflair.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(treeitemflair.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(treeitemflair, detaching); + } + }; +} +function create_if_block18(ctx) { + let div; + let nestededgelist; + let current; + nestededgelist = new NestedEdgeList({ + props: { + sort: ( + /*sort*/ + ctx[4] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + show_attributes: ( + /*show_attributes*/ + ctx[3] + ), + show_node_options: ( + /*show_node_options*/ + ctx[2] + ), + tree: ( + /*item*/ + ctx[9].children + ) + } + }); + return { + c() { + div = element("div"); + create_component(nestededgelist.$$.fragment); + attr(div, "class", "tree-item-children"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(nestededgelist, div, null); + current = true; + }, + p(ctx2, dirty) { + const nestededgelist_changes = {}; + if (dirty & /*sort*/ + 16) + nestededgelist_changes.sort = /*sort*/ + ctx2[4]; + if (dirty & /*plugin*/ + 1) + nestededgelist_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*show_attributes*/ + 8) + nestededgelist_changes.show_attributes = /*show_attributes*/ + ctx2[3]; + if (dirty & /*show_node_options*/ + 4) + nestededgelist_changes.show_node_options = /*show_node_options*/ + ctx2[2]; + if (dirty & /*tree, sort*/ + 18) + nestededgelist_changes.tree = /*item*/ + ctx2[9].children; + nestededgelist.$set(nestededgelist_changes); + }, + i(local) { + if (current) + return; + transition_in(nestededgelist.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(nestededgelist.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(nestededgelist); + } + }; +} +function create_each_block11(ctx) { + var _a; + let details; + let summary; + let t0; + let div; + let edgelink; + let t1; + let t2; + let t3; + let current; + let mounted; + let dispose; + let if_block0 = ( + /*item*/ + ctx[9].children.length && create_if_block_25(ctx) + ); + edgelink = new EdgeLink_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + edge: ( + /*item*/ + ctx[9].edge + ), + show_node_options: ( + /*show_node_options*/ + ctx[2] + ), + cls: "tree-item-inner-text" + } + }); + let if_block1 = ( + /*show_attributes*/ + ((_a = ctx[3]) == null ? void 0 : _a.length) && create_if_block_18(ctx) + ); + let if_block2 = ( + /*item*/ + ctx[9].children.length && create_if_block18(ctx) + ); + function details_toggle_handler() { + ctx[8].call( + details, + /*i*/ + ctx[11] + ); + } + return { + c() { + details = element("details"); + summary = element("summary"); + if (if_block0) + if_block0.c(); + t0 = space(); + div = element("div"); + create_component(edgelink.$$.fragment); + t1 = space(); + if (if_block1) + if_block1.c(); + t2 = space(); + if (if_block2) + if_block2.c(); + t3 = space(); + attr(div, "class", "tree-item-inner"); + attr(summary, "class", "tree-item-self is-clickable flex items-center"); + attr(details, "class", "tree-item"); + }, + m(target, anchor) { + insert(target, details, anchor); + append(details, summary); + if (if_block0) + if_block0.m(summary, null); + append(summary, t0); + append(summary, div); + mount_component(edgelink, div, null); + append(summary, t1); + if (if_block1) + if_block1.m(summary, null); + append(details, t2); + if (if_block2) + if_block2.m(details, null); + append(details, t3); + details.open = /*opens*/ + ctx[5][ + /*i*/ + ctx[11] + ]; + current = true; + if (!mounted) { + dispose = listen(details, "toggle", details_toggle_handler); + mounted = true; + } + }, + p(new_ctx, dirty) { + var _a2; + ctx = new_ctx; + if ( + /*item*/ + ctx[9].children.length + ) { + if (if_block0) { + if_block0.p(ctx, dirty); + if (dirty & /*tree, sort*/ + 18) { + transition_in(if_block0, 1); + } + } else { + if_block0 = create_if_block_25(ctx); + if_block0.c(); + transition_in(if_block0, 1); + if_block0.m(summary, t0); + } + } else if (if_block0) { + group_outros(); + transition_out(if_block0, 1, 1, () => { + if_block0 = null; + }); + check_outros(); + } + const edgelink_changes = {}; + if (dirty & /*plugin*/ + 1) + edgelink_changes.plugin = /*plugin*/ + ctx[0]; + if (dirty & /*tree, sort*/ + 18) + edgelink_changes.edge = /*item*/ + ctx[9].edge; + if (dirty & /*show_node_options*/ + 4) + edgelink_changes.show_node_options = /*show_node_options*/ + ctx[2]; + edgelink.$set(edgelink_changes); + if ( + /*show_attributes*/ + (_a2 = ctx[3]) == null ? void 0 : _a2.length + ) { + if (if_block1) { + if_block1.p(ctx, dirty); + if (dirty & /*show_attributes*/ + 8) { + transition_in(if_block1, 1); + } + } else { + if_block1 = create_if_block_18(ctx); + if_block1.c(); + transition_in(if_block1, 1); + if_block1.m(summary, null); + } + } else if (if_block1) { + group_outros(); + transition_out(if_block1, 1, 1, () => { + if_block1 = null; + }); + check_outros(); + } + if ( + /*item*/ + ctx[9].children.length + ) { + if (if_block2) { + if_block2.p(ctx, dirty); + if (dirty & /*tree, sort*/ + 18) { + transition_in(if_block2, 1); + } + } else { + if_block2 = create_if_block18(ctx); + if_block2.c(); + transition_in(if_block2, 1); + if_block2.m(details, t3); + } + } else if (if_block2) { + group_outros(); + transition_out(if_block2, 1, 1, () => { + if_block2 = null; + }); + check_outros(); + } + if (dirty & /*opens*/ + 32) { + details.open = /*opens*/ + ctx[5][ + /*i*/ + ctx[11] + ]; + } + }, + i(local) { + if (current) + return; + transition_in(if_block0); + transition_in(edgelink.$$.fragment, local); + transition_in(if_block1); + transition_in(if_block2); + current = true; + }, + o(local) { + transition_out(if_block0); + transition_out(edgelink.$$.fragment, local); + transition_out(if_block1); + transition_out(if_block2); + current = false; + }, + d(detaching) { + if (detaching) { + detach(details); + } + if (if_block0) + if_block0.d(); + destroy_component(edgelink); + if (if_block1) + if_block1.d(); + if (if_block2) + if_block2.d(); + mounted = false; + dispose(); + } + }; +} +function create_fragment52(ctx) { + let each_1_anchor; + let current; + let each_value = ensure_array_like( + /*tree*/ + ctx[1].sort( + /*func*/ + ctx[7] + ) + ); + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block11(get_each_context11(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + each_1_anchor = empty(); + }, + m(target, anchor) { + for (let i = 0; i < each_blocks.length; i += 1) { + if (each_blocks[i]) { + each_blocks[i].m(target, anchor); + } + } + insert(target, each_1_anchor, anchor); + current = true; + }, + p(ctx2, [dirty]) { + if (dirty & /*opens, sort, plugin, show_attributes, show_node_options, tree*/ + 63) { + each_value = ensure_array_like( + /*tree*/ + ctx2[1].sort( + /*func*/ + ctx2[7] + ) + ); + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context11(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block11(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) { + detach(each_1_anchor); + } + destroy_each(each_blocks, detaching); + } + }; +} +function instance52($$self, $$props, $$invalidate) { + let { plugin } = $$props; + let { tree } = $$props; + let { open_signal } = $$props; + let { show_node_options } = $$props; + let { show_attributes } = $$props; + let { sort } = $$props; + let opens = tree.map(() => true); + const func = (a, b) => sort(a.edge, b.edge); + function details_toggle_handler(i) { + opens[i] = this.open; + $$invalidate(5, opens), $$invalidate(6, open_signal); + } + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("tree" in $$props2) + $$invalidate(1, tree = $$props2.tree); + if ("open_signal" in $$props2) + $$invalidate(6, open_signal = $$props2.open_signal); + if ("show_node_options" in $$props2) + $$invalidate(2, show_node_options = $$props2.show_node_options); + if ("show_attributes" in $$props2) + $$invalidate(3, show_attributes = $$props2.show_attributes); + if ("sort" in $$props2) + $$invalidate(4, sort = $$props2.sort); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*open_signal, opens*/ + 96) { + $: + if (open_signal === true) { + $$invalidate(5, opens = opens.map(() => true)); + $$invalidate(6, open_signal = null); + } else if (open_signal === false) { + $$invalidate(5, opens = opens.map(() => false)); + $$invalidate(6, open_signal = null); + } + } + }; + return [ + plugin, + tree, + show_node_options, + show_attributes, + sort, + opens, + open_signal, + func, + details_toggle_handler + ]; +} +var NestedEdgeList = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance52, create_fragment52, safe_not_equal, { + plugin: 0, + tree: 1, + open_signal: 6, + show_node_options: 2, + show_attributes: 3, + sort: 4 + }); + } +}; +var NestedEdgeList_default = NestedEdgeList; + +// src/components/codeblocks/CodeblockTree.svelte +function create_if_block_19(ctx) { + let h3; + let t_value = ( + /*options*/ + ctx[1].title + "" + ); + let t; + return { + c() { + h3 = element("h3"); + t = text(t_value); + attr(h3, "class", "BC-codeblock-tree-title"); + }, + m(target, anchor) { + insert(target, h3, anchor); + append(h3, t); + }, + p(ctx2, dirty) { + if (dirty & /*options*/ + 2 && t_value !== (t_value = /*options*/ + ctx2[1].title + "")) + set_data(t, t_value); + }, + d(detaching) { + if (detaching) { + detach(h3); + } + } + }; +} +function create_else_block11(ctx) { + let p; + return { + c() { + p = element("p"); + p.textContent = "No paths found"; + attr(p, "class", "search-empty-state"); + }, + m(target, anchor) { + insert(target, p, anchor); + }, + p: noop, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(p); + } + } + }; +} +function create_if_block19(ctx) { + var _a; + let div2; + let div0; + let copytoclipboardbutton; + let t; + let div1; + let nestededgelist; + let current; + copytoclipboardbutton = new CopyToClipboardButton_default({ + props: { + cls: "clickable-icon nav-action-button", + text: ListIndex.edge_tree_to_list_index( + /*tree*/ + ctx[3], + { + .../*plugin*/ + ctx[0].settings.commands.list_index.default_options, + show_attributes: ( + /*options*/ + (_a = ctx[1]["show-attributes"]) != null ? _a : [] + ) + } + ) + } + }); + nestededgelist = new NestedEdgeList_default({ + props: { + sort: ( + /*sort*/ + ctx[4] + ), + tree: ( + /*tree*/ + ctx[3] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + show_node_options: ( + /*show_node_options*/ + ctx[5] + ), + open_signal: !/*options*/ + ctx[1].collapse, + show_attributes: ( + /*options*/ + ctx[1]["show-attributes"] + ) + } + }); + return { + c() { + div2 = element("div"); + div0 = element("div"); + create_component(copytoclipboardbutton.$$.fragment); + t = space(); + div1 = element("div"); + create_component(nestededgelist.$$.fragment); + attr(div0, "class", "absolute bottom-2 right-2 flex"); + attr(div1, "class", "pr-10"); + attr(div2, "class", "BC-codeblock-tree-items relative"); + }, + m(target, anchor) { + insert(target, div2, anchor); + append(div2, div0); + mount_component(copytoclipboardbutton, div0, null); + append(div2, t); + append(div2, div1); + mount_component(nestededgelist, div1, null); + current = true; + }, + p(ctx2, dirty) { + var _a2; + const copytoclipboardbutton_changes = {}; + if (dirty & /*tree, plugin, options*/ + 11) + copytoclipboardbutton_changes.text = ListIndex.edge_tree_to_list_index( + /*tree*/ + ctx2[3], + { + .../*plugin*/ + ctx2[0].settings.commands.list_index.default_options, + show_attributes: ( + /*options*/ + (_a2 = ctx2[1]["show-attributes"]) != null ? _a2 : [] + ) + } + ); + copytoclipboardbutton.$set(copytoclipboardbutton_changes); + const nestededgelist_changes = {}; + if (dirty & /*tree*/ + 8) + nestededgelist_changes.tree = /*tree*/ + ctx2[3]; + if (dirty & /*plugin*/ + 1) + nestededgelist_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*options*/ + 2) + nestededgelist_changes.open_signal = !/*options*/ + ctx2[1].collapse; + if (dirty & /*options*/ + 2) + nestededgelist_changes.show_attributes = /*options*/ + ctx2[1]["show-attributes"]; + nestededgelist.$set(nestededgelist_changes); + }, + i(local) { + if (current) + return; + transition_in(copytoclipboardbutton.$$.fragment, local); + transition_in(nestededgelist.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(copytoclipboardbutton.$$.fragment, local); + transition_out(nestededgelist.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div2); + } + destroy_component(copytoclipboardbutton); + destroy_component(nestededgelist); + } + }; +} +function create_fragment53(ctx) { + let div; + let codeblockerrors; + let t0; + let t1; + let current_block_type_index; + let if_block1; + let current; + codeblockerrors = new CodeblockErrors_default({ + props: { + plugin: ( + /*plugin*/ + ctx[0] + ), + errors: ( + /*errors*/ + ctx[2] + ) + } + }); + let if_block0 = ( + /*options*/ + ctx[1].title && create_if_block_19(ctx) + ); + const if_block_creators = [create_if_block19, create_else_block11]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*tree*/ + ctx2[3].length + ) + return 0; + return 1; + } + current_block_type_index = select_block_type(ctx, -1); + if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + return { + c() { + div = element("div"); + create_component(codeblockerrors.$$.fragment); + t0 = space(); + if (if_block0) + if_block0.c(); + t1 = space(); + if_block1.c(); + attr(div, "class", "BC-codeblock-tree"); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(codeblockerrors, div, null); + append(div, t0); + if (if_block0) + if_block0.m(div, null); + append(div, t1); + if_blocks[current_block_type_index].m(div, null); + current = true; + }, + p(ctx2, [dirty]) { + const codeblockerrors_changes = {}; + if (dirty & /*plugin*/ + 1) + codeblockerrors_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*errors*/ + 4) + codeblockerrors_changes.errors = /*errors*/ + ctx2[2]; + codeblockerrors.$set(codeblockerrors_changes); + if ( + /*options*/ + ctx2[1].title + ) { + if (if_block0) { + if_block0.p(ctx2, dirty); + } else { + if_block0 = create_if_block_19(ctx2); + if_block0.c(); + if_block0.m(div, t1); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + check_outros(); + if_block1 = if_blocks[current_block_type_index]; + if (!if_block1) { + if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2); + if_block1.c(); + } else { + if_block1.p(ctx2, dirty); + } + transition_in(if_block1, 1); + if_block1.m(div, null); + } + }, + i(local) { + if (current) + return; + transition_in(codeblockerrors.$$.fragment, local); + transition_in(if_block1); + current = true; + }, + o(local) { + transition_out(codeblockerrors.$$.fragment, local); + transition_out(if_block1); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div); + } + destroy_component(codeblockerrors); + if (if_block0) + if_block0.d(); + if_blocks[current_block_type_index].d(); + } + }; +} +function instance53($$self, $$props, $$invalidate) { + let source_path; + let $active_file_store; + component_subscribe($$self, active_file_store, ($$value) => $$invalidate(8, $active_file_store = $$value)); + var _a; + let { plugin } = $$props; + let { options } = $$props; + let { errors } = $$props; + let { file_path } = $$props; + const sort = get_edge_sorter( + // @ts-expect-error: ts(2345) + options.sort, + plugin.graph + ); + const { show_node_options } = plugin.settings.views.codeblocks; + let tree = []; + const update2 = () => { + $$invalidate(3, tree = get_tree()); + }; + const base_traversal = (attr2) => Traverse.build_tree(plugin.graph, source_path, { max_depth: options.depth[1] }, (e) => has_edge_attrs(e, Object.assign(Object.assign({}, attr2), { + $or_target_ids: options["dataview-from-paths"] + }))); + const edge_field_labels = (_a = options.fields) !== null && _a !== void 0 ? _a : plugin.settings.edge_fields.map((f) => f.label); + const get_tree = () => { + if (source_path && plugin.graph.hasNode(source_path)) { + const traversal = options["merge-fields"] ? base_traversal({ $or_fields: options.fields }) : edge_field_labels.flatMap((field) => base_traversal({ field })); + return options.flat ? Traverse.flatten_tree(traversal).map((item) => ({ depth: 0, children: [], edge: item.edge })) : traversal; + } else { + return []; + } + }; + onMount(update2); + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + if ("options" in $$props2) + $$invalidate(1, options = $$props2.options); + if ("errors" in $$props2) + $$invalidate(2, errors = $$props2.errors); + if ("file_path" in $$props2) + $$invalidate(6, file_path = $$props2.file_path); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*file_path, $active_file_store*/ + 320) { + $: + source_path = file_path ? file_path : $active_file_store ? $active_file_store.path : ""; + } + }; + return [ + plugin, + options, + errors, + tree, + sort, + show_node_options, + file_path, + update2, + $active_file_store + ]; +} +var CodeblockTree = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance53, create_fragment53, safe_not_equal, { + plugin: 0, + options: 1, + errors: 2, + file_path: 6, + update: 7 + }); + } + get update() { + return this.$$.ctx[7]; + } +}; +var CodeblockTree_default = CodeblockTree; + +// src/codeblocks/MDRC.ts +var CodeblockMDRC = class extends import_obsidian27.MarkdownRenderChild { + constructor(plugin, containerEl, source, file_path) { + super(containerEl); + this.plugin = plugin; + this.source = source; + this.file_path = file_path; + this.id = window.crypto.randomUUID(); + } + async update() { + log.debug("CodeblockMDRC.update"); + if (this.component) { + try { + this.component.update(); + } catch (e) { + log.error("CodeblockMDRC.update error >", e); + } + } + } + async onload() { + const timer_outer = new Timer(); + log.debug("CodeblockMDRC.load"); + Codeblocks.register(this); + this.containerEl.empty(); + const timer_inner = new Timer(); + const { parsed, errors } = Codeblocks.parse_source(this.source, { + edge_fields: this.plugin.settings.edge_fields, + field_groups: this.plugin.settings.edge_field_groups + }); + log.debug(timer_inner.elapsedMessage("Codeblocks.parse_source", true)); + if (!parsed) { + log.warn("fatal codeblock errors", errors); + new CodeblockErrors_default({ + target: this.containerEl, + props: { errors, plugin: this.plugin } + }); + return; + } + const { options, file_path } = Codeblocks.postprocess_options( + this.file_path, + parsed, + errors, + this.plugin + ); + log.debug("resolved codeblock options", options); + log.debug( + timer_inner.elapsedMessage("Codeblocks.postprocess_options", true) + ); + if (errors.length) + log.warn("non-fatal codeblock errors", errors); + if (options.type === "tree") { + this.component = new CodeblockTree_default({ + target: this.containerEl, + props: { + errors, + options, + file_path, + plugin: this.plugin + } + }); + } else if (options.type === "mermaid") { + this.component = new CodeblockMermaid_default({ + target: this.containerEl, + props: { + errors, + options, + file_path, + plugin: this.plugin + } + }); + } else if (options.type === "markmap") { + this.component = new CodeblockMarkmap_default({ + target: this.containerEl, + props: { + errors, + options, + file_path, + plugin: this.plugin + } + }); + } else { + log.error("CodeblockMDRC unknown type", options.type); + } + log.debug(timer_inner.elapsedMessage("component creation", true)); + log.debug(timer_outer.elapsedMessage("CodeblockMDRC.onload")); + } + onunload() { + var _a; + log.debug("CodeblockMDRC.unload"); + Codeblocks.unregister(this); + (_a = this.component) == null ? void 0 : _a.$destroy(); + } +}; + +// src/commands/init.ts +var import_obsidian34 = require("obsidian"); + +// src/components/input/SimpleInput.svelte +function create_if_block20(ctx) { + let label_1; + let t; + return { + c() { + label_1 = element("label"); + t = text( + /*label*/ + ctx[0] + ); + attr(label_1, "for", "input"); + }, + m(target, anchor) { + insert(target, label_1, anchor); + append(label_1, t); + }, + p(ctx2, dirty) { + if (dirty & /*label*/ + 1) + set_data( + t, + /*label*/ + ctx2[0] + ); + }, + d(detaching) { + if (detaching) { + detach(label_1); + } + } + }; +} +function create_fragment54(ctx) { + let div; + let t0; + let input; + let t1; + let button; + let t2; + let button_disabled_value; + let mounted; + let dispose; + let if_block = ( + /*label*/ + ctx[0] && create_if_block20(ctx) + ); + return { + c() { + div = element("div"); + if (if_block) + if_block.c(); + t0 = space(); + input = element("input"); + t1 = space(); + button = element("button"); + t2 = text("Submit"); + attr(input, "name", "input"); + attr(input, "type", "text"); + button.disabled = button_disabled_value = /*disabled_cb*/ + ctx[1]( + /*value*/ + ctx[2] + ); + attr(div, "class", "flex flex-col gap-1"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (if_block) + if_block.m(div, null); + append(div, t0); + append(div, input); + set_input_value( + input, + /*value*/ + ctx[2] + ); + append(div, t1); + append(div, button); + append(button, t2); + if (!mounted) { + dispose = [ + listen( + input, + "input", + /*input_input_handler*/ + ctx[4] + ), + listen( + button, + "click", + /*click_handler*/ + ctx[5] + ) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + if ( + /*label*/ + ctx2[0] + ) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block20(ctx2); + if_block.c(); + if_block.m(div, t0); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + if (dirty & /*value*/ + 4 && input.value !== /*value*/ + ctx2[2]) { + set_input_value( + input, + /*value*/ + ctx2[2] + ); + } + if (dirty & /*disabled_cb, value*/ + 6 && button_disabled_value !== (button_disabled_value = /*disabled_cb*/ + ctx2[1]( + /*value*/ + ctx2[2] + ))) { + button.disabled = button_disabled_value; + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(div); + } + if (if_block) + if_block.d(); + mounted = false; + run_all(dispose); + } + }; +} +function instance54($$self, $$props, $$invalidate) { + let { label = "" } = $$props; + let { disabled_cb = (_value) => false } = $$props; + let value = ""; + const dispatch = createEventDispatcher(); + function input_input_handler() { + value = this.value; + $$invalidate(2, value); + } + const click_handler = () => dispatch("submit", value); + $$self.$$set = ($$props2) => { + if ("label" in $$props2) + $$invalidate(0, label = $$props2.label); + if ("disabled_cb" in $$props2) + $$invalidate(1, disabled_cb = $$props2.disabled_cb); + }; + return [label, disabled_cb, value, dispatch, input_input_handler, click_handler]; +} +var SimpleInput = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance54, create_fragment54, safe_not_equal, { label: 0, disabled_cb: 1 }); + } +}; +var SimpleInput_default = SimpleInput; + +// src/modals/CreateListIndexModal.ts +var import_obsidian28 = require("obsidian"); +var CreateListIndexModal = class extends import_obsidian28.Modal { + constructor(app, plugin) { + super(app); + this.active_file = get_store_value(active_file_store); + this.plugin = plugin; + this.options = plugin.settings.commands.list_index.default_options; + } + onOpen() { + if (!this.active_file) { + new import_obsidian28.Notice("No active file"); + return this.close(); + } + const { contentEl, plugin } = this; + contentEl.createEl("h2", { + text: "Create List Index" + }); + new FieldGroupLabelsSettingItem_default({ + target: contentEl, + props: { + field_group_labels: this.options.field_group_labels, + edge_field_groups: plugin.settings.edge_field_groups + } + }).$on("select", (e) => { + this.options.field_group_labels = e.detail; + this.options.fields = resolve_field_group_labels( + plugin.settings.edge_field_groups, + this.options.field_group_labels + ); + }); + new_setting(contentEl, { + name: "Link Kind", + desc: "Format to use for links", + select: { + options: LINK_KINDS, + value: this.options.link_kind, + cb: (value) => this.options.link_kind = value + } + }); + new_setting(contentEl, { + name: "Indent", + desc: "Indentation to use for each level", + input: { + value: this.options.indent, + cb: (value) => this.options.indent = value + } + }); + new EdgeSortIdSettingItem_default({ + target: contentEl, + props: { edge_sort_id: this.options.edge_sort_id } + }).$on("select", (e) => { + this.options.edge_sort_id = e.detail; + }); + new ShowAttributesSettingItem_default({ + target: contentEl, + props: { show_attributes: this.options.show_attributes } + }).$on("select", (e) => { + this.options.show_attributes = e.detail; + }); + _add_settings_show_node_options( + plugin, + contentEl, + { + get: () => this.options.show_node_options, + set: (value) => this.options.show_node_options = value + }, + { save_and_refresh: false } + ); + new import_obsidian28.Setting(contentEl).addButton( + (btn) => btn.setButtonText("Build & Copy to Clipboard").setCta().onClick(async () => { + log.debug("build_list_index options", this.options); + const list_index = ListIndex.build( + plugin.graph, + this.active_file.path, + this.options + ); + if (list_index) { + await navigator.clipboard.writeText(list_index); + new import_obsidian28.Notice("List index copied to clipboard"); + } else { + new import_obsidian28.Notice("No list items to copy"); + } + this.close(); + }) + ); + } + onClose() { + this.contentEl.empty(); + } +}; + +// src/modals/GenericModal.ts +var import_obsidian29 = require("obsidian"); +var GenericModal = class extends import_obsidian29.Modal { + constructor(app, cb) { + super(app); + this.cb = cb; + } + onOpen() { + this.cb(this); + } + onClose() { + this.contentEl.empty(); + } +}; + +// src/commands/freeze_edges/index.ts +var import_obsidian31 = require("obsidian"); + +// src/utils/drop_crumb.ts +var import_obsidian30 = require("obsidian"); +var linkify_edge = (plugin, source_id, target_id, target_aliases) => { + const target_file = plugin.app.vault.getFileByPath(target_id); + if (!target_file) { + return `[[${Paths.drop_ext(target_id)}]]`; + } else { + return plugin.app.fileManager.generateMarkdownLink( + target_file, + source_id, + void 0, + target_aliases == null ? void 0 : target_aliases.at(0) + ); + } +}; +var drop_crumbs = async (plugin, destination_file, crumbs, options) => { + var _a, _b; + if (!crumbs.length) + return; + const links_by_field = group_projection( + group_by(crumbs, (e) => e.attr.field), + (edges) => edges.map( + (e) => linkify_edge( + plugin, + e.source_id, + e.target_id, + e.target_attr.aliases + ) + ) + ); + switch (options.destination) { + case "frontmatter": { + let mutated = false; + const frontmatter = (_b = (_a = plugin.app.metadataCache.getFileCache(destination_file)) == null ? void 0 : _a.frontmatter) != null ? _b : {}; + Object.entries(links_by_field).forEach(([field, links]) => { + if (!(links == null ? void 0 : links.length)) + return; + const existing = frontmatter[field]; + if (existing) { + const existing_array = ensure_is_array(existing); + const new_links = remove_duplicates( + existing_array.concat(links) + ); + if (new_links.length !== existing_array.length) { + mutated = true; + frontmatter[field] = new_links; + } + } else { + mutated = true; + frontmatter[field] = links; + } + }); + if (mutated) { + await plugin.app.fileManager.processFrontMatter( + destination_file, + (old_frontmatter) => { + const new_frontmatter = Object.assign( + old_frontmatter, + frontmatter + ); + log.debug( + "drop_crumbs > processed frontmatter", + new_frontmatter + ); + } + ); + } + break; + } + case "dataview-inline": { + const dataview_fields = Object.entries(links_by_field).map(([field, links]) => { + if (!(links == null ? void 0 : links.length)) + return ""; + else + return `${field}:: ${links.join(", ")}`; + }).filter(Boolean); + await plugin.app.vault.process(destination_file, (content) => { + content += "\n\n" + dataview_fields.join("\n"); + return content; + }); + break; + } + case "none": { + break; + } + } +}; + +// src/commands/freeze_edges/index.ts +var freeze_implied_edges_to_note = async (plugin, source_file, options) => { + const implied_edges = plugin.graph.get_out_edges(source_file.path).filter( + (e) => ( + // Don't freeze a note to itself (self_is_sibling) + !is_self_loop(e) && !e.attr.explicit && // If field === null, we don't have an opposite field to freeze to + e.attr.field !== null + ) + ); + await drop_crumbs(plugin, source_file, implied_edges, options); +}; + +// src/commands/jump/index.ts +var import_obsidian32 = require("obsidian"); +var jump_to_neighbour = async (plugin, options) => { + const active_file = get_store_value(active_file_store); + if (!active_file) + return; + const matches = plugin.graph.get_out_edges(active_file.path).filter( + (e) => has_edge_attrs(e, options.attr) && e.target_id !== active_file.path + ); + if (!matches.length) { + new import_obsidian32.Notice( + `No matches found with attributes: ${url_search_params(options.attr)}` + ); + return; + } else { + await plugin.app.workspace.openLinkText( + matches[0].target_id, + active_file.path + ); + } +}; + +// src/commands/stats/index.ts +var get_graph_stats = (graph, data) => { + var _a, _b; + const stats = { + nodes: { + resolved: {} + }, + edges: { + round: {}, + field: {}, + group: {}, + source: {}, + explicit: {}, + implied_kind: {} + } + }; + for (const node of graph.nodeEntries()) { + const resolved = String(node.attributes.resolved); + stats.nodes.resolved[resolved] = (stats.nodes.resolved[resolved] || 0) + 1; + } + for (const { attributes: attr2 } of graph.edgeEntries()) { + stats.edges.field[(_a = attr2.field) != null ? _a : "null"] = (stats.edges.field[(_b = attr2.field) != null ? _b : "null"] || 0) + 1; + data.groups.forEach((group) => { + if (group.fields.includes(attr2.field)) { + stats.edges.group[group.label] = (stats.edges.group[group.label] || 0) + 1; + } + }); + const explicit = String(attr2.explicit); + stats.edges.explicit[explicit] = (stats.edges.explicit[explicit] || 0) + 1; + if (attr2.explicit) { + stats.edges.source[attr2.source] = (stats.edges.source[attr2.source] || 0) + 1; + } else { + stats.edges.implied_kind[attr2.implied_kind] = (stats.edges.implied_kind[attr2.implied_kind] || 0) + 1; + const round = String(attr2.round); + stats.edges.round[round] = (stats.edges.round[round] || 0) + 1; + } + } + return stats; +}; + +// src/commands/thread/index.ts +var import_obsidian33 = require("obsidian"); +var thread = async (plugin, attr2, options) => { + var _a, _b; + const active_view = plugin.app.workspace.getActiveViewOfType(import_obsidian33.MarkdownView); + if (!active_view) + return; + const source_file = active_view.file; + if (!source_file) + return; + const template_data = { + attr: attr2, + source: { + path: source_file.path, + folder: (_b = (_a = source_file.parent) == null ? void 0 : _a.path) != null ? _b : "", + basename: source_file.basename + } + }; + log.info("template_data", template_data); + const target_path = Paths.normalise( + Paths.ensure_ext( + resolve_templates(options.target_path_template, template_data), + "md" + ) + ); + log.debug("thread > target_path", target_path); + let target_file = null; + try { + target_file = await plugin.app.vault.create(target_path, ""); + } catch (error) { + const msg = `Error creating file "${target_path}". ${error instanceof Error ? error.message : error}`; + new import_obsidian33.Notice(msg); + log.error(msg); + return; + } + await drop_crumbs( + plugin, + source_file, + [ + { + attr: attr2, + target_id: target_path, + source_id: source_file.path, + target_attr: { aliases: [] } + } + ], + options + ); + await Promise.all([ + // Let the cache update so that the refresh sees the new file + // NOTE: I half-completed a less-flaky solution by listening to app.metadataCache.on("changed", ...) + // But this only works if Dataview isn't enabled, and I couldn't find the correct event to listen to for Dataview + sleep(500), + active_view.leaf.openFile(target_file) + ]); + await plugin.refresh(); +}; + +// src/commands/init.ts +var init_all_commands = (plugin) => { + plugin.addCommand({ + id: "breadcrumbs:rebuild-graph", + name: "Rebuild graph", + callback: async () => await plugin.refresh() + }); + Object.keys(VIEW_IDS).forEach((view_id) => { + plugin.addCommand({ + id: `breadcrumbs:open-${view_id}-view`, + name: `Open ${view_id} view`, + callback: () => plugin.activateView(VIEW_IDS[view_id]) + }); + }); + plugin.addCommand({ + id: "breadcrumbs:create-list-index", + name: "Create list index", + callback: () => { + new CreateListIndexModal(plugin.app, plugin).open(); + } + }); + plugin.addCommand({ + id: "breadcrumbs:graph-stats", + name: "Show/Copy graph stats", + callback: async () => { + const stats = get_graph_stats(plugin.graph, { + groups: plugin.settings.edge_field_groups + }); + log.feat("Graph stats >", stats); + await navigator.clipboard.writeText(JSON.stringify(stats, null, 2)); + new import_obsidian34.Notice( + "Graph stats printed to console and copied to clipboard" + ); + } + }); + plugin.addCommand({ + id: "breadcrumbs:freeze-implied-edges-to-note", + name: "Freeze implied edges to note", + callback: async () => { + const active_file = get_store_value(active_file_store); + if (!active_file) + return; + await freeze_implied_edges_to_note( + plugin, + active_file, + plugin.settings.commands.freeze_implied_edges.default_options + ); + new import_obsidian34.Notice("Implied edges frozen to note"); + } + }); + plugin.addCommand({ + id: "breadcrumbs:freeze-implied-edges-to-vault", + name: "Freeze implied edges to all notes in vault", + callback: async () => { + if (!confirm( + "Are you sure you want to freeze implied edges to all notes in vault? This will write to all notes that have outgoing implied edges." + )) { + return new import_obsidian34.Notice("Command cancelled"); + } + const PROMPT_TARGET = "FREEZE TO VAULT"; + new GenericModal(plugin.app, (modal) => { + new SimpleInput_default({ + target: modal.contentEl, + props: { + label: `Type '${PROMPT_TARGET}' to confirm`, + disabled_cb: (value) => value !== PROMPT_TARGET + } + }).$on("submit", async (e) => { + if (e.detail !== PROMPT_TARGET) { + new import_obsidian34.Notice("Command cancelled"); + } else { + const timer = new Timer(); + const notice = new import_obsidian34.Notice( + "Freezing implied edges to all notes in vault..." + ); + await Promise.all( + plugin.app.vault.getMarkdownFiles().map( + (file) => freeze_implied_edges_to_note( + plugin, + file, + plugin.settings.commands.freeze_implied_edges.default_options + ) + ) + ); + log.debug( + `freeze-implied-edges-to-vault > took ${timer.elapsed_str()}ms` + ); + notice.setMessage( + `Implied edges frozen to all notes in ${timer.elapsed_str()}ms` + ); + } + modal.close(); + }); + }).open(); + } + }); + plugin.settings.edge_field_groups.forEach((group) => { + plugin.addCommand({ + id: `breadcrumbs:jump-to-first-neighbour-group:${group.label}`, + name: `Jump to first neighbour by group:${group.label}`, + callback: () => jump_to_neighbour(plugin, { + attr: { $or_fields: group.fields } + }) + }); + }); + plugin.settings.edge_fields.forEach(({ label }) => { + plugin.addCommand({ + id: `breadcrumbs:thread-field:${label}`, + name: `Thread by field:${label}`, + callback: () => thread( + plugin, + { field: label }, + plugin.settings.commands.thread.default_options + ) + }); + }); +}; + +// src/interfaces/settings.ts +var OLD_DIRECTIONS = ["up", "down", "same", "prev", "next"]; + +// src/settings/migration.ts +var get_opposite_direction = (dir) => { + switch (dir) { + case "up": + return "down"; + case "down": + return "up"; + case "same": + return "same"; + case "next": + return "prev"; + case "prev": + return "next"; + } +}; +var migrate_old_settings = (settings) => { + const old = settings; + if (old.userHiers && old.impliedRelations) { + const implied_relationships = { + opposite_direction: { + rounds: 1 + }, + self_is_sibling: { + rounds: Number(old.impliedRelations.siblingIdentity) + }, + cousin_is_sibling: { + rounds: Number(old.impliedRelations.cousinsIsSibling) + }, + same_parent_is_sibling: { + rounds: Number(old.impliedRelations.sameParentIsSibling) + }, + same_sibling_is_sibling: { + rounds: Number(old.impliedRelations.siblingsSiblingIsSibling) + }, + siblings_parent_is_parent: { + rounds: Number(old.impliedRelations.siblingsParentIsParent) + }, + parents_sibling_is_parent: { + rounds: Number(old.impliedRelations.parentsSiblingsIsParents) + } + }; + old.hierarchies = old.userHiers.map((hierarchy) => ({ + dirs: OLD_DIRECTIONS.reduce( + (acc, dir) => ({ + ...acc, + [dir]: hierarchy[dir] + }), + {} + ), + implied_relationships + })); + delete old.userHiers; + delete old.impliedRelations; + } + if (old.hierarchies) { + OLD_DIRECTIONS.forEach((dir) => { + const fields = old.hierarchies.flatMap((hier) => hier.dirs[dir]).filter(Boolean); + const label = `${dir}s`; + const existing = settings.edge_field_groups.find( + (group) => group.label === label + ); + if (existing) { + existing.fields.push(...fields); + existing.fields = remove_duplicates(existing.fields); + } else { + settings.edge_field_groups.push({ label, fields }); + } + }); + old.hierarchies.forEach((hier, hier_i) => { + Object.values(hier.dirs).flatMap((fields) => fields).filter(Boolean).forEach((label) => { + if (!settings.edge_fields.find( + (field) => field.label === label + )) { + settings.edge_fields.push({ label }); + } + }); + Object.entries(hier.implied_relationships).forEach( + ([rel, { rounds }]) => { + if (!rounds) + return; + const fields = { + up: hier.dirs.up[0], + same: hier.dirs.same[0], + down: hier.dirs.down[0], + next: hier.dirs.next[0], + prev: hier.dirs.prev[0] + }; + switch (rel) { + case "opposite_direction": { + OLD_DIRECTIONS.forEach((dir) => { + const field = fields[dir]; + const close_field = fields[get_opposite_direction(dir)]; + if (!field || !close_field) + return; + settings.implied_relations.transitive.push({ + rounds, + name: "", + close_field, + chain: [{ field }], + close_reversed: true + }); + }); + break; + } + case "cousin_is_sibling": { + if (!fields.up || !fields.same || !fields.down) { + return; + } + settings.implied_relations.transitive.push({ + rounds, + name: "", + chain: [ + { field: fields.up }, + { field: fields.same }, + { field: fields.down } + ], + close_reversed: false, + close_field: fields.same + }); + break; + } + case "same_parent_is_sibling": { + if (!fields.up || !fields.down || !fields.down) { + return; + } + settings.implied_relations.transitive.push({ + rounds, + name: "", + chain: [ + { field: fields.up }, + { field: fields.down } + ], + close_reversed: false, + close_field: fields.same + }); + break; + } + case "same_sibling_is_sibling": { + if (!fields.same) + return; + settings.implied_relations.transitive.push({ + rounds, + name: "", + chain: [ + { field: fields.same }, + { field: fields.same } + ], + close_reversed: false, + close_field: fields.same + }); + break; + } + case "siblings_parent_is_parent": { + if (!fields.up || !fields.same) + return; + settings.implied_relations.transitive.push({ + rounds, + name: "", + chain: [ + { field: fields.same }, + { field: fields.up } + ], + close_reversed: false, + close_field: fields.up + }); + break; + } + case "parents_sibling_is_parent": { + if (!fields.up || !fields.same) + return; + settings.implied_relations.transitive.push({ + rounds, + name: "", + chain: [ + { field: fields.up }, + { field: fields.same } + ], + close_reversed: false, + close_field: fields.up + }); + break; + } + } + } + ); + }); + delete old.hierarchies; + settings.edge_field_groups = remove_duplicates_by( + settings.edge_field_groups, + (group) => group.label + ); + } + if (old.custom_implied_relations) { + old.custom_implied_relations.transitive.forEach((rel) => { + settings.implied_relations.transitive.push({ + ...rel, + name: "", + close_reversed: false + }); + }); + delete old.custom_implied_relations; + } + settings.implied_relations.transitive = remove_duplicates_by( + settings.implied_relations.transitive, + stringify_transitive_relation + ); + if (old.tagNoteField !== void 0) { + settings.explicit_edge_sources.tag_note.default_field = old.tagNoteField; + delete old.tagNoteField; + } + if (old.hierarchyNotes !== void 0 && old.hierarchyNoteIsParent !== void 0 && old.HNUpField !== void 0) { + if (old.hierarchyNotes.length > 0) { + const msg = `DEPRECATED: The central Hierarchy Notes setting is deprecated in favour of the "${META_ALIAS["list-note-field"]}" field in each hierarchy note.`; + log.warn(msg); + } + delete old.HNUpField; + delete old.hierarchyNotes; + delete old.hierarchyNoteIsParent; + } + if (old.addDendronNotes !== void 0 && old.dendronNoteField !== void 0 && old.trimDendronNotes !== void 0 && old.dendronNoteDelimiter !== void 0) { + settings.explicit_edge_sources.dendron_note = { + enabled: old.addDendronNotes, + default_field: old.dendronNoteField, + delimiter: old.dendronNoteDelimiter, + display_trimmed: old.trimDendronNotes + }; + delete old.addDendronNotes; + delete old.dendronNoteField; + delete old.trimDendronNotes; + delete old.dendronNoteDelimiter; + } + if (old.addDateNotes !== void 0 && old.dateNoteField !== void 0 && old.dateNoteFormat !== void 0) { + settings.explicit_edge_sources.date_note = { + ...DEFAULT_SETTINGS.explicit_edge_sources.date_note, + enabled: old.addDateNotes, + default_field: old.dateNoteField, + date_format: old.dateNoteFormat + }; + delete old.addDateNotes; + delete old.dateNoteField; + delete old.dateNoteFormat; + } + if (old.respectReadableLineLength !== void 0) { + settings.views.page.all.readable_line_width = old.respectReadableLineLength; + delete old.respectReadableLineLength; + } + if (old.showBCs !== void 0) { + settings.views.page.trail.enabled = old.showBCs; + delete old.showBCs; + } + if (old.showGrid !== void 0) { + settings.views.page.trail.format = old.showGrid ? "grid" : "path"; + delete old.showGrid; + } + if (old.gridDefaultDepth !== void 0) { + settings.views.page.trail.default_depth = old.gridDefaultDepth; + delete old.gridDefaultDepth; + } + if (old.noPathMessage !== void 0) { + settings.views.page.trail.no_path_message = old.noPathMessage; + delete old.noPathMessage; + } + if (old.showPrevNext !== void 0) { + settings.views.page.prev_next.enabled = old.showPrevNext; + delete old.showPrevNext; + } + if (old.views.side.tree.default_dir !== void 0) { + delete old.views.side.tree.default_dir; + } + if (settings.codeblocks !== void 0) { + settings.views.codeblocks = settings.codeblocks; + delete settings.codeblocks; + } + if (old.showRefreshNotice !== void 0 && old.refreshOnNoteSave !== void 0 && old.refreshOnNoteChange !== void 0) { + settings.commands.rebuild_graph.notify = old.showRefreshNotice; + settings.commands.rebuild_graph.trigger = { + note_save: old.refreshOnNoteSave, + layout_change: old.refreshOnNoteChange + }; + delete old.showRefreshNotice; + delete old.refreshOnNoteSave; + delete old.refreshOnNoteChange; + } + if (old.wikilinkIndex !== void 0 && old.aliasesInIndex !== void 0 && old.createIndexIndent !== void 0) { + settings.commands.list_index.default_options = { + ...settings.commands.list_index.default_options, + indent: old.createIndexIndent, + link_kind: old.wikilinkIndex ? "wiki" : "none", + show_node_options: { + ...ListIndex.DEFAULT_OPTIONS.show_node_options, + alias: old.aliasesInIndex + } + }; + delete settings.commands.list_index.default_options.dir; + delete old.wikilinkIndex; + delete old.aliasesInIndex; + delete old.createIndexIndent; + } + if (old.writeBCsInline !== void 0) { + settings.commands.freeze_implied_edges.default_options.destination = old.writeBCsInline ? "dataview-inline" : "frontmatter"; + delete old.writeBCsInline; + } + if (old.threadingTemplate !== void 0) { + settings.commands.thread.default_options.target_path_template = old.threadingTemplate; + delete old.threadingTemplate; + } + if (old.threadUnderCursor !== void 0) { + settings.commands.thread.default_options.destination = old.threadUnderCursor ? "dataview-inline" : "frontmatter"; + delete old.threadUnderCursor; + } + if (old.enableRelationSuggestor !== void 0) { + settings.suggestors.edge_field.enabled = old.enableRelationSuggestor; + delete old.enableRelationSuggestor; + } + if (old.relSuggestorTrigger !== void 0) { + settings.suggestors.edge_field.trigger = old.relSuggestorTrigger; + delete old.relSuggestorTrigger; + } + if (old.suggestors.hierarchy_field !== void 0) { + settings.suggestors.edge_field = old.suggestors.hierarchy_field; + delete old.suggestors.hierarchy_field; + } + if (old.alphaSortAsc !== void 0) { + delete old.alphaSortAsc; + } + if (old.debugMode) { + delete old.debugMode; + } + if (old.dvWaitTime !== void 0) { + delete old.dvWaitTime; + } + if (old.fieldSuggestor !== void 0) { + delete old.fieldSuggestor; + } + if (old.filterImpliedSiblingsOfDifferentTypes !== void 0) { + delete old.filterImpliedSiblingsOfDifferentTypes; + } + if (old.jugglLayout !== void 0) { + delete old.jugglLayout; + } + return settings; +}; + +// src/suggestor/edge_fields.ts +var import_obsidian35 = require("obsidian"); +var EdgeFieldSuggestor = class extends import_obsidian35.EditorSuggest { + constructor(plugin) { + super(plugin.app); + this.getSuggestions = ({ query }) => this.plugin.settings.edge_fields.map((f) => f.label).filter((field) => field.includes(query)); + this.plugin = plugin; + } + onTrigger(cursor, editor, _file) { + const { trigger } = this.plugin.settings.suggestors.edge_field; + const sub = editor.getLine(cursor.line).substring(0, cursor.ch); + if (!sub.startsWith(trigger)) + return null; + const query = sub.slice(trigger.length); + return { + query, + end: cursor, + start: { ch: 0, line: cursor.line } + }; + } + renderSuggestion(suggestion, el) { + el.createDiv({ text: suggestion }); + } + selectSuggestion(suggestion) { + if (!this.context) + return; + const { start, end, editor } = this.context; + editor.replaceRange(suggestion + ":: [[", start, end); + } +}; + +// src/views/tree.ts +var import_obsidian36 = require("obsidian"); + +// src/components/side_views/TreeView.svelte +function create_else_block12(ctx) { + let div; + return { + c() { + div = element("div"); + div.textContent = "No paths found"; + attr(div, "class", "search-empty-state"); + }, + m(target, anchor) { + insert(target, div, anchor); + }, + p: noop, + i: noop, + o: noop, + d(detaching) { + if (detaching) { + detach(div); + } + } + }; +} +function create_if_block21(ctx) { + let nestededgelist; + let current; + nestededgelist = new NestedEdgeList_default({ + props: { + sort: ( + /*sort*/ + ctx[7] + ), + tree: ( + /*tree*/ + ctx[6] + ), + plugin: ( + /*plugin*/ + ctx[0] + ), + show_attributes: ( + /*show_attributes*/ + ctx[4] + ), + show_node_options: ( + /*show_node_options*/ + ctx[8] + ), + open_signal: !/*collapse*/ + ctx[5] + } + }); + return { + c() { + create_component(nestededgelist.$$.fragment); + }, + m(target, anchor) { + mount_component(nestededgelist, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const nestededgelist_changes = {}; + if (dirty & /*sort*/ + 128) + nestededgelist_changes.sort = /*sort*/ + ctx2[7]; + if (dirty & /*tree*/ + 64) + nestededgelist_changes.tree = /*tree*/ + ctx2[6]; + if (dirty & /*plugin*/ + 1) + nestededgelist_changes.plugin = /*plugin*/ + ctx2[0]; + if (dirty & /*show_attributes*/ + 16) + nestededgelist_changes.show_attributes = /*show_attributes*/ + ctx2[4]; + if (dirty & /*collapse*/ + 32) + nestededgelist_changes.open_signal = !/*collapse*/ + ctx2[5]; + nestededgelist.$set(nestededgelist_changes); + }, + i(local) { + if (current) + return; + transition_in(nestededgelist.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(nestededgelist.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(nestededgelist, detaching); + } + }; +} +function create_key_block6(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block21, create_else_block12]; + const if_blocks = []; + function select_block_type(ctx2, dirty) { + if ( + /*tree*/ + ctx2[6].length + ) + 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() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_blocks[current_block_type_index].m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx2, dirty); + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx2, dirty); + } else { + group_outros(); + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + 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](ctx2); + if_block.c(); + } else { + if_block.p(ctx2, dirty); + } + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(if_block_anchor); + } + if_blocks[current_block_type_index].d(detaching); + } + }; +} +function create_fragment55(ctx) { + let div3; + let div1; + let div0; + let rebuildgraphbutton; + let t0; + let edgesortidselector; + let updating_edge_sort_id; + let t1; + let showattributesselectormenu; + let updating_show_attributes; + let t2; + let chevroncollapsebutton; + let updating_collapse; + let t3; + let mergefieldsbutton; + let updating_merge_fields; + let t4; + let fieldgrouplabelsselector; + let updating_field_group_labels; + let t5; + let div2; + let previous_key = ( + /*tree*/ + ctx[6] || /*sort*/ + ctx[7] + ); + let current; + rebuildgraphbutton = new RebuildGraphButton_default({ + props: { + cls: "clickable-icon nav-action-button", + plugin: ( + /*plugin*/ + ctx[0] + ) + } + }); + function edgesortidselector_edge_sort_id_binding(value) { + ctx[11](value); + } + let edgesortidselector_props = { + cls: "clickable-icon nav-action-button", + exclude_fields: [] + }; + if ( + /*edge_sort_id*/ + ctx[1] !== void 0 + ) { + edgesortidselector_props.edge_sort_id = /*edge_sort_id*/ + ctx[1]; + } + edgesortidselector = new EdgeSortIdSelector_default({ props: edgesortidselector_props }); + binding_callbacks.push(() => bind(edgesortidselector, "edge_sort_id", edgesortidselector_edge_sort_id_binding)); + function showattributesselectormenu_show_attributes_binding(value) { + ctx[12](value); + } + let showattributesselectormenu_props = { cls: "clickable-icon nav-action-button" }; + if ( + /*show_attributes*/ + ctx[4] !== void 0 + ) { + showattributesselectormenu_props.show_attributes = /*show_attributes*/ + ctx[4]; + } + showattributesselectormenu = new ShowAttributesSelectorMenu_default({ props: showattributesselectormenu_props }); + binding_callbacks.push(() => bind(showattributesselectormenu, "show_attributes", showattributesselectormenu_show_attributes_binding)); + function chevroncollapsebutton_collapse_binding(value) { + ctx[13](value); + } + let chevroncollapsebutton_props = { cls: "clickable-icon nav-action-button" }; + if ( + /*collapse*/ + ctx[5] !== void 0 + ) { + chevroncollapsebutton_props.collapse = /*collapse*/ + ctx[5]; + } + chevroncollapsebutton = new ChevronCollapseButton_default({ props: chevroncollapsebutton_props }); + binding_callbacks.push(() => bind(chevroncollapsebutton, "collapse", chevroncollapsebutton_collapse_binding)); + function mergefieldsbutton_merge_fields_binding(value) { + ctx[14](value); + } + let mergefieldsbutton_props = { cls: "clickable-icon nav-action-button" }; + if ( + /*merge_fields*/ + ctx[2] !== void 0 + ) { + mergefieldsbutton_props.merge_fields = /*merge_fields*/ + ctx[2]; + } + mergefieldsbutton = new MergeFieldsButton_default({ props: mergefieldsbutton_props }); + binding_callbacks.push(() => bind(mergefieldsbutton, "merge_fields", mergefieldsbutton_merge_fields_binding)); + function fieldgrouplabelsselector_field_group_labels_binding(value) { + ctx[15](value); + } + let fieldgrouplabelsselector_props = { + cls: "clickable-icon nav-action-button", + edge_field_groups: ( + /*plugin*/ + ctx[0].settings.edge_field_groups + ) + }; + if ( + /*field_group_labels*/ + ctx[3] !== void 0 + ) { + fieldgrouplabelsselector_props.field_group_labels = /*field_group_labels*/ + ctx[3]; + } + fieldgrouplabelsselector = new FieldGroupLabelsSelector_default({ props: fieldgrouplabelsselector_props }); + binding_callbacks.push(() => bind(fieldgrouplabelsselector, "field_group_labels", fieldgrouplabelsselector_field_group_labels_binding)); + let key_block = create_key_block6(ctx); + return { + c() { + div3 = element("div"); + div1 = element("div"); + div0 = element("div"); + create_component(rebuildgraphbutton.$$.fragment); + t0 = space(); + create_component(edgesortidselector.$$.fragment); + t1 = space(); + create_component(showattributesselectormenu.$$.fragment); + t2 = space(); + create_component(chevroncollapsebutton.$$.fragment); + t3 = space(); + create_component(mergefieldsbutton.$$.fragment); + t4 = space(); + create_component(fieldgrouplabelsselector.$$.fragment); + t5 = space(); + div2 = element("div"); + key_block.c(); + attr(div0, "class", "nav-buttons-container"); + attr(div1, "class", "nav-header"); + attr(div2, "class", "BC-tree-view-items"); + attr(div3, "class", "markdown-rendered BC-tree-view"); + }, + m(target, anchor) { + insert(target, div3, anchor); + append(div3, div1); + append(div1, div0); + mount_component(rebuildgraphbutton, div0, null); + append(div0, t0); + mount_component(edgesortidselector, div0, null); + append(div0, t1); + mount_component(showattributesselectormenu, div0, null); + append(div0, t2); + mount_component(chevroncollapsebutton, div0, null); + append(div0, t3); + mount_component(mergefieldsbutton, div0, null); + append(div0, t4); + mount_component(fieldgrouplabelsselector, div0, null); + append(div3, t5); + append(div3, div2); + key_block.m(div2, null); + current = true; + }, + p(ctx2, [dirty]) { + const rebuildgraphbutton_changes = {}; + if (dirty & /*plugin*/ + 1) + rebuildgraphbutton_changes.plugin = /*plugin*/ + ctx2[0]; + rebuildgraphbutton.$set(rebuildgraphbutton_changes); + const edgesortidselector_changes = {}; + if (!updating_edge_sort_id && dirty & /*edge_sort_id*/ + 2) { + updating_edge_sort_id = true; + edgesortidselector_changes.edge_sort_id = /*edge_sort_id*/ + ctx2[1]; + add_flush_callback(() => updating_edge_sort_id = false); + } + edgesortidselector.$set(edgesortidselector_changes); + const showattributesselectormenu_changes = {}; + if (!updating_show_attributes && dirty & /*show_attributes*/ + 16) { + updating_show_attributes = true; + showattributesselectormenu_changes.show_attributes = /*show_attributes*/ + ctx2[4]; + add_flush_callback(() => updating_show_attributes = false); + } + showattributesselectormenu.$set(showattributesselectormenu_changes); + const chevroncollapsebutton_changes = {}; + if (!updating_collapse && dirty & /*collapse*/ + 32) { + updating_collapse = true; + chevroncollapsebutton_changes.collapse = /*collapse*/ + ctx2[5]; + add_flush_callback(() => updating_collapse = false); + } + chevroncollapsebutton.$set(chevroncollapsebutton_changes); + const mergefieldsbutton_changes = {}; + if (!updating_merge_fields && dirty & /*merge_fields*/ + 4) { + updating_merge_fields = true; + mergefieldsbutton_changes.merge_fields = /*merge_fields*/ + ctx2[2]; + add_flush_callback(() => updating_merge_fields = false); + } + mergefieldsbutton.$set(mergefieldsbutton_changes); + const fieldgrouplabelsselector_changes = {}; + if (dirty & /*plugin*/ + 1) + fieldgrouplabelsselector_changes.edge_field_groups = /*plugin*/ + ctx2[0].settings.edge_field_groups; + if (!updating_field_group_labels && dirty & /*field_group_labels*/ + 8) { + updating_field_group_labels = true; + fieldgrouplabelsselector_changes.field_group_labels = /*field_group_labels*/ + ctx2[3]; + add_flush_callback(() => updating_field_group_labels = false); + } + fieldgrouplabelsselector.$set(fieldgrouplabelsselector_changes); + if (dirty & /*tree, sort*/ + 192 && safe_not_equal(previous_key, previous_key = /*tree*/ + ctx2[6] || /*sort*/ + ctx2[7])) { + group_outros(); + transition_out(key_block, 1, 1, noop); + check_outros(); + key_block = create_key_block6(ctx2); + key_block.c(); + transition_in(key_block, 1); + key_block.m(div2, null); + } else { + key_block.p(ctx2, dirty); + } + }, + i(local) { + if (current) + return; + transition_in(rebuildgraphbutton.$$.fragment, local); + transition_in(edgesortidselector.$$.fragment, local); + transition_in(showattributesselectormenu.$$.fragment, local); + transition_in(chevroncollapsebutton.$$.fragment, local); + transition_in(mergefieldsbutton.$$.fragment, local); + transition_in(fieldgrouplabelsselector.$$.fragment, local); + transition_in(key_block); + current = true; + }, + o(local) { + transition_out(rebuildgraphbutton.$$.fragment, local); + transition_out(edgesortidselector.$$.fragment, local); + transition_out(showattributesselectormenu.$$.fragment, local); + transition_out(chevroncollapsebutton.$$.fragment, local); + transition_out(mergefieldsbutton.$$.fragment, local); + transition_out(fieldgrouplabelsselector.$$.fragment, local); + transition_out(key_block); + current = false; + }, + d(detaching) { + if (detaching) { + detach(div3); + } + destroy_component(rebuildgraphbutton); + destroy_component(edgesortidselector); + destroy_component(showattributesselectormenu); + destroy_component(chevroncollapsebutton); + destroy_component(mergefieldsbutton); + destroy_component(fieldgrouplabelsselector); + key_block.d(detaching); + } + }; +} +function instance55($$self, $$props, $$invalidate) { + let sort; + let edge_field_labels; + let tree; + let $active_file_store; + component_subscribe($$self, active_file_store, ($$value) => $$invalidate(10, $active_file_store = $$value)); + let { plugin } = $$props; + let { edge_sort_id, merge_fields, show_attributes, show_node_options, field_group_labels, collapse } = plugin.settings.views.side.tree; + const base_traversal = (attr2) => Traverse.build_tree( + plugin.graph, + $active_file_store.path, + // TODO: Customisable max depth + { max_depth: 20 }, + (edge) => has_edge_attrs(edge, attr2) + ); + function edgesortidselector_edge_sort_id_binding(value) { + edge_sort_id = value; + $$invalidate(1, edge_sort_id); + } + function showattributesselectormenu_show_attributes_binding(value) { + show_attributes = value; + $$invalidate(4, show_attributes); + } + function chevroncollapsebutton_collapse_binding(value) { + collapse = value; + $$invalidate(5, collapse); + } + function mergefieldsbutton_merge_fields_binding(value) { + merge_fields = value; + $$invalidate(2, merge_fields); + } + function fieldgrouplabelsselector_field_group_labels_binding(value) { + field_group_labels = value; + $$invalidate(3, field_group_labels); + } + $$self.$$set = ($$props2) => { + if ("plugin" in $$props2) + $$invalidate(0, plugin = $$props2.plugin); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & /*edge_sort_id, plugin*/ + 3) { + $: + $$invalidate(7, sort = get_edge_sorter(edge_sort_id, plugin.graph)); + } + if ($$self.$$.dirty & /*plugin, field_group_labels*/ + 9) { + $: + $$invalidate(9, edge_field_labels = resolve_field_group_labels(plugin.settings.edge_field_groups, field_group_labels)); + } + if ($$self.$$.dirty & /*$active_file_store, plugin, merge_fields, edge_field_labels*/ + 1541) { + $: + $$invalidate(6, tree = $active_file_store && plugin.graph.hasNode($active_file_store.path) ? merge_fields ? base_traversal({ $or_fields: edge_field_labels }) : edge_field_labels.flatMap((field) => base_traversal({ field })) : []); + } + }; + return [ + plugin, + edge_sort_id, + merge_fields, + field_group_labels, + show_attributes, + collapse, + tree, + sort, + show_node_options, + edge_field_labels, + $active_file_store, + edgesortidselector_edge_sort_id_binding, + showattributesselectormenu_show_attributes_binding, + chevroncollapsebutton_collapse_binding, + mergefieldsbutton_merge_fields_binding, + fieldgrouplabelsselector_field_group_labels_binding + ]; +} +var TreeView = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance55, create_fragment55, safe_not_equal, { plugin: 0 }); + } +}; +var TreeView_default = TreeView; + +// src/views/tree.ts +var TreeView2 = class extends import_obsidian36.ItemView { + constructor(leaf, plugin) { + super(leaf); + this.icon = "tree-pine"; + this.plugin = plugin; + } + getViewType() { + return VIEW_IDS.tree; + } + getDisplayText() { + return "Tree view"; + } + async onOpen() { + const container = this.containerEl.children[1]; + container.empty(); + this.component = new TreeView_default({ + target: this.contentEl, + props: { plugin: this.plugin } + }); + } + async onClose() { + var _a; + (_a = this.component) == null ? void 0 : _a.$destroy(); + } +}; + +// src/main.ts +var BreadcrumbsPlugin = class extends import_obsidian37.Plugin { + constructor() { + super(...arguments); + this.graph = new BCGraph(); + /** rebuild_graph, then react by updating active_file_store and redrawing page_views. + * Optionally disable any of these steps. + */ + this.refresh = async (options) => { + if ((options == null ? void 0 : options.rebuild_graph) !== false) { + const timer = new Timer(); + const notice = this.settings.commands.rebuild_graph.notify ? new import_obsidian37.Notice("Rebuilding graph") : null; + const rebuild_results = await rebuild_graph(this); + this.graph = rebuild_results.graph; + const explicit_edge_errors = rebuild_results.explicit_edge_results.filter((result) => result.errors.length).reduce( + (acc, { source, errors }) => { + acc[source] = errors; + return acc; + }, + {} + ); + const implied_edge_results = Object.fromEntries( + Object.entries(rebuild_results.implied_edge_results).filter(([_, errors]) => errors.length).map(([implied_kind, errors]) => [implied_kind, errors]) + ); + if (Object.keys(explicit_edge_errors).length) { + log.warn("explicit_edge_errors >", explicit_edge_errors); + } + if (Object.keys(implied_edge_results).length) { + log.warn("implied_edge_results >", implied_edge_results); + } + notice == null ? void 0 : notice.setMessage( + [ + `Rebuilt graph in ${timer.elapsed_str()}ms`, + explicit_edge_errors.length ? "\nExplicit edge errors (see console for details):" : null, + ...Object.entries(explicit_edge_errors).map( + ([source, errors]) => `- ${source}: ${errors.length} errors` + ), + implied_edge_results.length ? "\nImplied edge errors (see console for details):" : null, + ...Object.entries(implied_edge_results).map( + ([implied_kind, errors]) => `- ${implied_kind}: ${errors.length} errors` + ) + ].filter(Boolean).join("\n") + ); + } + if ((options == null ? void 0 : options.active_file_store) !== false) { + active_file_store.refresh(this.app); + } + if ((options == null ? void 0 : options.redraw_page_views) !== false) { + redraw_page_views(this); + } + if ((options == null ? void 0 : options.redraw_codeblocks) !== false) { + Codeblocks.update_all(); + } + if ((options == null ? void 0 : options.redraw_side_views) === true) { + this.app.workspace.getLeavesOfType(VIEW_IDS.matrix).forEach((leaf) => { + leaf.view.onOpen(); + }); + this.app.workspace.getLeavesOfType(VIEW_IDS.tree).forEach((leaf) => { + leaf.view.onOpen(); + }); + } + }; + } + async onload() { + var _a, _b; + await this.loadSettings(); + log.set_level(this.settings.debug.level); + log.info( + `loading plugin "${this.manifest.name}" plugin v${this.manifest.version}` + ); + log.debug("settings >", this.settings); + this.settings = migrate_old_settings(this.settings); + await this.saveSettings(); + try { + const all_properties = this.app.metadataTypeManager.getAllProperties(); + for (const field of this.settings.edge_fields) { + if (((_a = all_properties[field.label]) == null ? void 0 : _a.type) === "multitext") + continue; + this.app.metadataTypeManager.setType(field.label, "multitext"); + } + for (const [field, { property_type }] of Object.entries( + METADATA_FIELDS_MAP + )) { + if (((_b = all_properties[field]) == null ? void 0 : _b.type) === property_type) + continue; + this.app.metadataTypeManager.setType(field, property_type); + } + } catch (error) { + log.error("metadataTypeManager.setType error >", error); + } + this.addSettingTab(new BreadcrumbsSettingTab(this.app, this)); + this.api = new BCAPI(this); + window.BCAPI = this.api; + this.register( + // @ts-ignore: Don't want to make it optional, but still delete on unload + () => delete window.BCAPI + ); + this.registerHoverLinkSource("breadcrumbs", { + defaultMod: true, + display: "Breadcrumbs" + }); + if (this.settings.suggestors.edge_field.enabled) { + this.registerEditorSuggest(new EdgeFieldSuggestor(this)); + } + this.app.workspace.onLayoutReady(async () => { + log.debug("on:layout-ready"); + await dataview_plugin.await_if_enabled(this); + if (this.app.metadataCache.initialized) { + log.debug("metadataCache:initialized"); + await this.refresh(); + } else { + const metadatacache_init_event = this.app.metadataCache.on( + "initialized", + async () => { + log.debug("on:metadatacache-initialized"); + await this.refresh(); + this.app.metadataCache.offref(metadatacache_init_event); + } + ); + } + this.registerEvent( + this.app.workspace.on("layout-change", async () => { + log.debug("on:layout-change"); + await this.refresh({ + rebuild_graph: this.settings.commands.rebuild_graph.trigger.layout_change + }); + }) + ); + this.registerEvent( + this.app.workspace.on("active-leaf-change", async (leaf) => { + log.debug("on:active-leaf-change"); + if ((leaf == null ? void 0 : leaf.getViewState().type) !== "markdown") { + return; + } + this.refresh({ + rebuild_graph: false, + redraw_page_views: false + }); + }) + ); + this.registerEvent( + this.app.vault.on("create", (file) => { + log.debug("on:create >", file.path); + if (file instanceof import_obsidian37.TFile) { + this.graph.upsert_node(file.path, { resolved: true }); + } + }) + ); + this.registerEvent( + this.app.vault.on("rename", (file, old_path) => { + log.debug("on:rename >", old_path, "->", file.path); + if (file instanceof import_obsidian37.TFile) { + const res = this.graph.safe_rename_node( + old_path, + file.path + ); + if (!res.ok) { + log.error("safe_rename_node >", res.error.message); + } + } + }) + ); + this.registerEvent( + this.app.vault.on("delete", (file) => { + log.debug("on:delete >", file.path); + if (file instanceof import_obsidian37.TFile) { + this.graph.setNodeAttribute( + file.path, + "resolved", + false + ); + } + }) + ); + this.registerView( + VIEW_IDS.matrix, + (leaf) => new MatrixView(leaf, this) + ); + this.registerView( + VIEW_IDS.tree, + (leaf) => new TreeView2(leaf, this) + ); + }); + this.registerMarkdownCodeBlockProcessor( + "breadcrumbs", + (source, el, ctx) => { + const mdrc = new CodeblockMDRC( + this, + el, + source, + ctx.sourcePath + ); + ctx.addChild(mdrc); + } + ); + init_all_commands(this); + log.debug("loaded Breadcrumbs plugin"); + } + onunload() { + } + async loadSettings() { + var _a; + this.settings = deep_merge_objects( + (_a = await this.loadData()) != null ? _a : {}, + DEFAULT_SETTINGS + ); + } + async saveSettings() { + this.settings.is_dirty = false; + await this.saveData(this.settings); + } + // SOURCE: https://docs.obsidian.md/Plugins/User+interface/Views + async activateView(view_id, options) { + const { workspace } = this.app; + let leaf = null; + const leaves = workspace.getLeavesOfType(view_id); + if (leaves.length > 0) { + leaf = leaves[0]; + } else { + leaf = (options == null ? void 0 : options.side) === "left" ? workspace.getLeftLeaf(false) : workspace.getRightLeaf(false); + if (!leaf) { + log.warn("activate_view > no leaf found"); + return; + } + await leaf.setViewState({ type: view_id, active: true }); + } + workspace.revealLeaf(leaf); + } +}; +/*! Bundled license information: + +lucide-svelte/dist/defaultAttributes.js: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/arrow-down-wide-narrow.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/arrow-down.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/arrow-up-narrow-wide.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/arrow-up.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/check.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/chevron-down.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/chevron-right.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/chevrons-down-up.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/chevrons-up-down.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/clipboard.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/file-json.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/group.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/image.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/merge.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/pencil.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/plus.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/rotate-ccw.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/save.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/split.svelte: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/icons/index.js: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +lucide-svelte/dist/aliases.js: + (** + * @license lucide-svelte v0.360.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) +*/ diff --git a/.obsidian/plugins/breadcrumbs/manifest.json b/.obsidian/plugins/breadcrumbs/manifest.json new file mode 100644 index 0000000..031bde4 --- /dev/null +++ b/.obsidian/plugins/breadcrumbs/manifest.json @@ -0,0 +1 @@ +{"id":"breadcrumbs","name":"Breadcrumbs","version":"4.2.35-beta","minAppVersion":"1.0.0","description":"Add structured hierarchies to your notes","author":"SkepticMystic","authorUrl":"https://github.com/SkepticMystic/breadcrumbs","fundingUrl":"https://github.com/SkepticMystic/breadcrumbs#donations","helpUrl":"https://publish.obsidian.md/breadcrumbs-docs","isDesktopOnly":false} \ No newline at end of file diff --git a/.obsidian/plugins/breadcrumbs/styles.css b/.obsidian/plugins/breadcrumbs/styles.css new file mode 100644 index 0000000..b6957c4 --- /dev/null +++ b/.obsidian/plugins/breadcrumbs/styles.css @@ -0,0 +1 @@ +.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1536px){.container{max-width:1536px}}.\!collapse{visibility:collapse!important}.collapse{visibility:collapse}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.bottom-2{bottom:.5rem}.left-2{left:.5rem}.right-2{right:.5rem}.top-2{top:.5rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0{margin-top:0;margin-bottom:0}.my-2{margin-top:.5rem;margin-bottom:.5rem}.mb-1{margin-bottom:.25rem}.mb-4{margin-bottom:1rem}.block{display:block}.flex{display:flex}.grid{display:grid}.contents{display:contents}.hidden{display:none}.aspect-square{aspect-ratio:1/1}.h-32{height:8rem}.w-10{width:2.5rem}.w-48{width:12rem}.w-60{width:15rem}.w-8{width:2rem}.w-full{width:100%}.shrink{flex-shrink:1}.grow{flex-grow:1}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-pointer{cursor:pointer}.scroll-mt-40{scroll-margin-top:10rem}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0{gap:0}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-7{gap:1.75rem}.border{border-width:1px}.p-1{padding:.25rem}.p-2{padding:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pr-10{padding-right:2.5rem}.pr-2{padding-right:.5rem}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.font-semibold{font-weight:600}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.BC-matrix-view hr:last-child{display:none}.BC-page-views.BC-page-views-sticky{z-index:50;position:sticky;top:calc(var(--file-margins)*-1);background-color:var(--background-primary)}.text-faint{color:var(--text-faint)}.text-warning{color:var(--text-warning)}.text-error{color:var(--text-error)} \ No newline at end of file diff --git a/.obsidian/plugins/calendar/data.json b/.obsidian/plugins/calendar/data.json new file mode 100644 index 0000000..b03e21d --- /dev/null +++ b/.obsidian/plugins/calendar/data.json @@ -0,0 +1,10 @@ +{ + "shouldConfirmBeforeCreate": true, + "weekStart": "locale", + "wordsPerDot": 250, + "showWeeklyNote": false, + "weeklyNoteFormat": "", + "weeklyNoteTemplate": "", + "weeklyNoteFolder": "", + "localeOverride": "system-default" +} \ No newline at end of file diff --git a/.obsidian/plugins/calendar/main.js b/.obsidian/plugins/calendar/main.js new file mode 100644 index 0000000..ed6cea3 --- /dev/null +++ b/.obsidian/plugins/calendar/main.js @@ -0,0 +1,4459 @@ +'use strict'; + +var obsidian = require('obsidian'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var obsidian__default = /*#__PURE__*/_interopDefaultLegacy(obsidian); + +const DEFAULT_WEEK_FORMAT = "gggg-[W]ww"; +const DEFAULT_WORDS_PER_DOT = 250; +const VIEW_TYPE_CALENDAR = "calendar"; +const TRIGGER_ON_OPEN = "calendar:open"; + +const DEFAULT_DAILY_NOTE_FORMAT = "YYYY-MM-DD"; +const DEFAULT_WEEKLY_NOTE_FORMAT = "gggg-[W]ww"; +const DEFAULT_MONTHLY_NOTE_FORMAT = "YYYY-MM"; + +function shouldUsePeriodicNotesSettings(periodicity) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const periodicNotes = window.app.plugins.getPlugin("periodic-notes"); + return periodicNotes && periodicNotes.settings?.[periodicity]?.enabled; +} +/** + * Read the user settings for the `daily-notes` plugin + * to keep behavior of creating a new note in-sync. + */ +function getDailyNoteSettings() { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const { internalPlugins, plugins } = window.app; + if (shouldUsePeriodicNotesSettings("daily")) { + const { format, folder, template } = plugins.getPlugin("periodic-notes")?.settings?.daily || {}; + return { + format: format || DEFAULT_DAILY_NOTE_FORMAT, + folder: folder?.trim() || "", + template: template?.trim() || "", + }; + } + const { folder, format, template } = internalPlugins.getPluginById("daily-notes")?.instance?.options || {}; + return { + format: format || DEFAULT_DAILY_NOTE_FORMAT, + folder: folder?.trim() || "", + template: template?.trim() || "", + }; + } + catch (err) { + console.info("No custom daily note settings found!", err); + } +} +/** + * Read the user settings for the `weekly-notes` plugin + * to keep behavior of creating a new note in-sync. + */ +function getWeeklyNoteSettings() { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const pluginManager = window.app.plugins; + const calendarSettings = pluginManager.getPlugin("calendar")?.options; + const periodicNotesSettings = pluginManager.getPlugin("periodic-notes") + ?.settings?.weekly; + if (shouldUsePeriodicNotesSettings("weekly")) { + return { + format: periodicNotesSettings.format || DEFAULT_WEEKLY_NOTE_FORMAT, + folder: periodicNotesSettings.folder?.trim() || "", + template: periodicNotesSettings.template?.trim() || "", + }; + } + const settings = calendarSettings || {}; + return { + format: settings.weeklyNoteFormat || DEFAULT_WEEKLY_NOTE_FORMAT, + folder: settings.weeklyNoteFolder?.trim() || "", + template: settings.weeklyNoteTemplate?.trim() || "", + }; + } + catch (err) { + console.info("No custom weekly note settings found!", err); + } +} +/** + * Read the user settings for the `periodic-notes` plugin + * to keep behavior of creating a new note in-sync. + */ +function getMonthlyNoteSettings() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const pluginManager = window.app.plugins; + try { + const settings = (shouldUsePeriodicNotesSettings("monthly") && + pluginManager.getPlugin("periodic-notes")?.settings?.monthly) || + {}; + return { + format: settings.format || DEFAULT_MONTHLY_NOTE_FORMAT, + folder: settings.folder?.trim() || "", + template: settings.template?.trim() || "", + }; + } + catch (err) { + console.info("No custom monthly note settings found!", err); + } +} + +/** + * dateUID is a way of weekly identifying daily/weekly/monthly notes. + * They are prefixed with the granularity to avoid ambiguity. + */ +function getDateUID$1(date, granularity = "day") { + const ts = date.clone().startOf(granularity).format(); + return `${granularity}-${ts}`; +} +function removeEscapedCharacters(format) { + return format.replace(/\[[^\]]*\]/g, ""); // remove everything within brackets +} +/** + * XXX: When parsing dates that contain both week numbers and months, + * Moment choses to ignore the week numbers. For the week dateUID, we + * want the opposite behavior. Strip the MMM from the format to patch. + */ +function isFormatAmbiguous(format, granularity) { + if (granularity === "week") { + const cleanFormat = removeEscapedCharacters(format); + return (/w{1,2}/i.test(cleanFormat) && + (/M{1,4}/.test(cleanFormat) || /D{1,4}/.test(cleanFormat))); + } + return false; +} +function getDateFromFile(file, granularity) { + const getSettings = { + day: getDailyNoteSettings, + week: getWeeklyNoteSettings, + month: getMonthlyNoteSettings, + }; + const format = getSettings[granularity]().format.split("/").pop(); + const noteDate = window.moment(file.basename, format, true); + if (!noteDate.isValid()) { + return null; + } + if (isFormatAmbiguous(format, granularity)) { + if (granularity === "week") { + const cleanFormat = removeEscapedCharacters(format); + if (/w{1,2}/i.test(cleanFormat)) { + return window.moment(file.basename, + // If format contains week, remove day & month formatting + format.replace(/M{1,4}/g, "").replace(/D{1,4}/g, ""), false); + } + } + } + return noteDate; +} + +// Credit: @creationix/path.js +function join(...partSegments) { + // Split the inputs into a list of path commands. + let parts = []; + for (let i = 0, l = partSegments.length; i < l; i++) { + parts = parts.concat(partSegments[i].split("/")); + } + // Interpret the path commands to get the new resolved path. + const newParts = []; + for (let i = 0, l = parts.length; i < l; i++) { + const part = parts[i]; + // Remove leading and trailing slashes + // Also remove "." segments + if (!part || part === ".") + continue; + // Push new path segments. + else + newParts.push(part); + } + // Preserve the initial slash if there was one. + if (parts[0] === "") + newParts.unshift(""); + // Turn back into a single string path. + return newParts.join("/"); +} +async function ensureFolderExists(path) { + const dirs = path.replace(/\\/g, "/").split("/"); + dirs.pop(); // remove basename + if (dirs.length) { + const dir = join(...dirs); + if (!window.app.vault.getAbstractFileByPath(dir)) { + await window.app.vault.createFolder(dir); + } + } +} +async function getNotePath(directory, filename) { + if (!filename.endsWith(".md")) { + filename += ".md"; + } + const path = obsidian__default['default'].normalizePath(join(directory, filename)); + await ensureFolderExists(path); + return path; +} +async function getTemplateInfo(template) { + const { metadataCache, vault } = window.app; + const templatePath = obsidian__default['default'].normalizePath(template); + if (templatePath === "/") { + return Promise.resolve(["", null]); + } + try { + const templateFile = metadataCache.getFirstLinkpathDest(templatePath, ""); + const contents = await vault.cachedRead(templateFile); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const IFoldInfo = window.app.foldManager.load(templateFile); + return [contents, IFoldInfo]; + } + catch (err) { + console.error(`Failed to read the daily note template '${templatePath}'`, err); + new obsidian__default['default'].Notice("Failed to read the daily note template"); + return ["", null]; + } +} + +class DailyNotesFolderMissingError extends Error { +} +/** + * This function mimics the behavior of the daily-notes plugin + * so it will replace {{date}}, {{title}}, and {{time}} with the + * formatted timestamp. + * + * Note: it has an added bonus that it's not 'today' specific. + */ +async function createDailyNote(date) { + const app = window.app; + const { vault } = app; + const moment = window.moment; + const { template, format, folder } = getDailyNoteSettings(); + const [templateContents, IFoldInfo] = await getTemplateInfo(template); + const filename = date.format(format); + const normalizedPath = await getNotePath(folder, filename); + try { + const createdFile = await vault.create(normalizedPath, templateContents + .replace(/{{\s*date\s*}}/gi, filename) + .replace(/{{\s*time\s*}}/gi, moment().format("HH:mm")) + .replace(/{{\s*title\s*}}/gi, filename) + .replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => { + const now = moment(); + const currentDate = date.clone().set({ + hour: now.get("hour"), + minute: now.get("minute"), + second: now.get("second"), + }); + if (calc) { + currentDate.add(parseInt(timeDelta, 10), unit); + } + if (momentFormat) { + return currentDate.format(momentFormat.substring(1).trim()); + } + return currentDate.format(format); + }) + .replace(/{{\s*yesterday\s*}}/gi, date.clone().subtract(1, "day").format(format)) + .replace(/{{\s*tomorrow\s*}}/gi, date.clone().add(1, "d").format(format))); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + app.foldManager.save(createdFile, IFoldInfo); + return createdFile; + } + catch (err) { + console.error(`Failed to create file: '${normalizedPath}'`, err); + new obsidian__default['default'].Notice("Unable to create new file."); + } +} +function getDailyNote(date, dailyNotes) { + return dailyNotes[getDateUID$1(date, "day")] ?? null; +} +function getAllDailyNotes() { + /** + * Find all daily notes in the daily note folder + */ + const { vault } = window.app; + const { folder } = getDailyNoteSettings(); + const dailyNotesFolder = vault.getAbstractFileByPath(obsidian__default['default'].normalizePath(folder)); + if (!dailyNotesFolder) { + throw new DailyNotesFolderMissingError("Failed to find daily notes folder"); + } + const dailyNotes = {}; + obsidian__default['default'].Vault.recurseChildren(dailyNotesFolder, (note) => { + if (note instanceof obsidian__default['default'].TFile) { + const date = getDateFromFile(note, "day"); + if (date) { + const dateString = getDateUID$1(date, "day"); + dailyNotes[dateString] = note; + } + } + }); + return dailyNotes; +} + +class WeeklyNotesFolderMissingError extends Error { +} +function getDaysOfWeek$1() { + const { moment } = window; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let weekStart = moment.localeData()._week.dow; + const daysOfWeek = [ + "sunday", + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", + ]; + while (weekStart) { + daysOfWeek.push(daysOfWeek.shift()); + weekStart--; + } + return daysOfWeek; +} +function getDayOfWeekNumericalValue(dayOfWeekName) { + return getDaysOfWeek$1().indexOf(dayOfWeekName.toLowerCase()); +} +async function createWeeklyNote(date) { + const { vault } = window.app; + const { template, format, folder } = getWeeklyNoteSettings(); + const [templateContents, IFoldInfo] = await getTemplateInfo(template); + const filename = date.format(format); + const normalizedPath = await getNotePath(folder, filename); + try { + const createdFile = await vault.create(normalizedPath, templateContents + .replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => { + const now = window.moment(); + const currentDate = date.clone().set({ + hour: now.get("hour"), + minute: now.get("minute"), + second: now.get("second"), + }); + if (calc) { + currentDate.add(parseInt(timeDelta, 10), unit); + } + if (momentFormat) { + return currentDate.format(momentFormat.substring(1).trim()); + } + return currentDate.format(format); + }) + .replace(/{{\s*title\s*}}/gi, filename) + .replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")) + .replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi, (_, dayOfWeek, momentFormat) => { + const day = getDayOfWeekNumericalValue(dayOfWeek); + return date.weekday(day).format(momentFormat.trim()); + })); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window.app.foldManager.save(createdFile, IFoldInfo); + return createdFile; + } + catch (err) { + console.error(`Failed to create file: '${normalizedPath}'`, err); + new obsidian__default['default'].Notice("Unable to create new file."); + } +} +function getWeeklyNote(date, weeklyNotes) { + return weeklyNotes[getDateUID$1(date, "week")] ?? null; +} +function getAllWeeklyNotes() { + const { vault } = window.app; + const { folder } = getWeeklyNoteSettings(); + const weeklyNotesFolder = vault.getAbstractFileByPath(obsidian__default['default'].normalizePath(folder)); + if (!weeklyNotesFolder) { + throw new WeeklyNotesFolderMissingError("Failed to find weekly notes folder"); + } + const weeklyNotes = {}; + obsidian__default['default'].Vault.recurseChildren(weeklyNotesFolder, (note) => { + if (note instanceof obsidian__default['default'].TFile) { + const date = getDateFromFile(note, "week"); + if (date) { + const dateString = getDateUID$1(date, "week"); + weeklyNotes[dateString] = note; + } + } + }); + return weeklyNotes; +} + +function appHasDailyNotesPluginLoaded() { + const { app } = window; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const dailyNotesPlugin = app.internalPlugins.plugins["daily-notes"]; + if (dailyNotesPlugin && dailyNotesPlugin.enabled) { + return true; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const periodicNotes = app.plugins.getPlugin("periodic-notes"); + return periodicNotes && periodicNotes.settings?.daily?.enabled; +} +var appHasDailyNotesPluginLoaded_1 = appHasDailyNotesPluginLoaded; +var createDailyNote_1 = createDailyNote; +var createWeeklyNote_1 = createWeeklyNote; +var getAllDailyNotes_1 = getAllDailyNotes; +var getAllWeeklyNotes_1 = getAllWeeklyNotes; +var getDailyNote_1 = getDailyNote; +var getDailyNoteSettings_1 = getDailyNoteSettings; +var getDateFromFile_1 = getDateFromFile; +var getDateUID_1$1 = getDateUID$1; +var getWeeklyNote_1 = getWeeklyNote; +var getWeeklyNoteSettings_1 = getWeeklyNoteSettings; + +function noop$1() { } +function run$1(fn) { + return fn(); +} +function blank_object$1() { + return Object.create(null); +} +function run_all$1(fns) { + fns.forEach(run$1); +} +function is_function$1(thing) { + return typeof thing === 'function'; +} +function safe_not_equal$1(a, b) { + return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); +} +function not_equal$1(a, b) { + return a != a ? b == b : a !== b; +} +function is_empty$1(obj) { + return Object.keys(obj).length === 0; +} +function subscribe(store, ...callbacks) { + if (store == null) { + return noop$1; + } + const unsub = store.subscribe(...callbacks); + return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; +} +function get_store_value(store) { + let value; + subscribe(store, _ => value = _)(); + return value; +} +function component_subscribe(component, store, callback) { + component.$$.on_destroy.push(subscribe(store, callback)); +} +function detach$1(node) { + node.parentNode.removeChild(node); +} +function children$1(element) { + return Array.from(element.childNodes); +} + +let current_component$1; +function set_current_component$1(component) { + current_component$1 = component; +} +function get_current_component$1() { + if (!current_component$1) + throw new Error('Function called outside component initialization'); + return current_component$1; +} +function onDestroy(fn) { + get_current_component$1().$$.on_destroy.push(fn); +} + +const dirty_components$1 = []; +const binding_callbacks$1 = []; +const render_callbacks$1 = []; +const flush_callbacks$1 = []; +const resolved_promise$1 = Promise.resolve(); +let update_scheduled$1 = false; +function schedule_update$1() { + if (!update_scheduled$1) { + update_scheduled$1 = true; + resolved_promise$1.then(flush$1); + } +} +function add_render_callback$1(fn) { + render_callbacks$1.push(fn); +} +function add_flush_callback(fn) { + flush_callbacks$1.push(fn); +} +let flushing$1 = false; +const seen_callbacks$1 = new Set(); +function flush$1() { + if (flushing$1) + return; + flushing$1 = true; + do { + // first, call beforeUpdate functions + // and update components + for (let i = 0; i < dirty_components$1.length; i += 1) { + const component = dirty_components$1[i]; + set_current_component$1(component); + update$1(component.$$); + } + set_current_component$1(null); + dirty_components$1.length = 0; + while (binding_callbacks$1.length) + binding_callbacks$1.pop()(); + // then, once components are updated, call + // afterUpdate functions. This may cause + // subsequent updates... + for (let i = 0; i < render_callbacks$1.length; i += 1) { + const callback = render_callbacks$1[i]; + if (!seen_callbacks$1.has(callback)) { + // ...so guard against infinite loops + seen_callbacks$1.add(callback); + callback(); + } + } + render_callbacks$1.length = 0; + } while (dirty_components$1.length); + while (flush_callbacks$1.length) { + flush_callbacks$1.pop()(); + } + update_scheduled$1 = false; + flushing$1 = false; + seen_callbacks$1.clear(); +} +function update$1($$) { + if ($$.fragment !== null) { + $$.update(); + run_all$1($$.before_update); + const dirty = $$.dirty; + $$.dirty = [-1]; + $$.fragment && $$.fragment.p($$.ctx, dirty); + $$.after_update.forEach(add_render_callback$1); + } +} +const outroing$1 = new Set(); +let outros$1; +function transition_in$1(block, local) { + if (block && block.i) { + outroing$1.delete(block); + block.i(local); + } +} +function transition_out$1(block, local, detach, callback) { + if (block && block.o) { + if (outroing$1.has(block)) + return; + outroing$1.add(block); + outros$1.c.push(() => { + outroing$1.delete(block); + if (callback) { + if (detach) + block.d(1); + callback(); + } + }); + block.o(local); + } +} + +function bind(component, name, callback) { + const index = component.$$.props[name]; + if (index !== undefined) { + component.$$.bound[index] = callback; + callback(component.$$.ctx[index]); + } +} +function create_component$1(block) { + block && block.c(); +} +function mount_component$1(component, target, anchor, customElement) { + const { fragment, on_mount, on_destroy, after_update } = component.$$; + fragment && fragment.m(target, anchor); + if (!customElement) { + // onMount happens before the initial afterUpdate + add_render_callback$1(() => { + const new_on_destroy = on_mount.map(run$1).filter(is_function$1); + if (on_destroy) { + on_destroy.push(...new_on_destroy); + } + else { + // Edge case - component was destroyed immediately, + // most likely as a result of a binding initialising + run_all$1(new_on_destroy); + } + component.$$.on_mount = []; + }); + } + after_update.forEach(add_render_callback$1); +} +function destroy_component$1(component, detaching) { + const $$ = component.$$; + if ($$.fragment !== null) { + run_all$1($$.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 make_dirty$1(component, i) { + if (component.$$.dirty[0] === -1) { + dirty_components$1.push(component); + schedule_update$1(); + component.$$.dirty.fill(0); + } + component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31)); +} +function init$1(component, options, instance, create_fragment, not_equal, props, dirty = [-1]) { + const parent_component = current_component$1; + set_current_component$1(component); + const $$ = component.$$ = { + fragment: null, + ctx: null, + // state + props, + update: noop$1, + not_equal, + bound: blank_object$1(), + // lifecycle + on_mount: [], + on_destroy: [], + on_disconnect: [], + before_update: [], + after_update: [], + context: new Map(parent_component ? parent_component.$$.context : []), + // everything else + callbacks: blank_object$1(), + dirty, + skip_bound: false + }; + 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) + make_dirty$1(component, i); + } + return ret; + }) + : []; + $$.update(); + ready = true; + run_all$1($$.before_update); + // `false` as a special case of no DOM component + $$.fragment = create_fragment ? create_fragment($$.ctx) : false; + if (options.target) { + if (options.hydrate) { + const nodes = children$1(options.target); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.l(nodes); + nodes.forEach(detach$1); + } + else { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.c(); + } + if (options.intro) + transition_in$1(component.$$.fragment); + mount_component$1(component, options.target, options.anchor, options.customElement); + flush$1(); + } + set_current_component$1(parent_component); +} +/** + * Base class for Svelte components. Used when dev=false. + */ +class SvelteComponent$1 { + $destroy() { + destroy_component$1(this, 1); + this.$destroy = noop$1; + } + $on(type, callback) { + 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 && !is_empty$1($$props)) { + this.$$.skip_bound = true; + this.$$set($$props); + this.$$.skip_bound = false; + } + } +} + +const subscriber_queue = []; +/** + * Create a `Writable` store that allows both updating and reading by subscription. + * @param {*=}value initial value + * @param {StartStopNotifier=}start start and stop notifications for subscriptions + */ +function writable(value, start = noop$1) { + let stop; + const subscribers = []; + function set(new_value) { + if (safe_not_equal$1(value, new_value)) { + value = new_value; + if (stop) { // store is ready + const run_queue = !subscriber_queue.length; + for (let i = 0; i < subscribers.length; i += 1) { + const s = subscribers[i]; + s[1](); + subscriber_queue.push(s, value); + } + if (run_queue) { + for (let i = 0; i < subscriber_queue.length; i += 2) { + subscriber_queue[i][0](subscriber_queue[i + 1]); + } + subscriber_queue.length = 0; + } + } + } + } + function update(fn) { + set(fn(value)); + } + function subscribe(run, invalidate = noop$1) { + const subscriber = [run, invalidate]; + subscribers.push(subscriber); + if (subscribers.length === 1) { + stop = start(set) || noop$1; + } + run(value); + return () => { + const index = subscribers.indexOf(subscriber); + if (index !== -1) { + subscribers.splice(index, 1); + } + if (subscribers.length === 0) { + stop(); + stop = null; + } + }; + } + return { set, update, subscribe }; +} + +const weekdays$1 = [ + "sunday", + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", +]; +const defaultSettings = Object.freeze({ + shouldConfirmBeforeCreate: true, + weekStart: "locale", + wordsPerDot: DEFAULT_WORDS_PER_DOT, + showWeeklyNote: false, + weeklyNoteFormat: "", + weeklyNoteTemplate: "", + weeklyNoteFolder: "", + localeOverride: "system-default", +}); +function appHasPeriodicNotesPluginLoaded() { + var _a, _b; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const periodicNotes = window.app.plugins.getPlugin("periodic-notes"); + return periodicNotes && ((_b = (_a = periodicNotes.settings) === null || _a === void 0 ? void 0 : _a.weekly) === null || _b === void 0 ? void 0 : _b.enabled); +} +class CalendarSettingsTab extends obsidian.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + this.containerEl.empty(); + if (!appHasDailyNotesPluginLoaded_1()) { + this.containerEl.createDiv("settings-banner", (banner) => { + banner.createEl("h3", { + text: "⚠️ Daily Notes plugin not enabled", + }); + banner.createEl("p", { + cls: "setting-item-description", + text: "The calendar is best used in conjunction with either the Daily Notes plugin or the Periodic Notes plugin (available in the Community Plugins catalog).", + }); + }); + } + this.containerEl.createEl("h3", { + text: "General Settings", + }); + this.addDotThresholdSetting(); + this.addWeekStartSetting(); + this.addConfirmCreateSetting(); + this.addShowWeeklyNoteSetting(); + if (this.plugin.options.showWeeklyNote && + !appHasPeriodicNotesPluginLoaded()) { + this.containerEl.createEl("h3", { + text: "Weekly Note Settings", + }); + this.containerEl.createEl("p", { + cls: "setting-item-description", + text: "Note: Weekly Note settings are moving. You are encouraged to install the 'Periodic Notes' plugin to keep the functionality in the future.", + }); + this.addWeeklyNoteFormatSetting(); + this.addWeeklyNoteTemplateSetting(); + this.addWeeklyNoteFolderSetting(); + } + this.containerEl.createEl("h3", { + text: "Advanced Settings", + }); + this.addLocaleOverrideSetting(); + } + addDotThresholdSetting() { + new obsidian.Setting(this.containerEl) + .setName("Words per dot") + .setDesc("How many words should be represented by a single dot?") + .addText((textfield) => { + textfield.setPlaceholder(String(DEFAULT_WORDS_PER_DOT)); + textfield.inputEl.type = "number"; + textfield.setValue(String(this.plugin.options.wordsPerDot)); + textfield.onChange(async (value) => { + this.plugin.writeOptions(() => ({ + wordsPerDot: value !== "" ? Number(value) : undefined, + })); + }); + }); + } + addWeekStartSetting() { + const { moment } = window; + const localizedWeekdays = moment.weekdays(); + const localeWeekStartNum = window._bundledLocaleWeekSpec.dow; + const localeWeekStart = moment.weekdays()[localeWeekStartNum]; + new obsidian.Setting(this.containerEl) + .setName("Start week on:") + .setDesc("Choose what day of the week to start. Select 'Locale default' to use the default specified by moment.js") + .addDropdown((dropdown) => { + dropdown.addOption("locale", `Locale default (${localeWeekStart})`); + localizedWeekdays.forEach((day, i) => { + dropdown.addOption(weekdays$1[i], day); + }); + dropdown.setValue(this.plugin.options.weekStart); + dropdown.onChange(async (value) => { + this.plugin.writeOptions(() => ({ + weekStart: value, + })); + }); + }); + } + addConfirmCreateSetting() { + new obsidian.Setting(this.containerEl) + .setName("Confirm before creating new note") + .setDesc("Show a confirmation modal before creating a new note") + .addToggle((toggle) => { + toggle.setValue(this.plugin.options.shouldConfirmBeforeCreate); + toggle.onChange(async (value) => { + this.plugin.writeOptions(() => ({ + shouldConfirmBeforeCreate: value, + })); + }); + }); + } + addShowWeeklyNoteSetting() { + new obsidian.Setting(this.containerEl) + .setName("Show week number") + .setDesc("Enable this to add a column with the week number") + .addToggle((toggle) => { + toggle.setValue(this.plugin.options.showWeeklyNote); + toggle.onChange(async (value) => { + this.plugin.writeOptions(() => ({ showWeeklyNote: value })); + this.display(); // show/hide weekly settings + }); + }); + } + addWeeklyNoteFormatSetting() { + new obsidian.Setting(this.containerEl) + .setName("Weekly note format") + .setDesc("For more syntax help, refer to format reference") + .addText((textfield) => { + textfield.setValue(this.plugin.options.weeklyNoteFormat); + textfield.setPlaceholder(DEFAULT_WEEK_FORMAT); + textfield.onChange(async (value) => { + this.plugin.writeOptions(() => ({ weeklyNoteFormat: value })); + }); + }); + } + addWeeklyNoteTemplateSetting() { + new obsidian.Setting(this.containerEl) + .setName("Weekly note template") + .setDesc("Choose the file you want to use as the template for your weekly notes") + .addText((textfield) => { + textfield.setValue(this.plugin.options.weeklyNoteTemplate); + textfield.onChange(async (value) => { + this.plugin.writeOptions(() => ({ weeklyNoteTemplate: value })); + }); + }); + } + addWeeklyNoteFolderSetting() { + new obsidian.Setting(this.containerEl) + .setName("Weekly note folder") + .setDesc("New weekly notes will be placed here") + .addText((textfield) => { + textfield.setValue(this.plugin.options.weeklyNoteFolder); + textfield.onChange(async (value) => { + this.plugin.writeOptions(() => ({ weeklyNoteFolder: value })); + }); + }); + } + addLocaleOverrideSetting() { + var _a; + const { moment } = window; + const sysLocale = (_a = navigator.language) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + new obsidian.Setting(this.containerEl) + .setName("Override locale:") + .setDesc("Set this if you want to use a locale different from the default") + .addDropdown((dropdown) => { + dropdown.addOption("system-default", `Same as system (${sysLocale})`); + moment.locales().forEach((locale) => { + dropdown.addOption(locale, locale); + }); + dropdown.setValue(this.plugin.options.localeOverride); + dropdown.onChange(async (value) => { + this.plugin.writeOptions(() => ({ + localeOverride: value, + })); + }); + }); + } +} + +const classList = (obj) => { + return Object.entries(obj) + .filter(([_k, v]) => !!v) + .map(([k, _k]) => k); +}; +function clamp(num, lowerBound, upperBound) { + return Math.min(Math.max(lowerBound, num), upperBound); +} +function partition(arr, predicate) { + const pass = []; + const fail = []; + arr.forEach((elem) => { + if (predicate(elem)) { + pass.push(elem); + } + else { + fail.push(elem); + } + }); + return [pass, fail]; +} +/** + * Lookup the dateUID for a given file. It compares the filename + * to the daily and weekly note formats to find a match. + * + * @param file + */ +function getDateUIDFromFile(file) { + if (!file) { + return null; + } + // TODO: I'm not checking the path! + let date = getDateFromFile_1(file, "day"); + if (date) { + return getDateUID_1$1(date, "day"); + } + date = getDateFromFile_1(file, "week"); + if (date) { + return getDateUID_1$1(date, "week"); + } + return null; +} +function getWordCount(text) { + const spaceDelimitedChars = /A-Za-z\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\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\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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/ + .source; + const nonSpaceDelimitedWords = /\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u4E00-\u9FD5/ + .source; + const pattern = new RegExp([ + `(?:[0-9]+(?:(?:,|\\.)[0-9]+)*|[\\-${spaceDelimitedChars}])+`, + nonSpaceDelimitedWords, + ].join("|"), "g"); + return (text.match(pattern) || []).length; +} + +function createDailyNotesStore() { + let hasError = false; + const store = writable(null); + return Object.assign({ reindex: () => { + try { + const dailyNotes = getAllDailyNotes_1(); + store.set(dailyNotes); + hasError = false; + } + catch (err) { + if (!hasError) { + // Avoid error being shown multiple times + console.log("[Calendar] Failed to find daily notes folder", err); + } + store.set({}); + hasError = true; + } + } }, store); +} +function createWeeklyNotesStore() { + let hasError = false; + const store = writable(null); + return Object.assign({ reindex: () => { + try { + const weeklyNotes = getAllWeeklyNotes_1(); + store.set(weeklyNotes); + hasError = false; + } + catch (err) { + if (!hasError) { + // Avoid error being shown multiple times + console.log("[Calendar] Failed to find weekly notes folder", err); + } + store.set({}); + hasError = true; + } + } }, store); +} +const settings = writable(defaultSettings); +const dailyNotes = createDailyNotesStore(); +const weeklyNotes = createWeeklyNotesStore(); +function createSelectedFileStore() { + const store = writable(null); + return Object.assign({ setFile: (file) => { + const id = getDateUIDFromFile(file); + store.set(id); + } }, store); +} +const activeFile = createSelectedFileStore(); + +class ConfirmationModal extends obsidian.Modal { + constructor(app, config) { + super(app); + const { cta, onAccept, text, title } = config; + this.contentEl.createEl("h2", { text: title }); + this.contentEl.createEl("p", { text }); + this.contentEl.createDiv("modal-button-container", (buttonsEl) => { + buttonsEl + .createEl("button", { text: "Never mind" }) + .addEventListener("click", () => this.close()); + buttonsEl + .createEl("button", { + cls: "mod-cta", + text: cta, + }) + .addEventListener("click", async (e) => { + await onAccept(e); + this.close(); + }); + }); + } +} +function createConfirmationDialog({ cta, onAccept, text, title, }) { + new ConfirmationModal(window.app, { cta, onAccept, text, title }).open(); +} + +/** + * Create a Daily Note for a given date. + */ +async function tryToCreateDailyNote(date, inNewSplit, settings, cb) { + const { workspace } = window.app; + const { format } = getDailyNoteSettings_1(); + const filename = date.format(format); + const createFile = async () => { + const dailyNote = await createDailyNote_1(date); + const leaf = inNewSplit + ? workspace.splitActiveLeaf() + : workspace.getUnpinnedLeaf(); + await leaf.openFile(dailyNote); + cb === null || cb === void 0 ? void 0 : cb(dailyNote); + }; + if (settings.shouldConfirmBeforeCreate) { + createConfirmationDialog({ + cta: "Create", + onAccept: createFile, + text: `File ${filename} does not exist. Would you like to create it?`, + title: "New Daily Note", + }); + } + else { + await createFile(); + } +} + +/** + * Create a Weekly Note for a given date. + */ +async function tryToCreateWeeklyNote(date, inNewSplit, settings, cb) { + const { workspace } = window.app; + const { format } = getWeeklyNoteSettings_1(); + const filename = date.format(format); + const createFile = async () => { + const dailyNote = await createWeeklyNote_1(date); + const leaf = inNewSplit + ? workspace.splitActiveLeaf() + : workspace.getUnpinnedLeaf(); + await leaf.openFile(dailyNote); + cb === null || cb === void 0 ? void 0 : cb(dailyNote); + }; + if (settings.shouldConfirmBeforeCreate) { + createConfirmationDialog({ + cta: "Create", + onAccept: createFile, + text: `File ${filename} does not exist. Would you like to create it?`, + title: "New Weekly Note", + }); + } + else { + await createFile(); + } +} + +function noop() { } +function assign(tar, src) { + // @ts-ignore + for (const k in src) + tar[k] = src[k]; + return tar; +} +function is_promise(value) { + return value && typeof value === 'object' && typeof value.then === 'function'; +} +function run(fn) { + return fn(); +} +function blank_object() { + return Object.create(null); +} +function run_all(fns) { + fns.forEach(run); +} +function is_function(thing) { + return typeof thing === 'function'; +} +function safe_not_equal(a, b) { + return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); +} +function not_equal(a, b) { + return a != a ? b == b : a !== b; +} +function is_empty(obj) { + return Object.keys(obj).length === 0; +} +function create_slot(definition, ctx, $$scope, fn) { + if (definition) { + const slot_ctx = get_slot_context(definition, ctx, $$scope, fn); + return definition[0](slot_ctx); + } +} +function get_slot_context(definition, ctx, $$scope, fn) { + return definition[1] && fn + ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) + : $$scope.ctx; +} +function 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 update_slot(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) { + const slot_changes = get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn); + if (slot_changes) { + const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn); + slot.p(slot_context, slot_changes); + } +} +function null_to_empty(value) { + return value == null ? '' : value; +} + +function append(target, node) { + target.appendChild(node); +} +function insert(target, node, anchor) { + target.insertBefore(node, anchor || null); +} +function detach(node) { + node.parentNode.removeChild(node); +} +function destroy_each(iterations, detaching) { + for (let i = 0; i < iterations.length; i += 1) { + if (iterations[i]) + iterations[i].d(detaching); + } +} +function element(name) { + return document.createElement(name); +} +function svg_element(name) { + return document.createElementNS('http://www.w3.org/2000/svg', name); +} +function text(data) { + return document.createTextNode(data); +} +function space() { + return text(' '); +} +function empty() { + return text(''); +} +function listen(node, event, handler, options) { + node.addEventListener(event, handler, options); + return () => node.removeEventListener(event, handler, options); +} +function attr(node, attribute, value) { + if (value == null) + node.removeAttribute(attribute); + else if (node.getAttribute(attribute) !== value) + node.setAttribute(attribute, value); +} +function 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) { + node[key] = attributes[key]; + } + else { + attr(node, key, attributes[key]); + } + } +} +function children(element) { + return Array.from(element.childNodes); +} +function set_data(text, data) { + data = '' + data; + if (text.wholeText !== data) + text.data = data; +} +function toggle_class(element, name, toggle) { + element.classList[toggle ? 'add' : 'remove'](name); +} + +let current_component; +function set_current_component(component) { + current_component = component; +} +function get_current_component() { + if (!current_component) + throw new Error('Function called outside component initialization'); + return current_component; +} + +const dirty_components = []; +const binding_callbacks = []; +const render_callbacks = []; +const flush_callbacks = []; +const resolved_promise = Promise.resolve(); +let update_scheduled = false; +function schedule_update() { + if (!update_scheduled) { + update_scheduled = true; + resolved_promise.then(flush); + } +} +function add_render_callback(fn) { + render_callbacks.push(fn); +} +let flushing = false; +const seen_callbacks = new Set(); +function flush() { + if (flushing) + return; + flushing = true; + do { + // first, call beforeUpdate functions + // and update components + for (let i = 0; i < dirty_components.length; i += 1) { + const component = dirty_components[i]; + set_current_component(component); + update(component.$$); + } + set_current_component(null); + dirty_components.length = 0; + while (binding_callbacks.length) + binding_callbacks.pop()(); + // then, once components are updated, call + // afterUpdate functions. This may cause + // subsequent updates... + for (let i = 0; i < render_callbacks.length; i += 1) { + const callback = render_callbacks[i]; + if (!seen_callbacks.has(callback)) { + // ...so guard against infinite loops + seen_callbacks.add(callback); + callback(); + } + } + render_callbacks.length = 0; + } while (dirty_components.length); + while (flush_callbacks.length) { + flush_callbacks.pop()(); + } + update_scheduled = false; + flushing = false; + seen_callbacks.clear(); +} +function update($$) { + if ($$.fragment !== null) { + $$.update(); + run_all($$.before_update); + const dirty = $$.dirty; + $$.dirty = [-1]; + $$.fragment && $$.fragment.p($$.ctx, dirty); + $$.after_update.forEach(add_render_callback); + } +} +const outroing = new Set(); +let outros; +function group_outros() { + outros = { + r: 0, + c: [], + p: outros // parent group + }; +} +function check_outros() { + if (!outros.r) { + run_all(outros.c); + } + outros = outros.p; +} +function transition_in(block, local) { + if (block && block.i) { + outroing.delete(block); + block.i(local); + } +} +function transition_out(block, local, detach, callback) { + if (block && block.o) { + if (outroing.has(block)) + return; + outroing.add(block); + outros.c.push(() => { + outroing.delete(block); + if (callback) { + if (detach) + block.d(1); + callback(); + } + }); + block.o(local); + } +} + +function 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) { + group_outros(); + transition_out(block, 1, 1, () => { + if (info.blocks[i] === block) { + info.blocks[i] = null; + } + }); + check_outros(); + } + }); + } + else { + info.block.d(1); + } + block.c(); + 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) { + flush(); + } + } + if (is_promise(promise)) { + const current_component = get_current_component(); + promise.then(value => { + set_current_component(current_component); + update(info.then, 1, info.value, value); + set_current_component(null); + }, error => { + set_current_component(current_component); + update(info.catch, 2, info.error, error); + 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 outro_and_destroy_block(block, lookup) { + transition_out(block, 1, 1, () => { + lookup.delete(block.key); + }); +} +function 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(); + 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) { + 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) { + 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]); + return new_blocks; +} + +function 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 get_spread_object(spread_props) { + return typeof spread_props === 'object' && spread_props !== null ? spread_props : {}; +} +function create_component(block) { + block && block.c(); +} +function mount_component(component, target, anchor, customElement) { + const { fragment, on_mount, on_destroy, after_update } = component.$$; + fragment && fragment.m(target, anchor); + if (!customElement) { + // onMount happens before the initial afterUpdate + add_render_callback(() => { + const new_on_destroy = on_mount.map(run).filter(is_function); + if (on_destroy) { + on_destroy.push(...new_on_destroy); + } + else { + // Edge case - component was destroyed immediately, + // most likely as a result of a binding initialising + run_all(new_on_destroy); + } + component.$$.on_mount = []; + }); + } + after_update.forEach(add_render_callback); +} +function destroy_component(component, detaching) { + const $$ = component.$$; + if ($$.fragment !== null) { + 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 make_dirty(component, i) { + if (component.$$.dirty[0] === -1) { + dirty_components.push(component); + schedule_update(); + component.$$.dirty.fill(0); + } + component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31)); +} +function init(component, options, instance, create_fragment, not_equal, props, dirty = [-1]) { + const parent_component = current_component; + set_current_component(component); + const $$ = component.$$ = { + fragment: null, + ctx: null, + // state + props, + update: noop, + not_equal, + bound: blank_object(), + // lifecycle + on_mount: [], + on_destroy: [], + on_disconnect: [], + before_update: [], + after_update: [], + context: new Map(parent_component ? parent_component.$$.context : []), + // everything else + callbacks: blank_object(), + dirty, + skip_bound: false + }; + 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) + make_dirty(component, i); + } + return ret; + }) + : []; + $$.update(); + ready = true; + 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) { + const nodes = children(options.target); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.l(nodes); + nodes.forEach(detach); + } + else { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.c(); + } + if (options.intro) + transition_in(component.$$.fragment); + mount_component(component, options.target, options.anchor, options.customElement); + flush(); + } + set_current_component(parent_component); +} +/** + * Base class for Svelte components. Used when dev=false. + */ +class SvelteComponent { + $destroy() { + destroy_component(this, 1); + this.$destroy = noop; + } + $on(type, callback) { + 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 && !is_empty($$props)) { + this.$$.skip_bound = true; + this.$$set($$props); + this.$$.skip_bound = false; + } + } +} + +/** + * dateUID is a way of weekly identifying daily/weekly/monthly notes. + * They are prefixed with the granularity to avoid ambiguity. + */ +function getDateUID(date, granularity = "day") { + const ts = date.clone().startOf(granularity).format(); + return `${granularity}-${ts}`; +} +var getDateUID_1 = getDateUID; + +/* src/components/Dot.svelte generated by Svelte v3.35.0 */ + +function add_css$5() { + var style = element("style"); + style.id = "svelte-1widvzq-style"; + style.textContent = ".dot.svelte-1widvzq,.hollow.svelte-1widvzq{display:inline-block;height:6px;width:6px;margin:0 1px}.filled.svelte-1widvzq{fill:var(--color-dot)}.active.filled.svelte-1widvzq{fill:var(--text-on-accent)}.hollow.svelte-1widvzq{fill:none;stroke:var(--color-dot)}.active.hollow.svelte-1widvzq{fill:none;stroke:var(--text-on-accent)}"; + append(document.head, style); +} + +// (14:0) {:else} +function create_else_block$1(ctx) { + let svg; + let circle; + let svg_class_value; + + return { + c() { + svg = svg_element("svg"); + circle = svg_element("circle"); + attr(circle, "cx", "3"); + attr(circle, "cy", "3"); + attr(circle, "r", "2"); + attr(svg, "class", svg_class_value = "" + (null_to_empty(`hollow ${/*className*/ ctx[0]}`) + " svelte-1widvzq")); + attr(svg, "viewBox", "0 0 6 6"); + attr(svg, "xmlns", "http://www.w3.org/2000/svg"); + toggle_class(svg, "active", /*isActive*/ ctx[2]); + }, + m(target, anchor) { + insert(target, svg, anchor); + append(svg, circle); + }, + p(ctx, dirty) { + if (dirty & /*className*/ 1 && svg_class_value !== (svg_class_value = "" + (null_to_empty(`hollow ${/*className*/ ctx[0]}`) + " svelte-1widvzq"))) { + attr(svg, "class", svg_class_value); + } + + if (dirty & /*className, isActive*/ 5) { + toggle_class(svg, "active", /*isActive*/ ctx[2]); + } + }, + d(detaching) { + if (detaching) detach(svg); + } + }; +} + +// (6:0) {#if isFilled} +function create_if_block$2(ctx) { + let svg; + let circle; + let svg_class_value; + + return { + c() { + svg = svg_element("svg"); + circle = svg_element("circle"); + attr(circle, "cx", "3"); + attr(circle, "cy", "3"); + attr(circle, "r", "2"); + attr(svg, "class", svg_class_value = "" + (null_to_empty(`dot filled ${/*className*/ ctx[0]}`) + " svelte-1widvzq")); + attr(svg, "viewBox", "0 0 6 6"); + attr(svg, "xmlns", "http://www.w3.org/2000/svg"); + toggle_class(svg, "active", /*isActive*/ ctx[2]); + }, + m(target, anchor) { + insert(target, svg, anchor); + append(svg, circle); + }, + p(ctx, dirty) { + if (dirty & /*className*/ 1 && svg_class_value !== (svg_class_value = "" + (null_to_empty(`dot filled ${/*className*/ ctx[0]}`) + " svelte-1widvzq"))) { + attr(svg, "class", svg_class_value); + } + + if (dirty & /*className, isActive*/ 5) { + toggle_class(svg, "active", /*isActive*/ ctx[2]); + } + }, + d(detaching) { + if (detaching) detach(svg); + } + }; +} + +function create_fragment$6(ctx) { + let if_block_anchor; + + function select_block_type(ctx, dirty) { + if (/*isFilled*/ ctx[1]) return create_if_block$2; + return create_else_block$1; + } + + let current_block_type = select_block_type(ctx); + let if_block = current_block_type(ctx); + + return { + c() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + }, + p(ctx, [dirty]) { + if (current_block_type === (current_block_type = select_block_type(ctx)) && 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(if_block_anchor.parentNode, if_block_anchor); + } + } + }, + i: noop, + o: noop, + d(detaching) { + if_block.d(detaching); + if (detaching) detach(if_block_anchor); + } + }; +} + +function instance$6($$self, $$props, $$invalidate) { + let { className = "" } = $$props; + let { isFilled } = $$props; + let { isActive } = $$props; + + $$self.$$set = $$props => { + if ("className" in $$props) $$invalidate(0, className = $$props.className); + if ("isFilled" in $$props) $$invalidate(1, isFilled = $$props.isFilled); + if ("isActive" in $$props) $$invalidate(2, isActive = $$props.isActive); + }; + + return [className, isFilled, isActive]; +} + +class Dot extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-1widvzq-style")) add_css$5(); + init(this, options, instance$6, create_fragment$6, safe_not_equal, { className: 0, isFilled: 1, isActive: 2 }); + } +} + +/* src/components/MetadataResolver.svelte generated by Svelte v3.35.0 */ + +const get_default_slot_changes_1 = dirty => ({}); +const get_default_slot_context_1 = ctx => ({ metadata: null }); +const get_default_slot_changes = dirty => ({ metadata: dirty & /*metadata*/ 1 }); +const get_default_slot_context = ctx => ({ metadata: /*resolvedMeta*/ ctx[3] }); + +// (11:0) {:else} +function create_else_block(ctx) { + let current; + const default_slot_template = /*#slots*/ ctx[2].default; + const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[1], get_default_slot_context_1); + + return { + c() { + if (default_slot) default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + + current = true; + }, + p(ctx, dirty) { + if (default_slot) { + if (default_slot.p && dirty & /*$$scope*/ 2) { + update_slot(default_slot, default_slot_template, ctx, /*$$scope*/ ctx[1], dirty, get_default_slot_changes_1, get_default_slot_context_1); + } + } + }, + i(local) { + if (current) return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) default_slot.d(detaching); + } + }; +} + +// (7:0) {#if metadata} +function create_if_block$1(ctx) { + let await_block_anchor; + let promise; + let current; + + let info = { + ctx, + current: null, + token: null, + hasCatch: false, + pending: create_pending_block, + then: create_then_block, + catch: create_catch_block, + value: 3, + blocks: [,,,] + }; + + handle_promise(promise = /*metadata*/ ctx[0], info); + + return { + c() { + await_block_anchor = empty(); + info.block.c(); + }, + m(target, anchor) { + insert(target, await_block_anchor, anchor); + info.block.m(target, info.anchor = anchor); + info.mount = () => await_block_anchor.parentNode; + info.anchor = await_block_anchor; + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + info.ctx = ctx; + + if (dirty & /*metadata*/ 1 && promise !== (promise = /*metadata*/ ctx[0]) && handle_promise(promise, info)) ; else { + const child_ctx = ctx.slice(); + child_ctx[3] = info.resolved; + info.block.p(child_ctx, dirty); + } + }, + i(local) { + if (current) return; + transition_in(info.block); + current = true; + }, + o(local) { + for (let i = 0; i < 3; i += 1) { + const block = info.blocks[i]; + transition_out(block); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(await_block_anchor); + info.block.d(detaching); + info.token = null; + info = null; + } + }; +} + +// (1:0) {#if metadata} +function create_catch_block(ctx) { + return { + c: noop, + m: noop, + p: noop, + i: noop, + o: noop, + d: noop + }; +} + +// (8:37) ; export let metadata; {#if metadata} +function create_pending_block(ctx) { + return { + c: noop, + m: noop, + p: noop, + i: noop, + o: noop, + d: noop + }; +} + +function create_fragment$5(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block$1, create_else_block]; + const if_blocks = []; + + function select_block_type(ctx, dirty) { + if (/*metadata*/ ctx[0]) return 0; + return 1; + } + + current_block_type_index = select_block_type(ctx); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + + return { + c() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_blocks[current_block_type_index].m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx, [dirty]) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx); + + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx, dirty); + } else { + group_outros(); + + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + + 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); + } + + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + }, + i(local) { + if (current) return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if_blocks[current_block_type_index].d(detaching); + if (detaching) detach(if_block_anchor); + } + }; +} + +function instance$5($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + + let { metadata } = $$props; + + $$self.$$set = $$props => { + if ("metadata" in $$props) $$invalidate(0, metadata = $$props.metadata); + if ("$$scope" in $$props) $$invalidate(1, $$scope = $$props.$$scope); + }; + + return [metadata, $$scope, slots]; +} + +class MetadataResolver extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance$5, create_fragment$5, not_equal, { metadata: 0 }); + } +} + +function isMacOS() { + return navigator.appVersion.indexOf("Mac") !== -1; +} +function isMetaPressed(e) { + return isMacOS() ? e.metaKey : e.ctrlKey; +} +function getDaysOfWeek(..._args) { + return window.moment.weekdaysShort(true); +} +function isWeekend(date) { + return date.isoWeekday() === 6 || date.isoWeekday() === 7; +} +function getStartOfWeek(days) { + return days[0].weekday(0); +} +/** + * Generate a 2D array of daily information to power + * the calendar view. + */ +function getMonth(displayedMonth, ..._args) { + const locale = window.moment().locale(); + const month = []; + let week; + const startOfMonth = displayedMonth.clone().locale(locale).date(1); + const startOffset = startOfMonth.weekday(); + let date = startOfMonth.clone().subtract(startOffset, "days"); + for (let _day = 0; _day < 42; _day++) { + if (_day % 7 === 0) { + week = { + days: [], + weekNum: date.week(), + }; + month.push(week); + } + week.days.push(date); + date = date.clone().add(1, "days"); + } + return month; +} + +/* src/components/Day.svelte generated by Svelte v3.35.0 */ + +function add_css$4() { + var style = element("style"); + style.id = "svelte-q3wqg9-style"; + style.textContent = ".day.svelte-q3wqg9{background-color:var(--color-background-day);border-radius:4px;color:var(--color-text-day);cursor:pointer;font-size:0.8em;height:100%;padding:4px;position:relative;text-align:center;transition:background-color 0.1s ease-in, color 0.1s ease-in;vertical-align:baseline}.day.svelte-q3wqg9:hover{background-color:var(--interactive-hover)}.day.active.svelte-q3wqg9:hover{background-color:var(--interactive-accent-hover)}.adjacent-month.svelte-q3wqg9{opacity:0.25}.today.svelte-q3wqg9{color:var(--color-text-today)}.day.svelte-q3wqg9:active,.active.svelte-q3wqg9,.active.today.svelte-q3wqg9{color:var(--text-on-accent);background-color:var(--interactive-accent)}.dot-container.svelte-q3wqg9{display:flex;flex-wrap:wrap;justify-content:center;line-height:6px;min-height:6px}"; + append(document.head, style); +} + +function get_each_context$2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[11] = list[i]; + return child_ctx; +} + +// (36:8) {#each metadata.dots as dot} +function create_each_block$2(ctx) { + let dot; + let current; + const dot_spread_levels = [/*dot*/ ctx[11]]; + let dot_props = {}; + + for (let i = 0; i < dot_spread_levels.length; i += 1) { + dot_props = assign(dot_props, dot_spread_levels[i]); + } + + dot = new Dot({ props: dot_props }); + + return { + c() { + create_component(dot.$$.fragment); + }, + m(target, anchor) { + mount_component(dot, target, anchor); + current = true; + }, + p(ctx, dirty) { + const dot_changes = (dirty & /*metadata*/ 128) + ? get_spread_update(dot_spread_levels, [get_spread_object(/*dot*/ ctx[11])]) + : {}; + + dot.$set(dot_changes); + }, + i(local) { + if (current) return; + transition_in(dot.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(dot.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(dot, detaching); + } + }; +} + +// (22:2) +function create_default_slot$1(ctx) { + let div1; + let t0_value = /*date*/ ctx[0].format("D") + ""; + let t0; + let t1; + let div0; + let div1_class_value; + let current; + let mounted; + let dispose; + let each_value = /*metadata*/ ctx[7].dots; + let each_blocks = []; + + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i)); + } + + const out = i => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + + let div1_levels = [ + { + class: div1_class_value = `day ${/*metadata*/ ctx[7].classes.join(" ")}` + }, + /*metadata*/ ctx[7].dataAttributes || {} + ]; + + let div1_data = {}; + + for (let i = 0; i < div1_levels.length; i += 1) { + div1_data = assign(div1_data, div1_levels[i]); + } + + return { + c() { + div1 = element("div"); + t0 = text(t0_value); + t1 = space(); + div0 = element("div"); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + attr(div0, "class", "dot-container svelte-q3wqg9"); + set_attributes(div1, div1_data); + toggle_class(div1, "active", /*selectedId*/ ctx[6] === getDateUID_1(/*date*/ ctx[0], "day")); + toggle_class(div1, "adjacent-month", !/*date*/ ctx[0].isSame(/*displayedMonth*/ ctx[5], "month")); + toggle_class(div1, "today", /*date*/ ctx[0].isSame(/*today*/ ctx[4], "day")); + toggle_class(div1, "svelte-q3wqg9", true); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, t0); + append(div1, t1); + append(div1, div0); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div0, null); + } + + current = true; + + if (!mounted) { + dispose = [ + listen(div1, "click", function () { + if (is_function(/*onClick*/ ctx[2] && /*click_handler*/ ctx[8])) (/*onClick*/ ctx[2] && /*click_handler*/ ctx[8]).apply(this, arguments); + }), + listen(div1, "contextmenu", function () { + if (is_function(/*onContextMenu*/ ctx[3] && /*contextmenu_handler*/ ctx[9])) (/*onContextMenu*/ ctx[3] && /*contextmenu_handler*/ ctx[9]).apply(this, arguments); + }), + listen(div1, "pointerover", function () { + if (is_function(/*onHover*/ ctx[1] && /*pointerover_handler*/ ctx[10])) (/*onHover*/ ctx[1] && /*pointerover_handler*/ ctx[10]).apply(this, arguments); + }) + ]; + + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if ((!current || dirty & /*date*/ 1) && t0_value !== (t0_value = /*date*/ ctx[0].format("D") + "")) set_data(t0, t0_value); + + if (dirty & /*metadata*/ 128) { + each_value = /*metadata*/ ctx[7].dots; + let i; + + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context$2(ctx, each_value, i); + + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block$2(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div0, null); + } + } + + group_outros(); + + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + + check_outros(); + } + + set_attributes(div1, div1_data = get_spread_update(div1_levels, [ + (!current || dirty & /*metadata*/ 128 && div1_class_value !== (div1_class_value = `day ${/*metadata*/ ctx[7].classes.join(" ")}`)) && { class: div1_class_value }, + dirty & /*metadata*/ 128 && (/*metadata*/ ctx[7].dataAttributes || {}) + ])); + + toggle_class(div1, "active", /*selectedId*/ ctx[6] === getDateUID_1(/*date*/ ctx[0], "day")); + toggle_class(div1, "adjacent-month", !/*date*/ ctx[0].isSame(/*displayedMonth*/ ctx[5], "month")); + toggle_class(div1, "today", /*date*/ ctx[0].isSame(/*today*/ ctx[4], "day")); + toggle_class(div1, "svelte-q3wqg9", true); + }, + i(local) { + if (current) return; + + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(div1); + destroy_each(each_blocks, detaching); + mounted = false; + run_all(dispose); + } + }; +} + +function create_fragment$4(ctx) { + let td; + let metadataresolver; + let current; + + metadataresolver = new MetadataResolver({ + props: { + metadata: /*metadata*/ ctx[7], + $$slots: { + default: [ + create_default_slot$1, + ({ metadata }) => ({ 7: metadata }), + ({ metadata }) => metadata ? 128 : 0 + ] + }, + $$scope: { ctx } + } + }); + + return { + c() { + td = element("td"); + create_component(metadataresolver.$$.fragment); + }, + m(target, anchor) { + insert(target, td, anchor); + mount_component(metadataresolver, td, null); + current = true; + }, + p(ctx, [dirty]) { + const metadataresolver_changes = {}; + if (dirty & /*metadata*/ 128) metadataresolver_changes.metadata = /*metadata*/ ctx[7]; + + if (dirty & /*$$scope, metadata, selectedId, date, displayedMonth, today, onClick, onContextMenu, onHover*/ 16639) { + metadataresolver_changes.$$scope = { dirty, ctx }; + } + + metadataresolver.$set(metadataresolver_changes); + }, + i(local) { + if (current) return; + transition_in(metadataresolver.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(metadataresolver.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(td); + destroy_component(metadataresolver); + } + }; +} + +function instance$4($$self, $$props, $$invalidate) { + + + let { date } = $$props; + let { metadata } = $$props; + let { onHover } = $$props; + let { onClick } = $$props; + let { onContextMenu } = $$props; + let { today } = $$props; + let { displayedMonth = null } = $$props; + let { selectedId = null } = $$props; + const click_handler = e => onClick(date, isMetaPressed(e)); + const contextmenu_handler = e => onContextMenu(date, e); + const pointerover_handler = e => onHover(date, e.target, isMetaPressed(e)); + + $$self.$$set = $$props => { + if ("date" in $$props) $$invalidate(0, date = $$props.date); + if ("metadata" in $$props) $$invalidate(7, metadata = $$props.metadata); + if ("onHover" in $$props) $$invalidate(1, onHover = $$props.onHover); + if ("onClick" in $$props) $$invalidate(2, onClick = $$props.onClick); + if ("onContextMenu" in $$props) $$invalidate(3, onContextMenu = $$props.onContextMenu); + if ("today" in $$props) $$invalidate(4, today = $$props.today); + if ("displayedMonth" in $$props) $$invalidate(5, displayedMonth = $$props.displayedMonth); + if ("selectedId" in $$props) $$invalidate(6, selectedId = $$props.selectedId); + }; + + return [ + date, + onHover, + onClick, + onContextMenu, + today, + displayedMonth, + selectedId, + metadata, + click_handler, + contextmenu_handler, + pointerover_handler + ]; +} + +class Day extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-q3wqg9-style")) add_css$4(); + + init(this, options, instance$4, create_fragment$4, not_equal, { + date: 0, + metadata: 7, + onHover: 1, + onClick: 2, + onContextMenu: 3, + today: 4, + displayedMonth: 5, + selectedId: 6 + }); + } +} + +/* src/components/Arrow.svelte generated by Svelte v3.35.0 */ + +function add_css$3() { + var style = element("style"); + style.id = "svelte-156w7na-style"; + style.textContent = ".arrow.svelte-156w7na.svelte-156w7na{align-items:center;cursor:pointer;display:flex;justify-content:center;width:24px}.arrow.is-mobile.svelte-156w7na.svelte-156w7na{width:32px}.right.svelte-156w7na.svelte-156w7na{transform:rotate(180deg)}.arrow.svelte-156w7na svg.svelte-156w7na{color:var(--color-arrow);height:16px;width:16px}"; + append(document.head, style); +} + +function create_fragment$3(ctx) { + let div; + let svg; + let path; + let mounted; + let dispose; + + return { + c() { + div = element("div"); + svg = svg_element("svg"); + path = svg_element("path"); + attr(path, "fill", "currentColor"); + attr(path, "d", "M34.52 239.03L228.87 44.69c9.37-9.37 24.57-9.37 33.94 0l22.67 22.67c9.36 9.36 9.37 24.52.04 33.9L131.49 256l154.02 154.75c9.34 9.38 9.32 24.54-.04 33.9l-22.67 22.67c-9.37 9.37-24.57 9.37-33.94 0L34.52 272.97c-9.37-9.37-9.37-24.57 0-33.94z"); + attr(svg, "focusable", "false"); + attr(svg, "role", "img"); + attr(svg, "xmlns", "http://www.w3.org/2000/svg"); + attr(svg, "viewBox", "0 0 320 512"); + attr(svg, "class", "svelte-156w7na"); + attr(div, "class", "arrow svelte-156w7na"); + attr(div, "aria-label", /*tooltip*/ ctx[1]); + toggle_class(div, "is-mobile", /*isMobile*/ ctx[3]); + toggle_class(div, "right", /*direction*/ ctx[2] === "right"); + }, + m(target, anchor) { + insert(target, div, anchor); + append(div, svg); + append(svg, path); + + if (!mounted) { + dispose = listen(div, "click", function () { + if (is_function(/*onClick*/ ctx[0])) /*onClick*/ ctx[0].apply(this, arguments); + }); + + mounted = true; + } + }, + p(new_ctx, [dirty]) { + ctx = new_ctx; + + if (dirty & /*tooltip*/ 2) { + attr(div, "aria-label", /*tooltip*/ ctx[1]); + } + + if (dirty & /*direction*/ 4) { + toggle_class(div, "right", /*direction*/ ctx[2] === "right"); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) detach(div); + mounted = false; + dispose(); + } + }; +} + +function instance$3($$self, $$props, $$invalidate) { + let { onClick } = $$props; + let { tooltip } = $$props; + let { direction } = $$props; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let isMobile = window.app.isMobile; + + $$self.$$set = $$props => { + if ("onClick" in $$props) $$invalidate(0, onClick = $$props.onClick); + if ("tooltip" in $$props) $$invalidate(1, tooltip = $$props.tooltip); + if ("direction" in $$props) $$invalidate(2, direction = $$props.direction); + }; + + return [onClick, tooltip, direction, isMobile]; +} + +class Arrow extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-156w7na-style")) add_css$3(); + init(this, options, instance$3, create_fragment$3, safe_not_equal, { onClick: 0, tooltip: 1, direction: 2 }); + } +} + +/* src/components/Nav.svelte generated by Svelte v3.35.0 */ + +function add_css$2() { + var style = element("style"); + style.id = "svelte-1vwr9dd-style"; + style.textContent = ".nav.svelte-1vwr9dd.svelte-1vwr9dd{align-items:center;display:flex;margin:0.6em 0 1em;padding:0 8px;width:100%}.nav.is-mobile.svelte-1vwr9dd.svelte-1vwr9dd{padding:0}.title.svelte-1vwr9dd.svelte-1vwr9dd{color:var(--color-text-title);font-size:1.5em;margin:0}.is-mobile.svelte-1vwr9dd .title.svelte-1vwr9dd{font-size:1.3em}.month.svelte-1vwr9dd.svelte-1vwr9dd{font-weight:500;text-transform:capitalize}.year.svelte-1vwr9dd.svelte-1vwr9dd{color:var(--interactive-accent)}.right-nav.svelte-1vwr9dd.svelte-1vwr9dd{display:flex;justify-content:center;margin-left:auto}.reset-button.svelte-1vwr9dd.svelte-1vwr9dd{cursor:pointer;border-radius:4px;color:var(--text-muted);font-size:0.7em;font-weight:600;letter-spacing:1px;margin:0 4px;padding:0px 4px;text-transform:uppercase}.is-mobile.svelte-1vwr9dd .reset-button.svelte-1vwr9dd{display:none}"; + append(document.head, style); +} + +function create_fragment$2(ctx) { + let div2; + let h3; + let span0; + let t0_value = /*displayedMonth*/ ctx[0].format("MMM") + ""; + let t0; + let t1; + let span1; + let t2_value = /*displayedMonth*/ ctx[0].format("YYYY") + ""; + let t2; + let t3; + let div1; + let arrow0; + let t4; + let div0; + let t6; + let arrow1; + let current; + let mounted; + let dispose; + + arrow0 = new Arrow({ + props: { + direction: "left", + onClick: /*decrementDisplayedMonth*/ ctx[3], + tooltip: "Previous Month" + } + }); + + arrow1 = new Arrow({ + props: { + direction: "right", + onClick: /*incrementDisplayedMonth*/ ctx[2], + tooltip: "Next Month" + } + }); + + return { + c() { + div2 = element("div"); + h3 = element("h3"); + span0 = element("span"); + t0 = text(t0_value); + t1 = space(); + span1 = element("span"); + t2 = text(t2_value); + t3 = space(); + div1 = element("div"); + create_component(arrow0.$$.fragment); + t4 = space(); + div0 = element("div"); + div0.textContent = `${/*todayDisplayStr*/ ctx[4]}`; + t6 = space(); + create_component(arrow1.$$.fragment); + attr(span0, "class", "month svelte-1vwr9dd"); + attr(span1, "class", "year svelte-1vwr9dd"); + attr(h3, "class", "title svelte-1vwr9dd"); + attr(div0, "class", "reset-button svelte-1vwr9dd"); + attr(div1, "class", "right-nav svelte-1vwr9dd"); + attr(div2, "class", "nav svelte-1vwr9dd"); + toggle_class(div2, "is-mobile", /*isMobile*/ ctx[5]); + }, + m(target, anchor) { + insert(target, div2, anchor); + append(div2, h3); + append(h3, span0); + append(span0, t0); + append(h3, t1); + append(h3, span1); + append(span1, t2); + append(div2, t3); + append(div2, div1); + mount_component(arrow0, div1, null); + append(div1, t4); + append(div1, div0); + append(div1, t6); + mount_component(arrow1, div1, null); + current = true; + + if (!mounted) { + dispose = [ + listen(h3, "click", function () { + if (is_function(/*resetDisplayedMonth*/ ctx[1])) /*resetDisplayedMonth*/ ctx[1].apply(this, arguments); + }), + listen(div0, "click", function () { + if (is_function(/*resetDisplayedMonth*/ ctx[1])) /*resetDisplayedMonth*/ ctx[1].apply(this, arguments); + }) + ]; + + mounted = true; + } + }, + p(new_ctx, [dirty]) { + ctx = new_ctx; + if ((!current || dirty & /*displayedMonth*/ 1) && t0_value !== (t0_value = /*displayedMonth*/ ctx[0].format("MMM") + "")) set_data(t0, t0_value); + if ((!current || dirty & /*displayedMonth*/ 1) && t2_value !== (t2_value = /*displayedMonth*/ ctx[0].format("YYYY") + "")) set_data(t2, t2_value); + const arrow0_changes = {}; + if (dirty & /*decrementDisplayedMonth*/ 8) arrow0_changes.onClick = /*decrementDisplayedMonth*/ ctx[3]; + arrow0.$set(arrow0_changes); + const arrow1_changes = {}; + if (dirty & /*incrementDisplayedMonth*/ 4) arrow1_changes.onClick = /*incrementDisplayedMonth*/ ctx[2]; + arrow1.$set(arrow1_changes); + }, + i(local) { + if (current) return; + transition_in(arrow0.$$.fragment, local); + transition_in(arrow1.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(arrow0.$$.fragment, local); + transition_out(arrow1.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(div2); + destroy_component(arrow0); + destroy_component(arrow1); + mounted = false; + run_all(dispose); + } + }; +} + +function instance$2($$self, $$props, $$invalidate) { + + let { displayedMonth } = $$props; + let { today } = $$props; + let { resetDisplayedMonth } = $$props; + let { incrementDisplayedMonth } = $$props; + let { decrementDisplayedMonth } = $$props; + + // Get the word 'Today' but localized to the current language + const todayDisplayStr = today.calendar().split(/\d|\s/)[0]; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let isMobile = window.app.isMobile; + + $$self.$$set = $$props => { + if ("displayedMonth" in $$props) $$invalidate(0, displayedMonth = $$props.displayedMonth); + if ("today" in $$props) $$invalidate(6, today = $$props.today); + if ("resetDisplayedMonth" in $$props) $$invalidate(1, resetDisplayedMonth = $$props.resetDisplayedMonth); + if ("incrementDisplayedMonth" in $$props) $$invalidate(2, incrementDisplayedMonth = $$props.incrementDisplayedMonth); + if ("decrementDisplayedMonth" in $$props) $$invalidate(3, decrementDisplayedMonth = $$props.decrementDisplayedMonth); + }; + + return [ + displayedMonth, + resetDisplayedMonth, + incrementDisplayedMonth, + decrementDisplayedMonth, + todayDisplayStr, + isMobile, + today + ]; +} + +class Nav extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-1vwr9dd-style")) add_css$2(); + + init(this, options, instance$2, create_fragment$2, safe_not_equal, { + displayedMonth: 0, + today: 6, + resetDisplayedMonth: 1, + incrementDisplayedMonth: 2, + decrementDisplayedMonth: 3 + }); + } +} + +/* src/components/WeekNum.svelte generated by Svelte v3.35.0 */ + +function add_css$1() { + var style = element("style"); + style.id = "svelte-egt0yd-style"; + style.textContent = "td.svelte-egt0yd{border-right:1px solid var(--background-modifier-border)}.week-num.svelte-egt0yd{background-color:var(--color-background-weeknum);border-radius:4px;color:var(--color-text-weeknum);cursor:pointer;font-size:0.65em;height:100%;padding:4px;text-align:center;transition:background-color 0.1s ease-in, color 0.1s ease-in;vertical-align:baseline}.week-num.svelte-egt0yd:hover{background-color:var(--interactive-hover)}.week-num.active.svelte-egt0yd:hover{background-color:var(--interactive-accent-hover)}.active.svelte-egt0yd{color:var(--text-on-accent);background-color:var(--interactive-accent)}.dot-container.svelte-egt0yd{display:flex;flex-wrap:wrap;justify-content:center;line-height:6px;min-height:6px}"; + append(document.head, style); +} + +function get_each_context$1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[11] = list[i]; + return child_ctx; +} + +// (35:8) {#each metadata.dots as dot} +function create_each_block$1(ctx) { + let dot; + let current; + const dot_spread_levels = [/*dot*/ ctx[11]]; + let dot_props = {}; + + for (let i = 0; i < dot_spread_levels.length; i += 1) { + dot_props = assign(dot_props, dot_spread_levels[i]); + } + + dot = new Dot({ props: dot_props }); + + return { + c() { + create_component(dot.$$.fragment); + }, + m(target, anchor) { + mount_component(dot, target, anchor); + current = true; + }, + p(ctx, dirty) { + const dot_changes = (dirty & /*metadata*/ 64) + ? get_spread_update(dot_spread_levels, [get_spread_object(/*dot*/ ctx[11])]) + : {}; + + dot.$set(dot_changes); + }, + i(local) { + if (current) return; + transition_in(dot.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(dot.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(dot, detaching); + } + }; +} + +// (24:2) +function create_default_slot(ctx) { + let div1; + let t0; + let t1; + let div0; + let div1_class_value; + let current; + let mounted; + let dispose; + let each_value = /*metadata*/ ctx[6].dots; + let each_blocks = []; + + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i)); + } + + const out = i => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + + return { + c() { + div1 = element("div"); + t0 = text(/*weekNum*/ ctx[0]); + t1 = space(); + div0 = element("div"); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + attr(div0, "class", "dot-container svelte-egt0yd"); + attr(div1, "class", div1_class_value = "" + (null_to_empty(`week-num ${/*metadata*/ ctx[6].classes.join(" ")}`) + " svelte-egt0yd")); + toggle_class(div1, "active", /*selectedId*/ ctx[5] === getDateUID_1(/*days*/ ctx[1][0], "week")); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, t0); + append(div1, t1); + append(div1, div0); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div0, null); + } + + current = true; + + if (!mounted) { + dispose = [ + listen(div1, "click", function () { + if (is_function(/*onClick*/ ctx[3] && /*click_handler*/ ctx[8])) (/*onClick*/ ctx[3] && /*click_handler*/ ctx[8]).apply(this, arguments); + }), + listen(div1, "contextmenu", function () { + if (is_function(/*onContextMenu*/ ctx[4] && /*contextmenu_handler*/ ctx[9])) (/*onContextMenu*/ ctx[4] && /*contextmenu_handler*/ ctx[9]).apply(this, arguments); + }), + listen(div1, "pointerover", function () { + if (is_function(/*onHover*/ ctx[2] && /*pointerover_handler*/ ctx[10])) (/*onHover*/ ctx[2] && /*pointerover_handler*/ ctx[10]).apply(this, arguments); + }) + ]; + + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (!current || dirty & /*weekNum*/ 1) set_data(t0, /*weekNum*/ ctx[0]); + + if (dirty & /*metadata*/ 64) { + each_value = /*metadata*/ ctx[6].dots; + let i; + + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context$1(ctx, each_value, i); + + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block$1(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div0, null); + } + } + + group_outros(); + + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + + check_outros(); + } + + if (!current || dirty & /*metadata*/ 64 && div1_class_value !== (div1_class_value = "" + (null_to_empty(`week-num ${/*metadata*/ ctx[6].classes.join(" ")}`) + " svelte-egt0yd"))) { + attr(div1, "class", div1_class_value); + } + + if (dirty & /*metadata, selectedId, getDateUID, days*/ 98) { + toggle_class(div1, "active", /*selectedId*/ ctx[5] === getDateUID_1(/*days*/ ctx[1][0], "week")); + } + }, + i(local) { + if (current) return; + + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(div1); + destroy_each(each_blocks, detaching); + mounted = false; + run_all(dispose); + } + }; +} + +function create_fragment$1(ctx) { + let td; + let metadataresolver; + let current; + + metadataresolver = new MetadataResolver({ + props: { + metadata: /*metadata*/ ctx[6], + $$slots: { + default: [ + create_default_slot, + ({ metadata }) => ({ 6: metadata }), + ({ metadata }) => metadata ? 64 : 0 + ] + }, + $$scope: { ctx } + } + }); + + return { + c() { + td = element("td"); + create_component(metadataresolver.$$.fragment); + attr(td, "class", "svelte-egt0yd"); + }, + m(target, anchor) { + insert(target, td, anchor); + mount_component(metadataresolver, td, null); + current = true; + }, + p(ctx, [dirty]) { + const metadataresolver_changes = {}; + if (dirty & /*metadata*/ 64) metadataresolver_changes.metadata = /*metadata*/ ctx[6]; + + if (dirty & /*$$scope, metadata, selectedId, days, onClick, startOfWeek, onContextMenu, onHover, weekNum*/ 16639) { + metadataresolver_changes.$$scope = { dirty, ctx }; + } + + metadataresolver.$set(metadataresolver_changes); + }, + i(local) { + if (current) return; + transition_in(metadataresolver.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(metadataresolver.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(td); + destroy_component(metadataresolver); + } + }; +} + +function instance$1($$self, $$props, $$invalidate) { + + + let { weekNum } = $$props; + let { days } = $$props; + let { metadata } = $$props; + let { onHover } = $$props; + let { onClick } = $$props; + let { onContextMenu } = $$props; + let { selectedId = null } = $$props; + let startOfWeek; + const click_handler = e => onClick(startOfWeek, isMetaPressed(e)); + const contextmenu_handler = e => onContextMenu(days[0], e); + const pointerover_handler = e => onHover(startOfWeek, e.target, isMetaPressed(e)); + + $$self.$$set = $$props => { + if ("weekNum" in $$props) $$invalidate(0, weekNum = $$props.weekNum); + if ("days" in $$props) $$invalidate(1, days = $$props.days); + if ("metadata" in $$props) $$invalidate(6, metadata = $$props.metadata); + if ("onHover" in $$props) $$invalidate(2, onHover = $$props.onHover); + if ("onClick" in $$props) $$invalidate(3, onClick = $$props.onClick); + if ("onContextMenu" in $$props) $$invalidate(4, onContextMenu = $$props.onContextMenu); + if ("selectedId" in $$props) $$invalidate(5, selectedId = $$props.selectedId); + }; + + $$self.$$.update = () => { + if ($$self.$$.dirty & /*days*/ 2) { + $$invalidate(7, startOfWeek = getStartOfWeek(days)); + } + }; + + return [ + weekNum, + days, + onHover, + onClick, + onContextMenu, + selectedId, + metadata, + startOfWeek, + click_handler, + contextmenu_handler, + pointerover_handler + ]; +} + +class WeekNum extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-egt0yd-style")) add_css$1(); + + init(this, options, instance$1, create_fragment$1, not_equal, { + weekNum: 0, + days: 1, + metadata: 6, + onHover: 2, + onClick: 3, + onContextMenu: 4, + selectedId: 5 + }); + } +} + +async function metadataReducer(promisedMetadata) { + const meta = { + dots: [], + classes: [], + dataAttributes: {}, + }; + const metas = await Promise.all(promisedMetadata); + return metas.reduce((acc, meta) => ({ + classes: [...acc.classes, ...(meta.classes || [])], + dataAttributes: Object.assign(acc.dataAttributes, meta.dataAttributes), + dots: [...acc.dots, ...(meta.dots || [])], + }), meta); +} +function getDailyMetadata(sources, date, ..._args) { + return metadataReducer(sources.map((source) => source.getDailyMetadata(date))); +} +function getWeeklyMetadata(sources, date, ..._args) { + return metadataReducer(sources.map((source) => source.getWeeklyMetadata(date))); +} + +/* src/components/Calendar.svelte generated by Svelte v3.35.0 */ + +function add_css() { + var style = element("style"); + style.id = "svelte-pcimu8-style"; + style.textContent = ".container.svelte-pcimu8{--color-background-heading:transparent;--color-background-day:transparent;--color-background-weeknum:transparent;--color-background-weekend:transparent;--color-dot:var(--text-muted);--color-arrow:var(--text-muted);--color-button:var(--text-muted);--color-text-title:var(--text-normal);--color-text-heading:var(--text-muted);--color-text-day:var(--text-normal);--color-text-today:var(--interactive-accent);--color-text-weeknum:var(--text-muted)}.container.svelte-pcimu8{padding:0 8px}.container.is-mobile.svelte-pcimu8{padding:0}th.svelte-pcimu8{text-align:center}.weekend.svelte-pcimu8{background-color:var(--color-background-weekend)}.calendar.svelte-pcimu8{border-collapse:collapse;width:100%}th.svelte-pcimu8{background-color:var(--color-background-heading);color:var(--color-text-heading);font-size:0.6em;letter-spacing:1px;padding:4px;text-transform:uppercase}"; + append(document.head, style); +} + +function get_each_context(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[18] = list[i]; + return child_ctx; +} + +function get_each_context_1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[21] = list[i]; + return child_ctx; +} + +function get_each_context_2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[24] = list[i]; + return child_ctx; +} + +function get_each_context_3(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[27] = list[i]; + return child_ctx; +} + +// (55:6) {#if showWeekNums} +function create_if_block_2(ctx) { + let col; + + return { + c() { + col = element("col"); + }, + m(target, anchor) { + insert(target, col, anchor); + }, + d(detaching) { + if (detaching) detach(col); + } + }; +} + +// (58:6) {#each month[1].days as date} +function create_each_block_3(ctx) { + let col; + + return { + c() { + col = element("col"); + attr(col, "class", "svelte-pcimu8"); + toggle_class(col, "weekend", isWeekend(/*date*/ ctx[27])); + }, + m(target, anchor) { + insert(target, col, anchor); + }, + p(ctx, dirty) { + if (dirty & /*isWeekend, month*/ 16384) { + toggle_class(col, "weekend", isWeekend(/*date*/ ctx[27])); + } + }, + d(detaching) { + if (detaching) detach(col); + } + }; +} + +// (64:8) {#if showWeekNums} +function create_if_block_1(ctx) { + let th; + + return { + c() { + th = element("th"); + th.textContent = "W"; + attr(th, "class", "svelte-pcimu8"); + }, + m(target, anchor) { + insert(target, th, anchor); + }, + d(detaching) { + if (detaching) detach(th); + } + }; +} + +// (67:8) {#each daysOfWeek as dayOfWeek} +function create_each_block_2(ctx) { + let th; + let t_value = /*dayOfWeek*/ ctx[24] + ""; + let t; + + return { + c() { + th = element("th"); + t = text(t_value); + attr(th, "class", "svelte-pcimu8"); + }, + m(target, anchor) { + insert(target, th, anchor); + append(th, t); + }, + p(ctx, dirty) { + if (dirty & /*daysOfWeek*/ 32768 && t_value !== (t_value = /*dayOfWeek*/ ctx[24] + "")) set_data(t, t_value); + }, + d(detaching) { + if (detaching) detach(th); + } + }; +} + +// (75:10) {#if showWeekNums} +function create_if_block(ctx) { + let weeknum; + let current; + + const weeknum_spread_levels = [ + /*week*/ ctx[18], + { + metadata: getWeeklyMetadata(/*sources*/ ctx[8], /*week*/ ctx[18].days[0], /*today*/ ctx[10]) + }, + { onClick: /*onClickWeek*/ ctx[7] }, + { + onContextMenu: /*onContextMenuWeek*/ ctx[5] + }, + { onHover: /*onHoverWeek*/ ctx[3] }, + { selectedId: /*selectedId*/ ctx[9] } + ]; + + let weeknum_props = {}; + + for (let i = 0; i < weeknum_spread_levels.length; i += 1) { + weeknum_props = assign(weeknum_props, weeknum_spread_levels[i]); + } + + weeknum = new WeekNum({ props: weeknum_props }); + + return { + c() { + create_component(weeknum.$$.fragment); + }, + m(target, anchor) { + mount_component(weeknum, target, anchor); + current = true; + }, + p(ctx, dirty) { + const weeknum_changes = (dirty & /*month, getWeeklyMetadata, sources, today, onClickWeek, onContextMenuWeek, onHoverWeek, selectedId*/ 18344) + ? get_spread_update(weeknum_spread_levels, [ + dirty & /*month*/ 16384 && get_spread_object(/*week*/ ctx[18]), + dirty & /*getWeeklyMetadata, sources, month, today*/ 17664 && { + metadata: getWeeklyMetadata(/*sources*/ ctx[8], /*week*/ ctx[18].days[0], /*today*/ ctx[10]) + }, + dirty & /*onClickWeek*/ 128 && { onClick: /*onClickWeek*/ ctx[7] }, + dirty & /*onContextMenuWeek*/ 32 && { + onContextMenu: /*onContextMenuWeek*/ ctx[5] + }, + dirty & /*onHoverWeek*/ 8 && { onHover: /*onHoverWeek*/ ctx[3] }, + dirty & /*selectedId*/ 512 && { selectedId: /*selectedId*/ ctx[9] } + ]) + : {}; + + weeknum.$set(weeknum_changes); + }, + i(local) { + if (current) return; + transition_in(weeknum.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(weeknum.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(weeknum, detaching); + } + }; +} + +// (85:10) {#each week.days as day (day.format())} +function create_each_block_1(key_1, ctx) { + let first; + let day; + let current; + + day = new Day({ + props: { + date: /*day*/ ctx[21], + today: /*today*/ ctx[10], + displayedMonth: /*displayedMonth*/ ctx[0], + onClick: /*onClickDay*/ ctx[6], + onContextMenu: /*onContextMenuDay*/ ctx[4], + onHover: /*onHoverDay*/ ctx[2], + metadata: getDailyMetadata(/*sources*/ ctx[8], /*day*/ ctx[21], /*today*/ ctx[10]), + selectedId: /*selectedId*/ ctx[9] + } + }); + + return { + key: key_1, + first: null, + c() { + first = empty(); + create_component(day.$$.fragment); + this.first = first; + }, + m(target, anchor) { + insert(target, first, anchor); + mount_component(day, target, anchor); + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + const day_changes = {}; + if (dirty & /*month*/ 16384) day_changes.date = /*day*/ ctx[21]; + if (dirty & /*today*/ 1024) day_changes.today = /*today*/ ctx[10]; + if (dirty & /*displayedMonth*/ 1) day_changes.displayedMonth = /*displayedMonth*/ ctx[0]; + if (dirty & /*onClickDay*/ 64) day_changes.onClick = /*onClickDay*/ ctx[6]; + if (dirty & /*onContextMenuDay*/ 16) day_changes.onContextMenu = /*onContextMenuDay*/ ctx[4]; + if (dirty & /*onHoverDay*/ 4) day_changes.onHover = /*onHoverDay*/ ctx[2]; + if (dirty & /*sources, month, today*/ 17664) day_changes.metadata = getDailyMetadata(/*sources*/ ctx[8], /*day*/ ctx[21], /*today*/ ctx[10]); + if (dirty & /*selectedId*/ 512) day_changes.selectedId = /*selectedId*/ ctx[9]; + day.$set(day_changes); + }, + i(local) { + if (current) return; + transition_in(day.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(day.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(first); + destroy_component(day, detaching); + } + }; +} + +// (73:6) {#each month as week (week.weekNum)} +function create_each_block(key_1, ctx) { + let tr; + let t0; + let each_blocks = []; + let each_1_lookup = new Map(); + let t1; + let current; + let if_block = /*showWeekNums*/ ctx[1] && create_if_block(ctx); + let each_value_1 = /*week*/ ctx[18].days; + const get_key = ctx => /*day*/ ctx[21].format(); + + for (let i = 0; i < each_value_1.length; i += 1) { + let child_ctx = get_each_context_1(ctx, each_value_1, i); + let key = get_key(child_ctx); + each_1_lookup.set(key, each_blocks[i] = create_each_block_1(key, child_ctx)); + } + + return { + key: key_1, + first: null, + c() { + tr = element("tr"); + if (if_block) if_block.c(); + t0 = space(); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + t1 = space(); + this.first = tr; + }, + m(target, anchor) { + insert(target, tr, anchor); + if (if_block) if_block.m(tr, null); + append(tr, t0); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(tr, null); + } + + append(tr, t1); + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + + if (/*showWeekNums*/ ctx[1]) { + if (if_block) { + if_block.p(ctx, dirty); + + if (dirty & /*showWeekNums*/ 2) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block(ctx); + if_block.c(); + transition_in(if_block, 1); + if_block.m(tr, t0); + } + } else if (if_block) { + group_outros(); + + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + + check_outros(); + } + + if (dirty & /*month, today, displayedMonth, onClickDay, onContextMenuDay, onHoverDay, getDailyMetadata, sources, selectedId*/ 18261) { + each_value_1 = /*week*/ ctx[18].days; + group_outros(); + each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_1, each_1_lookup, tr, outro_and_destroy_block, create_each_block_1, t1, get_each_context_1); + check_outros(); + } + }, + i(local) { + if (current) return; + transition_in(if_block); + + for (let i = 0; i < each_value_1.length; i += 1) { + transition_in(each_blocks[i]); + } + + current = true; + }, + o(local) { + transition_out(if_block); + + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(tr); + if (if_block) if_block.d(); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].d(); + } + } + }; +} + +function create_fragment$7(ctx) { + let div; + let nav; + let t0; + let table; + let colgroup; + let t1; + let t2; + let thead; + let tr; + let t3; + let t4; + let tbody; + let each_blocks = []; + let each2_lookup = new Map(); + let current; + + nav = new Nav({ + props: { + today: /*today*/ ctx[10], + displayedMonth: /*displayedMonth*/ ctx[0], + incrementDisplayedMonth: /*incrementDisplayedMonth*/ ctx[11], + decrementDisplayedMonth: /*decrementDisplayedMonth*/ ctx[12], + resetDisplayedMonth: /*resetDisplayedMonth*/ ctx[13] + } + }); + + let if_block0 = /*showWeekNums*/ ctx[1] && create_if_block_2(); + let each_value_3 = /*month*/ ctx[14][1].days; + let each_blocks_2 = []; + + for (let i = 0; i < each_value_3.length; i += 1) { + each_blocks_2[i] = create_each_block_3(get_each_context_3(ctx, each_value_3, i)); + } + + let if_block1 = /*showWeekNums*/ ctx[1] && create_if_block_1(); + let each_value_2 = /*daysOfWeek*/ ctx[15]; + let each_blocks_1 = []; + + for (let i = 0; i < each_value_2.length; i += 1) { + each_blocks_1[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i)); + } + + let each_value = /*month*/ ctx[14]; + const get_key = ctx => /*week*/ ctx[18].weekNum; + + for (let i = 0; i < each_value.length; i += 1) { + let child_ctx = get_each_context(ctx, each_value, i); + let key = get_key(child_ctx); + each2_lookup.set(key, each_blocks[i] = create_each_block(key, child_ctx)); + } + + return { + c() { + div = element("div"); + create_component(nav.$$.fragment); + t0 = space(); + table = element("table"); + colgroup = element("colgroup"); + if (if_block0) if_block0.c(); + t1 = space(); + + for (let i = 0; i < each_blocks_2.length; i += 1) { + each_blocks_2[i].c(); + } + + t2 = space(); + thead = element("thead"); + tr = element("tr"); + if (if_block1) if_block1.c(); + t3 = space(); + + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].c(); + } + + t4 = space(); + tbody = element("tbody"); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + attr(table, "class", "calendar svelte-pcimu8"); + attr(div, "id", "calendar-container"); + attr(div, "class", "container svelte-pcimu8"); + toggle_class(div, "is-mobile", /*isMobile*/ ctx[16]); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(nav, div, null); + append(div, t0); + append(div, table); + append(table, colgroup); + if (if_block0) if_block0.m(colgroup, null); + append(colgroup, t1); + + for (let i = 0; i < each_blocks_2.length; i += 1) { + each_blocks_2[i].m(colgroup, null); + } + + append(table, t2); + append(table, thead); + append(thead, tr); + if (if_block1) if_block1.m(tr, null); + append(tr, t3); + + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].m(tr, null); + } + + append(table, t4); + append(table, tbody); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(tbody, null); + } + + current = true; + }, + p(ctx, [dirty]) { + const nav_changes = {}; + if (dirty & /*today*/ 1024) nav_changes.today = /*today*/ ctx[10]; + if (dirty & /*displayedMonth*/ 1) nav_changes.displayedMonth = /*displayedMonth*/ ctx[0]; + nav.$set(nav_changes); + + if (/*showWeekNums*/ ctx[1]) { + if (if_block0) ; else { + if_block0 = create_if_block_2(); + if_block0.c(); + if_block0.m(colgroup, t1); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + + if (dirty & /*isWeekend, month*/ 16384) { + each_value_3 = /*month*/ ctx[14][1].days; + let i; + + for (i = 0; i < each_value_3.length; i += 1) { + const child_ctx = get_each_context_3(ctx, each_value_3, i); + + if (each_blocks_2[i]) { + each_blocks_2[i].p(child_ctx, dirty); + } else { + each_blocks_2[i] = create_each_block_3(child_ctx); + each_blocks_2[i].c(); + each_blocks_2[i].m(colgroup, null); + } + } + + for (; i < each_blocks_2.length; i += 1) { + each_blocks_2[i].d(1); + } + + each_blocks_2.length = each_value_3.length; + } + + if (/*showWeekNums*/ ctx[1]) { + if (if_block1) ; else { + if_block1 = create_if_block_1(); + if_block1.c(); + if_block1.m(tr, t3); + } + } else if (if_block1) { + if_block1.d(1); + if_block1 = null; + } + + if (dirty & /*daysOfWeek*/ 32768) { + each_value_2 = /*daysOfWeek*/ ctx[15]; + let i; + + for (i = 0; i < each_value_2.length; i += 1) { + const child_ctx = get_each_context_2(ctx, each_value_2, i); + + if (each_blocks_1[i]) { + each_blocks_1[i].p(child_ctx, dirty); + } else { + each_blocks_1[i] = create_each_block_2(child_ctx); + each_blocks_1[i].c(); + each_blocks_1[i].m(tr, null); + } + } + + for (; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].d(1); + } + + each_blocks_1.length = each_value_2.length; + } + + if (dirty & /*month, today, displayedMonth, onClickDay, onContextMenuDay, onHoverDay, getDailyMetadata, sources, selectedId, getWeeklyMetadata, onClickWeek, onContextMenuWeek, onHoverWeek, showWeekNums*/ 18431) { + each_value = /*month*/ ctx[14]; + group_outros(); + each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value, each2_lookup, tbody, outro_and_destroy_block, create_each_block, null, get_each_context); + check_outros(); + } + }, + i(local) { + if (current) return; + transition_in(nav.$$.fragment, local); + + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + + current = true; + }, + o(local) { + transition_out(nav.$$.fragment, local); + + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(div); + destroy_component(nav); + if (if_block0) if_block0.d(); + destroy_each(each_blocks_2, detaching); + if (if_block1) if_block1.d(); + destroy_each(each_blocks_1, detaching); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].d(); + } + } + }; +} + +function instance$7($$self, $$props, $$invalidate) { + + + let { localeData } = $$props; + let { showWeekNums = false } = $$props; + let { onHoverDay } = $$props; + let { onHoverWeek } = $$props; + let { onContextMenuDay } = $$props; + let { onContextMenuWeek } = $$props; + let { onClickDay } = $$props; + let { onClickWeek } = $$props; + let { sources = [] } = $$props; + let { selectedId } = $$props; + let { today = window.moment() } = $$props; + let { displayedMonth = today } = $$props; + let month; + let daysOfWeek; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let isMobile = window.app.isMobile; + + function incrementDisplayedMonth() { + $$invalidate(0, displayedMonth = displayedMonth.clone().add(1, "month")); + } + + function decrementDisplayedMonth() { + $$invalidate(0, displayedMonth = displayedMonth.clone().subtract(1, "month")); + } + + function resetDisplayedMonth() { + $$invalidate(0, displayedMonth = today.clone()); + } + + $$self.$$set = $$props => { + if ("localeData" in $$props) $$invalidate(17, localeData = $$props.localeData); + if ("showWeekNums" in $$props) $$invalidate(1, showWeekNums = $$props.showWeekNums); + if ("onHoverDay" in $$props) $$invalidate(2, onHoverDay = $$props.onHoverDay); + if ("onHoverWeek" in $$props) $$invalidate(3, onHoverWeek = $$props.onHoverWeek); + if ("onContextMenuDay" in $$props) $$invalidate(4, onContextMenuDay = $$props.onContextMenuDay); + if ("onContextMenuWeek" in $$props) $$invalidate(5, onContextMenuWeek = $$props.onContextMenuWeek); + if ("onClickDay" in $$props) $$invalidate(6, onClickDay = $$props.onClickDay); + if ("onClickWeek" in $$props) $$invalidate(7, onClickWeek = $$props.onClickWeek); + if ("sources" in $$props) $$invalidate(8, sources = $$props.sources); + if ("selectedId" in $$props) $$invalidate(9, selectedId = $$props.selectedId); + if ("today" in $$props) $$invalidate(10, today = $$props.today); + if ("displayedMonth" in $$props) $$invalidate(0, displayedMonth = $$props.displayedMonth); + }; + + $$self.$$.update = () => { + if ($$self.$$.dirty & /*displayedMonth, localeData*/ 131073) { + $$invalidate(14, month = getMonth(displayedMonth, localeData)); + } + + if ($$self.$$.dirty & /*today, localeData*/ 132096) { + $$invalidate(15, daysOfWeek = getDaysOfWeek(today, localeData)); + } + }; + + return [ + displayedMonth, + showWeekNums, + onHoverDay, + onHoverWeek, + onContextMenuDay, + onContextMenuWeek, + onClickDay, + onClickWeek, + sources, + selectedId, + today, + incrementDisplayedMonth, + decrementDisplayedMonth, + resetDisplayedMonth, + month, + daysOfWeek, + isMobile, + localeData + ]; +} + +class Calendar$1 extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-pcimu8-style")) add_css(); + + init(this, options, instance$7, create_fragment$7, not_equal, { + localeData: 17, + showWeekNums: 1, + onHoverDay: 2, + onHoverWeek: 3, + onContextMenuDay: 4, + onContextMenuWeek: 5, + onClickDay: 6, + onClickWeek: 7, + sources: 8, + selectedId: 9, + today: 10, + displayedMonth: 0, + incrementDisplayedMonth: 11, + decrementDisplayedMonth: 12, + resetDisplayedMonth: 13 + }); + } + + get incrementDisplayedMonth() { + return this.$$.ctx[11]; + } + + get decrementDisplayedMonth() { + return this.$$.ctx[12]; + } + + get resetDisplayedMonth() { + return this.$$.ctx[13]; + } +} + +const langToMomentLocale = { + en: "en-gb", + zh: "zh-cn", + "zh-TW": "zh-tw", + ru: "ru", + ko: "ko", + it: "it", + id: "id", + ro: "ro", + "pt-BR": "pt-br", + cz: "cs", + da: "da", + de: "de", + es: "es", + fr: "fr", + no: "nn", + pl: "pl", + pt: "pt", + tr: "tr", + hi: "hi", + nl: "nl", + ar: "ar", + ja: "ja", +}; +const weekdays = [ + "sunday", + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", +]; +function overrideGlobalMomentWeekStart(weekStart) { + const { moment } = window; + const currentLocale = moment.locale(); + // Save the initial locale weekspec so that we can restore + // it when toggling between the different options in settings. + if (!window._bundledLocaleWeekSpec) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + window._bundledLocaleWeekSpec = moment.localeData()._week; + } + if (weekStart === "locale") { + moment.updateLocale(currentLocale, { + week: window._bundledLocaleWeekSpec, + }); + } + else { + moment.updateLocale(currentLocale, { + week: { + dow: weekdays.indexOf(weekStart) || 0, + }, + }); + } +} +/** + * Sets the locale used by the calendar. This allows the calendar to + * default to the user's locale (e.g. Start Week on Sunday/Monday/Friday) + * + * @param localeOverride locale string (e.g. "en-US") + */ +function configureGlobalMomentLocale(localeOverride = "system-default", weekStart = "locale") { + var _a; + const obsidianLang = localStorage.getItem("language") || "en"; + const systemLang = (_a = navigator.language) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + let momentLocale = langToMomentLocale[obsidianLang]; + if (localeOverride !== "system-default") { + momentLocale = localeOverride; + } + else if (systemLang.startsWith(obsidianLang)) { + // If the system locale is more specific (en-gb vs en), use the system locale. + momentLocale = systemLang; + } + const currentLocale = window.moment.locale(momentLocale); + console.debug(`[Calendar] Trying to switch Moment.js global locale to ${momentLocale}, got ${currentLocale}`); + overrideGlobalMomentWeekStart(weekStart); + return currentLocale; +} + +/* src/ui/Calendar.svelte generated by Svelte v3.35.0 */ + +function create_fragment(ctx) { + let calendarbase; + let updating_displayedMonth; + let current; + + function calendarbase_displayedMonth_binding(value) { + /*calendarbase_displayedMonth_binding*/ ctx[12](value); + } + + let calendarbase_props = { + sources: /*sources*/ ctx[1], + today: /*today*/ ctx[9], + onHoverDay: /*onHoverDay*/ ctx[2], + onHoverWeek: /*onHoverWeek*/ ctx[3], + onContextMenuDay: /*onContextMenuDay*/ ctx[6], + onContextMenuWeek: /*onContextMenuWeek*/ ctx[7], + onClickDay: /*onClickDay*/ ctx[4], + onClickWeek: /*onClickWeek*/ ctx[5], + localeData: /*today*/ ctx[9].localeData(), + selectedId: /*$activeFile*/ ctx[10], + showWeekNums: /*$settings*/ ctx[8].showWeeklyNote + }; + + if (/*displayedMonth*/ ctx[0] !== void 0) { + calendarbase_props.displayedMonth = /*displayedMonth*/ ctx[0]; + } + + calendarbase = new Calendar$1({ props: calendarbase_props }); + binding_callbacks$1.push(() => bind(calendarbase, "displayedMonth", calendarbase_displayedMonth_binding)); + + return { + c() { + create_component$1(calendarbase.$$.fragment); + }, + m(target, anchor) { + mount_component$1(calendarbase, target, anchor); + current = true; + }, + p(ctx, [dirty]) { + const calendarbase_changes = {}; + if (dirty & /*sources*/ 2) calendarbase_changes.sources = /*sources*/ ctx[1]; + if (dirty & /*today*/ 512) calendarbase_changes.today = /*today*/ ctx[9]; + if (dirty & /*onHoverDay*/ 4) calendarbase_changes.onHoverDay = /*onHoverDay*/ ctx[2]; + if (dirty & /*onHoverWeek*/ 8) calendarbase_changes.onHoverWeek = /*onHoverWeek*/ ctx[3]; + if (dirty & /*onContextMenuDay*/ 64) calendarbase_changes.onContextMenuDay = /*onContextMenuDay*/ ctx[6]; + if (dirty & /*onContextMenuWeek*/ 128) calendarbase_changes.onContextMenuWeek = /*onContextMenuWeek*/ ctx[7]; + if (dirty & /*onClickDay*/ 16) calendarbase_changes.onClickDay = /*onClickDay*/ ctx[4]; + if (dirty & /*onClickWeek*/ 32) calendarbase_changes.onClickWeek = /*onClickWeek*/ ctx[5]; + if (dirty & /*today*/ 512) calendarbase_changes.localeData = /*today*/ ctx[9].localeData(); + if (dirty & /*$activeFile*/ 1024) calendarbase_changes.selectedId = /*$activeFile*/ ctx[10]; + if (dirty & /*$settings*/ 256) calendarbase_changes.showWeekNums = /*$settings*/ ctx[8].showWeeklyNote; + + if (!updating_displayedMonth && dirty & /*displayedMonth*/ 1) { + updating_displayedMonth = true; + calendarbase_changes.displayedMonth = /*displayedMonth*/ ctx[0]; + add_flush_callback(() => updating_displayedMonth = false); + } + + calendarbase.$set(calendarbase_changes); + }, + i(local) { + if (current) return; + transition_in$1(calendarbase.$$.fragment, local); + current = true; + }, + o(local) { + transition_out$1(calendarbase.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component$1(calendarbase, detaching); + } + }; +} + +function instance($$self, $$props, $$invalidate) { + let $settings; + let $activeFile; + component_subscribe($$self, settings, $$value => $$invalidate(8, $settings = $$value)); + component_subscribe($$self, activeFile, $$value => $$invalidate(10, $activeFile = $$value)); + + + let today; + let { displayedMonth = today } = $$props; + let { sources } = $$props; + let { onHoverDay } = $$props; + let { onHoverWeek } = $$props; + let { onClickDay } = $$props; + let { onClickWeek } = $$props; + let { onContextMenuDay } = $$props; + let { onContextMenuWeek } = $$props; + + function tick() { + $$invalidate(9, today = window.moment()); + } + + function getToday(settings) { + configureGlobalMomentLocale(settings.localeOverride, settings.weekStart); + dailyNotes.reindex(); + weeklyNotes.reindex(); + return window.moment(); + } + + // 1 minute heartbeat to keep `today` reflecting the current day + let heartbeat = setInterval( + () => { + tick(); + const isViewingCurrentMonth = displayedMonth.isSame(today, "day"); + + if (isViewingCurrentMonth) { + // if it's midnight on the last day of the month, this will + // update the display to show the new month. + $$invalidate(0, displayedMonth = today); + } + }, + 1000 * 60 + ); + + onDestroy(() => { + clearInterval(heartbeat); + }); + + function calendarbase_displayedMonth_binding(value) { + displayedMonth = value; + $$invalidate(0, displayedMonth); + } + + $$self.$$set = $$props => { + if ("displayedMonth" in $$props) $$invalidate(0, displayedMonth = $$props.displayedMonth); + if ("sources" in $$props) $$invalidate(1, sources = $$props.sources); + if ("onHoverDay" in $$props) $$invalidate(2, onHoverDay = $$props.onHoverDay); + if ("onHoverWeek" in $$props) $$invalidate(3, onHoverWeek = $$props.onHoverWeek); + if ("onClickDay" in $$props) $$invalidate(4, onClickDay = $$props.onClickDay); + if ("onClickWeek" in $$props) $$invalidate(5, onClickWeek = $$props.onClickWeek); + if ("onContextMenuDay" in $$props) $$invalidate(6, onContextMenuDay = $$props.onContextMenuDay); + if ("onContextMenuWeek" in $$props) $$invalidate(7, onContextMenuWeek = $$props.onContextMenuWeek); + }; + + $$self.$$.update = () => { + if ($$self.$$.dirty & /*$settings*/ 256) { + $$invalidate(9, today = getToday($settings)); + } + }; + + return [ + displayedMonth, + sources, + onHoverDay, + onHoverWeek, + onClickDay, + onClickWeek, + onContextMenuDay, + onContextMenuWeek, + $settings, + today, + $activeFile, + tick, + calendarbase_displayedMonth_binding + ]; +} + +class Calendar extends SvelteComponent$1 { + constructor(options) { + super(); + + init$1(this, options, instance, create_fragment, not_equal$1, { + displayedMonth: 0, + sources: 1, + onHoverDay: 2, + onHoverWeek: 3, + onClickDay: 4, + onClickWeek: 5, + onContextMenuDay: 6, + onContextMenuWeek: 7, + tick: 11 + }); + } + + get tick() { + return this.$$.ctx[11]; + } +} + +function showFileMenu(app, file, position) { + const fileMenu = new obsidian.Menu(app); + fileMenu.addItem((item) => item + .setTitle("Delete") + .setIcon("trash") + .onClick(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + app.fileManager.promptForFileDeletion(file); + })); + app.workspace.trigger("file-menu", fileMenu, file, "calendar-context-menu", null); + fileMenu.showAtPosition(position); +} + +const getStreakClasses = (file) => { + return classList({ + "has-note": !!file, + }); +}; +const streakSource = { + getDailyMetadata: async (date) => { + const file = getDailyNote_1(date, get_store_value(dailyNotes)); + return { + classes: getStreakClasses(file), + dots: [], + }; + }, + getWeeklyMetadata: async (date) => { + const file = getWeeklyNote_1(date, get_store_value(weeklyNotes)); + return { + classes: getStreakClasses(file), + dots: [], + }; + }, +}; + +function getNoteTags(note) { + var _a; + if (!note) { + return []; + } + const { metadataCache } = window.app; + const frontmatter = (_a = metadataCache.getFileCache(note)) === null || _a === void 0 ? void 0 : _a.frontmatter; + const tags = []; + if (frontmatter) { + const frontmatterTags = obsidian.parseFrontMatterTags(frontmatter) || []; + tags.push(...frontmatterTags); + } + // strip the '#' at the beginning + return tags.map((tag) => tag.substring(1)); +} +function getFormattedTagAttributes(note) { + const attrs = {}; + const tags = getNoteTags(note); + const [emojiTags, nonEmojiTags] = partition(tags, (tag) => /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/.test(tag)); + if (nonEmojiTags) { + attrs["data-tags"] = nonEmojiTags.join(" "); + } + if (emojiTags) { + attrs["data-emoji-tag"] = emojiTags[0]; + } + return attrs; +} +const customTagsSource = { + getDailyMetadata: async (date) => { + const file = getDailyNote_1(date, get_store_value(dailyNotes)); + return { + dataAttributes: getFormattedTagAttributes(file), + dots: [], + }; + }, + getWeeklyMetadata: async (date) => { + const file = getWeeklyNote_1(date, get_store_value(weeklyNotes)); + return { + dataAttributes: getFormattedTagAttributes(file), + dots: [], + }; + }, +}; + +async function getNumberOfRemainingTasks(note) { + if (!note) { + return 0; + } + const { vault } = window.app; + const fileContents = await vault.cachedRead(note); + return (fileContents.match(/(-|\*) \[ \]/g) || []).length; +} +async function getDotsForDailyNote$1(dailyNote) { + if (!dailyNote) { + return []; + } + const numTasks = await getNumberOfRemainingTasks(dailyNote); + const dots = []; + if (numTasks) { + dots.push({ + className: "task", + color: "default", + isFilled: false, + }); + } + return dots; +} +const tasksSource = { + getDailyMetadata: async (date) => { + const file = getDailyNote_1(date, get_store_value(dailyNotes)); + const dots = await getDotsForDailyNote$1(file); + return { + dots, + }; + }, + getWeeklyMetadata: async (date) => { + const file = getWeeklyNote_1(date, get_store_value(weeklyNotes)); + const dots = await getDotsForDailyNote$1(file); + return { + dots, + }; + }, +}; + +const NUM_MAX_DOTS = 5; +async function getWordLengthAsDots(note) { + const { wordsPerDot = DEFAULT_WORDS_PER_DOT } = get_store_value(settings); + if (!note || wordsPerDot <= 0) { + return 0; + } + const fileContents = await window.app.vault.cachedRead(note); + const wordCount = getWordCount(fileContents); + const numDots = wordCount / wordsPerDot; + return clamp(Math.floor(numDots), 1, NUM_MAX_DOTS); +} +async function getDotsForDailyNote(dailyNote) { + if (!dailyNote) { + return []; + } + const numSolidDots = await getWordLengthAsDots(dailyNote); + const dots = []; + for (let i = 0; i < numSolidDots; i++) { + dots.push({ + color: "default", + isFilled: true, + }); + } + return dots; +} +const wordCountSource = { + getDailyMetadata: async (date) => { + const file = getDailyNote_1(date, get_store_value(dailyNotes)); + const dots = await getDotsForDailyNote(file); + return { + dots, + }; + }, + getWeeklyMetadata: async (date) => { + const file = getWeeklyNote_1(date, get_store_value(weeklyNotes)); + const dots = await getDotsForDailyNote(file); + return { + dots, + }; + }, +}; + +class CalendarView extends obsidian.ItemView { + constructor(leaf) { + super(leaf); + this.openOrCreateDailyNote = this.openOrCreateDailyNote.bind(this); + this.openOrCreateWeeklyNote = this.openOrCreateWeeklyNote.bind(this); + this.onNoteSettingsUpdate = this.onNoteSettingsUpdate.bind(this); + this.onFileCreated = this.onFileCreated.bind(this); + this.onFileDeleted = this.onFileDeleted.bind(this); + this.onFileModified = this.onFileModified.bind(this); + this.onFileOpen = this.onFileOpen.bind(this); + this.onHoverDay = this.onHoverDay.bind(this); + this.onHoverWeek = this.onHoverWeek.bind(this); + this.onContextMenuDay = this.onContextMenuDay.bind(this); + this.onContextMenuWeek = this.onContextMenuWeek.bind(this); + this.registerEvent( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.app.workspace.on("periodic-notes:settings-updated", this.onNoteSettingsUpdate)); + this.registerEvent(this.app.vault.on("create", this.onFileCreated)); + this.registerEvent(this.app.vault.on("delete", this.onFileDeleted)); + this.registerEvent(this.app.vault.on("modify", this.onFileModified)); + this.registerEvent(this.app.workspace.on("file-open", this.onFileOpen)); + this.settings = null; + settings.subscribe((val) => { + this.settings = val; + // Refresh the calendar if settings change + if (this.calendar) { + this.calendar.tick(); + } + }); + } + getViewType() { + return VIEW_TYPE_CALENDAR; + } + getDisplayText() { + return "Calendar"; + } + getIcon() { + return "calendar-with-checkmark"; + } + onClose() { + if (this.calendar) { + this.calendar.$destroy(); + } + return Promise.resolve(); + } + async onOpen() { + // Integration point: external plugins can listen for `calendar:open` + // to feed in additional sources. + const sources = [ + customTagsSource, + streakSource, + wordCountSource, + tasksSource, + ]; + this.app.workspace.trigger(TRIGGER_ON_OPEN, sources); + this.calendar = new Calendar({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + target: this.contentEl, + props: { + onClickDay: this.openOrCreateDailyNote, + onClickWeek: this.openOrCreateWeeklyNote, + onHoverDay: this.onHoverDay, + onHoverWeek: this.onHoverWeek, + onContextMenuDay: this.onContextMenuDay, + onContextMenuWeek: this.onContextMenuWeek, + sources, + }, + }); + } + onHoverDay(date, targetEl, isMetaPressed) { + if (!isMetaPressed) { + return; + } + const { format } = getDailyNoteSettings_1(); + const note = getDailyNote_1(date, get_store_value(dailyNotes)); + this.app.workspace.trigger("link-hover", this, targetEl, date.format(format), note === null || note === void 0 ? void 0 : note.path); + } + onHoverWeek(date, targetEl, isMetaPressed) { + if (!isMetaPressed) { + return; + } + const note = getWeeklyNote_1(date, get_store_value(weeklyNotes)); + const { format } = getWeeklyNoteSettings_1(); + this.app.workspace.trigger("link-hover", this, targetEl, date.format(format), note === null || note === void 0 ? void 0 : note.path); + } + onContextMenuDay(date, event) { + const note = getDailyNote_1(date, get_store_value(dailyNotes)); + if (!note) { + // If no file exists for a given day, show nothing. + return; + } + showFileMenu(this.app, note, { + x: event.pageX, + y: event.pageY, + }); + } + onContextMenuWeek(date, event) { + const note = getWeeklyNote_1(date, get_store_value(weeklyNotes)); + if (!note) { + // If no file exists for a given day, show nothing. + return; + } + showFileMenu(this.app, note, { + x: event.pageX, + y: event.pageY, + }); + } + onNoteSettingsUpdate() { + dailyNotes.reindex(); + weeklyNotes.reindex(); + this.updateActiveFile(); + } + async onFileDeleted(file) { + if (getDateFromFile_1(file, "day")) { + dailyNotes.reindex(); + this.updateActiveFile(); + } + if (getDateFromFile_1(file, "week")) { + weeklyNotes.reindex(); + this.updateActiveFile(); + } + } + async onFileModified(file) { + const date = getDateFromFile_1(file, "day") || getDateFromFile_1(file, "week"); + if (date && this.calendar) { + this.calendar.tick(); + } + } + onFileCreated(file) { + if (this.app.workspace.layoutReady && this.calendar) { + if (getDateFromFile_1(file, "day")) { + dailyNotes.reindex(); + this.calendar.tick(); + } + if (getDateFromFile_1(file, "week")) { + weeklyNotes.reindex(); + this.calendar.tick(); + } + } + } + onFileOpen(_file) { + if (this.app.workspace.layoutReady) { + this.updateActiveFile(); + } + } + updateActiveFile() { + const { view } = this.app.workspace.activeLeaf; + let file = null; + if (view instanceof obsidian.FileView) { + file = view.file; + } + activeFile.setFile(file); + if (this.calendar) { + this.calendar.tick(); + } + } + revealActiveNote() { + const { moment } = window; + const { activeLeaf } = this.app.workspace; + if (activeLeaf.view instanceof obsidian.FileView) { + // Check to see if the active note is a daily-note + let date = getDateFromFile_1(activeLeaf.view.file, "day"); + if (date) { + this.calendar.$set({ displayedMonth: date }); + return; + } + // Check to see if the active note is a weekly-note + const { format } = getWeeklyNoteSettings_1(); + date = moment(activeLeaf.view.file.basename, format, true); + if (date.isValid()) { + this.calendar.$set({ displayedMonth: date }); + return; + } + } + } + async openOrCreateWeeklyNote(date, inNewSplit) { + const { workspace } = this.app; + const startOfWeek = date.clone().startOf("week"); + const existingFile = getWeeklyNote_1(date, get_store_value(weeklyNotes)); + if (!existingFile) { + // File doesn't exist + tryToCreateWeeklyNote(startOfWeek, inNewSplit, this.settings, (file) => { + activeFile.setFile(file); + }); + return; + } + const leaf = inNewSplit + ? workspace.splitActiveLeaf() + : workspace.getUnpinnedLeaf(); + await leaf.openFile(existingFile); + activeFile.setFile(existingFile); + } + async openOrCreateDailyNote(date, inNewSplit) { + const { workspace } = this.app; + const existingFile = getDailyNote_1(date, get_store_value(dailyNotes)); + if (!existingFile) { + // File doesn't exist + tryToCreateDailyNote(date, inNewSplit, this.settings, (dailyNote) => { + activeFile.setFile(dailyNote); + }); + return; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mode = this.app.vault.getConfig("defaultViewMode"); + const leaf = inNewSplit + ? workspace.splitActiveLeaf() + : workspace.getUnpinnedLeaf(); + await leaf.openFile(existingFile, { mode }); + activeFile.setFile(existingFile); + } +} + +class CalendarPlugin extends obsidian.Plugin { + onunload() { + this.app.workspace + .getLeavesOfType(VIEW_TYPE_CALENDAR) + .forEach((leaf) => leaf.detach()); + } + async onload() { + this.register(settings.subscribe((value) => { + this.options = value; + })); + this.registerView(VIEW_TYPE_CALENDAR, (leaf) => (this.view = new CalendarView(leaf))); + this.addCommand({ + id: "show-calendar-view", + name: "Open view", + checkCallback: (checking) => { + if (checking) { + return (this.app.workspace.getLeavesOfType(VIEW_TYPE_CALENDAR).length === 0); + } + this.initLeaf(); + }, + }); + this.addCommand({ + id: "open-weekly-note", + name: "Open Weekly Note", + checkCallback: (checking) => { + if (checking) { + return !appHasPeriodicNotesPluginLoaded(); + } + this.view.openOrCreateWeeklyNote(window.moment(), false); + }, + }); + this.addCommand({ + id: "reveal-active-note", + name: "Reveal active note", + callback: () => this.view.revealActiveNote(), + }); + await this.loadOptions(); + this.addSettingTab(new CalendarSettingsTab(this.app, this)); + if (this.app.workspace.layoutReady) { + this.initLeaf(); + } + else { + this.registerEvent(this.app.workspace.on("layout-ready", this.initLeaf.bind(this))); + } + } + initLeaf() { + if (this.app.workspace.getLeavesOfType(VIEW_TYPE_CALENDAR).length) { + return; + } + this.app.workspace.getRightLeaf(false).setViewState({ + type: VIEW_TYPE_CALENDAR, + }); + } + async loadOptions() { + const options = await this.loadData(); + settings.update((old) => { + return Object.assign(Object.assign({}, old), (options || {})); + }); + await this.saveData(this.options); + } + async writeOptions(changeOpts) { + settings.update((old) => (Object.assign(Object.assign({}, old), changeOpts(old)))); + await this.saveData(this.options); + } +} + +module.exports = CalendarPlugin; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/calendar/manifest.json b/.obsidian/plugins/calendar/manifest.json new file mode 100644 index 0000000..028bfa5 --- /dev/null +++ b/.obsidian/plugins/calendar/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "calendar", + "name": "Calendar", + "description": "Calendar view of your daily notes", + "version": "1.5.10", + "author": "Liam Cain", + "authorUrl": "https://github.com/liamcain/", + "isDesktopOnly": false, + "minAppVersion": "0.9.11" +} diff --git a/.obsidian/plugins/dataview/main.js b/.obsidian/plugins/dataview/main.js new file mode 100644 index 0000000..898d702 --- /dev/null +++ b/.obsidian/plugins/dataview/main.js @@ -0,0 +1,20876 @@ +'use strict'; + +var obsidian = require('obsidian'); +var state = require('@codemirror/state'); +var view = require('@codemirror/view'); +var language = require('@codemirror/language'); + +// these aren't really private, but nor are they really useful to document + +/** + * @private + */ +class LuxonError extends Error {} + +/** + * @private + */ +class InvalidDateTimeError extends LuxonError { + constructor(reason) { + super(`Invalid DateTime: ${reason.toMessage()}`); + } +} + +/** + * @private + */ +class InvalidIntervalError extends LuxonError { + constructor(reason) { + super(`Invalid Interval: ${reason.toMessage()}`); + } +} + +/** + * @private + */ +class InvalidDurationError extends LuxonError { + constructor(reason) { + super(`Invalid Duration: ${reason.toMessage()}`); + } +} + +/** + * @private + */ +class ConflictingSpecificationError extends LuxonError {} + +/** + * @private + */ +class InvalidUnitError extends LuxonError { + constructor(unit) { + super(`Invalid unit ${unit}`); + } +} + +/** + * @private + */ +class InvalidArgumentError extends LuxonError {} + +/** + * @private + */ +class ZoneIsAbstractError extends LuxonError { + constructor() { + super("Zone is an abstract class"); + } +} + +/** + * @private + */ + +const n$1 = "numeric", + s$2 = "short", + l$2 = "long"; + +const DATE_SHORT = { + year: n$1, + month: n$1, + day: n$1, +}; + +const DATE_MED = { + year: n$1, + month: s$2, + day: n$1, +}; + +const DATE_MED_WITH_WEEKDAY = { + year: n$1, + month: s$2, + day: n$1, + weekday: s$2, +}; + +const DATE_FULL = { + year: n$1, + month: l$2, + day: n$1, +}; + +const DATE_HUGE = { + year: n$1, + month: l$2, + day: n$1, + weekday: l$2, +}; + +const TIME_SIMPLE = { + hour: n$1, + minute: n$1, +}; + +const TIME_WITH_SECONDS = { + hour: n$1, + minute: n$1, + second: n$1, +}; + +const TIME_WITH_SHORT_OFFSET = { + hour: n$1, + minute: n$1, + second: n$1, + timeZoneName: s$2, +}; + +const TIME_WITH_LONG_OFFSET = { + hour: n$1, + minute: n$1, + second: n$1, + timeZoneName: l$2, +}; + +const TIME_24_SIMPLE = { + hour: n$1, + minute: n$1, + hourCycle: "h23", +}; + +const TIME_24_WITH_SECONDS = { + hour: n$1, + minute: n$1, + second: n$1, + hourCycle: "h23", +}; + +const TIME_24_WITH_SHORT_OFFSET = { + hour: n$1, + minute: n$1, + second: n$1, + hourCycle: "h23", + timeZoneName: s$2, +}; + +const TIME_24_WITH_LONG_OFFSET = { + hour: n$1, + minute: n$1, + second: n$1, + hourCycle: "h23", + timeZoneName: l$2, +}; + +const DATETIME_SHORT = { + year: n$1, + month: n$1, + day: n$1, + hour: n$1, + minute: n$1, +}; + +const DATETIME_SHORT_WITH_SECONDS = { + year: n$1, + month: n$1, + day: n$1, + hour: n$1, + minute: n$1, + second: n$1, +}; + +const DATETIME_MED = { + year: n$1, + month: s$2, + day: n$1, + hour: n$1, + minute: n$1, +}; + +const DATETIME_MED_WITH_SECONDS = { + year: n$1, + month: s$2, + day: n$1, + hour: n$1, + minute: n$1, + second: n$1, +}; + +const DATETIME_MED_WITH_WEEKDAY = { + year: n$1, + month: s$2, + day: n$1, + weekday: s$2, + hour: n$1, + minute: n$1, +}; + +const DATETIME_FULL = { + year: n$1, + month: l$2, + day: n$1, + hour: n$1, + minute: n$1, + timeZoneName: s$2, +}; + +const DATETIME_FULL_WITH_SECONDS = { + year: n$1, + month: l$2, + day: n$1, + hour: n$1, + minute: n$1, + second: n$1, + timeZoneName: s$2, +}; + +const DATETIME_HUGE = { + year: n$1, + month: l$2, + day: n$1, + weekday: l$2, + hour: n$1, + minute: n$1, + timeZoneName: l$2, +}; + +const DATETIME_HUGE_WITH_SECONDS = { + year: n$1, + month: l$2, + day: n$1, + weekday: l$2, + hour: n$1, + minute: n$1, + second: n$1, + timeZoneName: l$2, +}; + +/** + * @interface + */ +class Zone { + /** + * The type of zone + * @abstract + * @type {string} + */ + get type() { + throw new ZoneIsAbstractError(); + } + + /** + * The name of this zone. + * @abstract + * @type {string} + */ + get name() { + throw new ZoneIsAbstractError(); + } + + get ianaName() { + return this.name; + } + + /** + * Returns whether the offset is known to be fixed for the whole year. + * @abstract + * @type {boolean} + */ + get isUniversal() { + throw new ZoneIsAbstractError(); + } + + /** + * Returns the offset's common name (such as EST) at the specified timestamp + * @abstract + * @param {number} ts - Epoch milliseconds for which to get the name + * @param {Object} opts - Options to affect the format + * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. + * @param {string} opts.locale - What locale to return the offset name in. + * @return {string} + */ + offsetName(ts, opts) { + throw new ZoneIsAbstractError(); + } + + /** + * Returns the offset's value as a string + * @abstract + * @param {number} ts - Epoch milliseconds for which to get the offset + * @param {string} format - What style of offset to return. + * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively + * @return {string} + */ + formatOffset(ts, format) { + throw new ZoneIsAbstractError(); + } + + /** + * Return the offset in minutes for this zone at the specified timestamp. + * @abstract + * @param {number} ts - Epoch milliseconds for which to compute the offset + * @return {number} + */ + offset(ts) { + throw new ZoneIsAbstractError(); + } + + /** + * Return whether this Zone is equal to another zone + * @abstract + * @param {Zone} otherZone - the zone to compare + * @return {boolean} + */ + equals(otherZone) { + throw new ZoneIsAbstractError(); + } + + /** + * Return whether this Zone is valid. + * @abstract + * @type {boolean} + */ + get isValid() { + throw new ZoneIsAbstractError(); + } +} + +let singleton$1 = null; + +/** + * Represents the local zone for this JavaScript environment. + * @implements {Zone} + */ +class SystemZone extends Zone { + /** + * Get a singleton instance of the local zone + * @return {SystemZone} + */ + static get instance() { + if (singleton$1 === null) { + singleton$1 = new SystemZone(); + } + return singleton$1; + } + + /** @override **/ + get type() { + return "system"; + } + + /** @override **/ + get name() { + return new Intl.DateTimeFormat().resolvedOptions().timeZone; + } + + /** @override **/ + get isUniversal() { + return false; + } + + /** @override **/ + offsetName(ts, { format, locale }) { + return parseZoneInfo(ts, format, locale); + } + + /** @override **/ + formatOffset(ts, format) { + return formatOffset(this.offset(ts), format); + } + + /** @override **/ + offset(ts) { + return -new Date(ts).getTimezoneOffset(); + } + + /** @override **/ + equals(otherZone) { + return otherZone.type === "system"; + } + + /** @override **/ + get isValid() { + return true; + } +} + +let dtfCache = {}; +function makeDTF(zone) { + if (!dtfCache[zone]) { + dtfCache[zone] = new Intl.DateTimeFormat("en-US", { + hour12: false, + timeZone: zone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + era: "short", + }); + } + return dtfCache[zone]; +} + +const typeToPos = { + year: 0, + month: 1, + day: 2, + era: 3, + hour: 4, + minute: 5, + second: 6, +}; + +function hackyOffset(dtf, date) { + const formatted = dtf.format(date).replace(/\u200E/g, ""), + parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), + [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; + return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; +} + +function partsOffset(dtf, date) { + const formatted = dtf.formatToParts(date); + const filled = []; + for (let i = 0; i < formatted.length; i++) { + const { type, value } = formatted[i]; + const pos = typeToPos[type]; + + if (type === "era") { + filled[pos] = value; + } else if (!isUndefined(pos)) { + filled[pos] = parseInt(value, 10); + } + } + return filled; +} + +let ianaZoneCache = {}; +/** + * A zone identified by an IANA identifier, like America/New_York + * @implements {Zone} + */ +class IANAZone extends Zone { + /** + * @param {string} name - Zone name + * @return {IANAZone} + */ + static create(name) { + if (!ianaZoneCache[name]) { + ianaZoneCache[name] = new IANAZone(name); + } + return ianaZoneCache[name]; + } + + /** + * Reset local caches. Should only be necessary in testing scenarios. + * @return {void} + */ + static resetCache() { + ianaZoneCache = {}; + dtfCache = {}; + } + + /** + * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that. + * @param {string} s - The string to check validity on + * @example IANAZone.isValidSpecifier("America/New_York") //=> true + * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false + * @deprecated This method returns false for some valid IANA names. Use isValidZone instead. + * @return {boolean} + */ + static isValidSpecifier(s) { + return this.isValidZone(s); + } + + /** + * Returns whether the provided string identifies a real zone + * @param {string} zone - The string to check + * @example IANAZone.isValidZone("America/New_York") //=> true + * @example IANAZone.isValidZone("Fantasia/Castle") //=> false + * @example IANAZone.isValidZone("Sport~~blorp") //=> false + * @return {boolean} + */ + static isValidZone(zone) { + if (!zone) { + return false; + } + try { + new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); + return true; + } catch (e) { + return false; + } + } + + constructor(name) { + super(); + /** @private **/ + this.zoneName = name; + /** @private **/ + this.valid = IANAZone.isValidZone(name); + } + + /** @override **/ + get type() { + return "iana"; + } + + /** @override **/ + get name() { + return this.zoneName; + } + + /** @override **/ + get isUniversal() { + return false; + } + + /** @override **/ + offsetName(ts, { format, locale }) { + return parseZoneInfo(ts, format, locale, this.name); + } + + /** @override **/ + formatOffset(ts, format) { + return formatOffset(this.offset(ts), format); + } + + /** @override **/ + offset(ts) { + const date = new Date(ts); + + if (isNaN(date)) return NaN; + + const dtf = makeDTF(this.name); + let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts + ? partsOffset(dtf, date) + : hackyOffset(dtf, date); + + if (adOrBc === "BC") { + year = -Math.abs(year) + 1; + } + + // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat + const adjustedHour = hour === 24 ? 0 : hour; + + const asUTC = objToLocalTS({ + year, + month, + day, + hour: adjustedHour, + minute, + second, + millisecond: 0, + }); + + let asTS = +date; + const over = asTS % 1000; + asTS -= over >= 0 ? over : 1000 + over; + return (asUTC - asTS) / (60 * 1000); + } + + /** @override **/ + equals(otherZone) { + return otherZone.type === "iana" && otherZone.name === this.name; + } + + /** @override **/ + get isValid() { + return this.valid; + } +} + +// todo - remap caching + +let intlLFCache = {}; +function getCachedLF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlLFCache[key]; + if (!dtf) { + dtf = new Intl.ListFormat(locString, opts); + intlLFCache[key] = dtf; + } + return dtf; +} + +let intlDTCache = {}; +function getCachedDTF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlDTCache[key]; + if (!dtf) { + dtf = new Intl.DateTimeFormat(locString, opts); + intlDTCache[key] = dtf; + } + return dtf; +} + +let intlNumCache = {}; +function getCachedINF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let inf = intlNumCache[key]; + if (!inf) { + inf = new Intl.NumberFormat(locString, opts); + intlNumCache[key] = inf; + } + return inf; +} + +let intlRelCache = {}; +function getCachedRTF(locString, opts = {}) { + const { base, ...cacheKeyOpts } = opts; // exclude `base` from the options + const key = JSON.stringify([locString, cacheKeyOpts]); + let inf = intlRelCache[key]; + if (!inf) { + inf = new Intl.RelativeTimeFormat(locString, opts); + intlRelCache[key] = inf; + } + return inf; +} + +let sysLocaleCache = null; +function systemLocale() { + if (sysLocaleCache) { + return sysLocaleCache; + } else { + sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; + return sysLocaleCache; + } +} + +function parseLocaleString(localeStr) { + // I really want to avoid writing a BCP 47 parser + // see, e.g. https://github.com/wooorm/bcp-47 + // Instead, we'll do this: + + // a) if the string has no -u extensions, just leave it alone + // b) if it does, use Intl to resolve everything + // c) if Intl fails, try again without the -u + + // private subtags and unicode subtags have ordering requirements, + // and we're not properly parsing this, so just strip out the + // private ones if they exist. + const xIndex = localeStr.indexOf("-x-"); + if (xIndex !== -1) { + localeStr = localeStr.substring(0, xIndex); + } + + const uIndex = localeStr.indexOf("-u-"); + if (uIndex === -1) { + return [localeStr]; + } else { + let options; + let selectedStr; + try { + options = getCachedDTF(localeStr).resolvedOptions(); + selectedStr = localeStr; + } catch (e) { + const smaller = localeStr.substring(0, uIndex); + options = getCachedDTF(smaller).resolvedOptions(); + selectedStr = smaller; + } + + const { numberingSystem, calendar } = options; + return [selectedStr, numberingSystem, calendar]; + } +} + +function intlConfigString(localeStr, numberingSystem, outputCalendar) { + if (outputCalendar || numberingSystem) { + if (!localeStr.includes("-u-")) { + localeStr += "-u"; + } + + if (outputCalendar) { + localeStr += `-ca-${outputCalendar}`; + } + + if (numberingSystem) { + localeStr += `-nu-${numberingSystem}`; + } + return localeStr; + } else { + return localeStr; + } +} + +function mapMonths(f) { + const ms = []; + for (let i = 1; i <= 12; i++) { + const dt = DateTime.utc(2009, i, 1); + ms.push(f(dt)); + } + return ms; +} + +function mapWeekdays(f) { + const ms = []; + for (let i = 1; i <= 7; i++) { + const dt = DateTime.utc(2016, 11, 13 + i); + ms.push(f(dt)); + } + return ms; +} + +function listStuff(loc, length, englishFn, intlFn) { + const mode = loc.listingMode(); + + if (mode === "error") { + return null; + } else if (mode === "en") { + return englishFn(length); + } else { + return intlFn(length); + } +} + +function supportsFastNumbers(loc) { + if (loc.numberingSystem && loc.numberingSystem !== "latn") { + return false; + } else { + return ( + loc.numberingSystem === "latn" || + !loc.locale || + loc.locale.startsWith("en") || + new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn" + ); + } +} + +/** + * @private + */ + +class PolyNumberFormatter { + constructor(intl, forceSimple, opts) { + this.padTo = opts.padTo || 0; + this.floor = opts.floor || false; + + const { padTo, floor, ...otherOpts } = opts; + + if (!forceSimple || Object.keys(otherOpts).length > 0) { + const intlOpts = { useGrouping: false, ...opts }; + if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo; + this.inf = getCachedINF(intl, intlOpts); + } + } + + format(i) { + if (this.inf) { + const fixed = this.floor ? Math.floor(i) : i; + return this.inf.format(fixed); + } else { + // to match the browser's numberformatter defaults + const fixed = this.floor ? Math.floor(i) : roundTo(i, 3); + return padStart(fixed, this.padTo); + } + } +} + +/** + * @private + */ + +class PolyDateFormatter { + constructor(dt, intl, opts) { + this.opts = opts; + this.originalZone = undefined; + + let z = undefined; + if (this.opts.timeZone) { + // Don't apply any workarounds if a timeZone is explicitly provided in opts + this.dt = dt; + } else if (dt.zone.type === "fixed") { + // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like. + // That is why fixed-offset TZ is set to that unless it is: + // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT. + // 2. Unsupported by the browser: + // - some do not support Etc/ + // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata + const gmtOffset = -1 * (dt.offset / 60); + const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; + if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { + z = offsetZ; + this.dt = dt; + } else { + // Not all fixed-offset zones like Etc/+4:30 are present in tzdata so + // we manually apply the offset and substitute the zone as needed. + z = "UTC"; + this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset }); + this.originalZone = dt.zone; + } + } else if (dt.zone.type === "system") { + this.dt = dt; + } else if (dt.zone.type === "iana") { + this.dt = dt; + z = dt.zone.name; + } else { + // Custom zones can have any offset / offsetName so we just manually + // apply the offset and substitute the zone as needed. + z = "UTC"; + this.dt = dt.setZone("UTC").plus({ minutes: dt.offset }); + this.originalZone = dt.zone; + } + + const intlOpts = { ...this.opts }; + intlOpts.timeZone = intlOpts.timeZone || z; + this.dtf = getCachedDTF(intl, intlOpts); + } + + format() { + if (this.originalZone) { + // If we have to substitute in the actual zone name, we have to use + // formatToParts so that the timezone can be replaced. + return this.formatToParts() + .map(({ value }) => value) + .join(""); + } + return this.dtf.format(this.dt.toJSDate()); + } + + formatToParts() { + const parts = this.dtf.formatToParts(this.dt.toJSDate()); + if (this.originalZone) { + return parts.map((part) => { + if (part.type === "timeZoneName") { + const offsetName = this.originalZone.offsetName(this.dt.ts, { + locale: this.dt.locale, + format: this.opts.timeZoneName, + }); + return { + ...part, + value: offsetName, + }; + } else { + return part; + } + }); + } + return parts; + } + + resolvedOptions() { + return this.dtf.resolvedOptions(); + } +} + +/** + * @private + */ +class PolyRelFormatter { + constructor(intl, isEnglish, opts) { + this.opts = { style: "long", ...opts }; + if (!isEnglish && hasRelative()) { + this.rtf = getCachedRTF(intl, opts); + } + } + + format(count, unit) { + if (this.rtf) { + return this.rtf.format(count, unit); + } else { + return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); + } + } + + formatToParts(count, unit) { + if (this.rtf) { + return this.rtf.formatToParts(count, unit); + } else { + return []; + } + } +} + +/** + * @private + */ + +class Locale { + static fromOpts(opts) { + return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); + } + + static create(locale, numberingSystem, outputCalendar, defaultToEN = false) { + const specifiedLocale = locale || Settings.defaultLocale; + // the system locale is useful for human readable strings but annoying for parsing/formatting known formats + const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); + const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; + const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; + return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale); + } + + static resetCache() { + sysLocaleCache = null; + intlDTCache = {}; + intlNumCache = {}; + intlRelCache = {}; + } + + static fromObject({ locale, numberingSystem, outputCalendar } = {}) { + return Locale.create(locale, numberingSystem, outputCalendar); + } + + constructor(locale, numbering, outputCalendar, specifiedLocale) { + const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale); + + this.locale = parsedLocale; + this.numberingSystem = numbering || parsedNumberingSystem || null; + this.outputCalendar = outputCalendar || parsedOutputCalendar || null; + this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); + + this.weekdaysCache = { format: {}, standalone: {} }; + this.monthsCache = { format: {}, standalone: {} }; + this.meridiemCache = null; + this.eraCache = {}; + + this.specifiedLocale = specifiedLocale; + this.fastNumbersCached = null; + } + + get fastNumbers() { + if (this.fastNumbersCached == null) { + this.fastNumbersCached = supportsFastNumbers(this); + } + + return this.fastNumbersCached; + } + + listingMode() { + const isActuallyEn = this.isEnglish(); + const hasNoWeirdness = + (this.numberingSystem === null || this.numberingSystem === "latn") && + (this.outputCalendar === null || this.outputCalendar === "gregory"); + return isActuallyEn && hasNoWeirdness ? "en" : "intl"; + } + + clone(alts) { + if (!alts || Object.getOwnPropertyNames(alts).length === 0) { + return this; + } else { + return Locale.create( + alts.locale || this.specifiedLocale, + alts.numberingSystem || this.numberingSystem, + alts.outputCalendar || this.outputCalendar, + alts.defaultToEN || false + ); + } + } + + redefaultToEN(alts = {}) { + return this.clone({ ...alts, defaultToEN: true }); + } + + redefaultToSystem(alts = {}) { + return this.clone({ ...alts, defaultToEN: false }); + } + + months(length, format = false) { + return listStuff(this, length, months, () => { + const intl = format ? { month: length, day: "numeric" } : { month: length }, + formatStr = format ? "format" : "standalone"; + if (!this.monthsCache[formatStr][length]) { + this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, "month")); + } + return this.monthsCache[formatStr][length]; + }); + } + + weekdays(length, format = false) { + return listStuff(this, length, weekdays, () => { + const intl = format + ? { weekday: length, year: "numeric", month: "long", day: "numeric" } + : { weekday: length }, + formatStr = format ? "format" : "standalone"; + if (!this.weekdaysCache[formatStr][length]) { + this.weekdaysCache[formatStr][length] = mapWeekdays((dt) => + this.extract(dt, intl, "weekday") + ); + } + return this.weekdaysCache[formatStr][length]; + }); + } + + meridiems() { + return listStuff( + this, + undefined, + () => meridiems, + () => { + // In theory there could be aribitrary day periods. We're gonna assume there are exactly two + // for AM and PM. This is probably wrong, but it's makes parsing way easier. + if (!this.meridiemCache) { + const intl = { hour: "numeric", hourCycle: "h12" }; + this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map( + (dt) => this.extract(dt, intl, "dayperiod") + ); + } + + return this.meridiemCache; + } + ); + } + + eras(length) { + return listStuff(this, length, eras, () => { + const intl = { era: length }; + + // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates + // to definitely enumerate them. + if (!this.eraCache[length]) { + this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) => + this.extract(dt, intl, "era") + ); + } + + return this.eraCache[length]; + }); + } + + extract(dt, intlOpts, field) { + const df = this.dtFormatter(dt, intlOpts), + results = df.formatToParts(), + matching = results.find((m) => m.type.toLowerCase() === field); + return matching ? matching.value : null; + } + + numberFormatter(opts = {}) { + // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave) + // (in contrast, the rest of the condition is used heavily) + return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); + } + + dtFormatter(dt, intlOpts = {}) { + return new PolyDateFormatter(dt, this.intl, intlOpts); + } + + relFormatter(opts = {}) { + return new PolyRelFormatter(this.intl, this.isEnglish(), opts); + } + + listFormatter(opts = {}) { + return getCachedLF(this.intl, opts); + } + + isEnglish() { + return ( + this.locale === "en" || + this.locale.toLowerCase() === "en-us" || + new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us") + ); + } + + equals(other) { + return ( + this.locale === other.locale && + this.numberingSystem === other.numberingSystem && + this.outputCalendar === other.outputCalendar + ); + } +} + +let singleton = null; + +/** + * A zone with a fixed offset (meaning no DST) + * @implements {Zone} + */ +class FixedOffsetZone extends Zone { + /** + * Get a singleton instance of UTC + * @return {FixedOffsetZone} + */ + static get utcInstance() { + if (singleton === null) { + singleton = new FixedOffsetZone(0); + } + return singleton; + } + + /** + * Get an instance with a specified offset + * @param {number} offset - The offset in minutes + * @return {FixedOffsetZone} + */ + static instance(offset) { + return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset); + } + + /** + * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" + * @param {string} s - The offset string to parse + * @example FixedOffsetZone.parseSpecifier("UTC+6") + * @example FixedOffsetZone.parseSpecifier("UTC+06") + * @example FixedOffsetZone.parseSpecifier("UTC-6:00") + * @return {FixedOffsetZone} + */ + static parseSpecifier(s) { + if (s) { + const r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); + if (r) { + return new FixedOffsetZone(signedOffset(r[1], r[2])); + } + } + return null; + } + + constructor(offset) { + super(); + /** @private **/ + this.fixed = offset; + } + + /** @override **/ + get type() { + return "fixed"; + } + + /** @override **/ + get name() { + return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; + } + + get ianaName() { + if (this.fixed === 0) { + return "Etc/UTC"; + } else { + return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; + } + } + + /** @override **/ + offsetName() { + return this.name; + } + + /** @override **/ + formatOffset(ts, format) { + return formatOffset(this.fixed, format); + } + + /** @override **/ + get isUniversal() { + return true; + } + + /** @override **/ + offset() { + return this.fixed; + } + + /** @override **/ + equals(otherZone) { + return otherZone.type === "fixed" && otherZone.fixed === this.fixed; + } + + /** @override **/ + get isValid() { + return true; + } +} + +/** + * A zone that failed to parse. You should never need to instantiate this. + * @implements {Zone} + */ +class InvalidZone extends Zone { + constructor(zoneName) { + super(); + /** @private */ + this.zoneName = zoneName; + } + + /** @override **/ + get type() { + return "invalid"; + } + + /** @override **/ + get name() { + return this.zoneName; + } + + /** @override **/ + get isUniversal() { + return false; + } + + /** @override **/ + offsetName() { + return null; + } + + /** @override **/ + formatOffset() { + return ""; + } + + /** @override **/ + offset() { + return NaN; + } + + /** @override **/ + equals() { + return false; + } + + /** @override **/ + get isValid() { + return false; + } +} + +/** + * @private + */ + +function normalizeZone(input, defaultZone) { + if (isUndefined(input) || input === null) { + return defaultZone; + } else if (input instanceof Zone) { + return input; + } else if (isString(input)) { + const lowered = input.toLowerCase(); + if (lowered === "default") return defaultZone; + else if (lowered === "local" || lowered === "system") return SystemZone.instance; + else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance; + else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); + } else if (isNumber(input)) { + return FixedOffsetZone.instance(input); + } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { + // This is dumb, but the instanceof check above doesn't seem to really work + // so we're duck checking it + return input; + } else { + return new InvalidZone(input); + } +} + +let now = () => Date.now(), + defaultZone = "system", + defaultLocale = null, + defaultNumberingSystem = null, + defaultOutputCalendar = null, + twoDigitCutoffYear = 60, + throwOnInvalid; + +/** + * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here. + */ +class Settings { + /** + * Get the callback for returning the current timestamp. + * @type {function} + */ + static get now() { + return now; + } + + /** + * Set the callback for returning the current timestamp. + * The function should return a number, which will be interpreted as an Epoch millisecond count + * @type {function} + * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future + * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time + */ + static set now(n) { + now = n; + } + + /** + * Set the default time zone to create DateTimes in. Does not affect existing instances. + * Use the value "system" to reset this value to the system's time zone. + * @type {string} + */ + static set defaultZone(zone) { + defaultZone = zone; + } + + /** + * Get the default time zone object currently used to create DateTimes. Does not affect existing instances. + * The default value is the system's time zone (the one set on the machine that runs this code). + * @type {Zone} + */ + static get defaultZone() { + return normalizeZone(defaultZone, SystemZone.instance); + } + + /** + * Get the default locale to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultLocale() { + return defaultLocale; + } + + /** + * Set the default locale to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultLocale(locale) { + defaultLocale = locale; + } + + /** + * Get the default numbering system to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultNumberingSystem() { + return defaultNumberingSystem; + } + + /** + * Set the default numbering system to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultNumberingSystem(numberingSystem) { + defaultNumberingSystem = numberingSystem; + } + + /** + * Get the default output calendar to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static get defaultOutputCalendar() { + return defaultOutputCalendar; + } + + /** + * Set the default output calendar to create DateTimes with. Does not affect existing instances. + * @type {string} + */ + static set defaultOutputCalendar(outputCalendar) { + defaultOutputCalendar = outputCalendar; + } + + /** + * Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. + * @type {number} + */ + static get twoDigitCutoffYear() { + return twoDigitCutoffYear; + } + + /** + * Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. + * @type {number} + * @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpreted as current century + * @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050 + * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50 + * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted as 50 + */ + static set twoDigitCutoffYear(cutoffYear) { + twoDigitCutoffYear = cutoffYear % 100; + } + + /** + * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals + * @type {boolean} + */ + static get throwOnInvalid() { + return throwOnInvalid; + } + + /** + * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals + * @type {boolean} + */ + static set throwOnInvalid(t) { + throwOnInvalid = t; + } + + /** + * Reset Luxon's global caches. Should only be necessary in testing scenarios. + * @return {void} + */ + static resetCaches() { + Locale.resetCache(); + IANAZone.resetCache(); + } +} + +/* + This is just a junk drawer, containing anything used across multiple classes. + Because Luxon is small(ish), this should stay small and we won't worry about splitting + it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area. +*/ + +/** + * @private + */ + +// TYPES + +function isUndefined(o) { + return typeof o === "undefined"; +} + +function isNumber(o) { + return typeof o === "number"; +} + +function isInteger(o) { + return typeof o === "number" && o % 1 === 0; +} + +function isString(o) { + return typeof o === "string"; +} + +function isDate(o) { + return Object.prototype.toString.call(o) === "[object Date]"; +} + +// CAPABILITIES + +function hasRelative() { + try { + return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; + } catch (e) { + return false; + } +} + +// OBJECTS AND ARRAYS + +function maybeArray(thing) { + return Array.isArray(thing) ? thing : [thing]; +} + +function bestBy(arr, by, compare) { + if (arr.length === 0) { + return undefined; + } + return arr.reduce((best, next) => { + const pair = [by(next), next]; + if (!best) { + return pair; + } else if (compare(best[0], pair[0]) === best[0]) { + return best; + } else { + return pair; + } + }, null)[1]; +} + +function pick(obj, keys) { + return keys.reduce((a, k) => { + a[k] = obj[k]; + return a; + }, {}); +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +// NUMBERS AND STRINGS + +function integerBetween(thing, bottom, top) { + return isInteger(thing) && thing >= bottom && thing <= top; +} + +// x % n but takes the sign of n instead of x +function floorMod(x, n) { + return x - n * Math.floor(x / n); +} + +function padStart(input, n = 2) { + const isNeg = input < 0; + let padded; + if (isNeg) { + padded = "-" + ("" + -input).padStart(n, "0"); + } else { + padded = ("" + input).padStart(n, "0"); + } + return padded; +} + +function parseInteger(string) { + if (isUndefined(string) || string === null || string === "") { + return undefined; + } else { + return parseInt(string, 10); + } +} + +function parseFloating(string) { + if (isUndefined(string) || string === null || string === "") { + return undefined; + } else { + return parseFloat(string); + } +} + +function parseMillis(fraction) { + // Return undefined (instead of 0) in these cases, where fraction is not set + if (isUndefined(fraction) || fraction === null || fraction === "") { + return undefined; + } else { + const f = parseFloat("0." + fraction) * 1000; + return Math.floor(f); + } +} + +function roundTo(number, digits, towardZero = false) { + const factor = 10 ** digits, + rounder = towardZero ? Math.trunc : Math.round; + return rounder(number * factor) / factor; +} + +// DATE BASICS + +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + +function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; +} + +function daysInMonth(year, month) { + const modMonth = floorMod(month - 1, 12) + 1, + modYear = year + (month - modMonth) / 12; + + if (modMonth === 2) { + return isLeapYear(modYear) ? 29 : 28; + } else { + return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; + } +} + +// convert a calendar object to a local timestamp (epoch, but with the offset baked in) +function objToLocalTS(obj) { + let d = Date.UTC( + obj.year, + obj.month - 1, + obj.day, + obj.hour, + obj.minute, + obj.second, + obj.millisecond + ); + + // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that + if (obj.year < 100 && obj.year >= 0) { + d = new Date(d); + // set the month and day again, this is necessary because year 2000 is a leap year, but year 100 is not + // so if obj.year is in 99, but obj.day makes it roll over into year 100, + // the calculations done by Date.UTC are using year 2000 - which is incorrect + d.setUTCFullYear(obj.year, obj.month - 1, obj.day); + } + return +d; +} + +function weeksInWeekYear(weekYear) { + const p1 = + (weekYear + + Math.floor(weekYear / 4) - + Math.floor(weekYear / 100) + + Math.floor(weekYear / 400)) % + 7, + last = weekYear - 1, + p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7; + return p1 === 4 || p2 === 3 ? 53 : 52; +} + +function untruncateYear(year) { + if (year > 99) { + return year; + } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year; +} + +// PARSING + +function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) { + const date = new Date(ts), + intlOpts = { + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + }; + + if (timeZone) { + intlOpts.timeZone = timeZone; + } + + const modified = { timeZoneName: offsetFormat, ...intlOpts }; + + const parsed = new Intl.DateTimeFormat(locale, modified) + .formatToParts(date) + .find((m) => m.type.toLowerCase() === "timezonename"); + return parsed ? parsed.value : null; +} + +// signedOffset('-5', '30') -> -330 +function signedOffset(offHourStr, offMinuteStr) { + let offHour = parseInt(offHourStr, 10); + + // don't || this because we want to preserve -0 + if (Number.isNaN(offHour)) { + offHour = 0; + } + + const offMin = parseInt(offMinuteStr, 10) || 0, + offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; + return offHour * 60 + offMinSigned; +} + +// COERCION + +function asNumber(value) { + const numericValue = Number(value); + if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) + throw new InvalidArgumentError(`Invalid unit value ${value}`); + return numericValue; +} + +function normalizeObject(obj, normalizer) { + const normalized = {}; + for (const u in obj) { + if (hasOwnProperty(obj, u)) { + const v = obj[u]; + if (v === undefined || v === null) continue; + normalized[normalizer(u)] = asNumber(v); + } + } + return normalized; +} + +function formatOffset(offset, format) { + const hours = Math.trunc(Math.abs(offset / 60)), + minutes = Math.trunc(Math.abs(offset % 60)), + sign = offset >= 0 ? "+" : "-"; + + switch (format) { + case "short": + return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`; + case "narrow": + return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`; + case "techie": + return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`; + default: + throw new RangeError(`Value format ${format} is out of range for property format`); + } +} + +function timeObject(obj) { + return pick(obj, ["hour", "minute", "second", "millisecond"]); +} + +/** + * @private + */ + +const monthsLong = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; + +const monthsShort = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", +]; + +const monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; + +function months(length) { + switch (length) { + case "narrow": + return [...monthsNarrow]; + case "short": + return [...monthsShort]; + case "long": + return [...monthsLong]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; + case "2-digit": + return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; + default: + return null; + } +} + +const weekdaysLong = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", +]; + +const weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + +const weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; + +function weekdays(length) { + switch (length) { + case "narrow": + return [...weekdaysNarrow]; + case "short": + return [...weekdaysShort]; + case "long": + return [...weekdaysLong]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7"]; + default: + return null; + } +} + +const meridiems = ["AM", "PM"]; + +const erasLong = ["Before Christ", "Anno Domini"]; + +const erasShort = ["BC", "AD"]; + +const erasNarrow = ["B", "A"]; + +function eras(length) { + switch (length) { + case "narrow": + return [...erasNarrow]; + case "short": + return [...erasShort]; + case "long": + return [...erasLong]; + default: + return null; + } +} + +function meridiemForDateTime(dt) { + return meridiems[dt.hour < 12 ? 0 : 1]; +} + +function weekdayForDateTime(dt, length) { + return weekdays(length)[dt.weekday - 1]; +} + +function monthForDateTime(dt, length) { + return months(length)[dt.month - 1]; +} + +function eraForDateTime(dt, length) { + return eras(length)[dt.year < 0 ? 0 : 1]; +} + +function formatRelativeTime(unit, count, numeric = "always", narrow = false) { + const units = { + years: ["year", "yr."], + quarters: ["quarter", "qtr."], + months: ["month", "mo."], + weeks: ["week", "wk."], + days: ["day", "day", "days"], + hours: ["hour", "hr."], + minutes: ["minute", "min."], + seconds: ["second", "sec."], + }; + + const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; + + if (numeric === "auto" && lastable) { + const isDay = unit === "days"; + switch (count) { + case 1: + return isDay ? "tomorrow" : `next ${units[unit][0]}`; + case -1: + return isDay ? "yesterday" : `last ${units[unit][0]}`; + case 0: + return isDay ? "today" : `this ${units[unit][0]}`; + } + } + + const isInPast = Object.is(count, -0) || count < 0, + fmtValue = Math.abs(count), + singular = fmtValue === 1, + lilUnits = units[unit], + fmtUnit = narrow + ? singular + ? lilUnits[1] + : lilUnits[2] || lilUnits[1] + : singular + ? units[unit][0] + : unit; + return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; +} + +function stringifyTokens(splits, tokenToString) { + let s = ""; + for (const token of splits) { + if (token.literal) { + s += token.val; + } else { + s += tokenToString(token.val); + } + } + return s; +} + +const macroTokenToFormatOpts = { + D: DATE_SHORT, + DD: DATE_MED, + DDD: DATE_FULL, + DDDD: DATE_HUGE, + t: TIME_SIMPLE, + tt: TIME_WITH_SECONDS, + ttt: TIME_WITH_SHORT_OFFSET, + tttt: TIME_WITH_LONG_OFFSET, + T: TIME_24_SIMPLE, + TT: TIME_24_WITH_SECONDS, + TTT: TIME_24_WITH_SHORT_OFFSET, + TTTT: TIME_24_WITH_LONG_OFFSET, + f: DATETIME_SHORT, + ff: DATETIME_MED, + fff: DATETIME_FULL, + ffff: DATETIME_HUGE, + F: DATETIME_SHORT_WITH_SECONDS, + FF: DATETIME_MED_WITH_SECONDS, + FFF: DATETIME_FULL_WITH_SECONDS, + FFFF: DATETIME_HUGE_WITH_SECONDS, +}; + +/** + * @private + */ + +class Formatter { + static create(locale, opts = {}) { + return new Formatter(locale, opts); + } + + static parseFormat(fmt) { + // white-space is always considered a literal in user-provided formats + // the " " token has a special meaning (see unitForToken) + + let current = null, + currentFull = "", + bracketed = false; + const splits = []; + for (let i = 0; i < fmt.length; i++) { + const c = fmt.charAt(i); + if (c === "'") { + if (currentFull.length > 0) { + splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + } + current = null; + currentFull = ""; + bracketed = !bracketed; + } else if (bracketed) { + currentFull += c; + } else if (c === current) { + currentFull += c; + } else { + if (currentFull.length > 0) { + splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull }); + } + currentFull = c; + current = c; + } + } + + if (currentFull.length > 0) { + splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); + } + + return splits; + } + + static macroTokenToFormatOpts(token) { + return macroTokenToFormatOpts[token]; + } + + constructor(locale, formatOpts) { + this.opts = formatOpts; + this.loc = locale; + this.systemLoc = null; + } + + formatWithSystemDefault(dt, opts) { + if (this.systemLoc === null) { + this.systemLoc = this.loc.redefaultToSystem(); + } + const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts }); + return df.format(); + } + + dtFormatter(dt, opts = {}) { + return this.loc.dtFormatter(dt, { ...this.opts, ...opts }); + } + + formatDateTime(dt, opts) { + return this.dtFormatter(dt, opts).format(); + } + + formatDateTimeParts(dt, opts) { + return this.dtFormatter(dt, opts).formatToParts(); + } + + formatInterval(interval, opts) { + const df = this.dtFormatter(interval.start, opts); + return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); + } + + resolvedOptions(dt, opts) { + return this.dtFormatter(dt, opts).resolvedOptions(); + } + + num(n, p = 0) { + // we get some perf out of doing this here, annoyingly + if (this.opts.forceSimple) { + return padStart(n, p); + } + + const opts = { ...this.opts }; + + if (p > 0) { + opts.padTo = p; + } + + return this.loc.numberFormatter(opts).format(n); + } + + formatDateTimeFromString(dt, fmt) { + const knownEnglish = this.loc.listingMode() === "en", + useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", + string = (opts, extract) => this.loc.extract(dt, opts, extract), + formatOffset = (opts) => { + if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { + return "Z"; + } + + return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; + }, + meridiem = () => + knownEnglish + ? meridiemForDateTime(dt) + : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), + month = (length, standalone) => + knownEnglish + ? monthForDateTime(dt, length) + : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), + weekday = (length, standalone) => + knownEnglish + ? weekdayForDateTime(dt, length) + : string( + standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, + "weekday" + ), + maybeMacro = (token) => { + const formatOpts = Formatter.macroTokenToFormatOpts(token); + if (formatOpts) { + return this.formatWithSystemDefault(dt, formatOpts); + } else { + return token; + } + }, + era = (length) => + knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"), + tokenToString = (token) => { + // Where possible: https://cldr.unicode.org/translation/date-time/date-time-symbols + switch (token) { + // ms + case "S": + return this.num(dt.millisecond); + case "u": + // falls through + case "SSS": + return this.num(dt.millisecond, 3); + // seconds + case "s": + return this.num(dt.second); + case "ss": + return this.num(dt.second, 2); + // fractional seconds + case "uu": + return this.num(Math.floor(dt.millisecond / 10), 2); + case "uuu": + return this.num(Math.floor(dt.millisecond / 100)); + // minutes + case "m": + return this.num(dt.minute); + case "mm": + return this.num(dt.minute, 2); + // hours + case "h": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); + case "hh": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); + case "H": + return this.num(dt.hour); + case "HH": + return this.num(dt.hour, 2); + // offset + case "Z": + // like +6 + return formatOffset({ format: "narrow", allowZ: this.opts.allowZ }); + case "ZZ": + // like +06:00 + return formatOffset({ format: "short", allowZ: this.opts.allowZ }); + case "ZZZ": + // like +0600 + return formatOffset({ format: "techie", allowZ: this.opts.allowZ }); + case "ZZZZ": + // like EST + return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale }); + case "ZZZZZ": + // like Eastern Standard Time + return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale }); + // zone + case "z": + // like America/New_York + return dt.zoneName; + // meridiems + case "a": + return meridiem(); + // dates + case "d": + return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day); + case "dd": + return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2); + // weekdays - standalone + case "c": + // like 1 + return this.num(dt.weekday); + case "ccc": + // like 'Tues' + return weekday("short", true); + case "cccc": + // like 'Tuesday' + return weekday("long", true); + case "ccccc": + // like 'T' + return weekday("narrow", true); + // weekdays - format + case "E": + // like 1 + return this.num(dt.weekday); + case "EEE": + // like 'Tues' + return weekday("short", false); + case "EEEE": + // like 'Tuesday' + return weekday("long", false); + case "EEEEE": + // like 'T' + return weekday("narrow", false); + // months - standalone + case "L": + // like 1 + return useDateTimeFormatter + ? string({ month: "numeric", day: "numeric" }, "month") + : this.num(dt.month); + case "LL": + // like 01, doesn't seem to work + return useDateTimeFormatter + ? string({ month: "2-digit", day: "numeric" }, "month") + : this.num(dt.month, 2); + case "LLL": + // like Jan + return month("short", true); + case "LLLL": + // like January + return month("long", true); + case "LLLLL": + // like J + return month("narrow", true); + // months - format + case "M": + // like 1 + return useDateTimeFormatter + ? string({ month: "numeric" }, "month") + : this.num(dt.month); + case "MM": + // like 01 + return useDateTimeFormatter + ? string({ month: "2-digit" }, "month") + : this.num(dt.month, 2); + case "MMM": + // like Jan + return month("short", false); + case "MMMM": + // like January + return month("long", false); + case "MMMMM": + // like J + return month("narrow", false); + // years + case "y": + // like 2014 + return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year); + case "yy": + // like 14 + return useDateTimeFormatter + ? string({ year: "2-digit" }, "year") + : this.num(dt.year.toString().slice(-2), 2); + case "yyyy": + // like 0012 + return useDateTimeFormatter + ? string({ year: "numeric" }, "year") + : this.num(dt.year, 4); + case "yyyyyy": + // like 000012 + return useDateTimeFormatter + ? string({ year: "numeric" }, "year") + : this.num(dt.year, 6); + // eras + case "G": + // like AD + return era("short"); + case "GG": + // like Anno Domini + return era("long"); + case "GGGGG": + return era("narrow"); + case "kk": + return this.num(dt.weekYear.toString().slice(-2), 2); + case "kkkk": + return this.num(dt.weekYear, 4); + case "W": + return this.num(dt.weekNumber); + case "WW": + return this.num(dt.weekNumber, 2); + case "o": + return this.num(dt.ordinal); + case "ooo": + return this.num(dt.ordinal, 3); + case "q": + // like 1 + return this.num(dt.quarter); + case "qq": + // like 01 + return this.num(dt.quarter, 2); + case "X": + return this.num(Math.floor(dt.ts / 1000)); + case "x": + return this.num(dt.ts); + default: + return maybeMacro(token); + } + }; + + return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); + } + + formatDurationFromString(dur, fmt) { + const tokenToField = (token) => { + switch (token[0]) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + return "hour"; + case "d": + return "day"; + case "w": + return "week"; + case "M": + return "month"; + case "y": + return "year"; + default: + return null; + } + }, + tokenToString = (lildur) => (token) => { + const mapped = tokenToField(token); + if (mapped) { + return this.num(lildur.get(mapped), token.length); + } else { + return token; + } + }, + tokens = Formatter.parseFormat(fmt), + realTokens = tokens.reduce( + (found, { literal, val }) => (literal ? found : found.concat(val)), + [] + ), + collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)); + return stringifyTokens(tokens, tokenToString(collapsed)); + } +} + +class Invalid { + constructor(reason, explanation) { + this.reason = reason; + this.explanation = explanation; + } + + toMessage() { + if (this.explanation) { + return `${this.reason}: ${this.explanation}`; + } else { + return this.reason; + } + } +} + +/* + * This file handles parsing for well-specified formats. Here's how it works: + * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match. + * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object + * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence. + * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors. + * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions. + * Some extractions are super dumb and simpleParse and fromStrings help DRY them. + */ + +const ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; + +function combineRegexes(...regexes) { + const full = regexes.reduce((f, r) => f + r.source, ""); + return RegExp(`^${full}$`); +} + +function combineExtractors(...extractors) { + return (m) => + extractors + .reduce( + ([mergedVals, mergedZone, cursor], ex) => { + const [val, zone, next] = ex(m, cursor); + return [{ ...mergedVals, ...val }, zone || mergedZone, next]; + }, + [{}, null, 1] + ) + .slice(0, 2); +} + +function parse(s, ...patterns) { + if (s == null) { + return [null, null]; + } + + for (const [regex, extractor] of patterns) { + const m = regex.exec(s); + if (m) { + return extractor(m); + } + } + return [null, null]; +} + +function simpleParse(...keys) { + return (match, cursor) => { + const ret = {}; + let i; + + for (i = 0; i < keys.length; i++) { + ret[keys[i]] = parseInteger(match[cursor + i]); + } + return [ret, null, cursor + i]; + }; +} + +// ISO and SQL parsing +const offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; +const isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; +const isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; +const isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`); +const isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`); +const isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; +const isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; +const isoOrdinalRegex = /(\d{4})-?(\d{3})/; +const extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); +const extractISOOrdinalData = simpleParse("year", "ordinal"); +const sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; // dumbed-down version of the ISO one +const sqlTimeRegex = RegExp( + `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?` +); +const sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); + +function int(match, pos, fallback) { + const m = match[pos]; + return isUndefined(m) ? fallback : parseInteger(m); +} + +function extractISOYmd(match, cursor) { + const item = { + year: int(match, cursor), + month: int(match, cursor + 1, 1), + day: int(match, cursor + 2, 1), + }; + + return [item, null, cursor + 3]; +} + +function extractISOTime(match, cursor) { + const item = { + hours: int(match, cursor, 0), + minutes: int(match, cursor + 1, 0), + seconds: int(match, cursor + 2, 0), + milliseconds: parseMillis(match[cursor + 3]), + }; + + return [item, null, cursor + 4]; +} + +function extractISOOffset(match, cursor) { + const local = !match[cursor] && !match[cursor + 1], + fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), + zone = local ? null : FixedOffsetZone.instance(fullOffset); + return [{}, zone, cursor + 3]; +} + +function extractIANAZone(match, cursor) { + const zone = match[cursor] ? IANAZone.create(match[cursor]) : null; + return [{}, zone, cursor + 1]; +} + +// ISO time parsing + +const isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); + +// ISO duration parsing + +const isoDuration = + /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; + +function extractISODuration(match) { + const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = + match; + + const hasNegativePrefix = s[0] === "-"; + const negativeSeconds = secondStr && secondStr[0] === "-"; + + const maybeNegate = (num, force = false) => + num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num; + + return [ + { + years: maybeNegate(parseFloating(yearStr)), + months: maybeNegate(parseFloating(monthStr)), + weeks: maybeNegate(parseFloating(weekStr)), + days: maybeNegate(parseFloating(dayStr)), + hours: maybeNegate(parseFloating(hourStr)), + minutes: maybeNegate(parseFloating(minuteStr)), + seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), + milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds), + }, + ]; +} + +// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York +// and not just that we're in -240 *right now*. But since I don't think these are used that often +// I'm just going to ignore that +const obsOffsets = { + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60, +}; + +function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + const result = { + year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), + month: monthsShort.indexOf(monthStr) + 1, + day: parseInteger(dayStr), + hour: parseInteger(hourStr), + minute: parseInteger(minuteStr), + }; + + if (secondStr) result.second = parseInteger(secondStr); + if (weekdayStr) { + result.weekday = + weekdayStr.length > 3 + ? weekdaysLong.indexOf(weekdayStr) + 1 + : weekdaysShort.indexOf(weekdayStr) + 1; + } + + return result; +} + +// RFC 2822/5322 +const rfc2822 = + /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; + +function extractRFC2822(match) { + const [ + , + weekdayStr, + dayStr, + monthStr, + yearStr, + hourStr, + minuteStr, + secondStr, + obsOffset, + milOffset, + offHourStr, + offMinuteStr, + ] = match, + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + + let offset; + if (obsOffset) { + offset = obsOffsets[obsOffset]; + } else if (milOffset) { + offset = 0; + } else { + offset = signedOffset(offHourStr, offMinuteStr); + } + + return [result, new FixedOffsetZone(offset)]; +} + +function preprocessRFC2822(s) { + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s + .replace(/\([^()]*\)|[\n\t]/g, " ") + .replace(/(\s\s+)/g, " ") + .trim(); +} + +// http date + +const rfc1123 = + /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/, + rfc850 = + /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/, + ascii = + /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; + +function extractRFC1123Or850(match) { + const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match, + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; +} + +function extractASCII(match) { + const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match, + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; +} + +const isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); +const isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); +const isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); +const isoTimeCombinedRegex = combineRegexes(isoTimeRegex); + +const extractISOYmdTimeAndOffset = combineExtractors( + extractISOYmd, + extractISOTime, + extractISOOffset, + extractIANAZone +); +const extractISOWeekTimeAndOffset = combineExtractors( + extractISOWeekData, + extractISOTime, + extractISOOffset, + extractIANAZone +); +const extractISOOrdinalDateAndTime = combineExtractors( + extractISOOrdinalData, + extractISOTime, + extractISOOffset, + extractIANAZone +); +const extractISOTimeAndOffset = combineExtractors( + extractISOTime, + extractISOOffset, + extractIANAZone +); + +/* + * @private + */ + +function parseISODate(s) { + return parse( + s, + [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], + [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], + [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], + [isoTimeCombinedRegex, extractISOTimeAndOffset] + ); +} + +function parseRFC2822Date(s) { + return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]); +} + +function parseHTTPDate(s) { + return parse( + s, + [rfc1123, extractRFC1123Or850], + [rfc850, extractRFC1123Or850], + [ascii, extractASCII] + ); +} + +function parseISODuration(s) { + return parse(s, [isoDuration, extractISODuration]); +} + +const extractISOTimeOnly = combineExtractors(extractISOTime); + +function parseISOTimeOnly(s) { + return parse(s, [isoTimeOnly, extractISOTimeOnly]); +} + +const sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); +const sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); + +const extractISOTimeOffsetAndIANAZone = combineExtractors( + extractISOTime, + extractISOOffset, + extractIANAZone +); + +function parseSQL(s) { + return parse( + s, + [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], + [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone] + ); +} + +const INVALID$2 = "Invalid Duration"; + +// unit conversion constants +const lowOrderMatrix = { + weeks: { + days: 7, + hours: 7 * 24, + minutes: 7 * 24 * 60, + seconds: 7 * 24 * 60 * 60, + milliseconds: 7 * 24 * 60 * 60 * 1000, + }, + days: { + hours: 24, + minutes: 24 * 60, + seconds: 24 * 60 * 60, + milliseconds: 24 * 60 * 60 * 1000, + }, + hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 }, + minutes: { seconds: 60, milliseconds: 60 * 1000 }, + seconds: { milliseconds: 1000 }, + }, + casualMatrix = { + years: { + quarters: 4, + months: 12, + weeks: 52, + days: 365, + hours: 365 * 24, + minutes: 365 * 24 * 60, + seconds: 365 * 24 * 60 * 60, + milliseconds: 365 * 24 * 60 * 60 * 1000, + }, + quarters: { + months: 3, + weeks: 13, + days: 91, + hours: 91 * 24, + minutes: 91 * 24 * 60, + seconds: 91 * 24 * 60 * 60, + milliseconds: 91 * 24 * 60 * 60 * 1000, + }, + months: { + weeks: 4, + days: 30, + hours: 30 * 24, + minutes: 30 * 24 * 60, + seconds: 30 * 24 * 60 * 60, + milliseconds: 30 * 24 * 60 * 60 * 1000, + }, + + ...lowOrderMatrix, + }, + daysInYearAccurate = 146097.0 / 400, + daysInMonthAccurate = 146097.0 / 4800, + accurateMatrix = { + years: { + quarters: 4, + months: 12, + weeks: daysInYearAccurate / 7, + days: daysInYearAccurate, + hours: daysInYearAccurate * 24, + minutes: daysInYearAccurate * 24 * 60, + seconds: daysInYearAccurate * 24 * 60 * 60, + milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000, + }, + quarters: { + months: 3, + weeks: daysInYearAccurate / 28, + days: daysInYearAccurate / 4, + hours: (daysInYearAccurate * 24) / 4, + minutes: (daysInYearAccurate * 24 * 60) / 4, + seconds: (daysInYearAccurate * 24 * 60 * 60) / 4, + milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4, + }, + months: { + weeks: daysInMonthAccurate / 7, + days: daysInMonthAccurate, + hours: daysInMonthAccurate * 24, + minutes: daysInMonthAccurate * 24 * 60, + seconds: daysInMonthAccurate * 24 * 60 * 60, + milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000, + }, + ...lowOrderMatrix, + }; + +// units ordered by size +const orderedUnits$1 = [ + "years", + "quarters", + "months", + "weeks", + "days", + "hours", + "minutes", + "seconds", + "milliseconds", +]; + +const reverseUnits = orderedUnits$1.slice(0).reverse(); + +// clone really means "create another instance just like this one, but with these changes" +function clone$1(dur, alts, clear = false) { + // deep merge for vals + const conf = { + values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) }, + loc: dur.loc.clone(alts.loc), + conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, + matrix: alts.matrix || dur.matrix, + }; + return new Duration(conf); +} + +function durationToMillis(matrix, vals) { + let sum = vals.milliseconds ?? 0; + for (const unit of reverseUnits.slice(1)) { + if (vals[unit]) { + sum += vals[unit] * matrix[unit]["milliseconds"]; + } + } + return sum; +} + +// NB: mutates parameters +function normalizeValues(matrix, vals) { + // the logic below assumes the overall value of the duration is positive + // if this is not the case, factor is used to make it so + const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; + + orderedUnits$1.reduceRight((previous, current) => { + if (!isUndefined(vals[current])) { + if (previous) { + const previousVal = vals[previous] * factor; + const conv = matrix[current][previous]; + + // if (previousVal < 0): + // lower order unit is negative (e.g. { years: 2, days: -2 }) + // normalize this by reducing the higher order unit by the appropriate amount + // and increasing the lower order unit + // this can never make the higher order unit negative, because this function only operates + // on positive durations, so the amount of time represented by the lower order unit cannot + // be larger than the higher order unit + // else: + // lower order unit is positive (e.g. { years: 2, days: 450 } or { years: -2, days: 450 }) + // in this case we attempt to convert as much as possible from the lower order unit into + // the higher order one + // + // Math.floor takes care of both of these cases, rounding away from 0 + // if previousVal < 0 it makes the absolute value larger + // if previousVal >= it makes the absolute value smaller + const rollUp = Math.floor(previousVal / conv); + vals[current] += rollUp * factor; + vals[previous] -= rollUp * conv * factor; + } + return current; + } else { + return previous; + } + }, null); + + // try to convert any decimals into smaller units if possible + // for example for { years: 2.5, days: 0, seconds: 0 } we want to get { years: 2, days: 182, hours: 12 } + orderedUnits$1.reduce((previous, current) => { + if (!isUndefined(vals[current])) { + if (previous) { + const fraction = vals[previous] % 1; + vals[previous] -= fraction; + vals[current] += fraction * matrix[previous][current]; + } + return current; + } else { + return previous; + } + }, null); +} + +// Remove all properties with a value of 0 from an object +function removeZeroes(vals) { + const newVals = {}; + for (const [key, value] of Object.entries(vals)) { + if (value !== 0) { + newVals[key] = value; + } + } + return newVals; +} + +/** + * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime. + * + * Here is a brief overview of commonly used methods and getters in Duration: + * + * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}. + * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors. + * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors. + * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}. + * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON} + * + * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation. + */ +class Duration { + /** + * @private + */ + constructor(config) { + const accurate = config.conversionAccuracy === "longterm" || false; + let matrix = accurate ? accurateMatrix : casualMatrix; + + if (config.matrix) { + matrix = config.matrix; + } + + /** + * @access private + */ + this.values = config.values; + /** + * @access private + */ + this.loc = config.loc || Locale.create(); + /** + * @access private + */ + this.conversionAccuracy = accurate ? "longterm" : "casual"; + /** + * @access private + */ + this.invalid = config.invalid || null; + /** + * @access private + */ + this.matrix = matrix; + /** + * @access private + */ + this.isLuxonDuration = true; + } + + /** + * Create Duration from a number of milliseconds. + * @param {number} count of milliseconds + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @return {Duration} + */ + static fromMillis(count, opts) { + return Duration.fromObject({ milliseconds: count }, opts); + } + + /** + * Create a Duration from a JavaScript object with keys like 'years' and 'hours'. + * If this object is empty then a zero milliseconds duration is returned. + * @param {Object} obj - the object to create the DateTime from + * @param {number} obj.years + * @param {number} obj.quarters + * @param {number} obj.months + * @param {number} obj.weeks + * @param {number} obj.days + * @param {number} obj.hours + * @param {number} obj.minutes + * @param {number} obj.seconds + * @param {number} obj.milliseconds + * @param {Object} [opts=[]] - options for creating this Duration + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the custom conversion system to use + * @return {Duration} + */ + static fromObject(obj, opts = {}) { + if (obj == null || typeof obj !== "object") { + throw new InvalidArgumentError( + `Duration.fromObject: argument expected to be an object, got ${ + obj === null ? "null" : typeof obj + }` + ); + } + + return new Duration({ + values: normalizeObject(obj, Duration.normalizeUnit), + loc: Locale.fromObject(opts), + conversionAccuracy: opts.conversionAccuracy, + matrix: opts.matrix, + }); + } + + /** + * Create a Duration from DurationLike. + * + * @param {Object | number | Duration} durationLike + * One of: + * - object with keys like 'years' and 'hours'. + * - number representing milliseconds + * - Duration instance + * @return {Duration} + */ + static fromDurationLike(durationLike) { + if (isNumber(durationLike)) { + return Duration.fromMillis(durationLike); + } else if (Duration.isDuration(durationLike)) { + return durationLike; + } else if (typeof durationLike === "object") { + return Duration.fromObject(durationLike); + } else { + throw new InvalidArgumentError( + `Unknown duration argument ${durationLike} of type ${typeof durationLike}` + ); + } + } + + /** + * Create a Duration from an ISO 8601 duration string. + * @param {string} text - text to parse + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the preset conversion system to use + * @see https://en.wikipedia.org/wiki/ISO_8601#Durations + * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } + * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } + * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } + * @return {Duration} + */ + static fromISO(text, opts) { + const [parsed] = parseISODuration(text); + if (parsed) { + return Duration.fromObject(parsed, opts); + } else { + return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); + } + } + + /** + * Create a Duration from an ISO 8601 time string. + * @param {string} text - text to parse + * @param {Object} opts - options for parsing + * @param {string} [opts.locale='en-US'] - the locale to use + * @param {string} opts.numberingSystem - the numbering system to use + * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use + * @param {string} [opts.matrix=Object] - the conversion system to use + * @see https://en.wikipedia.org/wiki/ISO_8601#Times + * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } + * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } + * @return {Duration} + */ + static fromISOTime(text, opts) { + const [parsed] = parseISOTimeOnly(text); + if (parsed) { + return Duration.fromObject(parsed, opts); + } else { + return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); + } + } + + /** + * Create an invalid Duration. + * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {Duration} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); + } + + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + + if (Settings.throwOnInvalid) { + throw new InvalidDurationError(invalid); + } else { + return new Duration({ invalid }); + } + } + + /** + * @private + */ + static normalizeUnit(unit) { + const normalized = { + year: "years", + years: "years", + quarter: "quarters", + quarters: "quarters", + month: "months", + months: "months", + week: "weeks", + weeks: "weeks", + day: "days", + days: "days", + hour: "hours", + hours: "hours", + minute: "minutes", + minutes: "minutes", + second: "seconds", + seconds: "seconds", + millisecond: "milliseconds", + milliseconds: "milliseconds", + }[unit ? unit.toLowerCase() : unit]; + + if (!normalized) throw new InvalidUnitError(unit); + + return normalized; + } + + /** + * Check if an object is a Duration. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isDuration(o) { + return (o && o.isLuxonDuration) || false; + } + + /** + * Get the locale of a Duration, such 'en-GB' + * @type {string} + */ + get locale() { + return this.isValid ? this.loc.locale : null; + } + + /** + * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration + * + * @type {string} + */ + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; + } + + /** + * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: + * * `S` for milliseconds + * * `s` for seconds + * * `m` for minutes + * * `h` for hours + * * `d` for days + * * `w` for weeks + * * `M` for months + * * `y` for years + * Notes: + * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits + * * Tokens can be escaped by wrapping with single quotes. + * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting. + * @param {string} fmt - the format string + * @param {Object} opts - options + * @param {boolean} [opts.floor=true] - floor numerical values + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" + * @return {string} + */ + toFormat(fmt, opts = {}) { + // reverse-compat since 1.2; we always round down now, never up, and we do it by default + const fmtOpts = { + ...opts, + floor: opts.round !== false && opts.floor !== false, + }; + return this.isValid + ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) + : INVALID$2; + } + + /** + * Returns a string representation of a Duration with all units included. + * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat + * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`. + * @example + * ```js + * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 }) + * dur.toHuman() //=> '1 day, 5 hours, 6 minutes' + * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes' + * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min' + * ``` + */ + toHuman(opts = {}) { + if (!this.isValid) return INVALID$2; + + const l = orderedUnits$1 + .map((unit) => { + const val = this.values[unit]; + if (isUndefined(val)) { + return null; + } + return this.loc + .numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }) + .format(val); + }) + .filter((n) => n); + + return this.loc + .listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }) + .format(l); + } + + /** + * Returns a JavaScript object with this Duration's values. + * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } + * @return {Object} + */ + toObject() { + if (!this.isValid) return {}; + return { ...this.values }; + } + + /** + * Returns an ISO 8601-compliant string representation of this Duration. + * @see https://en.wikipedia.org/wiki/ISO_8601#Durations + * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' + * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' + * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' + * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' + * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' + * @return {string} + */ + toISO() { + // we could use the formatter, but this is an easier way to get the minimum string + if (!this.isValid) return null; + + let s = "P"; + if (this.years !== 0) s += this.years + "Y"; + if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M"; + if (this.weeks !== 0) s += this.weeks + "W"; + if (this.days !== 0) s += this.days + "D"; + if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) + s += "T"; + if (this.hours !== 0) s += this.hours + "H"; + if (this.minutes !== 0) s += this.minutes + "M"; + if (this.seconds !== 0 || this.milliseconds !== 0) + // this will handle "floating point madness" by removing extra decimal places + // https://stackoverflow.com/questions/588004/is-floating-point-math-broken + s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; + if (s === "P") s += "T0S"; + return s; + } + + /** + * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day. + * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours. + * @see https://en.wikipedia.org/wiki/ISO_8601#Times + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includePrefix=false] - include the `T` prefix + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000' + * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' + * @return {string} + */ + toISOTime(opts = {}) { + if (!this.isValid) return null; + + const millis = this.toMillis(); + if (millis < 0 || millis >= 86400000) return null; + + opts = { + suppressMilliseconds: false, + suppressSeconds: false, + includePrefix: false, + format: "extended", + ...opts, + includeOffset: false, + }; + + const dateTime = DateTime.fromMillis(millis, { zone: "UTC" }); + return dateTime.toISOTime(opts); + } + + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. + * @return {string} + */ + toJSON() { + return this.toISO(); + } + + /** + * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. + * @return {string} + */ + toString() { + return this.toISO(); + } + + /** + * Returns an milliseconds value of this Duration. + * @return {number} + */ + toMillis() { + if (!this.isValid) return NaN; + + return durationToMillis(this.matrix, this.values); + } + + /** + * Returns an milliseconds value of this Duration. Alias of {@link toMillis} + * @return {number} + */ + valueOf() { + return this.toMillis(); + } + + /** + * Make this Duration longer by the specified amount. Return a newly-constructed Duration. + * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @return {Duration} + */ + plus(duration) { + if (!this.isValid) return this; + + const dur = Duration.fromDurationLike(duration), + result = {}; + + for (const k of orderedUnits$1) { + if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { + result[k] = dur.get(k) + this.get(k); + } + } + + return clone$1(this, { values: result }, true); + } + + /** + * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. + * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @return {Duration} + */ + minus(duration) { + if (!this.isValid) return this; + + const dur = Duration.fromDurationLike(duration); + return this.plus(dur.negate()); + } + + /** + * Scale this Duration by the specified amount. Return a newly-constructed Duration. + * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. + * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 } + * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 } + * @return {Duration} + */ + mapUnits(fn) { + if (!this.isValid) return this; + const result = {}; + for (const k of Object.keys(this.values)) { + result[k] = asNumber(fn(this.values[k], k)); + } + return clone$1(this, { values: result }, true); + } + + /** + * Get the value of unit. + * @param {string} unit - a unit such as 'minute' or 'day' + * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2 + * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0 + * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3 + * @return {number} + */ + get(unit) { + return this[Duration.normalizeUnit(unit)]; + } + + /** + * "Set" the values of specified units. Return a newly-constructed Duration. + * @param {Object} values - a mapping of units to numbers + * @example dur.set({ years: 2017 }) + * @example dur.set({ hours: 8, minutes: 30 }) + * @return {Duration} + */ + set(values) { + if (!this.isValid) return this; + + const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) }; + return clone$1(this, { values: mixed }); + } + + /** + * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. + * @example dur.reconfigure({ locale: 'en-GB' }) + * @return {Duration} + */ + reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) { + const loc = this.loc.clone({ locale, numberingSystem }); + const opts = { loc, matrix, conversionAccuracy }; + return clone$1(this, opts); + } + + /** + * Return the length of the duration in the specified unit. + * @param {string} unit - a unit such as 'minutes' or 'days' + * @example Duration.fromObject({years: 1}).as('days') //=> 365 + * @example Duration.fromObject({years: 1}).as('months') //=> 12 + * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 + * @return {number} + */ + as(unit) { + return this.isValid ? this.shiftTo(unit).get(unit) : NaN; + } + + /** + * Reduce this Duration to its canonical representation in its current units. + * Assuming the overall value of the Duration is positive, this means: + * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example) + * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise + * the overall value would be negative, see second example) + * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example) + * + * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`. + * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } + * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 } + * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } + * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 } + * @return {Duration} + */ + normalize() { + if (!this.isValid) return this; + const vals = this.toObject(); + normalizeValues(this.matrix, vals); + return clone$1(this, { values: vals }, true); + } + + /** + * Rescale units to its largest representation + * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 } + * @return {Duration} + */ + rescale() { + if (!this.isValid) return this; + const vals = removeZeroes(this.normalize().shiftToAll().toObject()); + return clone$1(this, { values: vals }, true); + } + + /** + * Convert this Duration into its representation in a different set of units. + * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } + * @return {Duration} + */ + shiftTo(...units) { + if (!this.isValid) return this; + + if (units.length === 0) { + return this; + } + + units = units.map((u) => Duration.normalizeUnit(u)); + + const built = {}, + accumulated = {}, + vals = this.toObject(); + let lastUnit; + + for (const k of orderedUnits$1) { + if (units.indexOf(k) >= 0) { + lastUnit = k; + + let own = 0; + + // anything we haven't boiled down yet should get boiled to this unit + for (const ak in accumulated) { + own += this.matrix[ak][k] * accumulated[ak]; + accumulated[ak] = 0; + } + + // plus anything that's already in this unit + if (isNumber(vals[k])) { + own += vals[k]; + } + + // only keep the integer part for now in the hopes of putting any decimal part + // into a smaller unit later + const i = Math.trunc(own); + built[k] = i; + accumulated[k] = (own * 1000 - i * 1000) / 1000; + + // otherwise, keep it in the wings to boil it later + } else if (isNumber(vals[k])) { + accumulated[k] = vals[k]; + } + } + + // anything leftover becomes the decimal for the last unit + // lastUnit must be defined since units is not empty + for (const key in accumulated) { + if (accumulated[key] !== 0) { + built[lastUnit] += + key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; + } + } + + normalizeValues(this.matrix, built); + return clone$1(this, { values: built }, true); + } + + /** + * Shift this Duration to all available units. + * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds") + * @return {Duration} + */ + shiftToAll() { + if (!this.isValid) return this; + return this.shiftTo( + "years", + "months", + "weeks", + "days", + "hours", + "minutes", + "seconds", + "milliseconds" + ); + } + + /** + * Return the negative of this Duration. + * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } + * @return {Duration} + */ + negate() { + if (!this.isValid) return this; + const negated = {}; + for (const k of Object.keys(this.values)) { + negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; + } + return clone$1(this, { values: negated }, true); + } + + /** + * Get the years. + * @type {number} + */ + get years() { + return this.isValid ? this.values.years || 0 : NaN; + } + + /** + * Get the quarters. + * @type {number} + */ + get quarters() { + return this.isValid ? this.values.quarters || 0 : NaN; + } + + /** + * Get the months. + * @type {number} + */ + get months() { + return this.isValid ? this.values.months || 0 : NaN; + } + + /** + * Get the weeks + * @type {number} + */ + get weeks() { + return this.isValid ? this.values.weeks || 0 : NaN; + } + + /** + * Get the days. + * @type {number} + */ + get days() { + return this.isValid ? this.values.days || 0 : NaN; + } + + /** + * Get the hours. + * @type {number} + */ + get hours() { + return this.isValid ? this.values.hours || 0 : NaN; + } + + /** + * Get the minutes. + * @type {number} + */ + get minutes() { + return this.isValid ? this.values.minutes || 0 : NaN; + } + + /** + * Get the seconds. + * @return {number} + */ + get seconds() { + return this.isValid ? this.values.seconds || 0 : NaN; + } + + /** + * Get the milliseconds. + * @return {number} + */ + get milliseconds() { + return this.isValid ? this.values.milliseconds || 0 : NaN; + } + + /** + * Returns whether the Duration is invalid. Invalid durations are returned by diff operations + * on invalid DateTimes or Intervals. + * @return {boolean} + */ + get isValid() { + return this.invalid === null; + } + + /** + * Returns an error code if this Duration became invalid, or null if the Duration is valid + * @return {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + + /** + * Returns an explanation of why this Duration became invalid, or null if the Duration is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + + /** + * Equality check + * Two Durations are equal iff they have the same units and the same values for each unit. + * @param {Duration} other + * @return {boolean} + */ + equals(other) { + if (!this.isValid || !other.isValid) { + return false; + } + + if (!this.loc.equals(other.loc)) { + return false; + } + + function eq(v1, v2) { + // Consider 0 and undefined as equal + if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0; + return v1 === v2; + } + + for (const u of orderedUnits$1) { + if (!eq(this.values[u], other.values[u])) { + return false; + } + } + return true; + } +} + +const INVALID$1 = "Invalid Interval"; + +// checks if the start is equal to or before the end +function validateStartEnd(start, end) { + if (!start || !start.isValid) { + return Interval.invalid("missing or invalid start"); + } else if (!end || !end.isValid) { + return Interval.invalid("missing or invalid end"); + } else if (end < start) { + return Interval.invalid( + "end before start", + `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}` + ); + } else { + return null; + } +} + +/** + * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them. + * + * Here is a brief overview of the most commonly used methods and getters in Interval: + * + * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}. + * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end. + * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}. + * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}. + * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs} + * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}. + */ +class Interval { + /** + * @private + */ + constructor(config) { + /** + * @access private + */ + this.s = config.start; + /** + * @access private + */ + this.e = config.end; + /** + * @access private + */ + this.invalid = config.invalid || null; + /** + * @access private + */ + this.isLuxonInterval = true; + } + + /** + * Create an invalid Interval. + * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {Interval} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); + } + + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + + if (Settings.throwOnInvalid) { + throw new InvalidIntervalError(invalid); + } else { + return new Interval({ invalid }); + } + } + + /** + * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. + * @param {DateTime|Date|Object} start + * @param {DateTime|Date|Object} end + * @return {Interval} + */ + static fromDateTimes(start, end) { + const builtStart = friendlyDateTime(start), + builtEnd = friendlyDateTime(end); + + const validateError = validateStartEnd(builtStart, builtEnd); + + if (validateError == null) { + return new Interval({ + start: builtStart, + end: builtEnd, + }); + } else { + return validateError; + } + } + + /** + * Create an Interval from a start DateTime and a Duration to extend to. + * @param {DateTime|Date|Object} start + * @param {Duration|Object|number} duration - the length of the Interval. + * @return {Interval} + */ + static after(start, duration) { + const dur = Duration.fromDurationLike(duration), + dt = friendlyDateTime(start); + return Interval.fromDateTimes(dt, dt.plus(dur)); + } + + /** + * Create an Interval from an end DateTime and a Duration to extend backwards to. + * @param {DateTime|Date|Object} end + * @param {Duration|Object|number} duration - the length of the Interval. + * @return {Interval} + */ + static before(end, duration) { + const dur = Duration.fromDurationLike(duration), + dt = friendlyDateTime(end); + return Interval.fromDateTimes(dt.minus(dur), dt); + } + + /** + * Create an Interval from an ISO 8601 string. + * Accepts `/`, `/`, and `/` formats. + * @param {string} text - the ISO string to parse + * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO} + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @return {Interval} + */ + static fromISO(text, opts) { + const [s, e] = (text || "").split("/", 2); + if (s && e) { + let start, startIsValid; + try { + start = DateTime.fromISO(s, opts); + startIsValid = start.isValid; + } catch (e) { + startIsValid = false; + } + + let end, endIsValid; + try { + end = DateTime.fromISO(e, opts); + endIsValid = end.isValid; + } catch (e) { + endIsValid = false; + } + + if (startIsValid && endIsValid) { + return Interval.fromDateTimes(start, end); + } + + if (startIsValid) { + const dur = Duration.fromISO(e, opts); + if (dur.isValid) { + return Interval.after(start, dur); + } + } else if (endIsValid) { + const dur = Duration.fromISO(s, opts); + if (dur.isValid) { + return Interval.before(end, dur); + } + } + } + return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); + } + + /** + * Check if an object is an Interval. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isInterval(o) { + return (o && o.isLuxonInterval) || false; + } + + /** + * Returns the start of the Interval + * @type {DateTime} + */ + get start() { + return this.isValid ? this.s : null; + } + + /** + * Returns the end of the Interval + * @type {DateTime} + */ + get end() { + return this.isValid ? this.e : null; + } + + /** + * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'. + * @type {boolean} + */ + get isValid() { + return this.invalidReason === null; + } + + /** + * Returns an error code if this Interval is invalid, or null if the Interval is valid + * @type {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + + /** + * Returns an explanation of why this Interval became invalid, or null if the Interval is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + + /** + * Returns the length of the Interval in the specified unit. + * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in. + * @return {number} + */ + length(unit = "milliseconds") { + return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; + } + + /** + * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. + * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' + * asks 'what dates are included in this interval?', not 'how many days long is this interval?' + * @param {string} [unit='milliseconds'] - the unit of time to count. + * @return {number} + */ + count(unit = "milliseconds") { + if (!this.isValid) return NaN; + const start = this.start.startOf(unit), + end = this.end.startOf(unit); + return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf()); + } + + /** + * Returns whether this Interval's start and end are both in the same unit of time + * @param {string} unit - the unit of time to check sameness on + * @return {boolean} + */ + hasSame(unit) { + return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; + } + + /** + * Return whether this Interval has the same start and end DateTimes. + * @return {boolean} + */ + isEmpty() { + return this.s.valueOf() === this.e.valueOf(); + } + + /** + * Return whether this Interval's start is after the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isAfter(dateTime) { + if (!this.isValid) return false; + return this.s > dateTime; + } + + /** + * Return whether this Interval's end is before the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + isBefore(dateTime) { + if (!this.isValid) return false; + return this.e <= dateTime; + } + + /** + * Return whether this Interval contains the specified DateTime. + * @param {DateTime} dateTime + * @return {boolean} + */ + contains(dateTime) { + if (!this.isValid) return false; + return this.s <= dateTime && this.e > dateTime; + } + + /** + * "Sets" the start and/or end dates. Returns a newly-constructed Interval. + * @param {Object} values - the values to set + * @param {DateTime} values.start - the starting DateTime + * @param {DateTime} values.end - the ending DateTime + * @return {Interval} + */ + set({ start, end } = {}) { + if (!this.isValid) return this; + return Interval.fromDateTimes(start || this.s, end || this.e); + } + + /** + * Split this Interval at each of the specified DateTimes + * @param {...DateTime} dateTimes - the unit of time to count. + * @return {Array} + */ + splitAt(...dateTimes) { + if (!this.isValid) return []; + const sorted = dateTimes + .map(friendlyDateTime) + .filter((d) => this.contains(d)) + .sort(), + results = []; + let { s } = this, + i = 0; + + while (s < this.e) { + const added = sorted[i] || this.e, + next = +added > +this.e ? this.e : added; + results.push(Interval.fromDateTimes(s, next)); + s = next; + i += 1; + } + + return results; + } + + /** + * Split this Interval into smaller Intervals, each of the specified length. + * Left over time is grouped into a smaller interval + * @param {Duration|Object|number} duration - The length of each resulting interval. + * @return {Array} + */ + splitBy(duration) { + const dur = Duration.fromDurationLike(duration); + + if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { + return []; + } + + let { s } = this, + idx = 1, + next; + + const results = []; + while (s < this.e) { + const added = this.start.plus(dur.mapUnits((x) => x * idx)); + next = +added > +this.e ? this.e : added; + results.push(Interval.fromDateTimes(s, next)); + s = next; + idx += 1; + } + + return results; + } + + /** + * Split this Interval into the specified number of smaller intervals. + * @param {number} numberOfParts - The number of Intervals to divide the Interval into. + * @return {Array} + */ + divideEqually(numberOfParts) { + if (!this.isValid) return []; + return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); + } + + /** + * Return whether this Interval overlaps with the specified Interval + * @param {Interval} other + * @return {boolean} + */ + overlaps(other) { + return this.e > other.s && this.s < other.e; + } + + /** + * Return whether this Interval's end is adjacent to the specified Interval's start. + * @param {Interval} other + * @return {boolean} + */ + abutsStart(other) { + if (!this.isValid) return false; + return +this.e === +other.s; + } + + /** + * Return whether this Interval's start is adjacent to the specified Interval's end. + * @param {Interval} other + * @return {boolean} + */ + abutsEnd(other) { + if (!this.isValid) return false; + return +other.e === +this.s; + } + + /** + * Return whether this Interval engulfs the start and end of the specified Interval. + * @param {Interval} other + * @return {boolean} + */ + engulfs(other) { + if (!this.isValid) return false; + return this.s <= other.s && this.e >= other.e; + } + + /** + * Return whether this Interval has the same start and end as the specified Interval. + * @param {Interval} other + * @return {boolean} + */ + equals(other) { + if (!this.isValid || !other.isValid) { + return false; + } + + return this.s.equals(other.s) && this.e.equals(other.e); + } + + /** + * Return an Interval representing the intersection of this Interval and the specified Interval. + * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. + * Returns null if the intersection is empty, meaning, the intervals don't intersect. + * @param {Interval} other + * @return {Interval} + */ + intersection(other) { + if (!this.isValid) return this; + const s = this.s > other.s ? this.s : other.s, + e = this.e < other.e ? this.e : other.e; + + if (s >= e) { + return null; + } else { + return Interval.fromDateTimes(s, e); + } + } + + /** + * Return an Interval representing the union of this Interval and the specified Interval. + * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. + * @param {Interval} other + * @return {Interval} + */ + union(other) { + if (!this.isValid) return this; + const s = this.s < other.s ? this.s : other.s, + e = this.e > other.e ? this.e : other.e; + return Interval.fromDateTimes(s, e); + } + + /** + * Merge an array of Intervals into a equivalent minimal set of Intervals. + * Combines overlapping and adjacent Intervals. + * @param {Array} intervals + * @return {Array} + */ + static merge(intervals) { + const [found, final] = intervals + .sort((a, b) => a.s - b.s) + .reduce( + ([sofar, current], item) => { + if (!current) { + return [sofar, item]; + } else if (current.overlaps(item) || current.abutsStart(item)) { + return [sofar, current.union(item)]; + } else { + return [sofar.concat([current]), item]; + } + }, + [[], null] + ); + if (final) { + found.push(final); + } + return found; + } + + /** + * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. + * @param {Array} intervals + * @return {Array} + */ + static xor(intervals) { + let start = null, + currentCount = 0; + const results = [], + ends = intervals.map((i) => [ + { time: i.s, type: "s" }, + { time: i.e, type: "e" }, + ]), + flattened = Array.prototype.concat(...ends), + arr = flattened.sort((a, b) => a.time - b.time); + + for (const i of arr) { + currentCount += i.type === "s" ? 1 : -1; + + if (currentCount === 1) { + start = i.time; + } else { + if (start && +start !== +i.time) { + results.push(Interval.fromDateTimes(start, i.time)); + } + + start = null; + } + } + + return Interval.merge(results); + } + + /** + * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. + * @param {...Interval} intervals + * @return {Array} + */ + difference(...intervals) { + return Interval.xor([this].concat(intervals)) + .map((i) => this.intersection(i)) + .filter((i) => i && !i.isEmpty()); + } + + /** + * Returns a string representation of this Interval appropriate for debugging. + * @return {string} + */ + toString() { + if (!this.isValid) return INVALID$1; + return `[${this.s.toISO()} – ${this.e.toISO()})`; + } + + /** + * Returns a localized string representing this Interval. Accepts the same options as the + * Intl.DateTimeFormat constructor and any presets defined by Luxon, such as + * {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method + * is browser-specific, but in general it will return an appropriate representation of the + * Interval in the assigned locale. Defaults to the system's locale if no locale has been + * specified. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or + * Intl.DateTimeFormat constructor options. + * @param {Object} opts - Options to override the configuration of the start DateTime. + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022 + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022 + * @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022 + * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM + * @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p + * @return {string} + */ + toLocaleString(formatOpts = DATE_SHORT, opts = {}) { + return this.isValid + ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) + : INVALID$1; + } + + /** + * Returns an ISO 8601-compliant string representation of this Interval. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @param {Object} opts - The same options as {@link DateTime#toISO} + * @return {string} + */ + toISO(opts) { + if (!this.isValid) return INVALID$1; + return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; + } + + /** + * Returns an ISO 8601-compliant string representation of date of this Interval. + * The time components are ignored. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @return {string} + */ + toISODate() { + if (!this.isValid) return INVALID$1; + return `${this.s.toISODate()}/${this.e.toISODate()}`; + } + + /** + * Returns an ISO 8601-compliant string representation of time of this Interval. + * The date components are ignored. + * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals + * @param {Object} opts - The same options as {@link DateTime#toISO} + * @return {string} + */ + toISOTime(opts) { + if (!this.isValid) return INVALID$1; + return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; + } + + /** + * Returns a string representation of this Interval formatted according to the specified format + * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible + * formatting tool. + * @param {string} dateFormat - The format string. This string formats the start and end time. + * See {@link DateTime#toFormat} for details. + * @param {Object} opts - Options. + * @param {string} [opts.separator = ' – '] - A separator to place between the start and end + * representations. + * @return {string} + */ + toFormat(dateFormat, { separator = " – " } = {}) { + if (!this.isValid) return INVALID$1; + return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; + } + + /** + * Return a Duration representing the time spanned by this interval. + * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } + * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } + * @return {Duration} + */ + toDuration(unit, opts) { + if (!this.isValid) { + return Duration.invalid(this.invalidReason); + } + return this.e.diff(this.s, unit, opts); + } + + /** + * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes + * @param {function} mapFn + * @return {Interval} + * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) + * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) + */ + mapEndpoints(mapFn) { + return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); + } +} + +/** + * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment. + */ +class Info { + /** + * Return whether the specified zone contains a DST. + * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. + * @return {boolean} + */ + static hasDST(zone = Settings.defaultZone) { + const proto = DateTime.now().setZone(zone).set({ month: 12 }); + + return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; + } + + /** + * Return whether the specified zone is a valid IANA specifier. + * @param {string} zone - Zone to check + * @return {boolean} + */ + static isValidIANAZone(zone) { + return IANAZone.isValidZone(zone); + } + + /** + * Converts the input into a {@link Zone} instance. + * + * * If `input` is already a Zone instance, it is returned unchanged. + * * If `input` is a string containing a valid time zone name, a Zone instance + * with that name is returned. + * * If `input` is a string that doesn't refer to a known time zone, a Zone + * instance with {@link Zone#isValid} == false is returned. + * * If `input is a number, a Zone instance with the specified fixed offset + * in minutes is returned. + * * If `input` is `null` or `undefined`, the default zone is returned. + * @param {string|Zone|number} [input] - the value to be converted + * @return {Zone} + */ + static normalizeZone(input) { + return normalizeZone(input, Settings.defaultZone); + } + + /** + * Return an array of standalone month names. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @param {string} [opts.outputCalendar='gregory'] - the calendar + * @example Info.months()[0] //=> 'January' + * @example Info.months('short')[0] //=> 'Jan' + * @example Info.months('numeric')[0] //=> '1' + * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' + * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' + * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' + * @return {Array} + */ + static months( + length = "long", + { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {} + ) { + return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); + } + + /** + * Return an array of format month names. + * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that + * changes the string. + * See {@link Info#months} + * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @param {string} [opts.outputCalendar='gregory'] - the calendar + * @return {Array} + */ + static monthsFormat( + length = "long", + { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {} + ) { + return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); + } + + /** + * Return an array of standalone week names. + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @example Info.weekdays()[0] //=> 'Monday' + * @example Info.weekdays('short')[0] //=> 'Mon' + * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' + * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' + * @return {Array} + */ + static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { + return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); + } + + /** + * Return an array of format week names. + * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that + * changes the string. + * See {@link Info#weekdays} + * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". + * @param {Object} opts - options + * @param {string} [opts.locale=null] - the locale code + * @param {string} [opts.numberingSystem=null] - the numbering system + * @param {string} [opts.locObj=null] - an existing locale object to use + * @return {Array} + */ + static weekdaysFormat( + length = "long", + { locale = null, numberingSystem = null, locObj = null } = {} + ) { + return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); + } + + /** + * Return an array of meridiems. + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @example Info.meridiems() //=> [ 'AM', 'PM' ] + * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] + * @return {Array} + */ + static meridiems({ locale = null } = {}) { + return Locale.create(locale).meridiems(); + } + + /** + * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. + * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". + * @param {Object} opts - options + * @param {string} [opts.locale] - the locale code + * @example Info.eras() //=> [ 'BC', 'AD' ] + * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] + * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] + * @return {Array} + */ + static eras(length = "short", { locale = null } = {}) { + return Locale.create(locale, null, "gregory").eras(length); + } + + /** + * Return the set of available features in this environment. + * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case. + * Keys: + * * `relative`: whether this environment supports relative time formatting + * @example Info.features() //=> { relative: false } + * @return {Object} + */ + static features() { + return { relative: hasRelative() }; + } +} + +function dayDiff(earlier, later) { + const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), + ms = utcDayStart(later) - utcDayStart(earlier); + return Math.floor(Duration.fromMillis(ms).as("days")); +} + +function highOrderDiffs(cursor, later, units) { + const differs = [ + ["years", (a, b) => b.year - a.year], + ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], + ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], + [ + "weeks", + (a, b) => { + const days = dayDiff(a, b); + return (days - (days % 7)) / 7; + }, + ], + ["days", dayDiff], + ]; + + const results = {}; + const earlier = cursor; + let lowestOrder, highWater; + + /* This loop tries to diff using larger units first. + If we overshoot, we backtrack and try the next smaller unit. + "cursor" starts out at the earlier timestamp and moves closer and closer to "later" + as we use smaller and smaller units. + highWater keeps track of where we would be if we added one more of the smallest unit, + this is used later to potentially convert any difference smaller than the smallest higher order unit + into a fraction of that smallest higher order unit + */ + for (const [unit, differ] of differs) { + if (units.indexOf(unit) >= 0) { + lowestOrder = unit; + + results[unit] = differ(cursor, later); + highWater = earlier.plus(results); + + if (highWater > later) { + // we overshot the end point, backtrack cursor by 1 + results[unit]--; + cursor = earlier.plus(results); + + // if we are still overshooting now, we need to backtrack again + // this happens in certain situations when diffing times in different zones, + // because this calculation ignores time zones + if (cursor > later) { + // keep the "overshot by 1" around as highWater + highWater = cursor; + // backtrack cursor by 1 + results[unit]--; + cursor = earlier.plus(results); + } + } else { + cursor = highWater; + } + } + } + + return [cursor, results, highWater, lowestOrder]; +} + +function diff (earlier, later, units, opts) { + let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units); + + const remainingMillis = later - cursor; + + const lowerOrderUnits = units.filter( + (u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0 + ); + + if (lowerOrderUnits.length === 0) { + if (highWater < later) { + highWater = cursor.plus({ [lowestOrder]: 1 }); + } + + if (highWater !== cursor) { + results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); + } + } + + const duration = Duration.fromObject(results, opts); + + if (lowerOrderUnits.length > 0) { + return Duration.fromMillis(remainingMillis, opts) + .shiftTo(...lowerOrderUnits) + .plus(duration); + } else { + return duration; + } +} + +const numberingSystems = { + arab: "[\u0660-\u0669]", + arabext: "[\u06F0-\u06F9]", + bali: "[\u1B50-\u1B59]", + beng: "[\u09E6-\u09EF]", + deva: "[\u0966-\u096F]", + fullwide: "[\uFF10-\uFF19]", + gujr: "[\u0AE6-\u0AEF]", + hanidec: "[〇|一|二|三|四|五|六|七|八|九]", + khmr: "[\u17E0-\u17E9]", + knda: "[\u0CE6-\u0CEF]", + laoo: "[\u0ED0-\u0ED9]", + limb: "[\u1946-\u194F]", + mlym: "[\u0D66-\u0D6F]", + mong: "[\u1810-\u1819]", + mymr: "[\u1040-\u1049]", + orya: "[\u0B66-\u0B6F]", + tamldec: "[\u0BE6-\u0BEF]", + telu: "[\u0C66-\u0C6F]", + thai: "[\u0E50-\u0E59]", + tibt: "[\u0F20-\u0F29]", + latn: "\\d", +}; + +const numberingSystemsUTF16 = { + arab: [1632, 1641], + arabext: [1776, 1785], + bali: [6992, 7001], + beng: [2534, 2543], + deva: [2406, 2415], + fullwide: [65296, 65303], + gujr: [2790, 2799], + khmr: [6112, 6121], + knda: [3302, 3311], + laoo: [3792, 3801], + limb: [6470, 6479], + mlym: [3430, 3439], + mong: [6160, 6169], + mymr: [4160, 4169], + orya: [2918, 2927], + tamldec: [3046, 3055], + telu: [3174, 3183], + thai: [3664, 3673], + tibt: [3872, 3881], +}; + +const hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); + +function parseDigits(str) { + let value = parseInt(str, 10); + if (isNaN(value)) { + value = ""; + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + + if (str[i].search(numberingSystems.hanidec) !== -1) { + value += hanidecChars.indexOf(str[i]); + } else { + for (const key in numberingSystemsUTF16) { + const [min, max] = numberingSystemsUTF16[key]; + if (code >= min && code <= max) { + value += code - min; + } + } + } + } + return parseInt(value, 10); + } else { + return value; + } +} + +function digitRegex({ numberingSystem }, append = "") { + return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`); +} + +const MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; + +function intUnit(regex, post = (i) => i) { + return { regex, deser: ([s]) => post(parseDigits(s)) }; +} + +const NBSP = String.fromCharCode(160); +const spaceOrNBSP = `[ ${NBSP}]`; +const spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); + +function fixListRegex(s) { + // make dots optional and also make them literal + // make space and non breakable space characters interchangeable + return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); +} + +function stripInsensitivities(s) { + return s + .replace(/\./g, "") // ignore dots that were made optional + .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp + .toLowerCase(); +} + +function oneOf(strings, startIndex) { + if (strings === null) { + return null; + } else { + return { + regex: RegExp(strings.map(fixListRegex).join("|")), + deser: ([s]) => + strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex, + }; + } +} + +function offset(regex, groups) { + return { regex, deser: ([, h, m]) => signedOffset(h, m), groups }; +} + +function simple(regex) { + return { regex, deser: ([s]) => s }; +} + +function escapeToken(value) { + return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); +} + +/** + * @param token + * @param {Locale} loc + */ +function unitForToken(token, loc) { + const one = digitRegex(loc), + two = digitRegex(loc, "{2}"), + three = digitRegex(loc, "{3}"), + four = digitRegex(loc, "{4}"), + six = digitRegex(loc, "{6}"), + oneOrTwo = digitRegex(loc, "{1,2}"), + oneToThree = digitRegex(loc, "{1,3}"), + oneToSix = digitRegex(loc, "{1,6}"), + oneToNine = digitRegex(loc, "{1,9}"), + twoToFour = digitRegex(loc, "{2,4}"), + fourToSix = digitRegex(loc, "{4,6}"), + literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }), + unitate = (t) => { + if (token.literal) { + return literal(t); + } + switch (t.val) { + // era + case "G": + return oneOf(loc.eras("short"), 0); + case "GG": + return oneOf(loc.eras("long"), 0); + // years + case "y": + return intUnit(oneToSix); + case "yy": + return intUnit(twoToFour, untruncateYear); + case "yyyy": + return intUnit(four); + case "yyyyy": + return intUnit(fourToSix); + case "yyyyyy": + return intUnit(six); + // months + case "M": + return intUnit(oneOrTwo); + case "MM": + return intUnit(two); + case "MMM": + return oneOf(loc.months("short", true), 1); + case "MMMM": + return oneOf(loc.months("long", true), 1); + case "L": + return intUnit(oneOrTwo); + case "LL": + return intUnit(two); + case "LLL": + return oneOf(loc.months("short", false), 1); + case "LLLL": + return oneOf(loc.months("long", false), 1); + // dates + case "d": + return intUnit(oneOrTwo); + case "dd": + return intUnit(two); + // ordinals + case "o": + return intUnit(oneToThree); + case "ooo": + return intUnit(three); + // time + case "HH": + return intUnit(two); + case "H": + return intUnit(oneOrTwo); + case "hh": + return intUnit(two); + case "h": + return intUnit(oneOrTwo); + case "mm": + return intUnit(two); + case "m": + return intUnit(oneOrTwo); + case "q": + return intUnit(oneOrTwo); + case "qq": + return intUnit(two); + case "s": + return intUnit(oneOrTwo); + case "ss": + return intUnit(two); + case "S": + return intUnit(oneToThree); + case "SSS": + return intUnit(three); + case "u": + return simple(oneToNine); + case "uu": + return simple(oneOrTwo); + case "uuu": + return intUnit(one); + // meridiem + case "a": + return oneOf(loc.meridiems(), 0); + // weekYear (k) + case "kkkk": + return intUnit(four); + case "kk": + return intUnit(twoToFour, untruncateYear); + // weekNumber (W) + case "W": + return intUnit(oneOrTwo); + case "WW": + return intUnit(two); + // weekdays + case "E": + case "c": + return intUnit(one); + case "EEE": + return oneOf(loc.weekdays("short", false), 1); + case "EEEE": + return oneOf(loc.weekdays("long", false), 1); + case "ccc": + return oneOf(loc.weekdays("short", true), 1); + case "cccc": + return oneOf(loc.weekdays("long", true), 1); + // offset/zone + case "Z": + case "ZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); + case "ZZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); + // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing + // because we don't have any way to figure out what they are + case "z": + return simple(/[a-z_+-/]{1,256}?/i); + // this special-case "token" represents a place where a macro-token expanded into a white-space literal + // in this case we accept any non-newline white-space + case " ": + return simple(/[^\S\n\r]/); + default: + return literal(t); + } + }; + + const unit = unitate(token) || { + invalidReason: MISSING_FTP, + }; + + unit.token = token; + + return unit; +} + +const partTypeStyleToTokenVal = { + year: { + "2-digit": "yy", + numeric: "yyyyy", + }, + month: { + numeric: "M", + "2-digit": "MM", + short: "MMM", + long: "MMMM", + }, + day: { + numeric: "d", + "2-digit": "dd", + }, + weekday: { + short: "EEE", + long: "EEEE", + }, + dayperiod: "a", + dayPeriod: "a", + hour12: { + numeric: "h", + "2-digit": "hh", + }, + hour24: { + numeric: "H", + "2-digit": "HH", + }, + minute: { + numeric: "m", + "2-digit": "mm", + }, + second: { + numeric: "s", + "2-digit": "ss", + }, + timeZoneName: { + long: "ZZZZZ", + short: "ZZZ", + }, +}; + +function tokenForPart(part, formatOpts, resolvedOpts) { + const { type, value } = part; + + if (type === "literal") { + const isSpace = /^\s+$/.test(value); + return { + literal: !isSpace, + val: isSpace ? " " : value, + }; + } + + const style = formatOpts[type]; + + // The user might have explicitly specified hour12 or hourCycle + // if so, respect their decision + // if not, refer back to the resolvedOpts, which are based on the locale + let actualType = type; + if (type === "hour") { + if (formatOpts.hour12 != null) { + actualType = formatOpts.hour12 ? "hour12" : "hour24"; + } else if (formatOpts.hourCycle != null) { + if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") { + actualType = "hour12"; + } else { + actualType = "hour24"; + } + } else { + // tokens only differentiate between 24 hours or not, + // so we do not need to check hourCycle here, which is less supported anyways + actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; + } + } + let val = partTypeStyleToTokenVal[actualType]; + if (typeof val === "object") { + val = val[style]; + } + + if (val) { + return { + literal: false, + val, + }; + } + + return undefined; +} + +function buildRegex(units) { + const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); + return [`^${re}$`, units]; +} + +function match(input, regex, handlers) { + const matches = input.match(regex); + + if (matches) { + const all = {}; + let matchIndex = 1; + for (const i in handlers) { + if (hasOwnProperty(handlers, i)) { + const h = handlers[i], + groups = h.groups ? h.groups + 1 : 1; + if (!h.literal && h.token) { + all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); + } + matchIndex += groups; + } + } + return [matches, all]; + } else { + return [matches, {}]; + } +} + +function dateTimeFromMatches(matches) { + const toField = (token) => { + switch (token) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + case "H": + return "hour"; + case "d": + return "day"; + case "o": + return "ordinal"; + case "L": + case "M": + return "month"; + case "y": + return "year"; + case "E": + case "c": + return "weekday"; + case "W": + return "weekNumber"; + case "k": + return "weekYear"; + case "q": + return "quarter"; + default: + return null; + } + }; + + let zone = null; + let specificOffset; + if (!isUndefined(matches.z)) { + zone = IANAZone.create(matches.z); + } + + if (!isUndefined(matches.Z)) { + if (!zone) { + zone = new FixedOffsetZone(matches.Z); + } + specificOffset = matches.Z; + } + + if (!isUndefined(matches.q)) { + matches.M = (matches.q - 1) * 3 + 1; + } + + if (!isUndefined(matches.h)) { + if (matches.h < 12 && matches.a === 1) { + matches.h += 12; + } else if (matches.h === 12 && matches.a === 0) { + matches.h = 0; + } + } + + if (matches.G === 0 && matches.y) { + matches.y = -matches.y; + } + + if (!isUndefined(matches.u)) { + matches.S = parseMillis(matches.u); + } + + const vals = Object.keys(matches).reduce((r, k) => { + const f = toField(k); + if (f) { + r[f] = matches[k]; + } + + return r; + }, {}); + + return [vals, zone, specificOffset]; +} + +let dummyDateTimeCache = null; + +function getDummyDateTime() { + if (!dummyDateTimeCache) { + dummyDateTimeCache = DateTime.fromMillis(1555555555555); + } + + return dummyDateTimeCache; +} + +function maybeExpandMacroToken(token, locale) { + if (token.literal) { + return token; + } + + const formatOpts = Formatter.macroTokenToFormatOpts(token.val); + const tokens = formatOptsToTokens(formatOpts, locale); + + if (tokens == null || tokens.includes(undefined)) { + return token; + } + + return tokens; +} + +function expandMacroTokens(tokens, locale) { + return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale))); +} + +/** + * @private + */ + +function explainFromTokens(locale, input, format) { + const tokens = expandMacroTokens(Formatter.parseFormat(format), locale), + units = tokens.map((t) => unitForToken(t, locale)), + disqualifyingUnit = units.find((t) => t.invalidReason); + + if (disqualifyingUnit) { + return { input, tokens, invalidReason: disqualifyingUnit.invalidReason }; + } else { + const [regexString, handlers] = buildRegex(units), + regex = RegExp(regexString, "i"), + [rawMatches, matches] = match(input, regex, handlers), + [result, zone, specificOffset] = matches + ? dateTimeFromMatches(matches) + : [null, null, undefined]; + if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { + throw new ConflictingSpecificationError( + "Can't include meridiem when specifying 24-hour format" + ); + } + return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset }; + } +} + +function parseFromTokens(locale, input, format) { + const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format); + return [result, zone, specificOffset, invalidReason]; +} + +function formatOptsToTokens(formatOpts, locale) { + if (!formatOpts) { + return null; + } + + const formatter = Formatter.create(locale, formatOpts); + const df = formatter.dtFormatter(getDummyDateTime()); + const parts = df.formatToParts(); + const resolvedOpts = df.resolvedOptions(); + return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts)); +} + +const nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], + leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; + +function unitOutOfRange(unit, value) { + return new Invalid( + "unit out of range", + `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid` + ); +} + +function dayOfWeek(year, month, day) { + const d = new Date(Date.UTC(year, month - 1, day)); + + if (year < 100 && year >= 0) { + d.setUTCFullYear(d.getUTCFullYear() - 1900); + } + + const js = d.getUTCDay(); + + return js === 0 ? 7 : js; +} + +function computeOrdinal(year, month, day) { + return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; +} + +function uncomputeOrdinal(year, ordinal) { + const table = isLeapYear(year) ? leapLadder : nonLeapLadder, + month0 = table.findIndex((i) => i < ordinal), + day = ordinal - table[month0]; + return { month: month0 + 1, day }; +} + +/** + * @private + */ + +function gregorianToWeek(gregObj) { + const { year, month, day } = gregObj, + ordinal = computeOrdinal(year, month, day), + weekday = dayOfWeek(year, month, day); + + let weekNumber = Math.floor((ordinal - weekday + 10) / 7), + weekYear; + + if (weekNumber < 1) { + weekYear = year - 1; + weekNumber = weeksInWeekYear(weekYear); + } else if (weekNumber > weeksInWeekYear(year)) { + weekYear = year + 1; + weekNumber = 1; + } else { + weekYear = year; + } + + return { weekYear, weekNumber, weekday, ...timeObject(gregObj) }; +} + +function weekToGregorian(weekData) { + const { weekYear, weekNumber, weekday } = weekData, + weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), + yearInDays = daysInYear(weekYear); + + let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, + year; + + if (ordinal < 1) { + year = weekYear - 1; + ordinal += daysInYear(year); + } else if (ordinal > yearInDays) { + year = weekYear + 1; + ordinal -= daysInYear(weekYear); + } else { + year = weekYear; + } + + const { month, day } = uncomputeOrdinal(year, ordinal); + return { year, month, day, ...timeObject(weekData) }; +} + +function gregorianToOrdinal(gregData) { + const { year, month, day } = gregData; + const ordinal = computeOrdinal(year, month, day); + return { year, ordinal, ...timeObject(gregData) }; +} + +function ordinalToGregorian(ordinalData) { + const { year, ordinal } = ordinalData; + const { month, day } = uncomputeOrdinal(year, ordinal); + return { year, month, day, ...timeObject(ordinalData) }; +} + +function hasInvalidWeekData(obj) { + const validYear = isInteger(obj.weekYear), + validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), + validWeekday = integerBetween(obj.weekday, 1, 7); + + if (!validYear) { + return unitOutOfRange("weekYear", obj.weekYear); + } else if (!validWeek) { + return unitOutOfRange("week", obj.week); + } else if (!validWeekday) { + return unitOutOfRange("weekday", obj.weekday); + } else return false; +} + +function hasInvalidOrdinalData(obj) { + const validYear = isInteger(obj.year), + validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); + + if (!validYear) { + return unitOutOfRange("year", obj.year); + } else if (!validOrdinal) { + return unitOutOfRange("ordinal", obj.ordinal); + } else return false; +} + +function hasInvalidGregorianData(obj) { + const validYear = isInteger(obj.year), + validMonth = integerBetween(obj.month, 1, 12), + validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); + + if (!validYear) { + return unitOutOfRange("year", obj.year); + } else if (!validMonth) { + return unitOutOfRange("month", obj.month); + } else if (!validDay) { + return unitOutOfRange("day", obj.day); + } else return false; +} + +function hasInvalidTimeData(obj) { + const { hour, minute, second, millisecond } = obj; + const validHour = + integerBetween(hour, 0, 23) || + (hour === 24 && minute === 0 && second === 0 && millisecond === 0), + validMinute = integerBetween(minute, 0, 59), + validSecond = integerBetween(second, 0, 59), + validMillisecond = integerBetween(millisecond, 0, 999); + + if (!validHour) { + return unitOutOfRange("hour", hour); + } else if (!validMinute) { + return unitOutOfRange("minute", minute); + } else if (!validSecond) { + return unitOutOfRange("second", second); + } else if (!validMillisecond) { + return unitOutOfRange("millisecond", millisecond); + } else return false; +} + +const INVALID = "Invalid DateTime"; +const MAX_DATE = 8.64e15; + +function unsupportedZone(zone) { + return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); +} + +// we cache week data on the DT object and this intermediates the cache +function possiblyCachedWeekData(dt) { + if (dt.weekData === null) { + dt.weekData = gregorianToWeek(dt.c); + } + return dt.weekData; +} + +// clone really means, "make a new object with these modifications". all "setters" really use this +// to create a new object while only changing some of the properties +function clone(inst, alts) { + const current = { + ts: inst.ts, + zone: inst.zone, + c: inst.c, + o: inst.o, + loc: inst.loc, + invalid: inst.invalid, + }; + return new DateTime({ ...current, ...alts, old: current }); +} + +// find the right offset a given local time. The o input is our guess, which determines which +// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) +function fixOffset(localTS, o, tz) { + // Our UTC time is just a guess because our offset is just a guess + let utcGuess = localTS - o * 60 * 1000; + + // Test whether the zone matches the offset for this ts + const o2 = tz.offset(utcGuess); + + // If so, offset didn't change and we're done + if (o === o2) { + return [utcGuess, o]; + } + + // If not, change the ts by the difference in the offset + utcGuess -= (o2 - o) * 60 * 1000; + + // If that gives us the local time we want, we're done + const o3 = tz.offset(utcGuess); + if (o2 === o3) { + return [utcGuess, o2]; + } + + // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time + return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)]; +} + +// convert an epoch timestamp into a calendar object with the given offset +function tsToObj(ts, offset) { + ts += offset * 60 * 1000; + + const d = new Date(ts); + + return { + year: d.getUTCFullYear(), + month: d.getUTCMonth() + 1, + day: d.getUTCDate(), + hour: d.getUTCHours(), + minute: d.getUTCMinutes(), + second: d.getUTCSeconds(), + millisecond: d.getUTCMilliseconds(), + }; +} + +// convert a calendar object to a epoch timestamp +function objToTS(obj, offset, zone) { + return fixOffset(objToLocalTS(obj), offset, zone); +} + +// create a new DT instance by adding a duration, adjusting for DSTs +function adjustTime(inst, dur) { + const oPre = inst.o, + year = inst.c.year + Math.trunc(dur.years), + month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, + c = { + ...inst.c, + year, + month, + day: + Math.min(inst.c.day, daysInMonth(year, month)) + + Math.trunc(dur.days) + + Math.trunc(dur.weeks) * 7, + }, + millisToAdd = Duration.fromObject({ + years: dur.years - Math.trunc(dur.years), + quarters: dur.quarters - Math.trunc(dur.quarters), + months: dur.months - Math.trunc(dur.months), + weeks: dur.weeks - Math.trunc(dur.weeks), + days: dur.days - Math.trunc(dur.days), + hours: dur.hours, + minutes: dur.minutes, + seconds: dur.seconds, + milliseconds: dur.milliseconds, + }).as("milliseconds"), + localTS = objToLocalTS(c); + + let [ts, o] = fixOffset(localTS, oPre, inst.zone); + + if (millisToAdd !== 0) { + ts += millisToAdd; + // that could have changed the offset by going over a DST, but we want to keep the ts the same + o = inst.zone.offset(ts); + } + + return { ts, o }; +} + +// helper useful in turning the results of parsing into real dates +// by handling the zone options +function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) { + const { setZone, zone } = opts; + if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) { + const interpretationZone = parsedZone || zone, + inst = DateTime.fromObject(parsed, { + ...opts, + zone: interpretationZone, + specificOffset, + }); + return setZone ? inst : inst.setZone(zone); + } else { + return DateTime.invalid( + new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`) + ); + } +} + +// if you want to output a technical format (e.g. RFC 2822), this helper +// helps handle the details +function toTechFormat(dt, format, allowZ = true) { + return dt.isValid + ? Formatter.create(Locale.create("en-US"), { + allowZ, + forceSimple: true, + }).formatDateTimeFromString(dt, format) + : null; +} + +function toISODate(o, extended) { + const longFormat = o.c.year > 9999 || o.c.year < 0; + let c = ""; + if (longFormat && o.c.year >= 0) c += "+"; + c += padStart(o.c.year, longFormat ? 6 : 4); + + if (extended) { + c += "-"; + c += padStart(o.c.month); + c += "-"; + c += padStart(o.c.day); + } else { + c += padStart(o.c.month); + c += padStart(o.c.day); + } + return c; +} + +function toISOTime( + o, + extended, + suppressSeconds, + suppressMilliseconds, + includeOffset, + extendedZone +) { + let c = padStart(o.c.hour); + if (extended) { + c += ":"; + c += padStart(o.c.minute); + if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { + c += ":"; + } + } else { + c += padStart(o.c.minute); + } + + if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { + c += padStart(o.c.second); + + if (o.c.millisecond !== 0 || !suppressMilliseconds) { + c += "."; + c += padStart(o.c.millisecond, 3); + } + } + + if (includeOffset) { + if (o.isOffsetFixed && o.offset === 0 && !extendedZone) { + c += "Z"; + } else if (o.o < 0) { + c += "-"; + c += padStart(Math.trunc(-o.o / 60)); + c += ":"; + c += padStart(Math.trunc(-o.o % 60)); + } else { + c += "+"; + c += padStart(Math.trunc(o.o / 60)); + c += ":"; + c += padStart(Math.trunc(o.o % 60)); + } + } + + if (extendedZone) { + c += "[" + o.zone.ianaName + "]"; + } + return c; +} + +// defaults for unspecified units in the supported calendars +const defaultUnitValues = { + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + }, + defaultWeekUnitValues = { + weekNumber: 1, + weekday: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + }, + defaultOrdinalUnitValues = { + ordinal: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + }; + +// Units in the supported calendars, sorted by bigness +const orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"], + orderedWeekUnits = [ + "weekYear", + "weekNumber", + "weekday", + "hour", + "minute", + "second", + "millisecond", + ], + orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; + +// standardize case and plurality in units +function normalizeUnit(unit) { + const normalized = { + year: "year", + years: "year", + month: "month", + months: "month", + day: "day", + days: "day", + hour: "hour", + hours: "hour", + minute: "minute", + minutes: "minute", + quarter: "quarter", + quarters: "quarter", + second: "second", + seconds: "second", + millisecond: "millisecond", + milliseconds: "millisecond", + weekday: "weekday", + weekdays: "weekday", + weeknumber: "weekNumber", + weeksnumber: "weekNumber", + weeknumbers: "weekNumber", + weekyear: "weekYear", + weekyears: "weekYear", + ordinal: "ordinal", + }[unit.toLowerCase()]; + + if (!normalized) throw new InvalidUnitError(unit); + + return normalized; +} + +// this is a dumbed down version of fromObject() that runs about 60% faster +// but doesn't do any validation, makes a bunch of assumptions about what units +// are present, and so on. +function quickDT(obj, opts) { + const zone = normalizeZone(opts.zone, Settings.defaultZone), + loc = Locale.fromObject(opts), + tsNow = Settings.now(); + + let ts, o; + + // assume we have the higher-order units + if (!isUndefined(obj.year)) { + for (const u of orderedUnits) { + if (isUndefined(obj[u])) { + obj[u] = defaultUnitValues[u]; + } + } + + const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); + if (invalid) { + return DateTime.invalid(invalid); + } + + const offsetProvis = zone.offset(tsNow); + [ts, o] = objToTS(obj, offsetProvis, zone); + } else { + ts = tsNow; + } + + return new DateTime({ ts, zone, loc, o }); +} + +function diffRelative(start, end, opts) { + const round = isUndefined(opts.round) ? true : opts.round, + format = (c, unit) => { + c = roundTo(c, round || opts.calendary ? 0 : 2, true); + const formatter = end.loc.clone(opts).relFormatter(opts); + return formatter.format(c, unit); + }, + differ = (unit) => { + if (opts.calendary) { + if (!end.hasSame(start, unit)) { + return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); + } else return 0; + } else { + return end.diff(start, unit).get(unit); + } + }; + + if (opts.unit) { + return format(differ(opts.unit), opts.unit); + } + + for (const unit of opts.units) { + const count = differ(unit); + if (Math.abs(count) >= 1) { + return format(count, unit); + } + } + return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); +} + +function lastOpts(argList) { + let opts = {}, + args; + if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { + opts = argList[argList.length - 1]; + args = Array.from(argList).slice(0, argList.length - 1); + } else { + args = Array.from(argList); + } + return [opts, args]; +} + +/** + * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them. + * + * A DateTime comprises of: + * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch. + * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone). + * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`. + * + * Here is a brief overview of the most commonly used functionality it provides: + * + * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}. + * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month}, + * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors. + * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors. + * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors. + * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}. + * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}. + * + * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation. + */ +class DateTime { + /** + * @access private + */ + constructor(config) { + const zone = config.zone || Settings.defaultZone; + + let invalid = + config.invalid || + (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || + (!zone.isValid ? unsupportedZone(zone) : null); + /** + * @access private + */ + this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; + + let c = null, + o = null; + if (!invalid) { + const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); + + if (unchanged) { + [c, o] = [config.old.c, config.old.o]; + } else { + const ot = zone.offset(this.ts); + c = tsToObj(this.ts, ot); + invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; + c = invalid ? null : c; + o = invalid ? null : ot; + } + } + + /** + * @access private + */ + this._zone = zone; + /** + * @access private + */ + this.loc = config.loc || Locale.create(); + /** + * @access private + */ + this.invalid = invalid; + /** + * @access private + */ + this.weekData = null; + /** + * @access private + */ + this.c = c; + /** + * @access private + */ + this.o = o; + /** + * @access private + */ + this.isLuxonDateTime = true; + } + + // CONSTRUCT + + /** + * Create a DateTime for the current instant, in the system's time zone. + * + * Use Settings to override these default values if needed. + * @example DateTime.now().toISO() //~> now in the ISO format + * @return {DateTime} + */ + static now() { + return new DateTime({}); + } + + /** + * Create a local DateTime + * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used + * @param {number} [month=1] - The month, 1-indexed + * @param {number} [day=1] - The day of the month, 1-indexed + * @param {number} [hour=0] - The hour of the day, in 24-hour time + * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 + * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 + * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 + * @example DateTime.local() //~> now + * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time + * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 + * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 + * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale + * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 + * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC + * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 + * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 + * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 + * @return {DateTime} + */ + static local() { + const [opts, args] = lastOpts(arguments), + [year, month, day, hour, minute, second, millisecond] = args; + return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); + } + + /** + * Create a DateTime in UTC + * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used + * @param {number} [month=1] - The month, 1-indexed + * @param {number} [day=1] - The day of the month + * @param {number} [hour=0] - The hour of the day, in 24-hour time + * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 + * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 + * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 + * @param {Object} options - configuration options for the DateTime + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance + * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance + * @example DateTime.utc() //~> now + * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z + * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z + * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z + * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z + * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z + * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale + * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z + * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale + * @return {DateTime} + */ + static utc() { + const [opts, args] = lastOpts(arguments), + [year, month, day, hour, minute, second, millisecond] = args; + + opts.zone = FixedOffsetZone.utcInstance; + return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); + } + + /** + * Create a DateTime from a JavaScript Date object. Uses the default zone. + * @param {Date} date - a JavaScript Date object + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @return {DateTime} + */ + static fromJSDate(date, options = {}) { + const ts = isDate(date) ? date.valueOf() : NaN; + if (Number.isNaN(ts)) { + return DateTime.invalid("invalid input"); + } + + const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); + if (!zoneToUse.isValid) { + return DateTime.invalid(unsupportedZone(zoneToUse)); + } + + return new DateTime({ + ts: ts, + zone: zoneToUse, + loc: Locale.fromObject(options), + }); + } + + /** + * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. + * @param {number} milliseconds - a number of milliseconds since 1970 UTC + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromMillis(milliseconds, options = {}) { + if (!isNumber(milliseconds)) { + throw new InvalidArgumentError( + `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}` + ); + } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { + // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start + return DateTime.invalid("Timestamp out of range"); + } else { + return new DateTime({ + ts: milliseconds, + zone: normalizeZone(options.zone, Settings.defaultZone), + loc: Locale.fromObject(options), + }); + } + } + + /** + * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. + * @param {number} seconds - a number of seconds since 1970 UTC + * @param {Object} options - configuration options for the DateTime + * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into + * @param {string} [options.locale] - a locale to set on the resulting DateTime instance + * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromSeconds(seconds, options = {}) { + if (!isNumber(seconds)) { + throw new InvalidArgumentError("fromSeconds requires a numerical input"); + } else { + return new DateTime({ + ts: seconds * 1000, + zone: normalizeZone(options.zone, Settings.defaultZone), + loc: Locale.fromObject(options), + }); + } + } + + /** + * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults. + * @param {Object} obj - the object to create the DateTime from + * @param {number} obj.year - a year, such as 1987 + * @param {number} obj.month - a month, 1-12 + * @param {number} obj.day - a day of the month, 1-31, depending on the month + * @param {number} obj.ordinal - day of the year, 1-365 or 366 + * @param {number} obj.weekYear - an ISO week year + * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year + * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday + * @param {number} obj.hour - hour of the day, 0-23 + * @param {number} obj.minute - minute of the hour, 0-59 + * @param {number} obj.second - second of the minute, 0-59 + * @param {number} obj.millisecond - millisecond of the second, 0-999 + * @param {Object} opts - options for creating this DateTime + * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' + * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }), + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' }) + * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' }) + * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' + * @return {DateTime} + */ + static fromObject(obj, opts = {}) { + obj = obj || {}; + const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); + if (!zoneToUse.isValid) { + return DateTime.invalid(unsupportedZone(zoneToUse)); + } + + const tsNow = Settings.now(), + offsetProvis = !isUndefined(opts.specificOffset) + ? opts.specificOffset + : zoneToUse.offset(tsNow), + normalized = normalizeObject(obj, normalizeUnit), + containsOrdinal = !isUndefined(normalized.ordinal), + containsGregorYear = !isUndefined(normalized.year), + containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), + containsGregor = containsGregorYear || containsGregorMD, + definiteWeekDef = normalized.weekYear || normalized.weekNumber, + loc = Locale.fromObject(opts); + + // cases: + // just a weekday -> this week's instance of that weekday, no worries + // (gregorian data or ordinal) + (weekYear or weekNumber) -> error + // (gregorian month or day) + ordinal -> error + // otherwise just use weeks or ordinals or gregorian, depending on what's specified + + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError( + "Can't mix weekYear/weekNumber units with year/month/day or ordinals" + ); + } + + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); + } + + const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor); + + // configure ourselves to deal with gregorian dates or week stuff + let units, + defaultValues, + objNow = tsToObj(tsNow, offsetProvis); + if (useWeekData) { + units = orderedWeekUnits; + defaultValues = defaultWeekUnitValues; + objNow = gregorianToWeek(objNow); + } else if (containsOrdinal) { + units = orderedOrdinalUnits; + defaultValues = defaultOrdinalUnitValues; + objNow = gregorianToOrdinal(objNow); + } else { + units = orderedUnits; + defaultValues = defaultUnitValues; + } + + // set default values for missing stuff + let foundFirst = false; + for (const u of units) { + const v = normalized[u]; + if (!isUndefined(v)) { + foundFirst = true; + } else if (foundFirst) { + normalized[u] = defaultValues[u]; + } else { + normalized[u] = objNow[u]; + } + } + + // make sure the values we have are in range + const higherOrderInvalid = useWeekData + ? hasInvalidWeekData(normalized) + : containsOrdinal + ? hasInvalidOrdinalData(normalized) + : hasInvalidGregorianData(normalized), + invalid = higherOrderInvalid || hasInvalidTimeData(normalized); + + if (invalid) { + return DateTime.invalid(invalid); + } + + // compute the actual time + const gregorian = useWeekData + ? weekToGregorian(normalized) + : containsOrdinal + ? ordinalToGregorian(normalized) + : normalized, + [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), + inst = new DateTime({ + ts: tsFinal, + zone: zoneToUse, + o: offsetFinal, + loc, + }); + + // gregorian data + weekday serves only to validate + if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { + return DateTime.invalid( + "mismatched weekday", + `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}` + ); + } + + return inst; + } + + /** + * Create a DateTime from an ISO 8601 string + * @param {string} text - the ISO string + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance + * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromISO('2016-05-25T09:08:34.123') + * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') + * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) + * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) + * @example DateTime.fromISO('2016-W05-4') + * @return {DateTime} + */ + static fromISO(text, opts = {}) { + const [vals, parsedZone] = parseISODate(text); + return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); + } + + /** + * Create a DateTime from an RFC 2822 string + * @param {string} text - the RFC 2822 string + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. + * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') + * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') + * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') + * @return {DateTime} + */ + static fromRFC2822(text, opts = {}) { + const [vals, parsedZone] = parseRFC2822Date(text); + return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); + } + + /** + * Create a DateTime from an HTTP header date + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 + * @param {string} text - the HTTP header date + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. + * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. + * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance + * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') + * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') + * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') + * @return {DateTime} + */ + static fromHTTP(text, opts = {}) { + const [vals, parsedZone] = parseHTTPDate(text); + return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); + } + + /** + * Create a DateTime from an input string and format string. + * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens). + * @param {string} text - the string to parse + * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale + * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @return {DateTime} + */ + static fromFormat(text, fmt, opts = {}) { + if (isUndefined(text) || isUndefined(fmt)) { + throw new InvalidArgumentError("fromFormat requires an input string and a format"); + } + + const { locale = null, numberingSystem = null } = opts, + localeToUse = Locale.fromOpts({ + locale, + numberingSystem, + defaultToEN: true, + }), + [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt); + if (invalid) { + return DateTime.invalid(invalid); + } else { + return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset); + } + } + + /** + * @deprecated use fromFormat instead + */ + static fromString(text, fmt, opts = {}) { + return DateTime.fromFormat(text, fmt, opts); + } + + /** + * Create a DateTime from a SQL date, time, or datetime + * Defaults to en-US if no locale has been specified, regardless of the system's locale + * @param {string} text - the string to parse + * @param {Object} opts - options to affect the creation + * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone + * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one + * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale + * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system + * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance + * @example DateTime.fromSQL('2017-05-15') + * @example DateTime.fromSQL('2017-05-15 09:12:34') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') + * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) + * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) + * @example DateTime.fromSQL('09:12:34.342') + * @return {DateTime} + */ + static fromSQL(text, opts = {}) { + const [vals, parsedZone] = parseSQL(text); + return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); + } + + /** + * Create an invalid DateTime. + * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent. + * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information + * @return {DateTime} + */ + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); + } + + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + + if (Settings.throwOnInvalid) { + throw new InvalidDateTimeError(invalid); + } else { + return new DateTime({ invalid }); + } + } + + /** + * Check if an object is an instance of DateTime. Works across context boundaries + * @param {object} o + * @return {boolean} + */ + static isDateTime(o) { + return (o && o.isLuxonDateTime) || false; + } + + /** + * Produce the format string for a set of options + * @param formatOpts + * @param localeOpts + * @returns {string} + */ + static parseFormatForOpts(formatOpts, localeOpts = {}) { + const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); + return !tokenList ? null : tokenList.map((t) => (t ? t.val : null)).join(""); + } + + /** + * Produce the the fully expanded format token for the locale + * Does NOT quote characters, so quoted tokens will not round trip correctly + * @param fmt + * @param localeOpts + * @returns {string} + */ + static expandFormat(fmt, localeOpts = {}) { + const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); + return expanded.map((t) => t.val).join(""); + } + + // INFO + + /** + * Get the value of unit. + * @param {string} unit - a unit such as 'minute' or 'day' + * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 + * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 + * @return {number} + */ + get(unit) { + return this[unit]; + } + + /** + * Returns whether the DateTime is valid. Invalid DateTimes occur when: + * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 + * * The DateTime was created by an operation on another invalid date + * @type {boolean} + */ + get isValid() { + return this.invalid === null; + } + + /** + * Returns an error code if this DateTime is invalid, or null if the DateTime is valid + * @type {string} + */ + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + + /** + * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid + * @type {string} + */ + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + + /** + * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime + * + * @type {string} + */ + get locale() { + return this.isValid ? this.loc.locale : null; + } + + /** + * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime + * + * @type {string} + */ + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; + } + + /** + * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime + * + * @type {string} + */ + get outputCalendar() { + return this.isValid ? this.loc.outputCalendar : null; + } + + /** + * Get the time zone associated with this DateTime. + * @type {Zone} + */ + get zone() { + return this._zone; + } + + /** + * Get the name of the time zone. + * @type {string} + */ + get zoneName() { + return this.isValid ? this.zone.name : null; + } + + /** + * Get the year + * @example DateTime.local(2017, 5, 25).year //=> 2017 + * @type {number} + */ + get year() { + return this.isValid ? this.c.year : NaN; + } + + /** + * Get the quarter + * @example DateTime.local(2017, 5, 25).quarter //=> 2 + * @type {number} + */ + get quarter() { + return this.isValid ? Math.ceil(this.c.month / 3) : NaN; + } + + /** + * Get the month (1-12). + * @example DateTime.local(2017, 5, 25).month //=> 5 + * @type {number} + */ + get month() { + return this.isValid ? this.c.month : NaN; + } + + /** + * Get the day of the month (1-30ish). + * @example DateTime.local(2017, 5, 25).day //=> 25 + * @type {number} + */ + get day() { + return this.isValid ? this.c.day : NaN; + } + + /** + * Get the hour of the day (0-23). + * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 + * @type {number} + */ + get hour() { + return this.isValid ? this.c.hour : NaN; + } + + /** + * Get the minute of the hour (0-59). + * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 + * @type {number} + */ + get minute() { + return this.isValid ? this.c.minute : NaN; + } + + /** + * Get the second of the minute (0-59). + * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 + * @type {number} + */ + get second() { + return this.isValid ? this.c.second : NaN; + } + + /** + * Get the millisecond of the second (0-999). + * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 + * @type {number} + */ + get millisecond() { + return this.isValid ? this.c.millisecond : NaN; + } + + /** + * Get the week year + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2014, 12, 31).weekYear //=> 2015 + * @type {number} + */ + get weekYear() { + return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; + } + + /** + * Get the week number of the week year (1-52ish). + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 + * @type {number} + */ + get weekNumber() { + return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; + } + + /** + * Get the day of the week. + * 1 is Monday and 7 is Sunday + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2014, 11, 31).weekday //=> 4 + * @type {number} + */ + get weekday() { + return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; + } + + /** + * Get the ordinal (meaning the day of the year) + * @example DateTime.local(2017, 5, 25).ordinal //=> 145 + * @type {number|DateTime} + */ + get ordinal() { + return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; + } + + /** + * Get the human readable short month name, such as 'Oct'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).monthShort //=> Oct + * @type {string} + */ + get monthShort() { + return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null; + } + + /** + * Get the human readable long month name, such as 'October'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).monthLong //=> October + * @type {string} + */ + get monthLong() { + return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null; + } + + /** + * Get the human readable short weekday, such as 'Mon'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon + * @type {string} + */ + get weekdayShort() { + return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null; + } + + /** + * Get the human readable long weekday, such as 'Monday'. + * Defaults to the system's locale if no locale has been specified + * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday + * @type {string} + */ + get weekdayLong() { + return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null; + } + + /** + * Get the UTC offset of this DateTime in minutes + * @example DateTime.now().offset //=> -240 + * @example DateTime.utc().offset //=> 0 + * @type {number} + */ + get offset() { + return this.isValid ? +this.o : NaN; + } + + /** + * Get the short human name for the zone's current offset, for example "EST" or "EDT". + * Defaults to the system's locale if no locale has been specified + * @type {string} + */ + get offsetNameShort() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "short", + locale: this.locale, + }); + } else { + return null; + } + } + + /** + * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". + * Defaults to the system's locale if no locale has been specified + * @type {string} + */ + get offsetNameLong() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "long", + locale: this.locale, + }); + } else { + return null; + } + } + + /** + * Get whether this zone's offset ever changes, as in a DST. + * @type {boolean} + */ + get isOffsetFixed() { + return this.isValid ? this.zone.isUniversal : null; + } + + /** + * Get whether the DateTime is in a DST. + * @type {boolean} + */ + get isInDST() { + if (this.isOffsetFixed) { + return false; + } else { + return ( + this.offset > this.set({ month: 1, day: 1 }).offset || + this.offset > this.set({ month: 5 }).offset + ); + } + } + + /** + * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC + * in this DateTime's zone. During DST changes local time can be ambiguous, for example + * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`. + * This method will return both possible DateTimes if this DateTime's local time is ambiguous. + * @returns {DateTime[]} + */ + getPossibleOffsets() { + if (!this.isValid || this.isOffsetFixed) { + return [this]; + } + const dayMs = 86400000; + const minuteMs = 60000; + const localTS = objToLocalTS(this.c); + const oEarlier = this.zone.offset(localTS - dayMs); + const oLater = this.zone.offset(localTS + dayMs); + + const o1 = this.zone.offset(localTS - oEarlier * minuteMs); + const o2 = this.zone.offset(localTS - oLater * minuteMs); + if (o1 === o2) { + return [this]; + } + const ts1 = localTS - o1 * minuteMs; + const ts2 = localTS - o2 * minuteMs; + const c1 = tsToObj(ts1, o1); + const c2 = tsToObj(ts2, o2); + if ( + c1.hour === c2.hour && + c1.minute === c2.minute && + c1.second === c2.second && + c1.millisecond === c2.millisecond + ) { + return [clone(this, { ts: ts1 }), clone(this, { ts: ts2 })]; + } + return [this]; + } + + /** + * Returns true if this DateTime is in a leap year, false otherwise + * @example DateTime.local(2016).isInLeapYear //=> true + * @example DateTime.local(2013).isInLeapYear //=> false + * @type {boolean} + */ + get isInLeapYear() { + return isLeapYear(this.year); + } + + /** + * Returns the number of days in this DateTime's month + * @example DateTime.local(2016, 2).daysInMonth //=> 29 + * @example DateTime.local(2016, 3).daysInMonth //=> 31 + * @type {number} + */ + get daysInMonth() { + return daysInMonth(this.year, this.month); + } + + /** + * Returns the number of days in this DateTime's year + * @example DateTime.local(2016).daysInYear //=> 366 + * @example DateTime.local(2013).daysInYear //=> 365 + * @type {number} + */ + get daysInYear() { + return this.isValid ? daysInYear(this.year) : NaN; + } + + /** + * Returns the number of weeks in this DateTime's year + * @see https://en.wikipedia.org/wiki/ISO_week_date + * @example DateTime.local(2004).weeksInWeekYear //=> 53 + * @example DateTime.local(2013).weeksInWeekYear //=> 52 + * @type {number} + */ + get weeksInWeekYear() { + return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; + } + + /** + * Returns the resolved Intl options for this DateTime. + * This is useful in understanding the behavior of formatting methods + * @param {Object} opts - the same options as toLocaleString + * @return {Object} + */ + resolvedLocaleOptions(opts = {}) { + const { locale, numberingSystem, calendar } = Formatter.create( + this.loc.clone(opts), + opts + ).resolvedOptions(this); + return { locale, numberingSystem, outputCalendar: calendar }; + } + + // TRANSFORM + + /** + * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. + * + * Equivalent to {@link DateTime#setZone}('utc') + * @param {number} [offset=0] - optionally, an offset from UTC in minutes + * @param {Object} [opts={}] - options to pass to `setZone()` + * @return {DateTime} + */ + toUTC(offset = 0, opts = {}) { + return this.setZone(FixedOffsetZone.instance(offset), opts); + } + + /** + * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. + * + * Equivalent to `setZone('local')` + * @return {DateTime} + */ + toLocal() { + return this.setZone(Settings.defaultZone); + } + + /** + * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. + * + * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones. + * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class. + * @param {Object} opts - options + * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. + * @return {DateTime} + */ + setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) { + zone = normalizeZone(zone, Settings.defaultZone); + if (zone.equals(this.zone)) { + return this; + } else if (!zone.isValid) { + return DateTime.invalid(unsupportedZone(zone)); + } else { + let newTS = this.ts; + if (keepLocalTime || keepCalendarTime) { + const offsetGuess = zone.offset(this.ts); + const asObj = this.toObject(); + [newTS] = objToTS(asObj, offsetGuess, zone); + } + return clone(this, { ts: newTS, zone }); + } + } + + /** + * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. + * @param {Object} properties - the properties to set + * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) + * @return {DateTime} + */ + reconfigure({ locale, numberingSystem, outputCalendar } = {}) { + const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); + return clone(this, { loc }); + } + + /** + * "Set" the locale. Returns a newly-constructed DateTime. + * Just a convenient alias for reconfigure({ locale }) + * @example DateTime.local(2017, 5, 25).setLocale('en-GB') + * @return {DateTime} + */ + setLocale(locale) { + return this.reconfigure({ locale }); + } + + /** + * "Set" the values of specified units. Returns a newly-constructed DateTime. + * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}. + * @param {Object} values - a mapping of units to numbers + * @example dt.set({ year: 2017 }) + * @example dt.set({ hour: 8, minute: 30 }) + * @example dt.set({ weekday: 5 }) + * @example dt.set({ year: 2005, ordinal: 234 }) + * @return {DateTime} + */ + set(values) { + if (!this.isValid) return this; + + const normalized = normalizeObject(values, normalizeUnit), + settingWeekStuff = + !isUndefined(normalized.weekYear) || + !isUndefined(normalized.weekNumber) || + !isUndefined(normalized.weekday), + containsOrdinal = !isUndefined(normalized.ordinal), + containsGregorYear = !isUndefined(normalized.year), + containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), + containsGregor = containsGregorYear || containsGregorMD, + definiteWeekDef = normalized.weekYear || normalized.weekNumber; + + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError( + "Can't mix weekYear/weekNumber units with year/month/day or ordinals" + ); + } + + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); + } + + let mixed; + if (settingWeekStuff) { + mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized }); + } else if (!isUndefined(normalized.ordinal)) { + mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized }); + } else { + mixed = { ...this.toObject(), ...normalized }; + + // if we didn't set the day but we ended up on an overflow date, + // use the last day of the right month + if (isUndefined(normalized.day)) { + mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); + } + } + + const [ts, o] = objToTS(mixed, this.o, this.zone); + return clone(this, { ts, o }); + } + + /** + * Add a period of time to this DateTime and return the resulting DateTime + * + * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. + * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + * @example DateTime.now().plus(123) //~> in 123 milliseconds + * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes + * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow + * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday + * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min + * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min + * @return {DateTime} + */ + plus(duration) { + if (!this.isValid) return this; + const dur = Duration.fromDurationLike(duration); + return clone(this, adjustTime(this, dur)); + } + + /** + * Subtract a period of time to this DateTime and return the resulting DateTime + * See {@link DateTime#plus} + * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() + @return {DateTime} + */ + minus(duration) { + if (!this.isValid) return this; + const dur = Duration.fromDurationLike(duration).negate(); + return clone(this, adjustTime(this, dur)); + } + + /** + * "Set" this DateTime to the beginning of a unit of time. + * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. + * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' + * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' + * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays + * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' + * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' + * @return {DateTime} + */ + startOf(unit) { + if (!this.isValid) return this; + const o = {}, + normalizedUnit = Duration.normalizeUnit(unit); + switch (normalizedUnit) { + case "years": + o.month = 1; + // falls through + case "quarters": + case "months": + o.day = 1; + // falls through + case "weeks": + case "days": + o.hour = 0; + // falls through + case "hours": + o.minute = 0; + // falls through + case "minutes": + o.second = 0; + // falls through + case "seconds": + o.millisecond = 0; + break; + // no default, invalid units throw in normalizeUnit() + } + + if (normalizedUnit === "weeks") { + o.weekday = 1; + } + + if (normalizedUnit === "quarters") { + const q = Math.ceil(this.month / 3); + o.month = (q - 1) * 3 + 1; + } + + return this.set(o); + } + + /** + * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time + * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. + * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays + * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' + * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' + * @return {DateTime} + */ + endOf(unit) { + return this.isValid + ? this.plus({ [unit]: 1 }) + .startOf(unit) + .minus(1) + : this; + } + + // OUTPUT + + /** + * Returns a string representation of this DateTime formatted according to the specified format string. + * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). + * Defaults to en-US if no locale has been specified, regardless of the system's locale. + * @param {string} fmt - the format string + * @param {Object} opts - opts to override the configuration options on this DateTime + * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' + * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' + * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' + * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' + * @return {string} + */ + toFormat(fmt, opts = {}) { + return this.isValid + ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) + : INVALID; + } + + /** + * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. + * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation + * of the DateTime in the assigned locale. + * Defaults to the system's locale if no locale has been specified + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat + * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options + * @param {Object} opts - opts to override the configuration options on this DateTime + * @example DateTime.now().toLocaleString(); //=> 4/20/2017 + * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' + * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' + * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022' + * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' + * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' + * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' + * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' + * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' + * @return {string} + */ + toLocaleString(formatOpts = DATE_SHORT, opts = {}) { + return this.isValid + ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) + : INVALID; + } + + /** + * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. + * Defaults to the system's locale if no locale has been specified + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts + * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. + * @example DateTime.now().toLocaleParts(); //=> [ + * //=> { type: 'day', value: '25' }, + * //=> { type: 'literal', value: '/' }, + * //=> { type: 'month', value: '05' }, + * //=> { type: 'literal', value: '/' }, + * //=> { type: 'year', value: '1982' } + * //=> ] + */ + toLocaleParts(opts = {}) { + return this.isValid + ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) + : []; + } + + /** + * Returns an ISO 8601-compliant string representation of this DateTime + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.extendedZone=false] - add the time zone format extension + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' + * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' + * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' + * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' + * @return {string} + */ + toISO({ + format = "extended", + suppressSeconds = false, + suppressMilliseconds = false, + includeOffset = true, + extendedZone = false, + } = {}) { + if (!this.isValid) { + return null; + } + + const ext = format === "extended"; + + let c = toISODate(this, ext); + c += "T"; + c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); + return c; + } + + /** + * Returns an ISO 8601-compliant string representation of this DateTime's date component + * @param {Object} opts - options + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' + * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' + * @return {string} + */ + toISODate({ format = "extended" } = {}) { + if (!this.isValid) { + return null; + } + + return toISODate(this, format === "extended"); + } + + /** + * Returns an ISO 8601-compliant string representation of this DateTime's week date + * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' + * @return {string} + */ + toISOWeekDate() { + return toTechFormat(this, "kkkk-'W'WW-c"); + } + + /** + * Returns an ISO 8601-compliant string representation of this DateTime's time component + * @param {Object} opts - options + * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 + * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.extendedZone=true] - add the time zone format extension + * @param {boolean} [opts.includePrefix=false] - include the `T` prefix + * @param {string} [opts.format='extended'] - choose between the basic and extended format + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' + * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' + * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' + * @return {string} + */ + toISOTime({ + suppressMilliseconds = false, + suppressSeconds = false, + includeOffset = true, + includePrefix = false, + extendedZone = false, + format = "extended", + } = {}) { + if (!this.isValid) { + return null; + } + + let c = includePrefix ? "T" : ""; + return ( + c + + toISOTime( + this, + format === "extended", + suppressSeconds, + suppressMilliseconds, + includeOffset, + extendedZone + ) + ); + } + + /** + * Returns an RFC 2822-compatible string representation of this DateTime + * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' + * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' + * @return {string} + */ + toRFC2822() { + return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); + } + + /** + * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT. + * Specifically, the string conforms to RFC 1123. + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 + * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' + * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' + * @return {string} + */ + toHTTP() { + return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); + } + + /** + * Returns a string representation of this DateTime appropriate for use in SQL Date + * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' + * @return {string} + */ + toSQLDate() { + if (!this.isValid) { + return null; + } + return toISODate(this, true); + } + + /** + * Returns a string representation of this DateTime appropriate for use in SQL Time + * @param {Object} opts - options + * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' + * @example DateTime.utc().toSQL() //=> '05:15:16.345' + * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' + * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' + * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' + * @return {string} + */ + toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { + let fmt = "HH:mm:ss.SSS"; + + if (includeZone || includeOffset) { + if (includeOffsetSpace) { + fmt += " "; + } + if (includeZone) { + fmt += "z"; + } else if (includeOffset) { + fmt += "ZZ"; + } + } + + return toTechFormat(this, fmt, true); + } + + /** + * Returns a string representation of this DateTime appropriate for use in SQL DateTime + * @param {Object} opts - options + * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. + * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' + * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' + * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' + * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' + * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' + * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' + * @return {string} + */ + toSQL(opts = {}) { + if (!this.isValid) { + return null; + } + + return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; + } + + /** + * Returns a string representation of this DateTime appropriate for debugging + * @return {string} + */ + toString() { + return this.isValid ? this.toISO() : INVALID; + } + + /** + * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis} + * @return {number} + */ + valueOf() { + return this.toMillis(); + } + + /** + * Returns the epoch milliseconds of this DateTime. + * @return {number} + */ + toMillis() { + return this.isValid ? this.ts : NaN; + } + + /** + * Returns the epoch seconds of this DateTime. + * @return {number} + */ + toSeconds() { + return this.isValid ? this.ts / 1000 : NaN; + } + + /** + * Returns the epoch seconds (as a whole number) of this DateTime. + * @return {number} + */ + toUnixInteger() { + return this.isValid ? Math.floor(this.ts / 1000) : NaN; + } + + /** + * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. + * @return {string} + */ + toJSON() { + return this.toISO(); + } + + /** + * Returns a BSON serializable equivalent to this DateTime. + * @return {Date} + */ + toBSON() { + return this.toJSDate(); + } + + /** + * Returns a JavaScript object with this DateTime's year, month, day, and so on. + * @param opts - options for generating the object + * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output + * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } + * @return {Object} + */ + toObject(opts = {}) { + if (!this.isValid) return {}; + + const base = { ...this.c }; + + if (opts.includeConfig) { + base.outputCalendar = this.outputCalendar; + base.numberingSystem = this.loc.numberingSystem; + base.locale = this.loc.locale; + } + return base; + } + + /** + * Returns a JavaScript Date equivalent to this DateTime. + * @return {Date} + */ + toJSDate() { + return new Date(this.isValid ? this.ts : NaN); + } + + // COMPARE + + /** + * Return the difference between two DateTimes as a Duration. + * @param {DateTime} otherDateTime - the DateTime to compare this one to + * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @example + * var i1 = DateTime.fromISO('1982-05-25T09:45'), + * i2 = DateTime.fromISO('1983-10-14T10:30'); + * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } + * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } + * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } + * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } + * @return {Duration} + */ + diff(otherDateTime, unit = "milliseconds", opts = {}) { + if (!this.isValid || !otherDateTime.isValid) { + return Duration.invalid("created by diffing an invalid DateTime"); + } + + const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts }; + + const units = maybeArray(unit).map(Duration.normalizeUnit), + otherIsLater = otherDateTime.valueOf() > this.valueOf(), + earlier = otherIsLater ? this : otherDateTime, + later = otherIsLater ? otherDateTime : this, + diffed = diff(earlier, later, units, durOpts); + + return otherIsLater ? diffed.negate() : diffed; + } + + /** + * Return the difference between this DateTime and right now. + * See {@link DateTime#diff} + * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration + * @param {Object} opts - options that affect the creation of the Duration + * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use + * @return {Duration} + */ + diffNow(unit = "milliseconds", opts = {}) { + return this.diff(DateTime.now(), unit, opts); + } + + /** + * Return an Interval spanning between this DateTime and another DateTime + * @param {DateTime} otherDateTime - the other end point of the Interval + * @return {Interval} + */ + until(otherDateTime) { + return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; + } + + /** + * Return whether this DateTime is in the same unit of time as another DateTime. + * Higher-order units must also be identical for this function to return `true`. + * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed. + * @param {DateTime} otherDateTime - the other DateTime + * @param {string} unit - the unit of time to check sameness on + * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day + * @return {boolean} + */ + hasSame(otherDateTime, unit) { + if (!this.isValid) return false; + + const inputMs = otherDateTime.valueOf(); + const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true }); + return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit); + } + + /** + * Equality check + * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid. + * To compare just the millisecond values, use `+dt1 === +dt2`. + * @param {DateTime} other - the other DateTime + * @return {boolean} + */ + equals(other) { + return ( + this.isValid && + other.isValid && + this.valueOf() === other.valueOf() && + this.zone.equals(other.zone) && + this.loc.equals(other.loc) + ); + } + + /** + * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your + * platform supports Intl.RelativeTimeFormat. Rounds down by default. + * @param {Object} options - options that affect the output + * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. + * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" + * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" + * @param {boolean} [options.round=true] - whether to round the numbers in the output. + * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. + * @param {string} options.locale - override the locale of this DateTime + * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this + * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" + * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" + * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" + * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" + * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" + * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" + */ + toRelative(options = {}) { + if (!this.isValid) return null; + const base = options.base || DateTime.fromObject({}, { zone: this.zone }), + padding = options.padding ? (this < base ? -options.padding : options.padding) : 0; + let units = ["years", "months", "days", "hours", "minutes", "seconds"]; + let unit = options.unit; + if (Array.isArray(options.unit)) { + units = options.unit; + unit = undefined; + } + return diffRelative(base, this.plus(padding), { + ...options, + numeric: "always", + units, + unit, + }); + } + + /** + * Returns a string representation of this date relative to today, such as "yesterday" or "next month". + * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. + * @param {Object} options - options that affect the output + * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. + * @param {string} options.locale - override the locale of this DateTime + * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" + * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this + * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" + * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" + * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" + * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" + */ + toRelativeCalendar(options = {}) { + if (!this.isValid) return null; + + return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, { + ...options, + numeric: "auto", + units: ["years", "months", "days"], + calendary: true, + }); + } + + /** + * Return the min of several date times + * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum + * @return {DateTime} the min DateTime, or undefined if called with no argument + */ + static min(...dateTimes) { + if (!dateTimes.every(DateTime.isDateTime)) { + throw new InvalidArgumentError("min requires all arguments be DateTimes"); + } + return bestBy(dateTimes, (i) => i.valueOf(), Math.min); + } + + /** + * Return the max of several date times + * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum + * @return {DateTime} the max DateTime, or undefined if called with no argument + */ + static max(...dateTimes) { + if (!dateTimes.every(DateTime.isDateTime)) { + throw new InvalidArgumentError("max requires all arguments be DateTimes"); + } + return bestBy(dateTimes, (i) => i.valueOf(), Math.max); + } + + // MISC + + /** + * Explain how a string would be parsed by fromFormat() + * @param {string} text - the string to parse + * @param {string} fmt - the format the string is expected to be in (see description) + * @param {Object} options - options taken by fromFormat() + * @return {Object} + */ + static fromFormatExplain(text, fmt, options = {}) { + const { locale = null, numberingSystem = null } = options, + localeToUse = Locale.fromOpts({ + locale, + numberingSystem, + defaultToEN: true, + }); + return explainFromTokens(localeToUse, text, fmt); + } + + /** + * @deprecated use fromFormatExplain instead + */ + static fromStringExplain(text, fmt, options = {}) { + return DateTime.fromFormatExplain(text, fmt, options); + } + + // FORMAT PRESETS + + /** + * {@link DateTime#toLocaleString} format like 10/14/1983 + * @type {Object} + */ + static get DATE_SHORT() { + return DATE_SHORT; + } + + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983' + * @type {Object} + */ + static get DATE_MED() { + return DATE_MED; + } + + /** + * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983' + * @type {Object} + */ + static get DATE_MED_WITH_WEEKDAY() { + return DATE_MED_WITH_WEEKDAY; + } + + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983' + * @type {Object} + */ + static get DATE_FULL() { + return DATE_FULL; + } + + /** + * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983' + * @type {Object} + */ + static get DATE_HUGE() { + return DATE_HUGE; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_SIMPLE() { + return TIME_SIMPLE; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_SECONDS() { + return TIME_WITH_SECONDS; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_SHORT_OFFSET() { + return TIME_WITH_SHORT_OFFSET; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get TIME_WITH_LONG_OFFSET() { + return TIME_WITH_LONG_OFFSET; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30', always 24-hour. + * @type {Object} + */ + static get TIME_24_SIMPLE() { + return TIME_24_SIMPLE; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_SECONDS() { + return TIME_24_WITH_SECONDS; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_SHORT_OFFSET() { + return TIME_24_WITH_SHORT_OFFSET; + } + + /** + * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. + * @type {Object} + */ + static get TIME_24_WITH_LONG_OFFSET() { + return TIME_24_WITH_LONG_OFFSET; + } + + /** + * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_SHORT() { + return DATETIME_SHORT; + } + + /** + * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_SHORT_WITH_SECONDS() { + return DATETIME_SHORT_WITH_SECONDS; + } + + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED() { + return DATETIME_MED; + } + + /** + * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED_WITH_SECONDS() { + return DATETIME_MED_WITH_SECONDS; + } + + /** + * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_MED_WITH_WEEKDAY() { + return DATETIME_MED_WITH_WEEKDAY; + } + + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_FULL() { + return DATETIME_FULL; + } + + /** + * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_FULL_WITH_SECONDS() { + return DATETIME_FULL_WITH_SECONDS; + } + + /** + * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_HUGE() { + return DATETIME_HUGE; + } + + /** + * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. + * @type {Object} + */ + static get DATETIME_HUGE_WITH_SECONDS() { + return DATETIME_HUGE_WITH_SECONDS; + } +} + +/** + * @private + */ +function friendlyDateTime(dateTimeish) { + if (DateTime.isDateTime(dateTimeish)) { + return dateTimeish; + } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { + return DateTime.fromJSDate(dateTimeish); + } else if (dateTimeish && typeof dateTimeish === "object") { + return DateTime.fromObject(dateTimeish); + } else { + throw new InvalidArgumentError( + `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}` + ); + } +} + +const VERSION = "3.4.3"; + +var Luxon = /*#__PURE__*/Object.freeze({ + __proto__: null, + VERSION: VERSION, + DateTime: DateTime, + Duration: Duration, + Interval: Interval, + Info: Info, + Zone: Zone, + FixedOffsetZone: FixedOffsetZone, + IANAZone: IANAZone, + InvalidZone: InvalidZone, + SystemZone: SystemZone, + Settings: Settings +}); + +//////////////////// +// Query Settings // +//////////////////// +const DEFAULT_QUERY_SETTINGS = { + renderNullAs: "\\-", + taskCompletionTracking: false, + taskCompletionUseEmojiShorthand: false, + taskCompletionText: "completion", + taskCompletionDateFormat: "yyyy-MM-dd", + recursiveSubTaskCompletion: false, + warnOnEmptyResult: true, + refreshEnabled: true, + refreshInterval: 2500, + defaultDateFormat: "MMMM dd, yyyy", + defaultDateTimeFormat: "h:mm a - MMMM dd, yyyy", + maxRecursiveRenderDepth: 4, + tableIdColumnName: "File", + tableGroupColumnName: "Group", + showResultCount: true, +}; +const DEFAULT_EXPORT_SETTINGS = { + allowHtml: true, +}; +/** Default settings for dataview on install. */ +const DEFAULT_SETTINGS = { + ...DEFAULT_QUERY_SETTINGS, + ...DEFAULT_EXPORT_SETTINGS, + ...{ + inlineQueryPrefix: "=", + inlineJsQueryPrefix: "$=", + inlineQueriesInCodeblocks: true, + enableInlineDataview: true, + enableDataviewJs: false, + enableInlineDataviewJs: false, + prettyRenderInlineFields: true, + prettyRenderInlineFieldsInLivePreview: true, + dataviewJsKeyword: "dataviewjs", + }, +}; + +/** Functional return type for error handling. */ +class Success { + value; + successful; + constructor(value) { + this.value = value; + this.successful = true; + } + map(f) { + return new Success(f(this.value)); + } + flatMap(f) { + return f(this.value); + } + mapErr(f) { + return this; + } + bimap(succ, _fail) { + return this.map(succ); + } + orElse(_value) { + return this.value; + } + cast() { + return this; + } + orElseThrow(_message) { + return this.value; + } +} +/** Functional return type for error handling. */ +class Failure { + error; + successful; + constructor(error) { + this.error = error; + this.successful = false; + } + map(_f) { + return this; + } + flatMap(_f) { + return this; + } + mapErr(f) { + return new Failure(f(this.error)); + } + bimap(_succ, fail) { + return this.mapErr(fail); + } + orElse(value) { + return value; + } + cast() { + return this; + } + orElseThrow(message) { + if (message) + throw new Error(message(this.error)); + else + throw new Error("" + this.error); + } +} +/** Monadic 'Result' type which encapsulates whether a procedure succeeded or failed, as well as it's return value. */ +var Result; +(function (Result) { + /** Construct a new success result wrapping the given value. */ + function success(value) { + return new Success(value); + } + Result.success = success; + /** Construct a new failure value wrapping the given error. */ + function failure(error) { + return new Failure(error); + } + Result.failure = failure; + /** Join two results with a bi-function and return a new result. */ + function flatMap2(first, second, f) { + if (first.successful) { + if (second.successful) + return f(first.value, second.value); + else + return failure(second.error); + } + else { + return failure(first.error); + } + } + Result.flatMap2 = flatMap2; + /** Join two results with a bi-function and return a new result. */ + function map2(first, second, f) { + return flatMap2(first, second, (a, b) => success(f(a, b))); + } + Result.map2 = map2; +})(Result || (Result = {})); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var parsimmon_umd_min = {exports: {}}; + +parsimmon_umd_min.exports; + +(function (module, exports) { + !function(n,t){module.exports=t();}("undefined"!=typeof self?self:commonjsGlobal,function(){return function(n){var t={};function r(e){if(t[e])return t[e].exports;var u=t[e]={i:e,l:!1,exports:{}};return n[e].call(u.exports,u,u.exports,r),u.l=!0,u.exports}return r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{configurable:!1,enumerable:!0,get:e});},r.r=function(n){Object.defineProperty(n,"__esModule",{value:!0});},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=0)}([function(n,t,r){function e(n){if(!(this instanceof e))return new e(n);this._=n;}var u=e.prototype;function o(n,t){for(var r=0;r>7),buf:function(n){var t=i(function(n,t,r,e){return n.concat(r===e.length-1?Buffer.from([t,0]).readUInt16BE(0):e.readUInt16BE(r))},[],n);return Buffer.from(a(function(n){return (n<<1&65535)>>8},t))}(r.buf)};}),r}function c(){return "undefined"!=typeof Buffer}function s(){if(!c())throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser.")}function l(n){s();var t=i(function(n,t){return n+t},0,n);if(t%8!=0)throw new Error("The bits ["+n.join(", ")+"] add up to "+t+" which is not an even number of bytes; the total should be divisible by 8");var r,u=t/8,o=(r=function(n){return n>48},i(function(n,t){return n||(r(t)?t:n)},null,n));if(o)throw new Error(o+" bit range requested exceeds 48 bit (6 byte) Number max.");return new e(function(t,r){var e=u+r;return e>t.length?x(r,u.toString()+" bytes"):b(e,i(function(n,t){var r=f(t,n.buf);return {coll:n.coll.concat(r.v),buf:r.buf}},{coll:[],buf:t.slice(r,e)},n).coll)})}function h(n,t){return new e(function(r,e){return s(),e+t>r.length?x(e,t+" bytes for "+n):b(e+t,r.slice(e,e+t))})}function p(n,t){if("number"!=typeof(r=t)||Math.floor(r)!==r||t<0||t>6)throw new Error(n+" requires integer length in range [0, 6].");var r;}function d(n){return p("uintBE",n),h("uintBE("+n+")",n).map(function(t){return t.readUIntBE(0,n)})}function v(n){return p("uintLE",n),h("uintLE("+n+")",n).map(function(t){return t.readUIntLE(0,n)})}function g(n){return p("intBE",n),h("intBE("+n+")",n).map(function(t){return t.readIntBE(0,n)})}function m(n){return p("intLE",n),h("intLE("+n+")",n).map(function(t){return t.readIntLE(0,n)})}function y(n){return n instanceof e}function E(n){return "[object Array]"==={}.toString.call(n)}function w(n){return c()&&Buffer.isBuffer(n)}function b(n,t){return {status:!0,index:n,value:t,furthest:-1,expected:[]}}function x(n,t){return E(t)||(t=[t]),{status:!1,index:-1,value:null,furthest:n,expected:t}}function B(n,t){if(!t)return n;if(n.furthest>t.furthest)return n;var r=n.furthest===t.furthest?function(n,t){if(function(){if(void 0!==e._supportsSet)return e._supportsSet;var n="undefined"!=typeof Set;return e._supportsSet=n,n}()&&Array.from){for(var r=new Set(n),u=0;u=0;){if(i in r){e=r[i].line,0===o&&(o=r[i].lineStart);break}("\n"===n.charAt(i)||"\r"===n.charAt(i)&&"\n"!==n.charAt(i+1))&&(u++,0===o&&(o=i+1)),i--;}var a=e+u,f=t-o;return r[t]={line:a,lineStart:o},{offset:t,line:a+1,column:f+1}}function _(n){if(!y(n))throw new Error("not a parser: "+n)}function L(n,t){return "string"==typeof n?n.charAt(t):n[t]}function O(n){if("number"!=typeof n)throw new Error("not a number: "+n)}function k(n){if("function"!=typeof n)throw new Error("not a function: "+n)}function P(n){if("string"!=typeof n)throw new Error("not a string: "+n)}var q=2,A=3,I=8,F=5*I,M=4*I,z=" ";function R(n,t){return new Array(t+1).join(n)}function U(n,t,r){var e=t-n.length;return e<=0?n:R(r,e)+n}function W(n,t,r,e){return {from:n-t>0?n-t:0,to:n+r>e?e:n+r}}function D(n,t){var r,e,u,o,f,c=t.index,s=c.offset,l=1;if(s===n.length)return "Got the end of the input";if(w(n)){var h=s-s%I,p=s-h,d=W(h,F,M+I,n.length),v=a(function(n){return a(function(n){return U(n.toString(16),2,"0")},n)},function(n,t){var r=n.length,e=[],u=0;if(r<=t)return [n.slice()];for(var o=0;o=4&&(r+=1),l=2,u=a(function(n){return n.length<=4?n.join(" "):n.slice(0,4).join(" ")+" "+n.slice(4).join(" ")},v),(f=(8*(o.to>0?o.to-1:o.to)).toString(16).length)<2&&(f=2);}else {var g=n.split(/\r\n|[\n\r\u2028\u2029]/);r=c.column-1,e=c.line-1,o=W(e,q,A,g.length),u=g.slice(o.from,o.to),f=o.to.toString().length;}var m=e-o.from;return w(n)&&(f=(8*(o.to>0?o.to-1:o.to)).toString(16).length)<2&&(f=2),i(function(t,e,u){var i,a=u===m,c=a?"> ":z;return i=w(n)?U((8*(o.from+u)).toString(16),f,"0"):U((o.from+u+1).toString(),f," "),[].concat(t,[c+i+" | "+e],a?[z+R(" ",f)+" | "+U("",r," ")+R("^",l)]:[])},[],u).join("\n")}function N(n,t){return ["\n","-- PARSING FAILED "+R("-",50),"\n\n",D(n,t),"\n\n",(r=t.expected,1===r.length?"Expected:\n\n"+r[0]:"Expected one of the following: \n\n"+r.join(", ")),"\n"].join("");var r;}function G(n){return void 0!==n.flags?n.flags:[n.global?"g":"",n.ignoreCase?"i":"",n.multiline?"m":"",n.unicode?"u":"",n.sticky?"y":""].join("")}function C(){for(var n=[].slice.call(arguments),t=n.length,r=0;r=2?O(t):t=0;var r=function(n){return RegExp("^(?:"+n.source+")",G(n))}(n),u=""+n;return e(function(n,e){var o=r.exec(n.slice(e));if(o){if(0<=t&&t<=o.length){var i=o[0],a=o[t];return b(e+i.length,a)}return x(e,"valid match group (0 to "+o.length+") in "+u)}return x(e,u)})}function X(n){return e(function(t,r){return b(r,n)})}function Y(n){return e(function(t,r){return x(r,n)})}function Z(n){if(y(n))return e(function(t,r){var e=n._(t,r);return e.index=r,e.value="",e});if("string"==typeof n)return Z(K(n));if(n instanceof RegExp)return Z(Q(n));throw new Error("not a string, regexp, or parser: "+n)}function $(n){return _(n),e(function(t,r){var e=n._(t,r),u=t.slice(r,e.index);return e.status?x(r,'not "'+u+'"'):b(r,null)})}function nn(n){return k(n),e(function(t,r){var e=L(t,r);return r=n.length?x(t,"any character/byte"):b(t+1,L(n,t))}),on=e(function(n,t){return b(n.length,n.slice(t))}),an=e(function(n,t){return t=0}).desc(t)},e.optWhitespace=hn,e.Parser=e,e.range=function(n,t){return nn(function(r){return n<=r&&r<=t}).desc(n+"-"+t)},e.regex=Q,e.regexp=Q,e.sepBy=V,e.sepBy1=H,e.seq=C,e.seqMap=J,e.seqObj=function(){for(var n,t={},r=0,u=(n=arguments,Array.prototype.slice.call(n)),o=u.length,i=0;i255)throw new Error("Value specified to byte constructor ("+n+"=0x"+n.toString(16)+") is larger in value than a single byte.");var t=(n>15?"0x":"0x0")+n.toString(16);return e(function(r,e){var u=L(r,e);return u===n?b(e+1,u):x(e,t)})},buffer:function(n){return h("buffer",n).map(function(n){return Buffer.from(n)})},encodedString:function(n,t){return h("string",t).map(function(t){return t.toString(n)})},uintBE:d,uint8BE:d(1),uint16BE:d(2),uint32BE:d(4),uintLE:v,uint8LE:v(1),uint16LE:v(2),uint32LE:v(4),intBE:g,int8BE:g(1),int16BE:g(2),int32BE:g(4),intLE:m,int8LE:m(1),int16LE:m(2),int32LE:m(4),floatBE:h("floatBE",4).map(function(n){return n.readFloatBE(0)}),floatLE:h("floatLE",4).map(function(n){return n.readFloatLE(0)}),doubleBE:h("doubleBE",8).map(function(n){return n.readDoubleBE(0)}),doubleLE:h("doubleLE",8).map(function(n){return n.readDoubleLE(0)})},n.exports=e;}])}); +} (parsimmon_umd_min, parsimmon_umd_min.exports)); + +var parsimmon_umd_minExports = parsimmon_umd_min.exports; + +var emojiRegex = () => { + // https://mths.be/emoji + return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC3\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\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47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; +}; + +var removeMarkdown = function(md, options) { + options = options || {}; + options.listUnicodeChar = options.hasOwnProperty('listUnicodeChar') ? options.listUnicodeChar : false; + options.stripListLeaders = options.hasOwnProperty('stripListLeaders') ? options.stripListLeaders : true; + options.gfm = options.hasOwnProperty('gfm') ? options.gfm : true; + options.useImgAltText = options.hasOwnProperty('useImgAltText') ? options.useImgAltText : true; + options.abbr = options.hasOwnProperty('abbr') ? options.abbr : false; + options.replaceLinksWithURL = options.hasOwnProperty('replaceLinksWithURL') ? options.replaceLinksWithURL : false; + options.htmlTagsToSkip = options.hasOwnProperty('htmlTagsToSkip') ? options.htmlTagsToSkip : []; + options.throwError = options.hasOwnProperty('throwError') ? options.throwError : false; + + var output = md || ''; + + // Remove horizontal rules (stripListHeaders conflict with this rule, which is why it has been moved to the top) + output = output.replace(/^(-\s*?|\*\s*?|_\s*?){3,}\s*/gm, ''); + + try { + if (options.stripListLeaders) { + if (options.listUnicodeChar) + output = output.replace(/^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm, options.listUnicodeChar + ' $1'); + else + output = output.replace(/^([\s\t]*)([\*\-\+]|\d+\.)\s+/gm, '$1'); + } + if (options.gfm) { + output = output + // Header + .replace(/\n={2,}/g, '\n') + // Fenced codeblocks + .replace(/~{3}.*\n/g, '') + // Strikethrough + .replace(/~~/g, '') + // Fenced codeblocks + .replace(/`{3}.*\n/g, ''); + } + if (options.abbr) { + // Remove abbreviations + output = output.replace(/\*\[.*\]:.*\n/, ''); + } + output = output + // Remove HTML tags + .replace(/<[^>]*>/g, ''); + + var htmlReplaceRegex = new RegExp('<[^>]*>', 'g'); + if (options.htmlTagsToSkip.length > 0) { + // Using negative lookahead. Eg. (?!sup|sub) will not match 'sup' and 'sub' tags. + var joinedHtmlTagsToSkip = '(?!' + options.htmlTagsToSkip.join("|") + ')'; + + // Adding the lookahead literal with the default regex for html. Eg./<(?!sup|sub)[^>]*>/ig + htmlReplaceRegex = new RegExp( + '<' + + joinedHtmlTagsToSkip + + '[^>]*>', + 'ig' + ); + } + + output = output + // Remove HTML tags + .replace(htmlReplaceRegex, '') + // Remove setext-style headers + .replace(/^[=\-]{2,}\s*$/g, '') + // Remove footnotes? + .replace(/\[\^.+?\](\: .*?$)?/g, '') + .replace(/\s{0,2}\[.*?\]: .*?$/g, '') + // Remove images + .replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, options.useImgAltText ? '$1' : '') + // Remove inline links + .replace(/\[([^\]]*?)\][\[\(].*?[\]\)]/g, options.replaceLinksWithURL ? '$2' : '$1') + // Remove blockquotes + .replace(/^(\n)?\s{0,3}>\s?/gm, '$1') + // .replace(/(^|\n)\s{0,3}>\s?/g, '\n\n') + // Remove reference-style links? + .replace(/^\s{1,2}\[(.*?)\]: (\S+)( ".*?")?\s*$/g, '') + // Remove atx-style headers + .replace(/^(\n)?\s{0,}#{1,6}\s*( (.+))? +#+$|^(\n)?\s{0,}#{1,6}\s*( (.+))?$/gm, '$1$3$4$6') + // Remove * emphasis + .replace(/([\*]+)(\S)(.*?\S)??\1/g, '$2$3') + // Remove _ emphasis. Unlike *, _ emphasis gets rendered only if + // 1. Either there is a whitespace character before opening _ and after closing _. + // 2. Or _ is at the start/end of the string. + .replace(/(^|\W)([_]+)(\S)(.*?\S)??\2($|\W)/g, '$1$3$4$5') + // Remove code blocks + .replace(/(`{3,})(.*?)\1/gm, '$2') + // Remove inline code + .replace(/`(.+?)`/g, '$1') + // // Replace two or more newlines with exactly two? Not entirely sure this belongs here... + // .replace(/\n{2,}/g, '\n\n') + // // Remove newlines in a paragraph + // .replace(/(\S+)\n\s*(\S+)/g, '$1 $2') + // Replace strike through + .replace(/~(.*?)~/g, '$1'); + } catch(e) { + if (options.throwError) throw e; + + console.error("remove-markdown encountered error: %s", e); + return md; + } + return output; +}; + +var removeMd = /*@__PURE__*/getDefaultExportFromCjs(removeMarkdown); + +/** Normalize a duration to all of the proper units. */ +function normalizeDuration(dur) { + if (dur === undefined || dur === null) + return dur; + return dur.shiftToAll().normalize(); +} +/** Strip the time components of a date time object. */ +function stripTime(dt) { + if (dt === null || dt === undefined) + return dt; + return DateTime.fromObject({ + year: dt.year, + month: dt.month, + day: dt.day, + }); +} +/** Get the folder containing the given path (i.e., like computing 'path/..'). */ +function getParentFolder(path) { + return path.split("/").slice(0, -1).join("/"); +} +/** Get the "title" for a file, by stripping other parts of the path as well as the extension. */ +function getFileTitle(path) { + if (path.includes("/")) + path = path.substring(path.lastIndexOf("/") + 1); + if (path.endsWith(".md")) + path = path.substring(0, path.length - 3); + return path; +} +/** Get the extension of a file from the file path. */ +function getExtension(path) { + if (!path.includes(".")) + return ""; + return path.substring(path.lastIndexOf(".") + 1); +} +/** Parse all subtags out of the given tag. I.e., #hello/i/am would yield [#hello/i/am, #hello/i, #hello]. */ +function extractSubtags(tag) { + let result = [tag]; + while (tag.includes("/")) { + tag = tag.substring(0, tag.lastIndexOf("/")); + result.push(tag); + } + return result; +} +/** Try calling the given function; on failure, return the error message. */ +function tryOrPropagate(func) { + try { + return func(); + } + catch (error) { + return Result.failure("" + error + "\n\n" + error.stack); + } +} +/** Try asynchronously calling the given function; on failure, return the error message. */ +async function asyncTryOrPropagate(func) { + try { + return await func(); + } + catch (error) { + return Result.failure("" + error + "\n\n" + error.stack); + } +} +/** + * Escape regex characters in a string. + * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions. + */ +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +/** A parsimmon parser which canonicalizes variable names while properly respecting emoji. */ +const VAR_NAME_CANONICALIZER = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u).map(str => str.toLocaleLowerCase()), parsimmon_umd_minExports.whitespace.map(_ => "-"), parsimmon_umd_minExports.any.map(_ => "")) + .many() + .map(result => result.join("")); +/** Convert an arbitrary variable name into something JS/query friendly. */ +function canonicalizeVarName(name) { + return VAR_NAME_CANONICALIZER.tryParse(name); +} +const HEADER_CANONICALIZER = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u), parsimmon_umd_minExports.whitespace.map(_ => " "), parsimmon_umd_minExports.any.map(_ => " ")) + .many() + .map(result => { + return result.join("").split(/\s+/).join(" ").trim(); +}); +/** + * Normalizes the text in a header to be something that is actually linkable to. This mimics + * how Obsidian does it's normalization, collapsing repeated spaces and stripping out control characters. + */ +function normalizeHeaderForLink(header) { + return HEADER_CANONICALIZER.tryParse(header); +} +/** Render a DateTime in a minimal format to save space. */ +function renderMinimalDate(time, settings, locale) { + // If there is no relevant time specified, fall back to just rendering the date. + if (time.second == 0 && time.minute == 0 && time.hour == 0) { + return time.toLocal().toFormat(settings.defaultDateFormat, { locale }); + } + return time.toLocal().toFormat(settings.defaultDateTimeFormat, { locale }); +} +/** Render a duration in a minimal format to save space. */ +function renderMinimalDuration(dur) { + dur = normalizeDuration(dur); + // toHuman outputs zero quantities e.g. "0 seconds" + dur = Duration.fromObject(Object.fromEntries(Object.entries(dur.toObject()).filter(([, quantity]) => quantity != 0))); + return dur.toHuman(); +} +/** Determine if two sets are equal in contents. */ +function setsEqual(first, second) { + if (first.size != second.size) + return false; + for (let elem of first) + if (!second.has(elem)) + return false; + return true; +} +/** Normalize a markdown string. Removes all markdown tags and obsidian links. */ +function normalizeMarkdown(str) { + // [[test]] -> test + let interim = str.replace(/\[\[([^\|]*?)\]\]/g, "$1"); + // [[test|test]] -> test + interim = interim.replace(/\[\[.*?\|(.*?)\]\]/, "$1"); + // remove markdown tags + interim = removeMd(interim); + return interim; +} + +var Values; +(function (Values) { + /** Convert an arbitrary value into a reasonable, Markdown-friendly string if possible. */ + function toString(field, setting = DEFAULT_QUERY_SETTINGS, recursive = false) { + let wrapped = wrapValue(field); + if (!wrapped) + return setting.renderNullAs; + switch (wrapped.type) { + case "null": + return setting.renderNullAs; + case "string": + return wrapped.value; + case "number": + case "boolean": + return "" + wrapped.value; + case "html": + return wrapped.value.outerHTML; + case "widget": + return wrapped.value.markdown(); + case "link": + return wrapped.value.markdown(); + case "function": + return ""; + case "array": + let result = ""; + if (recursive) + result += "["; + result += wrapped.value.map(f => toString(f, setting, true)).join(", "); + if (recursive) + result += "]"; + return result; + case "object": + return ("{ " + + Object.entries(wrapped.value) + .map(e => e[0] + ": " + toString(e[1], setting, true)) + .join(", ") + + " }"); + case "date": + if (wrapped.value.second == 0 && wrapped.value.hour == 0 && wrapped.value.minute == 0) { + return wrapped.value.toFormat(setting.defaultDateFormat); + } + return wrapped.value.toFormat(setting.defaultDateTimeFormat); + case "duration": + return renderMinimalDuration(wrapped.value); + } + } + Values.toString = toString; + /** Wrap a literal value so you can switch on it easily. */ + function wrapValue(val) { + if (isNull(val)) + return { type: "null", value: val }; + else if (isNumber(val)) + return { type: "number", value: val }; + else if (isString(val)) + return { type: "string", value: val }; + else if (isBoolean(val)) + return { type: "boolean", value: val }; + else if (isDuration(val)) + return { type: "duration", value: val }; + else if (isDate(val)) + return { type: "date", value: val }; + else if (isWidget(val)) + return { type: "widget", value: val }; + else if (isArray(val)) + return { type: "array", value: val }; + else if (isLink(val)) + return { type: "link", value: val }; + else if (isFunction(val)) + return { type: "function", value: val }; + else if (isHtml(val)) + return { type: "html", value: val }; + else if (isObject(val)) + return { type: "object", value: val }; + else + return undefined; + } + Values.wrapValue = wrapValue; + /** Recursively map complex objects at the leaves. */ + function mapLeaves(val, func) { + if (isObject(val)) { + let result = {}; + for (let [key, value] of Object.entries(val)) + result[key] = mapLeaves(value, func); + return result; + } + else if (isArray(val)) { + let result = []; + for (let value of val) + result.push(mapLeaves(value, func)); + return result; + } + else { + return func(val); + } + } + Values.mapLeaves = mapLeaves; + /** Compare two arbitrary JavaScript values. Produces a total ordering over ANY possible dataview value. */ + function compareValue(val1, val2, linkNormalizer) { + // Handle undefined/nulls first. + if (val1 === undefined) + val1 = null; + if (val2 === undefined) + val2 = null; + if (val1 === null && val2 === null) + return 0; + else if (val1 === null) + return -1; + else if (val2 === null) + return 1; + // A non-null value now which we can wrap & compare on. + let wrap1 = wrapValue(val1); + let wrap2 = wrapValue(val2); + if (wrap1 === undefined && wrap2 === undefined) + return 0; + else if (wrap1 === undefined) + return -1; + else if (wrap2 === undefined) + return 1; + // Short-circuit on different types or on reference equality. + if (wrap1.type != wrap2.type) + return wrap1.type.localeCompare(wrap2.type); + if (wrap1.value === wrap2.value) + return 0; + switch (wrap1.type) { + case "string": + return wrap1.value.localeCompare(wrap2.value); + case "number": + if (wrap1.value < wrap2.value) + return -1; + else if (wrap1.value == wrap2.value) + return 0; + return 1; + case "null": + return 0; + case "boolean": + if (wrap1.value == wrap2.value) + return 0; + else + return wrap1.value ? 1 : -1; + case "link": + let link1 = wrap1.value; + let link2 = wrap2.value; + let normalize = linkNormalizer ?? ((x) => x); + // We can't compare by file name or display, since that would break link equality. Compare by path. + let pathCompare = normalize(link1.path).localeCompare(normalize(link2.path)); + if (pathCompare != 0) + return pathCompare; + // Then compare by type. + let typeCompare = link1.type.localeCompare(link2.type); + if (typeCompare != 0) + return typeCompare; + // Then compare by subpath existence. + if (link1.subpath && !link2.subpath) + return 1; + if (!link1.subpath && link2.subpath) + return -1; + if (!link1.subpath && !link2.subpath) + return 0; + // Since both have a subpath, compare by subpath. + return (link1.subpath ?? "").localeCompare(link2.subpath ?? ""); + case "date": + return wrap1.value < wrap2.value + ? -1 + : wrap1.value.equals(wrap2.value) + ? 0 + : 1; + case "duration": + return wrap1.value < wrap2.value + ? -1 + : wrap1.value.equals(wrap2.value) + ? 0 + : 1; + case "array": + let f1 = wrap1.value; + let f2 = wrap2.value; + for (let index = 0; index < Math.min(f1.length, f2.length); index++) { + let comp = compareValue(f1[index], f2[index]); + if (comp != 0) + return comp; + } + return f1.length - f2.length; + case "object": + let o1 = wrap1.value; + let o2 = wrap2.value; + let k1 = Array.from(Object.keys(o1)); + let k2 = Array.from(Object.keys(o2)); + k1.sort(); + k2.sort(); + let keyCompare = compareValue(k1, k2); + if (keyCompare != 0) + return keyCompare; + for (let key of k1) { + let comp = compareValue(o1[key], o2[key]); + if (comp != 0) + return comp; + } + return 0; + case "widget": + case "html": + case "function": + return 0; + } + } + Values.compareValue = compareValue; + /** Find the corresponding Dataview type for an arbitrary value. */ + function typeOf(val) { + return wrapValue(val)?.type; + } + Values.typeOf = typeOf; + /** Determine if the given value is "truthy" (i.e., is non-null and has data in it). */ + function isTruthy(field) { + let wrapped = wrapValue(field); + if (!wrapped) + return false; + switch (wrapped.type) { + case "number": + return wrapped.value != 0; + case "string": + return wrapped.value.length > 0; + case "boolean": + return wrapped.value; + case "link": + return !!wrapped.value.path; + case "date": + return wrapped.value.toMillis() != 0; + case "duration": + return wrapped.value.as("seconds") != 0; + case "object": + return Object.keys(wrapped.value).length > 0; + case "array": + return wrapped.value.length > 0; + case "null": + return false; + case "html": + case "widget": + case "function": + return true; + } + } + Values.isTruthy = isTruthy; + /** Deep copy a field. */ + function deepCopy(field) { + if (field === null || field === undefined) + return field; + if (Values.isArray(field)) { + return [].concat(field.map(v => deepCopy(v))); + } + else if (Values.isObject(field)) { + let result = {}; + for (let [key, value] of Object.entries(field)) + result[key] = deepCopy(value); + return result; + } + else { + return field; + } + } + Values.deepCopy = deepCopy; + function isString(val) { + return typeof val == "string"; + } + Values.isString = isString; + function isNumber(val) { + return typeof val == "number"; + } + Values.isNumber = isNumber; + function isDate(val) { + return val instanceof DateTime; + } + Values.isDate = isDate; + function isDuration(val) { + return val instanceof Duration; + } + Values.isDuration = isDuration; + function isNull(val) { + return val === null || val === undefined; + } + Values.isNull = isNull; + function isArray(val) { + return Array.isArray(val); + } + Values.isArray = isArray; + function isBoolean(val) { + return typeof val === "boolean"; + } + Values.isBoolean = isBoolean; + function isLink(val) { + return val instanceof Link; + } + Values.isLink = isLink; + function isWidget(val) { + return val instanceof Widget; + } + Values.isWidget = isWidget; + function isHtml(val) { + if (typeof HTMLElement !== "undefined") { + return val instanceof HTMLElement; + } + else { + return false; + } + } + Values.isHtml = isHtml; + /** Checks if the given value is an object (and not any other dataview-recognized object-like type). */ + function isObject(val) { + return (typeof val == "object" && + !isHtml(val) && + !isWidget(val) && + !isArray(val) && + !isDuration(val) && + !isDate(val) && + !isLink(val) && + val !== undefined && + !isNull(val)); + } + Values.isObject = isObject; + function isFunction(val) { + return typeof val == "function"; + } + Values.isFunction = isFunction; +})(Values || (Values = {})); +/////////////// +// Groupings // +/////////////// +var Groupings; +(function (Groupings) { + /** Determines if the given group entry is a standalone value, or a grouping of sub-entries. */ + function isElementGroup(entry) { + return Values.isObject(entry) && Object.keys(entry).length == 2 && "key" in entry && "rows" in entry; + } + Groupings.isElementGroup = isElementGroup; + /** Determines if the given array is a grouping array. */ + function isGrouping(entry) { + for (let element of entry) + if (!isElementGroup(element)) + return false; + return true; + } + Groupings.isGrouping = isGrouping; + /** Count the total number of elements in a recursive grouping. */ + function count(elements) { + if (isGrouping(elements)) { + let result = 0; + for (let subgroup of elements) + result += count(subgroup.rows); + return result; + } + else { + return elements.length; + } + } + Groupings.count = count; +})(Groupings || (Groupings = {})); +////////// +// LINK // +////////// +/** The Obsidian 'link', used for uniquely describing a file, header, or block. */ +class Link { + /** The file path this link points to. */ + path; + /** The display name associated with the link. */ + display; + /** The block ID or header this link points to within a file, if relevant. */ + subpath; + /** Is this link an embedded link (!)? */ + embed; + /** The type of this link, which determines what 'subpath' refers to, if anything. */ + type; + /** Create a link to a specific file. */ + static file(path, embed = false, display) { + return new Link({ + path, + embed, + display, + subpath: undefined, + type: "file", + }); + } + static infer(linkpath, embed = false, display) { + if (linkpath.includes("#^")) { + let split = linkpath.split("#^"); + return Link.block(split[0], split[1], embed, display); + } + else if (linkpath.includes("#")) { + let split = linkpath.split("#"); + return Link.header(split[0], split[1], embed, display); + } + else + return Link.file(linkpath, embed, display); + } + /** Create a link to a specific file and header in that file. */ + static header(path, header, embed, display) { + // Headers need to be normalized to alpha-numeric & with extra spacing removed. + return new Link({ + path, + embed, + display, + subpath: normalizeHeaderForLink(header), + type: "header", + }); + } + /** Create a link to a specific file and block in that file. */ + static block(path, blockId, embed, display) { + return new Link({ + path, + embed, + display, + subpath: blockId, + type: "block", + }); + } + static fromObject(object) { + return new Link(object); + } + constructor(fields) { + Object.assign(this, fields); + } + /** Checks for link equality (i.e., that the links are pointing to the same exact location). */ + equals(other) { + if (other == undefined || other == null) + return false; + return this.path == other.path && this.type == other.type && this.subpath == other.subpath; + } + /** Convert this link to it's markdown representation. */ + toString() { + return this.markdown(); + } + /** Convert this link to a raw object which is serialization-friendly. */ + toObject() { + return { path: this.path, type: this.type, subpath: this.subpath, display: this.display, embed: this.embed }; + } + /** Update this link with a new path. */ + //@ts-ignore; error appeared after updating Obsidian to 0.15.4; it also updated other packages but didn't say which + withPath(path) { + return new Link(Object.assign({}, this, { path })); + } + /** Return a new link which points to the same location but with a new display value. */ + withDisplay(display) { + return new Link(Object.assign({}, this, { display })); + } + /** Convert a file link into a link to a specific header. */ + withHeader(header) { + return Link.header(this.path, header, this.embed, this.display); + } + /** Convert any link into a link to its file. */ + toFile() { + return Link.file(this.path, this.embed, this.display); + } + /** Convert this link into an embedded link. */ + toEmbed() { + if (this.embed) { + return this; + } + else { + let link = new Link(this); + link.embed = true; + return link; + } + } + /** Convert this link into a non-embedded link. */ + fromEmbed() { + if (!this.embed) { + return this; + } + else { + let link = new Link(this); + link.embed = false; + return link; + } + } + /** Convert this link to markdown so it can be rendered. */ + markdown() { + let result = (this.embed ? "!" : "") + "[[" + this.obsidianLink(); + if (this.display) { + result += "|" + this.display; + } + else { + result += "|" + getFileTitle(this.path); + if (this.type == "header" || this.type == "block") + result += " > " + this.subpath; + } + result += "]]"; + return result; + } + /** Convert the inner part of the link to something that Obsidian can open / understand. */ + obsidianLink() { + const escaped = this.path.replaceAll("|", "\\|"); + if (this.type == "header") + return escaped + "#" + this.subpath?.replaceAll("|", "\\|"); + if (this.type == "block") + return escaped + "#^" + this.subpath?.replaceAll("|", "\\|"); + else + return escaped; + } + /** The stripped name of the file this link points to. */ + fileName() { + return getFileTitle(this.path).replace(".md", ""); + } +} +///////////////// +// WIDGET BASE // +///////////////// +/** + * A trivial base class which just defines the '$widget' identifier type. Subtypes of + * widget are responsible for adding whatever metadata is relevant. If you want your widget + * to have rendering functionality (which you probably do), you should extend `RenderWidget`. + */ +class Widget { + $widget; + constructor($widget) { + this.$widget = $widget; + } +} +/** A trivial widget which renders a (key, value) pair, and allows accessing the key and value. */ +class ListPairWidget extends Widget { + key; + value; + constructor(key, value) { + super("dataview:list-pair"); + this.key = key; + this.value = value; + } + markdown() { + return `${Values.toString(this.key)}: ${Values.toString(this.value)}`; + } +} +/** A simple widget which renders an external link. */ +class ExternalLinkWidget extends Widget { + url; + display; + constructor(url, display) { + super("dataview:external-link"); + this.url = url; + this.display = display; + } + markdown() { + return `[${this.display ?? this.url}](${this.url})`; + } +} +var Widgets; +(function (Widgets) { + /** Create a list pair widget matching the given key and value. */ + function listPair(key, value) { + return new ListPairWidget(key, value); + } + Widgets.listPair = listPair; + /** Create an external link widget which renders an external Obsidian link. */ + function externalLink(url, display) { + return new ExternalLinkWidget(url, display); + } + Widgets.externalLink = externalLink; + /** Checks if the given widget is a list pair widget. */ + function isListPair(widget) { + return widget.$widget === "dataview:list-pair"; + } + Widgets.isListPair = isListPair; + function isExternalLink(widget) { + return widget.$widget === "dataview:external-link"; + } + Widgets.isExternalLink = isExternalLink; + /** Determines if the given widget is any kind of built-in widget with special rendering handling. */ + function isBuiltin(widget) { + return isListPair(widget) || isExternalLink(widget); + } + Widgets.isBuiltin = isBuiltin; +})(Widgets || (Widgets = {})); + +/** Implementation of DataArray, minus the dynamic variable access, which is implemented via proxy. */ +class DataArrayImpl { + values; + settings; + defaultComparator; + static ARRAY_FUNCTIONS = new Set([ + "where", + "filter", + "map", + "flatMap", + "mutate", + "slice", + "concat", + "indexOf", + "limit", + "find", + "findIndex", + "includes", + "join", + "sort", + "sortInPlace", + "groupBy", + "groupIn", + "distinct", + "every", + "some", + "none", + "first", + "last", + "to", + "into", + "lwrap", + "expand", + "forEach", + "length", + "values", + "array", + "defaultComparator", + "toString", + "settings", + "sum", + "avg", + "min", + "max", + ]); + static ARRAY_PROXY = { + get: function (target, prop, receiver) { + if (typeof prop === "symbol") + return target[prop]; + else if (typeof prop === "number") + return target.values[prop]; + else if (prop === "constructor") + return target.values.constructor; + else if (!isNaN(parseInt(prop))) + return target.values[parseInt(prop)]; + else if (DataArrayImpl.ARRAY_FUNCTIONS.has(prop.toString())) + return target[prop.toString()]; + return target.to(prop); + }, + }; + static wrap(arr, settings, defaultComparator = Values.compareValue) { + return new Proxy(new DataArrayImpl(arr, settings, defaultComparator), DataArrayImpl.ARRAY_PROXY); + } + length; + constructor(values, settings, defaultComparator = Values.compareValue) { + this.values = values; + this.settings = settings; + this.defaultComparator = defaultComparator; + this.length = values.length; + } + lwrap(values) { + return DataArrayImpl.wrap(values, this.settings, this.defaultComparator); + } + where(predicate) { + return this.lwrap(this.values.filter(predicate)); + } + filter(predicate) { + return this.where(predicate); + } + map(f) { + return this.lwrap(this.values.map(f)); + } + flatMap(f) { + let result = []; + for (let index = 0; index < this.length; index++) { + let value = f(this.values[index], index, this.values); + if (!value || value.length == 0) + continue; + for (let r of value) + result.push(r); + } + return this.lwrap(result); + } + mutate(f) { + for (let index = 0; index < this.values.length; index++) { + f(this.values[index], index, this.values); + } + return this; + } + limit(count) { + return this.lwrap(this.values.slice(0, count)); + } + slice(start, end) { + return this.lwrap(this.values.slice(start, end)); + } + concat(other) { + return this.lwrap(this.values.concat(other.values)); + } + /** Return the first index of the given (optionally starting the search) */ + indexOf(element, fromIndex) { + return this.findIndex(e => this.defaultComparator(e, element) == 0, fromIndex); + } + /** Return the first element that satisfies the given predicate. */ + find(pred) { + let index = this.findIndex(pred); + if (index == -1) + return undefined; + else + return this.values[index]; + } + findIndex(pred, fromIndex) { + for (let index = fromIndex ?? 0; index < this.length; index++) { + if (pred(this.values[index], index, this.values)) + return index; + } + return -1; + } + includes(element) { + return this.indexOf(element, 0) != -1; + } + join(sep) { + return this.map(s => Values.toString(s, this.settings)) + .array() + .join(sep ?? ", "); + } + sort(key, direction, comparator) { + if (this.values.length == 0) + return this; + let realComparator = comparator ?? this.defaultComparator; + let realKey = key ?? ((l) => l); + // Associate each entry with it's index for the key function, and then do a normal sort. + let copy = [].concat(this.array()).map((elem, index) => { + return { index: index, value: elem }; + }); + copy.sort((a, b) => { + let aKey = realKey(a.value, a.index, this.values); + let bKey = realKey(b.value, b.index, this.values); + return direction === "desc" ? -realComparator(aKey, bKey) : realComparator(aKey, bKey); + }); + return this.lwrap(copy.map(e => e.value)); + } + sortInPlace(key, direction, comparator) { + if (this.values.length == 0) + return this; + let realComparator = comparator ?? this.defaultComparator; + let realKey = key ?? ((l) => l); + this.values.sort((a, b) => { + let aKey = realKey(a); + let bKey = realKey(b); + return direction == "desc" ? -realComparator(aKey, bKey) : realComparator(aKey, bKey); + }); + return this; + } + groupBy(key, comparator) { + if (this.values.length == 0) + return this.lwrap([]); + // JavaScript sucks and we can't make hash maps over arbitrary types (only strings/ints), so + // we do a poor man algorithm where we SORT, followed by grouping. + let intermediate = this.sort(key, "asc", comparator); + comparator = comparator ?? this.defaultComparator; + let result = []; + let currentRow = [intermediate[0]]; + let current = key(intermediate[0], 0, intermediate.values); + for (let index = 1; index < intermediate.length; index++) { + let newKey = key(intermediate[index], index, intermediate.values); + if (comparator(current, newKey) != 0) { + result.push({ key: current, rows: this.lwrap(currentRow) }); + current = newKey; + currentRow = [intermediate[index]]; + } + else { + currentRow.push(intermediate[index]); + } + } + result.push({ key: current, rows: this.lwrap(currentRow) }); + return this.lwrap(result); + } + groupIn(key, comparator) { + if (Groupings.isGrouping(this.values)) { + return this.map(v => { + return { + key: v.key, + rows: DataArray.wrap(v.rows, this.settings).groupIn(key, comparator), + }; + }); + } + else { + return this.groupBy(key, comparator); + } + } + distinct(key, comparator) { + if (this.values.length == 0) + return this; + let realKey = key ?? (x => x); + // For similar reasons to groupBy, do a sort and take the first element of each block. + let intermediate = this.map((x, index) => { + return { key: realKey(x, index, this.values), value: x }; + }).sort(x => x.key, "asc", comparator); + comparator = comparator ?? this.defaultComparator; + let result = [intermediate[0].value]; + for (let index = 1; index < intermediate.length; index++) { + if (comparator(intermediate[index - 1].key, intermediate[index].key) != 0) { + result.push(intermediate[index].value); + } + } + return this.lwrap(result); + } + every(f) { + return this.values.every(f); + } + some(f) { + return this.values.some(f); + } + none(f) { + return this.values.every((v, i, a) => !f(v, i, a)); + } + first() { + return this.values.length > 0 ? this.values[0] : undefined; + } + last() { + return this.values.length > 0 ? this.values[this.values.length - 1] : undefined; + } + to(key) { + let result = []; + for (let child of this.values) { + let value = child[key]; + if (value === undefined || value === null) + continue; + if (Array.isArray(value) || DataArray.isDataArray(value)) + value.forEach(v => result.push(v)); + else + result.push(value); + } + return this.lwrap(result); + } + into(key) { + let result = []; + for (let child of this.values) { + let value = child[key]; + if (value === undefined || value === null) + continue; + result.push(value); + } + return this.lwrap(result); + } + expand(key) { + let result = []; + let queue = [].concat(this.values); + while (queue.length > 0) { + let next = queue.pop(); + let value = next[key]; + if (value === undefined || value === null) + continue; + if (Array.isArray(value)) + value.forEach(v => queue.push(v)); + else if (value instanceof DataArrayImpl) + value.forEach(v => queue.push(v)); + else + queue.push(value); + result.push(next); + } + return this.lwrap(result); + } + forEach(f) { + for (let index = 0; index < this.values.length; index++) { + f(this.values[index], index, this.values); + } + } + sum() { + return this.values.reduce((a, b) => a + b, 0); + } + avg() { + return this.sum() / this.values.length; + } + min() { + return Math.min(...this.values); + } + max() { + return Math.max(...this.values); + } + array() { + return [].concat(this.values); + } + [Symbol.iterator]() { + return this.values[Symbol.iterator](); + } + toString() { + return "[" + this.values.join(", ") + "]"; + } +} +/** Provides utility functions for generating data arrays. */ +var DataArray; +(function (DataArray) { + /** Create a new Dataview data array. */ + function wrap(raw, settings) { + if (isDataArray(raw)) + return raw; + return DataArrayImpl.wrap(raw, settings); + } + DataArray.wrap = wrap; + /** Create a new DataArray from an iterable object. */ + function from(raw, settings) { + if (isDataArray(raw)) + return raw; + let data = []; + for (let elem of raw) + data.push(elem); + return DataArrayImpl.wrap(data, settings); + } + DataArray.from = from; + /** Return true if the given object is a data array. */ + function isDataArray(obj) { + return obj instanceof DataArrayImpl; + } + DataArray.isDataArray = isDataArray; +})(DataArray || (DataArray = {})); +// A scary looking polyfill, sure, but it fixes up data array/array interop for us. +const oldArrayIsArray = Array.isArray; +Array.isArray = (arg) => { + return oldArrayIsArray(arg) || DataArray.isDataArray(arg); +}; + +/** Test-environment-friendly function which fetches the current system locale. */ +function currentLocale() { + if (typeof window === "undefined") + return "en-US"; + return window.navigator.language; +} + +/** Render simple fields compactly, removing wrapping content like paragraph and span. */ +async function renderCompactMarkdown(app, markdown, container, sourcePath, component, isInlineFieldLivePreview = false) { + // check if the call is from the CM6 view plugin defined in src/ui/views/inline-field-live-preview.ts + if (isInlineFieldLivePreview) { + await renderCompactMarkdownForInlineFieldLivePreview(app, markdown, container, sourcePath, component); + } + else { + let subcontainer = container.createSpan(); + await obsidian.MarkdownRenderer.render(app, markdown, subcontainer, sourcePath, component); + let paragraph = subcontainer.querySelector(":scope > p"); + if (subcontainer.children.length == 1 && paragraph) { + while (paragraph.firstChild) { + subcontainer.appendChild(paragraph.firstChild); + } + subcontainer.removeChild(paragraph); + } + } +} +async function renderCompactMarkdownForInlineFieldLivePreview(app, markdown, container, sourcePath, component) { + const tmpContainer = createSpan(); + await obsidian.MarkdownRenderer.render(app, markdown, tmpContainer, sourcePath, component); + let paragraph = tmpContainer.querySelector(":scope > p"); + if (tmpContainer.childNodes.length == 1 && paragraph) { + container.appendChild(paragraph.childNodes.item(paragraph.childNodes.length - 1)); + } + else { + container.replaceChildren(...tmpContainer.childNodes); + } + tmpContainer.remove(); +} +/** Render a pre block with an error in it; returns the element to allow for dynamic updating. */ +function renderErrorPre(container, error) { + let pre = container.createEl("pre", { cls: ["dataview", "dataview-error"] }); + pre.appendText(error); + return pre; +} +/** Render a static codeblock. */ +function renderCodeBlock(container, source, language) { + let code = container.createEl("code", { cls: ["dataview"] }); + if (language) + code.classList.add("language-" + language); + code.appendText(source); + return code; +} +/** Prettily render a value into a container with the given settings. */ +async function renderValue(app, field, container, originFile, component, settings, expandList = false, context = "root", depth = 0, isInlineFieldLivePreview = false) { + // Prevent infinite recursion. + if (depth > settings.maxRecursiveRenderDepth) { + container.appendText("..."); + return; + } + if (Values.isNull(field)) { + await renderCompactMarkdown(app, settings.renderNullAs, container, originFile, component, isInlineFieldLivePreview); + } + else if (Values.isDate(field)) { + container.appendText(renderMinimalDate(field, settings, currentLocale())); + } + else if (Values.isDuration(field)) { + container.appendText(renderMinimalDuration(field)); + } + else if (Values.isString(field) || Values.isBoolean(field) || Values.isNumber(field)) { + await renderCompactMarkdown(app, "" + field, container, originFile, component, isInlineFieldLivePreview); + } + else if (Values.isLink(field)) { + await renderCompactMarkdown(app, field.markdown(), container, originFile, component, isInlineFieldLivePreview); + } + else if (Values.isHtml(field)) { + container.appendChild(field); + } + else if (Values.isWidget(field)) { + if (Widgets.isListPair(field)) { + await renderValue(app, field.key, container, originFile, component, settings, expandList, context, depth, isInlineFieldLivePreview); + container.appendText(": "); + await renderValue(app, field.value, container, originFile, component, settings, expandList, context, depth, isInlineFieldLivePreview); + } + else if (Widgets.isExternalLink(field)) { + let elem = document.createElement("a"); + elem.textContent = field.display ?? field.url; + elem.rel = "noopener"; + elem.target = "_blank"; + elem.classList.add("external-link"); + elem.href = field.url; + container.appendChild(elem); + } + else { + container.appendText(``); + } + } + else if (Values.isFunction(field)) { + container.appendText(""); + } + else if (Values.isArray(field) || DataArray.isDataArray(field)) { + if (expandList) { + let list = container.createEl("ul", { + cls: [ + "dataview", + "dataview-ul", + context == "list" ? "dataview-result-list-ul" : "dataview-result-list-root-ul", + ], + }); + for (let child of field) { + let li = list.createEl("li", { cls: "dataview-result-list-li" }); + await renderValue(app, child, li, originFile, component, settings, expandList, "list", depth + 1, isInlineFieldLivePreview); + } + } + else { + if (field.length == 0) { + container.appendText(""); + return; + } + let span = container.createEl("span", { cls: ["dataview", "dataview-result-list-span"] }); + let first = true; + for (let val of field) { + if (first) + first = false; + else + span.appendText(", "); + await renderValue(app, val, span, originFile, component, settings, expandList, "list", depth + 1, isInlineFieldLivePreview); + } + } + } + else if (Values.isObject(field)) { + // Don't render classes in case they have recursive references; spoopy. + if (field?.constructor?.name && field?.constructor?.name != "Object") { + container.appendText(`<${field.constructor.name}>`); + return; + } + if (expandList) { + let list = container.createEl("ul", { cls: ["dataview", "dataview-ul", "dataview-result-object-ul"] }); + for (let [key, value] of Object.entries(field)) { + let li = list.createEl("li", { cls: ["dataview", "dataview-li", "dataview-result-object-li"] }); + li.appendText(key + ": "); + await renderValue(app, value, li, originFile, component, settings, expandList, "list", depth + 1, isInlineFieldLivePreview); + } + } + else { + if (Object.keys(field).length == 0) { + container.appendText(""); + return; + } + let span = container.createEl("span", { cls: ["dataview", "dataview-result-object-span"] }); + let first = true; + for (let [key, value] of Object.entries(field)) { + if (first) + first = false; + else + span.appendText(", "); + span.appendText(key + ": "); + await renderValue(app, value, span, originFile, component, settings, expandList, "list", depth + 1, isInlineFieldLivePreview); + } + } + } + else { + container.appendText("Unrecognized: " + JSON.stringify(field)); + } +} + +var papaparse_min = {exports: {}}; + +/* @license +Papa Parse +v5.4.1 +https://github.com/mholt/PapaParse +License: MIT +*/ +papaparse_min.exports; + +(function (module, exports) { + !function(e,t){module.exports=t();}(commonjsGlobal,function s(){var f="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==f?f:{};var n=!f.document&&!!f.postMessage,o=f.IS_PAPA_WORKER||!1,a={},u=0,b={parse:function(e,t){var r=(t=t||{}).dynamicTyping||!1;J(r)&&(t.dynamicTypingFunction=r,r={});if(t.dynamicTyping=r,t.transform=!!J(t.transform)&&t.transform,t.worker&&b.WORKERS_SUPPORTED){var i=function(){if(!b.WORKERS_SUPPORTED)return !1;var e=(r=f.URL||f.webkitURL||null,i=s.toString(),b.BLOB_URL||(b.BLOB_URL=r.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",i,")();"],{type:"text/javascript"})))),t=new f.Worker(e);var r,i;return t.onmessage=_,t.id=u++,a[t.id]=t}();return i.userStep=t.step,i.userChunk=t.chunk,i.userComplete=t.complete,i.userError=t.error,t.step=J(t.step),t.chunk=J(t.chunk),t.complete=J(t.complete),t.error=J(t.error),delete t.worker,void i.postMessage({input:e,config:t,workerId:i.id})}var n=null;b.NODE_STREAM_INPUT,"string"==typeof e?(e=function(e){if(65279===e.charCodeAt(0))return e.slice(1);return e}(e),n=t.download?new l(t):new p(t)):!0===e.readable&&J(e.read)&&J(e.on)?n=new g(t):(f.File&&e instanceof File||e instanceof Object)&&(n=new c(t));return n.stream(e)},unparse:function(e,t){var n=!1,_=!0,m=",",y="\r\n",s='"',a=s+s,r=!1,i=null,o=!1;!function(){if("object"!=typeof t)return;"string"!=typeof t.delimiter||b.BAD_DELIMITERS.filter(function(e){return -1!==t.delimiter.indexOf(e)}).length||(m=t.delimiter);("boolean"==typeof t.quotes||"function"==typeof t.quotes||Array.isArray(t.quotes))&&(n=t.quotes);"boolean"!=typeof t.skipEmptyLines&&"string"!=typeof t.skipEmptyLines||(r=t.skipEmptyLines);"string"==typeof t.newline&&(y=t.newline);"string"==typeof t.quoteChar&&(s=t.quoteChar);"boolean"==typeof t.header&&(_=t.header);if(Array.isArray(t.columns)){if(0===t.columns.length)throw new Error("Option columns is empty");i=t.columns;}void 0!==t.escapeChar&&(a=t.escapeChar+s);("boolean"==typeof t.escapeFormulae||t.escapeFormulae instanceof RegExp)&&(o=t.escapeFormulae instanceof RegExp?t.escapeFormulae:/^[=+\-@\t\r].*$/);}();var u=new RegExp(Q(s),"g");"string"==typeof e&&(e=JSON.parse(e));if(Array.isArray(e)){if(!e.length||Array.isArray(e[0]))return h(null,e,r);if("object"==typeof e[0])return h(i||Object.keys(e[0]),e,r)}else if("object"==typeof e)return "string"==typeof e.data&&(e.data=JSON.parse(e.data)),Array.isArray(e.data)&&(e.fields||(e.fields=e.meta&&e.meta.fields||i),e.fields||(e.fields=Array.isArray(e.data[0])?e.fields:"object"==typeof e.data[0]?Object.keys(e.data[0]):[]),Array.isArray(e.data[0])||"object"==typeof e.data[0]||(e.data=[e.data])),h(e.fields||[],e.data||[],r);throw new Error("Unable to serialize unrecognized input");function h(e,t,r){var i="";"string"==typeof e&&(e=JSON.parse(e)),"string"==typeof t&&(t=JSON.parse(t));var n=Array.isArray(e)&&0=this._config.preview;if(o)f.postMessage({results:n,workerId:b.WORKER_ID,finished:a});else if(J(this._config.chunk)&&!t){if(this._config.chunk(n,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);n=void 0,this._completeResults=void 0;}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(n.data),this._completeResults.errors=this._completeResults.errors.concat(n.errors),this._completeResults.meta=n.meta),this._completed||!a||!J(this._config.complete)||n&&n.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),a||n&&n.meta.paused||this._nextChunk(),n}this._halted=!0;},this._sendError=function(e){J(this._config.error)?this._config.error(e):o&&this._config.error&&f.postMessage({workerId:b.WORKER_ID,error:e,finished:!1});};}function l(e){var i;(e=e||{}).chunkSize||(e.chunkSize=b.RemoteChunkSize),h.call(this,e),this._nextChunk=n?function(){this._readChunk(),this._chunkLoaded();}:function(){this._readChunk();},this.stream=function(e){this._input=e,this._nextChunk();},this._readChunk=function(){if(this._finished)this._chunkLoaded();else {if(i=new XMLHttpRequest,this._config.withCredentials&&(i.withCredentials=this._config.withCredentials),n||(i.onload=v(this._chunkLoaded,this),i.onerror=v(this._chunkError,this)),i.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var e=this._config.downloadRequestHeaders;for(var t in e)i.setRequestHeader(t,e[t]);}if(this._config.chunkSize){var r=this._start+this._config.chunkSize-1;i.setRequestHeader("Range","bytes="+this._start+"-"+r);}try{i.send(this._config.downloadRequestBody);}catch(e){this._chunkError(e.message);}n&&0===i.status&&this._chunkError();}},this._chunkLoaded=function(){4===i.readyState&&(i.status<200||400<=i.status?this._chunkError():(this._start+=this._config.chunkSize?this._config.chunkSize:i.responseText.length,this._finished=!this._config.chunkSize||this._start>=function(e){var t=e.getResponseHeader("Content-Range");if(null===t)return -1;return parseInt(t.substring(t.lastIndexOf("/")+1))}(i),this.parseChunk(i.responseText)));},this._chunkError=function(e){var t=i.statusText||e;this._sendError(new Error(t));};}function c(e){var i,n;(e=e||{}).chunkSize||(e.chunkSize=b.LocalChunkSize),h.call(this,e);var s="undefined"!=typeof FileReader;this.stream=function(e){this._input=e,n=e.slice||e.webkitSlice||e.mozSlice,s?((i=new FileReader).onload=v(this._chunkLoaded,this),i.onerror=v(this._chunkError,this)):i=new FileReaderSync,this._nextChunk();},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(e.target.result);},this._chunkError=function(){this._sendError(i.error);};}function p(e){var r;h.call(this,e=e||{}),this.stream=function(e){return r=e,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var e,t=this._config.chunkSize;return t?(e=r.substring(0,t),r=r.substring(t)):(e=r,r=""),this._finished=!r,this.parseChunk(e)}};}function g(e){h.call(this,e=e||{});var t=[],r=!0,i=!1;this.pause=function(){h.prototype.pause.apply(this,arguments),this._input.pause();},this.resume=function(){h.prototype.resume.apply(this,arguments),this._input.resume();},this.stream=function(e){this._input=e,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError);},this._checkIsFinished=function(){i&&1===t.length&&(this._finished=!0);},this._nextChunk=function(){this._checkIsFinished(),t.length?this.parseChunk(t.shift()):r=!0;},this._streamData=v(function(e){try{t.push("string"==typeof e?e:e.toString(this._config.encoding)),r&&(r=!1,this._checkIsFinished(),this.parseChunk(t.shift()));}catch(e){this._streamError(e);}},this),this._streamError=v(function(e){this._streamCleanUp(),this._sendError(e);},this),this._streamEnd=v(function(){this._streamCleanUp(),i=!0,this._streamData("");},this),this._streamCleanUp=v(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError);},this);}function r(m){var a,o,u,i=Math.pow(2,53),n=-i,s=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,h=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,t=this,r=0,f=0,d=!1,e=!1,l=[],c={data:[],errors:[],meta:{}};if(J(m.step)){var p=m.step;m.step=function(e){if(c=e,_())g();else {if(g(),0===c.data.length)return;r+=e.data.length,m.preview&&r>m.preview?o.abort():(c.data=c.data[0],p(c,t));}};}function y(e){return "greedy"===m.skipEmptyLines?""===e.join("").trim():1===e.length&&0===e[0].length}function g(){return c&&u&&(k("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+b.DefaultDelimiter+"'"),u=!1),m.skipEmptyLines&&(c.data=c.data.filter(function(e){return !y(e)})),_()&&function(){if(!c)return;function e(e,t){J(m.transformHeader)&&(e=m.transformHeader(e,t)),l.push(e);}if(Array.isArray(c.data[0])){for(var t=0;_()&&t=l.length?"__parsed_extra":l[r]),m.transform&&(s=m.transform(s,n)),s=v(n,s),"__parsed_extra"===n?(i[n]=i[n]||[],i[n].push(s)):i[n]=s;}return m.header&&(r>l.length?k("FieldMismatch","TooManyFields","Too many fields: expected "+l.length+" fields but parsed "+r,f+t):r=i.length/2?"\r\n":"\r"}(e,i)),u=!1,m.delimiter)J(m.delimiter)&&(m.delimiter=m.delimiter(e),c.meta.delimiter=m.delimiter);else {var n=function(e,t,r,i,n){var s,a,o,u;n=n||[",","\t","|",";",b.RECORD_SEP,b.UNIT_SEP];for(var h=0;h=N)return L(!0)}else for(S=W,W++;;){if(-1===(S=i.indexOf(z,S+1)))return r||h.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:u.length,index:W}),T();if(S===n-1)return T(i.substring(W,S).replace(C,z));if(z!==K||i[S+1]!==K){if(z===K||0===S||i[S-1]!==K){-1!==w&&w=N)return L(!0);break}h.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:u.length,index:W}),S++;}}else S++;}return T();function I(e){u.push(e),d=W;}function A(e){var t=0;if(-1!==e){var r=i.substring(S+1,e);r&&""===r.trim()&&(t=r.length);}return t}function T(e){return r||(void 0===e&&(e=i.substring(W)),f.push(e),W=n,I(f),o&&F()),L()}function D(e){W=e,I(f),f=[],R=i.indexOf(P,W);}function L(e){return {data:u,errors:h,meta:{delimiter:M,linebreak:P,aborted:H,truncated:!!e,cursor:d+(t||0)}}}function F(){q(L()),u=[],h=[];}},this.abort=function(){H=!0;},this.getCharIndex=function(){return W};}function _(e){var t=e.data,r=a[t.workerId],i=!1;if(t.error)r.userError(t.error,t.file);else if(t.results&&t.results.data){var n={abort:function(){i=!0,m(t.workerId,{data:[],errors:[],meta:{aborted:!0}});},pause:y,resume:y};if(J(r.userStep)){for(var s=0;s" || op == ">=" || op == "!=" || op == "="; + } + Fields.isCompareOp = isCompareOp; + Fields.NULL = Fields.literal(null); +})(Fields || (Fields = {})); + +/** AST implementation for queries over data sources. */ +/** Utility functions for creating and manipulating sources. */ +var Sources; +(function (Sources) { + /** Create a source which searches from a tag. */ + function tag(tag) { + return { type: "tag", tag }; + } + Sources.tag = tag; + /** Create a source which fetches from a CSV file. */ + function csv(path) { + return { type: "csv", path }; + } + Sources.csv = csv; + /** Create a source which searches for files under a folder prefix. */ + function folder(prefix) { + return { type: "folder", folder: prefix }; + } + Sources.folder = folder; + /** Create a source which searches for files which link to/from a given file. */ + function link(file, incoming) { + return { type: "link", file, direction: incoming ? "incoming" : "outgoing" }; + } + Sources.link = link; + /** Create a source which joins two sources by a logical operator (and/or). */ + function binaryOp(left, op, right) { + return { type: "binaryop", left, op, right }; + } + Sources.binaryOp = binaryOp; + /** Create a source which takes the intersection of two sources. */ + function and(left, right) { + return { type: "binaryop", left, op: "&", right }; + } + Sources.and = and; + /** Create a source which takes the union of two sources. */ + function or(left, right) { + return { type: "binaryop", left, op: "|", right }; + } + Sources.or = or; + /** Create a source which negates the underlying source. */ + function negate(child) { + return { type: "negate", child }; + } + Sources.negate = negate; + function empty() { + return { type: "empty" }; + } + Sources.empty = empty; +})(Sources || (Sources = {})); + +/** Emoji regex without any additional flags. */ +const EMOJI_REGEX = new RegExp(emojiRegex(), ""); +/** Provides a lookup table for unit durations of the given type. */ +const DURATION_TYPES = { + year: Duration.fromObject({ years: 1 }), + years: Duration.fromObject({ years: 1 }), + yr: Duration.fromObject({ years: 1 }), + yrs: Duration.fromObject({ years: 1 }), + month: Duration.fromObject({ months: 1 }), + months: Duration.fromObject({ months: 1 }), + mo: Duration.fromObject({ months: 1 }), + mos: Duration.fromObject({ months: 1 }), + week: Duration.fromObject({ weeks: 1 }), + weeks: Duration.fromObject({ weeks: 1 }), + wk: Duration.fromObject({ weeks: 1 }), + wks: Duration.fromObject({ weeks: 1 }), + w: Duration.fromObject({ weeks: 1 }), + day: Duration.fromObject({ days: 1 }), + days: Duration.fromObject({ days: 1 }), + d: Duration.fromObject({ days: 1 }), + hour: Duration.fromObject({ hours: 1 }), + hours: Duration.fromObject({ hours: 1 }), + hr: Duration.fromObject({ hours: 1 }), + hrs: Duration.fromObject({ hours: 1 }), + h: Duration.fromObject({ hours: 1 }), + minute: Duration.fromObject({ minutes: 1 }), + minutes: Duration.fromObject({ minutes: 1 }), + min: Duration.fromObject({ minutes: 1 }), + mins: Duration.fromObject({ minutes: 1 }), + m: Duration.fromObject({ minutes: 1 }), + second: Duration.fromObject({ seconds: 1 }), + seconds: Duration.fromObject({ seconds: 1 }), + sec: Duration.fromObject({ seconds: 1 }), + secs: Duration.fromObject({ seconds: 1 }), + s: Duration.fromObject({ seconds: 1 }), +}; +/** Shorthand for common dates (relative to right now). */ +const DATE_SHORTHANDS = { + now: () => DateTime.local(), + today: () => DateTime.local().startOf("day"), + yesterday: () => DateTime.local() + .startOf("day") + .minus(Duration.fromObject({ days: 1 })), + tomorrow: () => DateTime.local() + .startOf("day") + .plus(Duration.fromObject({ days: 1 })), + sow: () => DateTime.local().startOf("week"), + "start-of-week": () => DateTime.local().startOf("week"), + eow: () => DateTime.local().endOf("week"), + "end-of-week": () => DateTime.local().endOf("week"), + soy: () => DateTime.local().startOf("year"), + "start-of-year": () => DateTime.local().startOf("year"), + eoy: () => DateTime.local().endOf("year"), + "end-of-year": () => DateTime.local().endOf("year"), + som: () => DateTime.local().startOf("month"), + "start-of-month": () => DateTime.local().startOf("month"), + eom: () => DateTime.local().endOf("month"), + "end-of-month": () => DateTime.local().endOf("month"), +}; +/** + * Keywords which cannot be used as variables directly. Use `row.` if it is a variable you have defined and want + * to access. + */ +const KEYWORDS = ["FROM", "WHERE", "LIMIT", "GROUP", "FLATTEN"]; +/////////////// +// Utilities // +/////////////// +/** Split on unescaped pipes in an inner link. */ +function splitOnUnescapedPipe(link) { + let pipe = -1; + while ((pipe = link.indexOf("|", pipe + 1)) >= 0) { + if (pipe > 0 && link[pipe - 1] == "\\") + continue; + return [link.substring(0, pipe).replace(/\\\|/g, "|"), link.substring(pipe + 1)]; + } + return [link.replace(/\\\|/g, "|"), undefined]; +} +/** Attempt to parse the inside of a link to pull out display name, subpath, etc. */ +function parseInnerLink(rawlink) { + let [link, display] = splitOnUnescapedPipe(rawlink); + return Link.infer(link, false, display); +} +/** Create a left-associative binary parser which parses the given sub-element and separator. Handles whitespace. */ +function createBinaryParser(child, sep, combine) { + return parsimmon_umd_minExports.seqMap(child, parsimmon_umd_minExports.seq(parsimmon_umd_minExports.optWhitespace, sep, parsimmon_umd_minExports.optWhitespace, child).many(), (first, rest) => { + if (rest.length == 0) + return first; + let node = combine(first, rest[0][1], rest[0][3]); + for (let index = 1; index < rest.length; index++) { + node = combine(node, rest[index][1], rest[index][3]); + } + return node; + }); +} +function chainOpt(base, ...funcs) { + return parsimmon_umd_minExports.custom((success, failure) => { + return (input, i) => { + let result = base._(input, i); + if (!result.status) + return result; + for (let func of funcs) { + let next = func(result.value)._(input, result.index); + if (!next.status) + return result; + result = next; + } + return result; + }; + }); +} +const EXPRESSION = parsimmon_umd_minExports.createLanguage({ + // A floating point number; the decimal point is optional. + number: q => parsimmon_umd_minExports.regexp(/-?[0-9]+(\.[0-9]+)?/) + .map(str => Number.parseFloat(str)) + .desc("number"), + // A quote-surrounded string which supports escape characters ('\'). + string: q => parsimmon_umd_minExports.string('"') + .then(parsimmon_umd_minExports.alt(q.escapeCharacter, parsimmon_umd_minExports.noneOf('"\\')) + .atLeast(0) + .map(chars => chars.join(""))) + .skip(parsimmon_umd_minExports.string('"')) + .desc("string"), + escapeCharacter: _ => parsimmon_umd_minExports.string("\\") + .then(parsimmon_umd_minExports.any) + .map(escaped => { + // If we are escaping a backslash or a quote, pass in on in escaped form + if (escaped === '"') + return '"'; + if (escaped === "\\") + return "\\"; + else + return "\\" + escaped; + }), + // A boolean true/false value. + bool: _ => parsimmon_umd_minExports.regexp(/true|false|True|False/) + .map(str => str.toLowerCase() == "true") + .desc("boolean ('true' or 'false')"), + // A tag of the form '#stuff/hello-there'. + tag: _ => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("#"), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]/).desc("text")).many(), (start, rest) => start + rest.join("")).desc("tag ('#hello/stuff')"), + // A variable identifier, which is alphanumeric and must start with a letter or... emoji. + identifier: _ => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/\p{Letter}/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/[0-9\p{Letter}_-]/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")).many(), (first, rest) => first + rest.join("")).desc("variable identifier"), + // An Obsidian link of the form [[]]. + link: _ => parsimmon_umd_minExports.regexp(/\[\[([^\[\]]*?)\]\]/u, 1) + .map(linkInner => parseInnerLink(linkInner)) + .desc("file link"), + // An embeddable link which can start with '!'. This overlaps with the normal negation operator, so it is only + // provided for metadata parsing. + embedLink: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!").atMost(1), q.link, (p, l) => { + if (p.length > 0) + l.embed = true; + return l; + }).desc("file link"), + // Binary plus or minus operator. + binaryPlusMinus: _ => parsimmon_umd_minExports.regexp(/\+|-/) + .map(str => str) + .desc("'+' or '-'"), + // Binary times or divide operator. + binaryMulDiv: _ => parsimmon_umd_minExports.regexp(/\*|\/|%/) + .map(str => str) + .desc("'*' or '/' or '%'"), + // Binary comparison operator. + binaryCompareOp: _ => parsimmon_umd_minExports.regexp(/>=|<=|!=|>|<|=/) + .map(str => str) + .desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"), + // Binary boolean combination operator. + binaryBooleanOp: _ => parsimmon_umd_minExports.regexp(/and|or|&|\|/i) + .map(str => { + if (str.toLowerCase() == "and") + return "&"; + else if (str.toLowerCase() == "or") + return "|"; + else + return str; + }) + .desc("'and' or 'or'"), + // A date which can be YYYY-MM[-DDTHH:mm:ss]. + rootDate: _ => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/\d{4}/), parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (year, _, month) => { + return DateTime.fromObject({ year: Number.parseInt(year), month: Number.parseInt(month) }); + }).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"), + dateShorthand: _ => parsimmon_umd_minExports.alt(...Object.keys(DATE_SHORTHANDS) + .sort((a, b) => b.length - a.length) + .map(parsimmon_umd_minExports.string)), + date: q => chainOpt(q.rootDate, (ym) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, day) => ym.set({ day: Number.parseInt(day) })), (ymd) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("T"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, hour) => ymd.set({ hour: Number.parseInt(hour) })), (ymdh) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, minute) => ymdh.set({ minute: Number.parseInt(minute) })), (ymdhm) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, second) => ymdhm.set({ second: Number.parseInt(second) })), (ymdhms) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), parsimmon_umd_minExports.regexp(/\d{3}/), (_, millisecond) => ymdhms.set({ millisecond: Number.parseInt(millisecond) })), parsimmon_umd_minExports.succeed(ymdhms) // pass + ), (dt) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("+").or(parsimmon_umd_minExports.string("-")), parsimmon_umd_minExports.regexp(/\d{1,2}(:\d{2})?/), (pm, hr) => dt.setZone("UTC" + pm + hr, { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("Z"), () => dt.setZone("utc", { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.regexp(/[0-9A-Za-z+-\/]+/u), parsimmon_umd_minExports.string("]"), (_a, zone, _b) => dt.setZone(zone, { keepLocalTime: true })))) + .assert((dt) => dt.isValid, "valid date") + .desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"), + // A date, plus various shorthand times of day it could be. + datePlus: q => parsimmon_umd_minExports.alt(q.dateShorthand.map(d => DATE_SHORTHANDS[d]()), q.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"), + // A duration of time. + durationType: _ => parsimmon_umd_minExports.alt(...Object.keys(DURATION_TYPES) + .sort((a, b) => b.length - a.length) + .map(parsimmon_umd_minExports.string)), + duration: q => parsimmon_umd_minExports.seqMap(q.number, parsimmon_umd_minExports.optWhitespace, q.durationType, (count, _, t) => DURATION_TYPES[t].mapUnits(x => x * count)) + .sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).or(parsimmon_umd_minExports.optWhitespace)) + .map(durations => durations.reduce((p, c) => p.plus(c))) + .desc("duration like 4hr2min"), + // A raw null value. + rawNull: _ => parsimmon_umd_minExports.string("null"), + // Source parsing. + tagSource: q => q.tag.map(tag => Sources.tag(tag)), + csvSource: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("csv(").skip(parsimmon_umd_minExports.optWhitespace), q.string, parsimmon_umd_minExports.string(")"), (_1, path, _2) => Sources.csv(path)), + linkIncomingSource: q => q.link.map(link => Sources.link(link.path, true)), + linkOutgoingSource: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("outgoing(").skip(parsimmon_umd_minExports.optWhitespace), q.link, parsimmon_umd_minExports.string(")"), (_1, link, _2) => Sources.link(link.path, false)), + folderSource: q => q.string.map(str => Sources.folder(str)), + parensSource: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.source, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field), + negateSource: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.string("!")), q.atomSource, (_, source) => Sources.negate(source)), + atomSource: q => parsimmon_umd_minExports.alt(q.parensSource, q.negateSource, q.linkOutgoingSource, q.linkIncomingSource, q.folderSource, q.tagSource, q.csvSource), + binaryOpSource: q => createBinaryParser(q.atomSource, q.binaryBooleanOp.map(s => s), Sources.binaryOp), + source: q => q.binaryOpSource, + // Field parsing. + variableField: q => q.identifier + .chain(r => { + if (KEYWORDS.includes(r.toUpperCase())) { + return parsimmon_umd_minExports.fail("Variable fields cannot be a keyword (" + KEYWORDS.join(" or ") + ")"); + } + else { + return parsimmon_umd_minExports.succeed(Fields.variable(r)); + } + }) + .desc("variable"), + numberField: q => q.number.map(val => Fields.literal(val)).desc("number"), + stringField: q => q.string.map(val => Fields.literal(val)).desc("string"), + boolField: q => q.bool.map(val => Fields.literal(val)).desc("boolean"), + dateField: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("date("), parsimmon_umd_minExports.optWhitespace, q.datePlus, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, date, _2, postfix) => Fields.literal(date)).desc("date"), + durationField: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("dur("), parsimmon_umd_minExports.optWhitespace, q.duration, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, dur, _2, postfix) => Fields.literal(dur)).desc("duration"), + nullField: q => q.rawNull.map(_ => Fields.NULL), + linkField: q => q.link.map(f => Fields.literal(f)), + listField: q => q.field + .sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)) + .wrap(parsimmon_umd_minExports.string("[").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.string("]"))) + .map(l => Fields.list(l)) + .desc("list ('[1, 2, 3]')"), + objectField: q => parsimmon_umd_minExports.seqMap(q.identifier.or(q.string), parsimmon_umd_minExports.string(":").trim(parsimmon_umd_minExports.optWhitespace), q.field, (name, _sep, value) => { + return { name, value }; + }) + .sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)) + .wrap(parsimmon_umd_minExports.string("{").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.string("}"))) + .map(vals => { + let res = {}; + for (let entry of vals) + res[entry.name] = entry.value; + return Fields.object(res); + }) + .desc("object ('{ a: 1, b: 2 }')"), + atomInlineField: q => parsimmon_umd_minExports.alt(q.date, q.duration.map(d => normalizeDuration(d)), q.string, q.tag, q.embedLink, q.bool, q.number, q.rawNull), + inlineFieldList: q => q.atomInlineField.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).lookahead(q.atomInlineField)), + inlineField: q => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(q.atomInlineField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace), q.inlineFieldList, (f, _s, l) => [f].concat(l)), q.atomInlineField), + atomField: q => parsimmon_umd_minExports.alt( + // Place embed links above negated fields as they are the special parser case '![[thing]]' and are generally unambiguous. + q.embedLink.map(l => Fields.literal(l)), q.negatedField, q.linkField, q.listField, q.objectField, q.lambdaField, q.parensField, q.boolField, q.numberField, q.stringField, q.dateField, q.durationField, q.nullField, q.variableField), + indexField: q => parsimmon_umd_minExports.seqMap(q.atomField, parsimmon_umd_minExports.alt(q.dotPostfix, q.indexPostfix, q.functionPostfix).many(), (obj, postfixes) => { + let result = obj; + for (let post of postfixes) { + switch (post.type) { + case "dot": + result = Fields.index(result, Fields.literal(post.field)); + break; + case "index": + result = Fields.index(result, post.field); + break; + case "function": + result = Fields.func(result, post.fields); + break; + } + } + return result; + }), + negatedField: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!"), q.indexField, (_, field) => Fields.negate(field)).desc("negated field"), + parensField: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field), + lambdaField: q => parsimmon_umd_minExports.seqMap(q.identifier + .sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)) + .wrap(parsimmon_umd_minExports.string("(").trim(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.string(")").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.string("=>").trim(parsimmon_umd_minExports.optWhitespace), q.field, (ident, _ignore, value) => { + return { type: "lambda", arguments: ident, value }; + }), + dotPostfix: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), q.identifier, (_, field) => { + return { type: "dot", field: field }; + }), + indexPostfix: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.optWhitespace, q.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string("]"), (_, _2, field, _3, _4) => { + return { type: "index", field }; + }), + functionPostfix: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q.field.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_, _1, fields, _2, _3) => { + return { type: "function", fields }; + }), + // The precedence hierarchy of operators - multiply/divide, add/subtract, compare, and then boolean operations. + binaryMulDivField: q => createBinaryParser(q.indexField, q.binaryMulDiv, Fields.binaryOp), + binaryPlusMinusField: q => createBinaryParser(q.binaryMulDivField, q.binaryPlusMinus, Fields.binaryOp), + binaryCompareField: q => createBinaryParser(q.binaryPlusMinusField, q.binaryCompareOp, Fields.binaryOp), + binaryBooleanField: q => createBinaryParser(q.binaryCompareField, q.binaryBooleanOp, Fields.binaryOp), + binaryOpField: q => q.binaryBooleanField, + field: q => q.binaryOpField, +}); +/** + * Attempt to parse a field from the given text, returning a string error if the + * parse failed. + */ +function parseField(text) { + try { + return Result.success(EXPRESSION.field.tryParse(text)); + } + catch (error) { + return Result.failure("" + error); + } +} + +/** Parse inline fields and other embedded metadata in a line. */ +/** The wrapper characters that can be used to define an inline field. */ +const INLINE_FIELD_WRAPPERS = Object.freeze({ + "[": "]", + "(": ")", +}); +/** + * Find a matching closing bracket that occurs at or after `start`, respecting nesting and escapes. If found, + * returns the value contained within and the string index after the end of the value. + */ +function findClosing(line, start, open, close) { + let nesting = 0; + let escaped = false; + for (let index = start; index < line.length; index++) { + let char = line.charAt(index); + // Allows for double escapes like '\\' to be rendered normally. + if (char == "\\") { + escaped = !escaped; + continue; + } + // If escaped, ignore the next character for computing nesting, regardless of what it is. + if (escaped) { + escaped = false; + continue; + } + if (char == open) + nesting++; + else if (char == close) + nesting--; + // Only occurs if we are on a close character and there is no more nesting. + if (nesting < 0) + return { value: line.substring(start, index).trim(), endIndex: index + 1 }; + escaped = false; + } + return undefined; +} +/** Find the '::' separator in an inline field. */ +function findSeparator(line, start) { + let sep = line.indexOf("::", start); + if (sep < 0) + return undefined; + return { key: line.substring(start, sep).trim(), valueIndex: sep + 2 }; +} +/** Try to completely parse an inline field starting at the given position. Assumes `start` is on a wrapping character. */ +function findSpecificInlineField(line, start) { + let open = line.charAt(start); + let key = findSeparator(line, start + 1); + if (key === undefined) + return undefined; + // Fail the match if we find any separator characters (not allowed in keys). + for (let sep of Object.keys(INLINE_FIELD_WRAPPERS).concat(Object.values(INLINE_FIELD_WRAPPERS))) { + if (key.key.includes(sep)) + return undefined; + } + let value = findClosing(line, key.valueIndex, open, INLINE_FIELD_WRAPPERS[open]); + if (value === undefined) + return undefined; + return { + key: key.key, + value: value.value, + start: start, + startValue: key.valueIndex, + end: value.endIndex, + wrapping: open, + }; +} +/** Parse a textual inline field value into something we can work with. */ +function parseInlineValue(value) { + // Empty inline values (i.e., no text) should map to null to match long-term Dataview semantics. + // Null is also a more universal type to deal with than strings, since all functions accept nulls. + if (value.trim() == "") + return null; + // The stripped literal field parser understands all of the non-array/non-object fields and can parse them for us. + // Inline field objects are not currently supported; inline array objects have to be handled by the parser + // separately. + let inline = EXPRESSION.inlineField.parse(value); + if (inline.status) + return inline.value; + else + return value; +} +/** Extracts inline fields of the form '[key:: value]' from a line of text. This is done in a relatively + * "robust" way to avoid failing due to bad nesting or other interfering Markdown symbols: + * + * - Look for any wrappers ('[' and '(') in the line, trying to parse whatever comes after it as an inline key::. + * - If successful, scan until you find a matching end bracket, and parse whatever remains as an inline value. + */ +function extractInlineFields(line, includeTaskFields = false) { + let fields = []; + for (let wrapper of Object.keys(INLINE_FIELD_WRAPPERS)) { + let foundIndex = line.indexOf(wrapper); + while (foundIndex >= 0) { + let parsedField = findSpecificInlineField(line, foundIndex); + if (!parsedField) { + foundIndex = line.indexOf(wrapper, foundIndex + 1); + continue; + } + fields.push(parsedField); + foundIndex = line.indexOf(wrapper, parsedField.end); + } + } + if (includeTaskFields) + fields = fields.concat(extractSpecialTaskFields(line)); + fields.sort((a, b) => a.start - b.start); + let filteredFields = []; + for (let i = 0; i < fields.length; i++) { + if (i == 0 || filteredFields[filteredFields.length - 1].end < fields[i].start) { + filteredFields.push(fields[i]); + } + } + return filteredFields; +} +/** Validates that a raw field name has a valid form. */ +const FULL_LINE_KEY_PART = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(new RegExp(emojiRegex(), "u")), parsimmon_umd_minExports.regexp(/[0-9\p{Letter}\w\s_/-]+/u)) + .many() + .map(parts => parts.join("")); +parsimmon_umd_minExports.regexp(/[^0-9\w\p{Letter}]*/u) + .then(FULL_LINE_KEY_PART) + .skip(parsimmon_umd_minExports.regexp(/[_\*~`]*/u)); +const CREATED_DATE_REGEX = /\u{2795}\s*(\d{4}-\d{2}-\d{2})/u; +const DUE_DATE_REGEX = /(?:\u{1F4C5}|\u{1F4C6}|\u{1F5D3}\u{FE0F}?)\s*(\d{4}-\d{2}-\d{2})/u; +const DONE_DATE_REGEX = /\u{2705}\s*(\d{4}-\d{2}-\d{2})/u; +const SCHEDULED_DATE_REGEX = /[\u{23F3}\u{231B}]\s*(\d{4}-\d{2}-\d{2})/u; +const START_DATE_REGEX = /\u{1F6EB}\s*(\d{4}-\d{2}-\d{2})/u; +const EMOJI_REGEXES = [ + { regex: CREATED_DATE_REGEX, key: "created" }, + { regex: START_DATE_REGEX, key: "start" }, + { regex: SCHEDULED_DATE_REGEX, key: "scheduled" }, + { regex: DUE_DATE_REGEX, key: "due" }, + { regex: DONE_DATE_REGEX, key: "completion" }, +]; +/** Parse special completed/due/done task fields which are marked via emoji. */ +function extractSpecialTaskFields(line) { + let results = []; + for (let { regex, key } of EMOJI_REGEXES) { + const match = regex.exec(line); + if (!match) + continue; + results.push({ + key, + value: match[1], + start: match.index, + startValue: match.index + 1, + end: match.index + match[0].length, + wrapping: "emoji-shorthand", + }); + } + return results; +} +/** Sets or replaces the value of an inline field; if the value is 'undefined', deletes the key. */ +function setInlineField(source, key, value) { + let existing = extractInlineFields(source); + let existingKeys = existing.filter(f => f.key == key); + // Don't do anything if there are duplicate keys OR the key already doesn't exist. + if (existingKeys.length > 2 || (existingKeys.length == 0 && !value)) + return source; + let existingKey = existingKeys[0]; + let annotation = value ? `[${key}:: ${value}]` : ""; + if (existingKey) { + let prefix = source.substring(0, existingKey.start); + let suffix = source.substring(existingKey.end); + if (annotation) + return `${prefix}${annotation}${suffix}`; + else + return `${prefix}${suffix.trimStart()}`; + } + else if (annotation) { + return `${source.trimEnd()} ${annotation}`; + } + return source; +} +function setEmojiShorthandCompletionField(source, value) { + const existing = extractInlineFields(source, true); + const existingKeys = existing.filter(f => f.key === "completion" && f.wrapping === "emoji-shorthand"); + // Don't do anything if there are duplicate keys OR the key already doesn't exist. + if (existingKeys.length > 2 || (existingKeys.length == 0 && !value)) + return source; + /* No wrapper, add own spacing at start */ + const annotation = value ? ` ✅ ${value}` : ""; + let existingKey = existingKeys[0]; + if (existingKey) { + const prefix = source.substring(0, existingKey.start); + const suffix = source.substring(existingKey.end); + return `${prefix.trimEnd()}${annotation}${suffix}`; + } + else { + return `${source.trimEnd()}${annotation}`; + } +} + +/** All extracted markdown file metadata obtained from a file. */ +class PageMetadata { + /** The path this file exists at. */ + path; + /** Obsidian-provided date this page was created. */ + ctime; + /** Obsidian-provided date this page was modified. */ + mtime; + /** Obsidian-provided size of this page in bytes. */ + size; + /** The day associated with this page, if relevant. */ + day; + /** The first H1/H2 header in the file. May not exist. */ + title; + /** All of the fields contained in this markdown file - both frontmatter AND in-file links. */ + fields; + /** All of the exact tags (prefixed with '#') in this file overall. */ + tags; + /** All of the aliases defined for this file. */ + aliases; + /** All OUTGOING links (including embeds, header + block links) in this file. */ + links; + /** All list items contained within this page. Filter for tasks to get just tasks. */ + lists; + /** The raw frontmatter for this document. */ + frontmatter; + constructor(path, init) { + this.path = path; + this.fields = new Map(); + this.frontmatter = {}; + this.tags = new Set(); + this.aliases = new Set(); + this.links = []; + Object.assign(this, init); + this.lists = (this.lists || []).map(l => new ListItem$1(l)); + } + /** Canonicalize raw links and other data in partial data with normalizers, returning a completed object. */ + static canonicalize(data, linkNormalizer) { + // Mutate the data for now, which is probably a bad idea but... all well. + if (data.frontmatter) { + data.frontmatter = Values.mapLeaves(data.frontmatter, t => Values.isLink(t) ? linkNormalizer(t) : t); + } + if (data.fields) { + for (let [key, value] of data.fields.entries()) { + data.fields.set(key, Values.mapLeaves(value, t => (Values.isLink(t) ? linkNormalizer(t) : t))); + } + } + if (data.lists) { + for (let item of data.lists) { + for (let [key, value] of item.fields.entries()) { + item.fields.set(key, value.map(x => Values.mapLeaves(x, t => (Values.isLink(t) ? linkNormalizer(t) : t)))); + } + } + } + if (data.links) { + data.links = data.links.map(l => linkNormalizer(l)); + } + // This is pretty ugly, but it's not possible to normalize on the worker thread that does parsing. + // The best way to improve this is to instead just canonicalize the entire data object; I can try to + // optimize `Values.mapLeaves` to only mutate if it actually changes things. + return new PageMetadata(data.path, data); + } + /** The name (based on path) of this file. */ + name() { + return getFileTitle(this.path); + } + /** The containing folder (based on path) of this file. */ + folder() { + return getParentFolder(this.path); + } + /** The extension of this file (likely 'md'). */ + extension() { + return getExtension(this.path); + } + /** Return a set of tags AND all of their parent tags (so #hello/yes would become #hello, #hello/yes). */ + fullTags() { + let result = new Set(); + for (let tag of this.tags) { + for (let subtag of extractSubtags(tag)) + result.add(subtag); + } + return result; + } + /** Convert all links in this file to file links. */ + fileLinks() { + // We want to make them distinct, but where links are not raw links we + // now keep the additional metadata. + let distinctLinks = new Set(this.links); + return Array.from(distinctLinks); + } + /** Map this metadata to a full object; uses the index for additional data lookups. */ + serialize(index, cache) { + // Convert list items via the canonicalization cache. + let realCache = cache ?? new ListSerializationCache(this.lists); + let result = { + file: { + path: this.path, + folder: this.folder(), + name: this.name(), + link: Link.file(this.path), + outlinks: this.fileLinks(), + inlinks: Array.from(index.links.getInverse(this.path)).map(l => Link.file(l)), + etags: Array.from(this.tags), + tags: Array.from(this.fullTags()), + aliases: Array.from(this.aliases), + lists: this.lists.map(l => realCache.get(l.line)), + tasks: this.lists.filter(l => !!l.task).map(l => realCache.get(l.line)), + ctime: this.ctime, + cday: stripTime(this.ctime), + mtime: this.mtime, + mday: stripTime(this.mtime), + size: this.size, + starred: index.starred.starred(this.path), + frontmatter: Values.deepCopy(this.frontmatter), + ext: this.extension(), + }, + }; + // Add the current day if present. + if (this.day) + result.file.day = this.day; + // Then append the computed fields. + for (let [key, value] of this.fields.entries()) { + if (key in result) + continue; // Don't allow fields to override existing keys. + result[key] = value; + } + return result; + } +} +/** A list item inside of a list. */ +class ListItem$1 { + /** The symbol ('*', '-', '1.') used to define this list item. */ + symbol; + /** A link which points to this task, or to the closest block that this task is contained in. */ + link; + /** A link to the section that contains this list element; could be a file if this is not in a section. */ + section; + /** The text of this list item. This may be multiple lines of markdown. */ + text; + /** The line that this list item starts on in the file. */ + line; + /** The number of lines that define this list item. */ + lineCount; + /** The line number for the first list item in the list this item belongs to. */ + list; + /** Any links contained within this list item. */ + links; + /** The tags contained within this list item. */ + tags; + /** The raw Obsidian-provided position for where this task is. */ + position; + /** The line number of the parent list item, if present; if this is undefined, this is a root item. */ + parent; + /** The line numbers of children of this list item. */ + children; + /** The block ID for this item, if one is present. */ + blockId; + /** Any fields defined in this list item. For tasks, this includes fields underneath the task. */ + fields; + task; + constructor(init) { + Object.assign(this, init); + this.fields = this.fields || new Map(); + this.tags = this.tags || new Set(); + this.children = this.children || []; + this.links = this.links || []; + } + id() { + return `${this.file().path}-${this.line}`; + } + file() { + return this.link.toFile(); + } + markdown() { + if (this.task) + return `${this.symbol} [${this.task.completed ? "x" : " "}] ${this.text}`; + else + return `${this.symbol} ${this.text}`; + } + created() { + return (this.fields.get("created") ?? this.fields.get("ctime") ?? this.fields.get("cday"))?.[0]; + } + due() { + return (this.fields.get("due") ?? this.fields.get("duetime") ?? this.fields.get("dueday"))?.[0]; + } + completed() { + return (this.fields.get("completed") ?? + this.fields.get("completion") ?? + this.fields.get("comptime") ?? + this.fields.get("compday"))?.[0]; + } + start() { + return this.fields.get("start")?.[0]; + } + scheduled() { + return this.fields.get("scheduled")?.[0]; + } + /** Create an API-friendly copy of this list item. De-duplication is done via the provided cache. */ + serialize(cache) { + // Map children to their serialized/de-duplicated equivalents right away. + let children = this.children.map(l => cache.get(l)).filter((l) => l !== undefined); + let result = { + symbol: this.symbol, + link: this.link, + section: this.section, + text: this.text, + tags: Array.from(this.tags), + line: this.line, + lineCount: this.lineCount, + list: this.list, + outlinks: Array.from(this.links), + path: this.link.path, + children: children, + task: !!this.task, + annotated: this.fields.size > 0, + position: Values.deepCopy(this.position), + subtasks: children, + real: !!this.task, + header: this.section, // @deprecated, use 'item.section' instead. + }; + if (this.parent || this.parent === 0) + result.parent = this.parent; + if (this.blockId) + result.blockId = this.blockId; + addFields(this.fields, result); + if (this.task) { + result.status = this.task.status; + result.checked = this.task.checked; + result.completed = this.task.completed; + result.fullyCompleted = this.task.fullyCompleted; + let created = this.created(), due = this.due(), completed = this.completed(), start = this.start(), scheduled = this.scheduled(); + if (created) + result.created = Values.deepCopy(created); + if (due) + result.due = Values.deepCopy(due); + if (completed) + result.completion = Values.deepCopy(completed); + if (start) + result.start = Values.deepCopy(start); + if (scheduled) + result.scheduled = Values.deepCopy(scheduled); + } + return result; + } +} +////////////////////////////////////////// +// Conversion / Serialization Utilities // +////////////////////////////////////////// +/** De-duplicates list items across section metadata and page metadata. */ +class ListSerializationCache { + listItems; + cache; + seen; + constructor(listItems) { + this.listItems = {}; + this.cache = {}; + this.seen = new Set(); + for (let item of listItems) + this.listItems[item.line] = item; + } + get(lineno) { + if (lineno in this.cache) + return this.cache[lineno]; + else if (this.seen.has(lineno)) { + console.log(`Dataview: Encountered a circular list (line number ${lineno}; children ${this.listItems[lineno].children.join(", ")})`); + return undefined; + } + this.seen.add(lineno); + let result = this.listItems[lineno].serialize(this); + this.cache[lineno] = result; + return result; + } +} +function addFields(fields, target) { + for (let [key, values] of fields.entries()) { + if (key in target) + continue; + target[key] = values.length == 1 ? values[0] : values; + } + return target; +} + +/** Importer for markdown documents. */ +// TODO: Consider using an actual parser in lieu of a more expensive regex. +const LIST_ITEM_REGEX = /^[\s>]*(\d+\.|\d+\)|\*|-|\+)\s*(\[.{0,1}\])?\s*(.*)$/mu; +/** Recursively convert frontmatter into fields. We have to dance around YAML structure. */ +function parseFrontmatter(value) { + if (value == null) { + return null; + } + else if (typeof value === "object") { + if (Array.isArray(value)) { + let result = []; + for (let child of value) { + result.push(parseFrontmatter(child)); + } + return result; + } + else if (value instanceof Date) { + let dateParse = DateTime.fromJSDate(value); + return dateParse; + } + else { + let object = value; + let result = {}; + for (let key in object) { + result[key] = parseFrontmatter(object[key]); + } + return result; + } + } + else if (typeof value === "number") { + return value; + } + else if (typeof value === "boolean") { + return value; + } + else if (typeof value === "string") { + let dateParse = EXPRESSION.date.parse(value); + if (dateParse.status) + return dateParse.value; + let durationParse = EXPRESSION.duration.parse(value); + if (durationParse.status) + return durationParse.value; + let linkParse = EXPRESSION.embedLink.parse(value); + if (linkParse.status) + return linkParse.value; + return value; + } + // Backup if we don't understand the type. + return null; +} + +/** Parse a CSV file into a collection of data rows. */ +function parseCsv(content) { + let parsed = papaparse_minExports.parse(content, { + header: true, + skipEmptyLines: true, + comments: "#", + dynamicTyping: true, + }); + let rows = []; + for (let parsedRow of parsed.data) { + let fields = parseFrontmatter(parsedRow); + let result = {}; + for (let [key, value] of Object.entries(fields)) { + result[key] = value; + result[canonicalizeVarName(key)] = value; + } + rows.push(result); + } + return rows; +} + +/** Simplifies passing dataview values across the JS web worker barrier. */ +var Transferable; +(function (Transferable) { + /** Convert a literal value to a serializer-friendly transferable value. */ + function transferable(value) { + // Handle simple universal types first. + if (value instanceof Map) { + let copied = new Map(); + for (let [key, val] of value.entries()) + copied.set(transferable(key), transferable(val)); + return copied; + } + else if (value instanceof Set) { + let copied = new Set(); + for (let val of value) + copied.add(transferable(val)); + return copied; + } + let wrapped = Values.wrapValue(value); + if (wrapped === undefined) + throw Error("Unrecognized transferable value: " + value); + switch (wrapped.type) { + case "null": + case "number": + case "string": + case "boolean": + return wrapped.value; + case "date": + return { + "___transfer-type": "date", + value: transferable(wrapped.value.toObject()), + options: { + zone: wrapped.value.zone.equals(SystemZone.instance) ? undefined : wrapped.value.zoneName, + }, + }; + case "duration": + return { "___transfer-type": "duration", value: transferable(wrapped.value.toObject()) }; + case "array": + return wrapped.value.map(v => transferable(v)); + case "link": + return { "___transfer-type": "link", value: transferable(wrapped.value.toObject()) }; + case "object": + let result = {}; + for (let [key, value] of Object.entries(wrapped.value)) + result[key] = transferable(value); + return result; + } + } + Transferable.transferable = transferable; + /** Convert a transferable value back to a literal value we can work with. */ + function value(transferable) { + if (transferable === null) { + return null; + } + else if (transferable === undefined) { + return undefined; + } + else if (transferable instanceof Map) { + let real = new Map(); + for (let [key, val] of transferable.entries()) + real.set(value(key), value(val)); + return real; + } + else if (transferable instanceof Set) { + let real = new Set(); + for (let val of transferable) + real.add(value(val)); + return real; + } + else if (Array.isArray(transferable)) { + return transferable.map(v => value(v)); + } + else if (typeof transferable === "object") { + if ("___transfer-type" in transferable) { + switch (transferable["___transfer-type"]) { + case "date": + let dateOpts = value(transferable.options); + let dateData = value(transferable.value); + return DateTime.fromObject(dateData, { zone: dateOpts.zone }); + case "duration": + return Duration.fromObject(value(transferable.value)); + case "link": + return Link.fromObject(value(transferable.value)); + default: + throw Error(`Unrecognized transfer type '${transferable["___transfer-type"]}'`); + } + } + let result = {}; + for (let [key, val] of Object.entries(transferable)) + result[key] = value(val); + return result; + } + return transferable; + } + Transferable.value = value; +})(Transferable || (Transferable = {})); + +function commonjsRequire(path) { + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); +} + +var localforage$1 = {exports: {}}; + +/*! + localForage -- Offline Storage, Improved + Version 1.10.0 + https://localforage.github.io/localForage + (c) 2013-2017 Mozilla, Apache License 2.0 +*/ +localforage$1.exports; + +(function (module, exports) { + (function(f){{module.exports=f();}})(function(){return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted + // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. + var scriptEl = global.document.createElement('script'); + scriptEl.onreadystatechange = function () { + nextTick(); + + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function () { + setTimeout(nextTick, 0); + }; + } + } + + var draining; + var queue = []; + //named nextTick for less confusing stack traces + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + + module.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } + + }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + },{}],2:[function(_dereq_,module,exports){ + var immediate = _dereq_(1); + + /* istanbul ignore next */ + function INTERNAL() {} + + var handlers = {}; + + var REJECTED = ['REJECTED']; + var FULFILLED = ['FULFILLED']; + var PENDING = ['PENDING']; + + module.exports = Promise; + + function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new TypeError('resolver must be a function'); + } + this.state = PENDING; + this.queue = []; + this.outcome = void 0; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + + Promise.prototype["catch"] = function (onRejected) { + return this.then(null, onRejected); + }; + Promise.prototype.then = function (onFulfilled, onRejected) { + if (typeof onFulfilled !== 'function' && this.state === FULFILLED || + typeof onRejected !== 'function' && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === 'function') { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === 'function') { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function (value) { + handlers.resolve(this.promise, value); + }; + QueueItem.prototype.otherCallFulfilled = function (value) { + unwrap(this.promise, this.onFulfilled, value); + }; + QueueItem.prototype.callRejected = function (value) { + handlers.reject(this.promise, value); + }; + QueueItem.prototype.otherCallRejected = function (value) { + unwrap(this.promise, this.onRejected, value); + }; + + function unwrap(promise, func, value) { + immediate(function () { + var returnValue; + try { + returnValue = func(value); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError('Cannot resolve promise with itself')); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + + handlers.resolve = function (self, value) { + var result = tryCatch(getThen, value); + if (result.status === 'error') { + return handlers.reject(self, result.value); + } + var thenable = result.value; + + if (thenable) { + safelyResolveThenable(self, thenable); + } else { + self.state = FULFILLED; + self.outcome = value; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callFulfilled(value); + } + } + return self; + }; + handlers.reject = function (self, error) { + self.state = REJECTED; + self.outcome = error; + var i = -1; + var len = self.queue.length; + while (++i < len) { + self.queue[i].callRejected(error); + } + return self; + }; + + function getThen(obj) { + // Make sure we only access the accessor once as required by the spec + var then = obj && obj.then; + if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + + function safelyResolveThenable(self, thenable) { + // Either fulfill, reject or reject with error + var called = false; + function onError(value) { + if (called) { + return; + } + called = true; + handlers.reject(self, value); + } + + function onSuccess(value) { + if (called) { + return; + } + called = true; + handlers.resolve(self, value); + } + + function tryToUnwrap() { + thenable(onSuccess, onError); + } + + var result = tryCatch(tryToUnwrap); + if (result.status === 'error') { + onError(result.value); + } + } + + function tryCatch(func, value) { + var out = {}; + try { + out.value = func(value); + out.status = 'success'; + } catch (e) { + out.status = 'error'; + out.value = e; + } + return out; + } + + Promise.resolve = resolve; + function resolve(value) { + if (value instanceof this) { + return value; + } + return handlers.resolve(new this(INTERNAL), value); + } + + Promise.reject = reject; + function reject(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + + Promise.all = all; + function all(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } + + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + + var values = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value, i) { + self.resolve(value).then(resolveFromAll, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values[i] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values); + } + } + } + } + + Promise.race = race; + function race(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== '[object Array]') { + return this.reject(new TypeError('must be an array')); + } + + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + + var i = -1; + var promise = new this(INTERNAL); + + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value) { + self.resolve(value).then(function (response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function (error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } + + },{"1":1}],3:[function(_dereq_,module,exports){ + (function (global){ + if (typeof global.Promise !== 'function') { + global.Promise = _dereq_(2); + } + + }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + },{"2":2}],4:[function(_dereq_,module,exports){ + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function getIDB() { + /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */ + try { + if (typeof indexedDB !== 'undefined') { + return indexedDB; + } + if (typeof webkitIndexedDB !== 'undefined') { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== 'undefined') { + return mozIndexedDB; + } + if (typeof OIndexedDB !== 'undefined') { + return OIndexedDB; + } + if (typeof msIndexedDB !== 'undefined') { + return msIndexedDB; + } + } catch (e) { + return; + } + } + + var idb = getIDB(); + + function isIndexedDBValid() { + try { + // Initialize IndexedDB; fall back to vendor-prefixed versions + // if needed. + if (!idb || !idb.open) { + return false; + } + // We mimic PouchDB here; + // + // We test for openDatabase because IE Mobile identifies itself + // as Safari. Oh the lulz... + var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform); + + var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1; + + // Safari <10.1 does not meet our requirements for IDB support + // (see: https://github.com/pouchdb/pouchdb/issues/5572). + // Safari 10.1 shipped with fetch, we can use that to detect it. + // Note: this creates issues with `window.fetch` polyfills and + // overrides; see: + // https://github.com/localForage/localForage/issues/856 + return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' && + // some outdated implementations of IDB that appear on Samsung + // and HTC Android devices <4.4 are missing IDBKeyRange + // See: https://github.com/mozilla/localForage/issues/128 + // See: https://github.com/mozilla/localForage/issues/272 + typeof IDBKeyRange !== 'undefined'; + } catch (e) { + return false; + } + } + + // Abstracts constructing a Blob object, so it also works in older + // browsers that don't support the native Blob constructor. (i.e. + // old QtWebKit versions, at least). + // Abstracts constructing a Blob object, so it also works in older + // browsers that don't support the native Blob constructor. (i.e. + // old QtWebKit versions, at least). + function createBlob(parts, properties) { + /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */ + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== 'TypeError') { + throw e; + } + var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder(); + for (var i = 0; i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } + } + + // This is CommonJS because lie is an external dependency, so Rollup + // can just ignore it. + if (typeof Promise === 'undefined') { + // In the "nopromises" build this will just throw if you don't have + // a global promise object, but it would throw anyway later. + _dereq_(3); + } + var Promise$1 = Promise; + + function executeCallback(promise, callback) { + if (callback) { + promise.then(function (result) { + callback(null, result); + }, function (error) { + callback(error); + }); + } + } + + function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === 'function') { + promise.then(callback); + } + + if (typeof errorCallback === 'function') { + promise["catch"](errorCallback); + } + } + + function normalizeKey(key) { + // Cast the key to a string, as that's all we can set as a key. + if (typeof key !== 'string') { + console.warn(key + ' used as a key, but it is not a string.'); + key = String(key); + } + + return key; + } + + function getCallback() { + if (arguments.length && typeof arguments[arguments.length - 1] === 'function') { + return arguments[arguments.length - 1]; + } + } + + // Some code originally from async_storage.js in + // [Gaia](https://github.com/mozilla-b2g/gaia). + + var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; + var supportsBlobs = void 0; + var dbContexts = {}; + var toString = Object.prototype.toString; + + // Transaction Modes + var READ_ONLY = 'readonly'; + var READ_WRITE = 'readwrite'; + + // Transform a binary string to an array buffer, because otherwise + // weird stuff happens when you try to work with the binary string directly. + // It is known. + // From http://stackoverflow.com/questions/14967647/ (continues on next line) + // encode-decode-image-with-base64-breaks-image (2013-04-21) + function _binStringToArrayBuffer(bin) { + var length = bin.length; + var buf = new ArrayBuffer(length); + var arr = new Uint8Array(buf); + for (var i = 0; i < length; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; + } + + // + // Blobs are not supported in all versions of IndexedDB, notably + // Chrome <37 and Android <5. In those versions, storing a blob will throw. + // + // Various other blob bugs exist in Chrome v37-42 (inclusive). + // Detecting them is expensive and confusing to users, and Chrome 37-42 + // is at very low usage worldwide, so we do a hacky userAgent check instead. + // + // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120 + // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 + // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 + // + // Code borrowed from PouchDB. See: + // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js + // + function _checkBlobSupportWithoutCaching(idb) { + return new Promise$1(function (resolve) { + var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE); + var blob = createBlob(['']); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); + + txn.onabort = function (e) { + // If the transaction aborts now its due to not being able to + // write to the database, likely due to the disk being full + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + + txn.oncomplete = function () { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + // MS Edge pretends to be Chrome 42: + // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function () { + return false; // error, so assume unsupported + }); + } + + function _checkBlobSupport(idb) { + if (typeof supportsBlobs === 'boolean') { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb).then(function (value) { + supportsBlobs = value; + return supportsBlobs; + }); + } + + function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Create a deferred object representing the current database operation. + var deferredOperation = {}; + + deferredOperation.promise = new Promise$1(function (resolve, reject) { + deferredOperation.resolve = resolve; + deferredOperation.reject = reject; + }); + + // Enqueue the deferred operation. + dbContext.deferredOperations.push(deferredOperation); + + // Chain its promise to the database readiness. + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function () { + return deferredOperation.promise; + }); + } + } + + function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + + // Dequeue a deferred operation. + var deferredOperation = dbContext.deferredOperations.pop(); + + // Resolve its promise (which is part of the database readiness + // chain of promises). + if (deferredOperation) { + deferredOperation.resolve(); + return deferredOperation.promise; + } + } + + function _rejectReadiness(dbInfo, err) { + var dbContext = dbContexts[dbInfo.name]; + + // Dequeue a deferred operation. + var deferredOperation = dbContext.deferredOperations.pop(); + + // Reject its promise (which is part of the database readiness + // chain of promises). + if (deferredOperation) { + deferredOperation.reject(err); + return deferredOperation.promise; + } + } + + function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function (resolve, reject) { + dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext(); + + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + + var dbArgs = [dbInfo.name]; + + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + + var openreq = idb.open.apply(idb, dbArgs); + + if (upgradeNeeded) { + openreq.onupgradeneeded = function (e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + // Added when support for blob shims was added + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === 'ConstraintError') { + console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + + openreq.onerror = function (e) { + e.preventDefault(); + reject(openreq.error); + }; + + openreq.onsuccess = function () { + var db = openreq.result; + db.onversionchange = function (e) { + // Triggered when the database is modified (e.g. adding an objectStore) or + // deleted (even when initiated by other sessions in different tabs). + // Closing the connection here prevents those operations from being blocked. + // If the database is accessed again later by this instance, the connection + // will be reopened or the database recreated as needed. + e.target.close(); + }; + resolve(db); + _advanceReadiness(dbInfo); + }; + }); + } + + function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); + } + + function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); + } + + function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + + if (isDowngrade) { + // If the version is not the default one + // then warn for impossible downgrade. + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); + } + // Align the versions to prevent errors. + dbInfo.version = dbInfo.db.version; + } + + if (isUpgrade || isNewStore) { + // If the store is new then increment the version (if needed). + // This will trigger an "upgradeneeded" event which is required + // for creating a store. + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + + return true; + } + + return false; + } + + // encode a blob for indexeddb engines that don't support blobs + function _encodeBlob(blob) { + return new Promise$1(function (resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = function (e) { + var base64 = btoa(e.target.result || ''); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); + } + + // decode an encoded blob + function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); + } + + // is this one of our fancy encoded blobs? + function _isEncodedBlob(value) { + return value && value.__local_forage_encoded_blob; + } + + // Specialize the default `ready()` function by making it dependent + // on the current database operations. Thus, the driver will be actually + // ready when it's been initialized (default) *and* there are no pending + // operations on the database (initiated by some other instances). + function _fullyReady(callback) { + var self = this; + + var promise = self._initReady().then(function () { + var dbContext = dbContexts[self._dbInfo.name]; + + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + + executeTwoCallbacks(promise, callback, callback); + return promise; + } + + // Try to establish a new db connection to replace the + // current one which is broken (i.e. experiencing + // InvalidStateError while creating a transaction). + function _tryReconnect(dbInfo) { + _deferReadiness(dbInfo); + + var dbContext = dbContexts[dbInfo.name]; + var forages = dbContext.forages; + + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + if (forage._dbInfo.db) { + forage._dbInfo.db.close(); + forage._dbInfo.db = null; + } + } + dbInfo.db = null; + + return _getOriginalConnection(dbInfo).then(function (db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function (db) { + // store the latest db reference + // in case the db was upgraded + dbInfo.db = dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + })["catch"](function (err) { + _rejectReadiness(dbInfo, err); + throw err; + }); + } + + // FF doesn't like Promises (micro-tasks) and IDDB store operations, + // so we have to do it with callbacks + function createTransaction(dbInfo, mode, callback, retries) { + if (retries === undefined) { + retries = 1; + } + + try { + var tx = dbInfo.db.transaction(dbInfo.storeName, mode); + callback(null, tx); + } catch (err) { + if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) { + return Promise$1.resolve().then(function () { + if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { + // increase the db version, to create the new ObjectStore + if (dbInfo.db) { + dbInfo.version = dbInfo.db.version + 1; + } + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + }).then(function () { + return _tryReconnect(dbInfo).then(function () { + createTransaction(dbInfo, mode, callback, retries - 1); + }); + })["catch"](callback); + } + + callback(err); + } + } + + function createDbContext() { + return { + // Running localForages sharing a database. + forages: [], + // Shared database. + db: null, + // Database readiness (promise). + dbReady: null, + // Deferred operations on the database. + deferredOperations: [] + }; + } + + // Open the IndexedDB database (automatically creates one if one didn't + // previously exist), using any options set in the config. + function _initStorage(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + // Get the current context of the database; + var dbContext = dbContexts[dbInfo.name]; + + // ...or create a new context. + if (!dbContext) { + dbContext = createDbContext(); + // Register the new context in the global container. + dbContexts[dbInfo.name] = dbContext; + } + + // Register itself as a running localForage in the current context. + dbContext.forages.push(self); + + // Replace the default `ready()` function with the specialized one. + if (!self._initReady) { + self._initReady = self.ready; + self.ready = _fullyReady; + } + + // Create an array of initialization states of the related localForages. + var initPromises = []; + + function ignoreErrors() { + // Don't handle errors here, + // just makes sure related localForages aren't pending. + return Promise$1.resolve(); + } + + for (var j = 0; j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self) { + // Don't wait for itself... + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + + // Take a snapshot of the related localForages. + var forages = dbContext.forages.slice(0); + + // Initialize the connection process only when + // all the related localForages aren't pending. + return Promise$1.all(initPromises).then(function () { + dbInfo.db = dbContext.db; + // Get the connection or open a new one without upgrade. + return _getOriginalConnection(dbInfo); + }).then(function (db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { + // Reopen the database for upgrading. + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function (db) { + dbInfo.db = dbContext.db = db; + self._dbInfo = dbInfo; + // Share the final connection amongst related localForages. + for (var k = 0; k < forages.length; k++) { + var forage = forages[k]; + if (forage !== self) { + // Self is already up-to-date. + forage._dbInfo.db = dbInfo.db; + forage._dbInfo.version = dbInfo.version; + } + } + }); + } + + function getItem(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.get(key); + + req.onsuccess = function () { + var value = req.result; + if (value === undefined) { + value = null; + } + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + resolve(value); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Iterate over all items stored in database. + function iterate(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.openCursor(); + var iterationNumber = 1; + + req.onsuccess = function () { + var cursor = req.result; + + if (cursor) { + var value = cursor.value; + if (_isEncodedBlob(value)) { + value = _decodeBlob(value); + } + var result = iterator(value, cursor.key, iterationNumber++); + + // when the iterator callback returns any + // (non-`undefined`) value, then we stop + // the iteration immediately + if (result !== void 0) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + + return promise; + } + + function setItem(key, value, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + var dbInfo; + self.ready().then(function () { + dbInfo = self._dbInfo; + if (toString.call(value) === '[object Blob]') { + return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { + if (blobSupport) { + return value; + } + return _encodeBlob(value); + }); + } + return value; + }).then(function (value) { + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + + // The reason we don't _save_ null is because IE 10 does + // not support saving the `null` type in IndexedDB. How + // ironic, given the bug below! + // See: https://github.com/mozilla/localForage/issues/161 + if (value === null) { + value = undefined; + } + + var req = store.put(value, key); + + transaction.oncomplete = function () { + // Cast to undefined so the value passed to + // callback/promise is the same as what one would get out + // of `getItem()` later. This leads to some weirdness + // (setItem('foo', undefined) will return `null`), but + // it's not my fault localStorage is our baseline and that + // it's weird. + if (value === undefined) { + value = null; + } + + resolve(value); + }; + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function removeItem(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + // We use a Grunt task to make this safe for IE and some + // versions of Android (including those used by Cordova). + // Normally IE won't like `.delete()` and will insist on + // using `['delete']()`, but we have a build step that + // fixes this for us now. + var req = store["delete"](key); + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onerror = function () { + reject(req.error); + }; + + // The request will be also be aborted if we've exceeded our storage + // space. + transaction.onabort = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function clear(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.clear(); + + transaction.oncomplete = function () { + resolve(); + }; + + transaction.onabort = transaction.onerror = function () { + var err = req.error ? req.error : req.transaction.error; + reject(err); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function length(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.count(); + + req.onsuccess = function () { + resolve(req.result); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function key(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + if (n < 0) { + resolve(null); + + return; + } + + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var advanced = false; + var req = store.openKeyCursor(); + + req.onsuccess = function () { + var cursor = req.result; + if (!cursor) { + // this means there weren't enough keys + resolve(null); + + return; + } + + if (n === 0) { + // We have the first key, return it if that's what they + // wanted. + resolve(cursor.key); + } else { + if (!advanced) { + // Otherwise, ask the cursor to skip ahead n + // records. + advanced = true; + cursor.advance(n); + } else { + // When we get here, we've got the nth key. + resolve(cursor.key); + } + } + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function keys(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { + if (err) { + return reject(err); + } + + try { + var store = transaction.objectStore(self._dbInfo.storeName); + var req = store.openKeyCursor(); + var keys = []; + + req.onsuccess = function () { + var cursor = req.result; + + if (!cursor) { + resolve(keys); + return; + } + + keys.push(cursor.key); + cursor["continue"](); + }; + + req.onerror = function () { + reject(req.error); + }; + } catch (e) { + reject(e); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function dropInstance(options, callback) { + callback = getCallback.apply(this, arguments); + + var currentConfig = this.config(); + options = typeof options !== 'function' && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db; + + var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) { + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + return db; + }); + + if (!options.storeName) { + promise = dbPromise.then(function (db) { + _deferReadiness(options); + + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + + db.close(); + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + } + + var dropDBPromise = new Promise$1(function (resolve, reject) { + var req = idb.deleteDatabase(options.name); + + req.onerror = function () { + var db = req.result; + if (db) { + db.close(); + } + reject(req.error); + }; + + req.onblocked = function () { + // Closing all open connections in onversionchange handler should prevent this situation, but if + // we do get here, it just means the request remains pending - eventually it will succeed or error + console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed'); + }; + + req.onsuccess = function () { + var db = req.result; + if (db) { + db.close(); + } + resolve(db); + }; + }); + + return dropDBPromise.then(function (db) { + dbContext.db = db; + for (var i = 0; i < forages.length; i++) { + var _forage = forages[i]; + _advanceReadiness(_forage._dbInfo); + } + })["catch"](function (err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); + throw err; + }); + }); + } else { + promise = dbPromise.then(function (db) { + if (!db.objectStoreNames.contains(options.storeName)) { + return; + } + + var newVersion = db.version + 1; + + _deferReadiness(options); + + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + + db.close(); + for (var i = 0; i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + forage._dbInfo.version = newVersion; + } + + var dropObjectPromise = new Promise$1(function (resolve, reject) { + var req = idb.open(options.name, newVersion); + + req.onerror = function (err) { + var db = req.result; + db.close(); + reject(err); + }; + + req.onupgradeneeded = function () { + var db = req.result; + db.deleteObjectStore(options.storeName); + }; + + req.onsuccess = function () { + var db = req.result; + db.close(); + resolve(db); + }; + }); + + return dropObjectPromise.then(function (db) { + dbContext.db = db; + for (var j = 0; j < forages.length; j++) { + var _forage2 = forages[j]; + _forage2._dbInfo.db = db; + _advanceReadiness(_forage2._dbInfo); + } + })["catch"](function (err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {}); + throw err; + }); + }); + } + } + + executeCallback(promise, callback); + return promise; + } + + var asyncStorage = { + _driver: 'asyncStorage', + _initStorage: _initStorage, + _support: isIndexedDBValid(), + iterate: iterate, + getItem: getItem, + setItem: setItem, + removeItem: removeItem, + clear: clear, + length: length, + key: key, + keys: keys, + dropInstance: dropInstance + }; + + function isWebSQLValid() { + return typeof openDatabase === 'function'; + } + + // Sadly, the best way to save binary data in WebSQL/localStorage is serializing + // it to Base64, so this is how we store it to prevent very strange errors with less + // verbose ways of binary <-> string data storage. + var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + var BLOB_TYPE_PREFIX = '~~local_forage_type~'; + var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + + var SERIALIZED_MARKER = '__lfsc__:'; + var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + + // OMG the serializations! + var TYPE_ARRAYBUFFER = 'arbf'; + var TYPE_BLOB = 'blob'; + var TYPE_INT8ARRAY = 'si08'; + var TYPE_UINT8ARRAY = 'ui08'; + var TYPE_UINT8CLAMPEDARRAY = 'uic8'; + var TYPE_INT16ARRAY = 'si16'; + var TYPE_INT32ARRAY = 'si32'; + var TYPE_UINT16ARRAY = 'ur16'; + var TYPE_UINT32ARRAY = 'ui32'; + var TYPE_FLOAT32ARRAY = 'fl32'; + var TYPE_FLOAT64ARRAY = 'fl64'; + var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + + var toString$1 = Object.prototype.toString; + + function stringToBuffer(serializedString) { + // Fill the string into a ArrayBuffer. + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (serializedString[serializedString.length - 1] === '=') { + bufferLength--; + if (serializedString[serializedString.length - 2] === '=') { + bufferLength--; + } + } + + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + + for (i = 0; i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + + /*jslint bitwise: true */ + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; + } + + // Converts a buffer to a string to store, serialized, in the backend + // storage library. + function bufferToString(buffer) { + // base64-arraybuffer + var bytes = new Uint8Array(buffer); + var base64String = ''; + var i; + + for (i = 0; i < bytes.length; i += 3) { + /*jslint bitwise: true */ + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + '='; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + '=='; + } + + return base64String; + } + + // Serialize a value, afterwards executing a callback (which usually + // instructs the `setItem()` callback/promise to be executed). This is how + // we store binary data with localStorage. + function serialize(value, callback) { + var valueType = ''; + if (value) { + valueType = toString$1.call(value); + } + + // Cannot use `value instanceof ArrayBuffer` or such here, as these + // checks fail when running the tests using casper.js... + // + // TODO: See why those tests fail and use a better solution. + if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) { + // Convert binary arrays to a string and prefix the string with + // a special marker. + var buffer; + var marker = SERIALIZED_MARKER; + + if (value instanceof ArrayBuffer) { + buffer = value; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value.buffer; + + if (valueType === '[object Int8Array]') { + marker += TYPE_INT8ARRAY; + } else if (valueType === '[object Uint8Array]') { + marker += TYPE_UINT8ARRAY; + } else if (valueType === '[object Uint8ClampedArray]') { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueType === '[object Int16Array]') { + marker += TYPE_INT16ARRAY; + } else if (valueType === '[object Uint16Array]') { + marker += TYPE_UINT16ARRAY; + } else if (valueType === '[object Int32Array]') { + marker += TYPE_INT32ARRAY; + } else if (valueType === '[object Uint32Array]') { + marker += TYPE_UINT32ARRAY; + } else if (valueType === '[object Float32Array]') { + marker += TYPE_FLOAT32ARRAY; + } else if (valueType === '[object Float64Array]') { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error('Failed to get type for BinaryArray')); + } + } + + callback(marker + bufferToString(buffer)); + } else if (valueType === '[object Blob]') { + // Conver the blob to a binaryArray and then to a string. + var fileReader = new FileReader(); + + fileReader.onload = function () { + // Backwards-compatible prefix for the blob type. + var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); + + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + + fileReader.readAsArrayBuffer(value); + } else { + try { + callback(JSON.stringify(value)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value); + + callback(null, e); + } + } + } + + // Deserialize data we've inserted into a value column/field. We place + // special markers into our strings to mark them as encoded; this isn't + // as nice as a meta field, but it's the only sane thing we can do whilst + // keeping localStorage support intact. + // + // Oftentimes this will just deserialize JSON content, but if we have a + // special marker (SERIALIZED_MARKER, defined above), we will extract + // some kind of arraybuffer/binary data/typed array out of the string. + function deserialize(value) { + // If we haven't marked this string as being specially serialized (i.e. + // something other than serialized JSON), we can just return it and be + // done with it. + if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value); + } + + // The following code deals with deserializing some kind of Blob or + // TypedArray. First we separate out the type of data we're dealing + // with from the data itself. + var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + + var blobType; + // Backwards-compatible blob type serialization strategy. + // DBs created with older versions of localForage will simply not have the blob type. + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + + // Return the right type based on the code/type set during + // serialization. + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error('Unkown type: ' + type); + } + } + + var localforageSerializer = { + serialize: serialize, + deserialize: deserialize, + stringToBuffer: stringToBuffer, + bufferToString: bufferToString + }; + + /* + * Includes code from: + * + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ + + function createDbTable(t, dbInfo, callback, errorCallback) { + t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback); + } + + // Open the WebSQL database (automatically creates one if one didn't + // previously exist), using any options set in the config. + function _initStorage$1(options) { + var self = this; + var dbInfo = { + db: null + }; + + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; + } + } + + var dbInfoPromise = new Promise$1(function (resolve, reject) { + // Open the database; the openDatabase API will automatically + // create it for us if it doesn't exist. + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return reject(e); + } + + // Create our key/value table if it doesn't exist. + dbInfo.db.transaction(function (t) { + createDbTable(t, dbInfo, function () { + self._dbInfo = dbInfo; + resolve(); + }, function (t, error) { + reject(error); + }); + }, reject); + }); + + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; + } + + function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) { + t.executeSql(sqlStatement, args, callback, function (t, error) { + if (error.code === error.SYNTAX_ERR) { + t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) { + if (!results.rows.length) { + // if the table is missing (was deleted) + // re-create it table and retry + createDbTable(t, dbInfo, function () { + t.executeSql(sqlStatement, args, callback, errorCallback); + }, errorCallback); + } else { + errorCallback(t, error); + } + }, errorCallback); + } else { + errorCallback(t, error); + } + }, errorCallback); + } + + function getItem$1(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + + // Check to see if this is serialized content we need to + // unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function iterate$1(iterator, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { + var rows = results.rows; + var length = rows.length; + + for (var i = 0; i < length; i++) { + var item = rows.item(i); + var result = item.value; + + // Check to see if this is serialized content + // we need to unpack. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + result = iterator(result, item.key, i + 1); + + // void(0) prevents problems with redefinition + // of `undefined`. + if (result !== void 0) { + resolve(result); + return; + } + } + + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function _setItem(key, value, callback, retriesLeft) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + // The localStorage API doesn't return undefined values in an + // "expected" way, so undefined is always cast to null in all + // drivers. See: https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () { + resolve(originalValue); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + // The transaction failed; check + // to see if it's a quota error. + if (sqlError.code === sqlError.QUOTA_ERR) { + // We reject the callback outright for now, but + // it's worth trying to re-run the transaction. + // Even if the user accepts the prompt to use + // more storage on Safari, this error will + // be called. + // + // Try to re-run the transaction. + if (retriesLeft > 0) { + resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1])); + return; + } + reject(sqlError); + } + }); + } + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function setItem$1(key, value, callback) { + return _setItem.apply(this, [key, value, callback, 1]); + } + + function removeItem$1(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Deletes every item in the table. + // TODO: Find out if this resets the AUTO_INCREMENT number. + function clear$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Does a simple `COUNT(key)` to get the number of items stored in + // localForage. + function length$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + // Ahhh, SQL makes this one soooooo easy. + tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { + var result = results.rows.item(0).c; + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // Return the key located at key index X; essentially gets the key from a + // `WHERE id = ?`. This is the most efficient way I can think to implement + // this rarely-used (in my experience) part of the API, but it can seem + // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so + // the ID of each key will change every time it's updated. Perhaps a stored + // procedure for the `setItem()` SQL would solve this problem? + // TODO: Don't change ID on `setItem()`. + function key$1(n, callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + function keys$1(callback) { + var self = this; + + var promise = new Promise$1(function (resolve, reject) { + self.ready().then(function () { + var dbInfo = self._dbInfo; + dbInfo.db.transaction(function (t) { + tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { + var keys = []; + + for (var i = 0; i < results.rows.length; i++) { + keys.push(results.rows.item(i).key); + } + + resolve(keys); + }, function (t, error) { + reject(error); + }); + }); + })["catch"](reject); + }); + + executeCallback(promise, callback); + return promise; + } + + // https://www.w3.org/TR/webdatabase/#databases + // > There is no way to enumerate or delete the databases available for an origin from this API. + function getAllStoreNames(db) { + return new Promise$1(function (resolve, reject) { + db.transaction(function (t) { + t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) { + var storeNames = []; + + for (var i = 0; i < results.rows.length; i++) { + storeNames.push(results.rows.item(i).name); + } + + resolve({ + db: db, + storeNames: storeNames + }); + }, function (t, error) { + reject(error); + }); + }, function (sqlError) { + reject(sqlError); + }); + }); + } + + function dropInstance$1(options, callback) { + callback = getCallback.apply(this, arguments); + + var currentConfig = this.config(); + options = typeof options !== 'function' && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + promise = new Promise$1(function (resolve) { + var db; + if (options.name === currentConfig.name) { + // use the db reference of the current instance + db = self._dbInfo.db; + } else { + db = openDatabase(options.name, '', '', 0); + } + + if (!options.storeName) { + // drop all database tables + resolve(getAllStoreNames(db)); + } else { + resolve({ + db: db, + storeNames: [options.storeName] + }); + } + }).then(function (operationInfo) { + return new Promise$1(function (resolve, reject) { + operationInfo.db.transaction(function (t) { + function dropTable(storeName) { + return new Promise$1(function (resolve, reject) { + t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () { + resolve(); + }, function (t, error) { + reject(error); + }); + }); + } + + var operations = []; + for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) { + operations.push(dropTable(operationInfo.storeNames[i])); + } + + Promise$1.all(operations).then(function () { + resolve(); + })["catch"](function (e) { + reject(e); + }); + }, function (sqlError) { + reject(sqlError); + }); + }); + }); + } + + executeCallback(promise, callback); + return promise; + } + + var webSQLStorage = { + _driver: 'webSQLStorage', + _initStorage: _initStorage$1, + _support: isWebSQLValid(), + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1, + dropInstance: dropInstance$1 + }; + + function isLocalStorageValid() { + try { + return typeof localStorage !== 'undefined' && 'setItem' in localStorage && + // in IE8 typeof localStorage.setItem === 'object' + !!localStorage.setItem; + } catch (e) { + return false; + } + } + + function _getKeyPrefix(options, defaultConfig) { + var keyPrefix = options.name + '/'; + + if (options.storeName !== defaultConfig.storeName) { + keyPrefix += options.storeName + '/'; + } + return keyPrefix; + } + + // Check if localStorage throws when saving an item + function checkIfLocalStorageThrows() { + var localStorageTestKey = '_localforage_support_test'; + + try { + localStorage.setItem(localStorageTestKey, true); + localStorage.removeItem(localStorageTestKey); + + return false; + } catch (e) { + return true; + } + } + + // Check if localStorage is usable and allows to save an item + // This method checks if localStorage is usable in Safari Private Browsing + // mode, or in any other case where the available quota for localStorage + // is 0 and there wasn't any saved items yet. + function _isLocalStorageUsable() { + return !checkIfLocalStorageThrows() || localStorage.length > 0; + } + + // Config the localStorage backend, using options set in the config. + function _initStorage$2(options) { + var self = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + + dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig); + + if (!_isLocalStorageUsable()) { + return Promise$1.reject(); + } + + self._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + + return Promise$1.resolve(); + } + + // Remove all keys from the datastore, effectively destroying all data in + // the app's key/value store! + function clear$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var keyPrefix = self._dbInfo.keyPrefix; + + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + + executeCallback(promise, callback); + return promise; + } + + // Retrieve an item from the store. Unlike the original async_storage + // library in Gaia, we don't modify return values at all. If a key's value + // is `undefined`, we pass that value to the callback function. + function getItem$2(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the key + // is likely undefined and we'll pass it straight to the + // callback. + if (result) { + result = dbInfo.serializer.deserialize(result); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; + } + + // Iterate over all items in the store. + function iterate$2(iterator, callback) { + var self = this; + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length = localStorage.length; + + // We use a dedicated iterator instead of the `i` variable below + // so other keys we fetch in localStorage aren't counted in + // the `iterationNumber` argument passed to the `iterate()` + // callback. + // + // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 + var iterationNumber = 1; + + for (var i = 0; i < length; i++) { + var key = localStorage.key(i); + if (key.indexOf(keyPrefix) !== 0) { + continue; + } + var value = localStorage.getItem(key); + + // If a result was found, parse it from the serialized + // string into a JS object. If result isn't truthy, the + // key is likely undefined and we'll pass it straight + // to the iterator. + if (value) { + value = dbInfo.serializer.deserialize(value); + } + + value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); + + if (value !== void 0) { + return value; + } + } + }); + + executeCallback(promise, callback); + return promise; + } + + // Same as localStorage's key() method, except takes a callback. + function key$2(n, callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + + // Remove the prefix from the key, if a key is found. + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + + return result; + }); + + executeCallback(promise, callback); + return promise; + } + + function keys$2(callback) { + var self = this; + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + var length = localStorage.length; + var keys = []; + + for (var i = 0; i < length; i++) { + var itemKey = localStorage.key(i); + if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { + keys.push(itemKey.substring(dbInfo.keyPrefix.length)); + } + } + + return keys; + }); + + executeCallback(promise, callback); + return promise; + } + + // Supply the number of keys in the datastore to the callback function. + function length$2(callback) { + var self = this; + var promise = self.keys().then(function (keys) { + return keys.length; + }); + + executeCallback(promise, callback); + return promise; + } + + // Remove an item from the store, nice and simple. + function removeItem$2(key, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = self.ready().then(function () { + var dbInfo = self._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key); + }); + + executeCallback(promise, callback); + return promise; + } + + // Set a key's value and run an optional callback once the value is set. + // Unlike Gaia's implementation, the callback function is passed the value, + // in case you want to operate on that value only after you're sure it + // saved, or something like that. + function setItem$2(key, value, callback) { + var self = this; + + key = normalizeKey(key); + + var promise = self.ready().then(function () { + // Convert undefined values to null. + // https://github.com/mozilla/localForage/pull/42 + if (value === undefined) { + value = null; + } + + // Save the original value to pass to the callback. + var originalValue = value; + + return new Promise$1(function (resolve, reject) { + var dbInfo = self._dbInfo; + dbInfo.serializer.serialize(value, function (value, error) { + if (error) { + reject(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key, value); + resolve(originalValue); + } catch (e) { + // localStorage capacity exceeded. + // TODO: Make this a specific error/event. + if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { + reject(e); + } + reject(e); + } + } + }); + }); + }); + + executeCallback(promise, callback); + return promise; + } + + function dropInstance$2(options, callback) { + callback = getCallback.apply(this, arguments); + + options = typeof options !== 'function' && options || {}; + if (!options.name) { + var currentConfig = this.config(); + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + + var self = this; + var promise; + if (!options.name) { + promise = Promise$1.reject('Invalid arguments'); + } else { + promise = new Promise$1(function (resolve) { + if (!options.storeName) { + resolve(options.name + '/'); + } else { + resolve(_getKeyPrefix(options, self._defaultConfig)); + } + }).then(function (keyPrefix) { + for (var i = localStorage.length - 1; i >= 0; i--) { + var key = localStorage.key(i); + + if (key.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key); + } + } + }); + } + + executeCallback(promise, callback); + return promise; + } + + var localStorageWrapper = { + _driver: 'localStorageWrapper', + _initStorage: _initStorage$2, + _support: isLocalStorageValid(), + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2, + dropInstance: dropInstance$2 + }; + + var sameValue = function sameValue(x, y) { + return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y); + }; + + var includes = function includes(array, searchElement) { + var len = array.length; + var i = 0; + while (i < len) { + if (sameValue(array[i], searchElement)) { + return true; + } + i++; + } + + return false; + }; + + var isArray = Array.isArray || function (arg) { + return Object.prototype.toString.call(arg) === '[object Array]'; + }; + + // Drivers are stored here when `defineDriver()` is called. + // They are shared across all instances of localForage. + var DefinedDrivers = {}; + + var DriverSupport = {}; + + var DefaultDrivers = { + INDEXEDDB: asyncStorage, + WEBSQL: webSQLStorage, + LOCALSTORAGE: localStorageWrapper + }; + + var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; + + var OptionalDriverMethods = ['dropInstance']; + + var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods); + + var DefaultConfig = { + description: '', + driver: DefaultDriverOrder.slice(), + name: 'localforage', + // Default DB size is _JUST UNDER_ 5MB, as it's the highest size + // we can use without a prompt. + size: 4980736, + storeName: 'keyvaluepairs', + version: 1.0 + }; + + function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function () { + var _args = arguments; + return localForageInstance.ready().then(function () { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; + } + + function extend() { + for (var i = 1; i < arguments.length; i++) { + var arg = arguments[i]; + + if (arg) { + for (var _key in arg) { + if (arg.hasOwnProperty(_key)) { + if (isArray(arg[_key])) { + arguments[0][_key] = arg[_key].slice(); + } else { + arguments[0][_key] = arg[_key]; + } + } + } + } + } + + return arguments[0]; + } + + var LocalForage = function () { + function LocalForage(options) { + _classCallCheck(this, LocalForage); + + for (var driverTypeKey in DefaultDrivers) { + if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { + var driver = DefaultDrivers[driverTypeKey]; + var driverName = driver._driver; + this[driverTypeKey] = driverName; + + if (!DefinedDrivers[driverName]) { + // we don't need to wait for the promise, + // since the default drivers can be defined + // in a blocking manner + this.defineDriver(driver); + } + } + } + + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver)["catch"](function () {}); + } + + // Set any config values for localForage; can be called anytime before + // the first API call (e.g. `getItem`, `setItem`). + // We loop through options so we don't overwrite existing config + // values. + + + LocalForage.prototype.config = function config(options) { + // If the options argument is an object, we use it to set values. + // Otherwise, we return either a specified config value or all + // config values. + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + // If localforage is ready and fully initialized, we can't set + // any new configuration values. Instead, we return an error. + if (this._ready) { + return new Error("Can't call config() after localforage " + 'has been used.'); + } + + for (var i in options) { + if (i === 'storeName') { + options[i] = options[i].replace(/\W/g, '_'); + } + + if (i === 'version' && typeof options[i] !== 'number') { + return new Error('Database version must be a number.'); + } + + this._config[i] = options[i]; + } + + // after all config options are set and + // the driver option is used, try setting it + if ('driver' in options && options.driver) { + return this.setDriver(this._config.driver); + } + + return true; + } else if (typeof options === 'string') { + return this._config[options]; + } else { + return this._config; + } + }; + + // Used to define a custom driver, shared across all instances of + // localForage. + + + LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function (resolve, reject) { + try { + var driverName = driverObject._driver; + var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); + + // A driver name should be defined and not overlap with the + // library-defined, default drivers. + if (!driverObject._driver) { + reject(complianceError); + return; + } + + var driverMethods = LibraryMethods.concat('_initStorage'); + for (var i = 0, len = driverMethods.length; i < len; i++) { + var driverMethodName = driverMethods[i]; + + // when the property is there, + // it should be a method even when optional + var isRequired = !includes(OptionalDriverMethods, driverMethodName); + if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') { + reject(complianceError); + return; + } + } + + var configureMissingMethods = function configureMissingMethods() { + var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) { + return function () { + var error = new Error('Method ' + methodName + ' is not implemented by the current driver'); + var promise = Promise$1.reject(error); + executeCallback(promise, arguments[arguments.length - 1]); + return promise; + }; + }; + + for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) { + var optionalDriverMethod = OptionalDriverMethods[_i]; + if (!driverObject[optionalDriverMethod]) { + driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); + } + } + }; + + configureMissingMethods(); + + var setDriverSupport = function setDriverSupport(support) { + if (DefinedDrivers[driverName]) { + console.info('Redefining LocalForage driver: ' + driverName); + } + DefinedDrivers[driverName] = driverObject; + DriverSupport[driverName] = support; + // don't use a then, so that we can define + // drivers that have simple _support methods + // in a blocking manner + resolve(); + }; + + if ('_support' in driverObject) { + if (driverObject._support && typeof driverObject._support === 'function') { + driverObject._support().then(setDriverSupport, reject); + } else { + setDriverSupport(!!driverObject._support); + } + } else { + setDriverSupport(true); + } + } catch (e) { + reject(e); + } + }); + + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + + LocalForage.prototype.driver = function driver() { + return this._driver || null; + }; + + LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.')); + + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + + LocalForage.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + + LocalForage.prototype.ready = function ready(callback) { + var self = this; + + var promise = self._driverSet.then(function () { + if (self._ready === null) { + self._ready = self._initDriver(); + } + + return self._ready; + }); + + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + + LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self = this; + + if (!isArray(drivers)) { + drivers = [drivers]; + } + + var supportedDrivers = this._getSupportedDrivers(drivers); + + function setDriverToConfig() { + self._config.driver = self.driver(); + } + + function extendSelfWithDriver(driver) { + self._extend(driver); + setDriverToConfig(); + + self._ready = self._initStorage(self._config); + return self._ready; + } + + function initDriver(supportedDrivers) { + return function () { + var currentDriverIndex = 0; + + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers.length) { + var driverName = supportedDrivers[currentDriverIndex]; + currentDriverIndex++; + + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop); + } + + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + } + + return driverPromiseLoop(); + }; + } + + // There might be a driver initialization in progress + // so wait for it to finish in order to avoid a possible + // race condition to set _dbInfo + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + + this._driverSet = oldDriverSetDone.then(function () { + var driverName = supportedDrivers[0]; + self._dbInfo = null; + self._ready = null; + + return self.getDriver(driverName).then(function (driver) { + self._driver = driver._driver; + setDriverToConfig(); + self._wrapLibraryMethodsWithReady(); + self._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function () { + setDriverToConfig(); + var error = new Error('No available storage method found.'); + self._driverSet = Promise$1.reject(error); + return self._driverSet; + }); + + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + + LocalForage.prototype.supports = function supports(driverName) { + return !!DriverSupport[driverName]; + }; + + LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + + LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length; i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + + LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + // Add a stub for each driver API method that delays the call to the + // corresponding driver method until localForage is ready. These stubs + // will be replaced by the driver methods as soon as the driver is + // loaded, so there is no performance impact. + for (var i = 0, len = LibraryMethods.length; i < len; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + + LocalForage.prototype.createInstance = function createInstance(options) { + return new LocalForage(options); + }; + + return LocalForage; + }(); + + // The actual localForage object that we expose as a module or via a + // global. It's extended by pulling in one of our other libraries. + + + var localforage_js = new LocalForage(); + + module.exports = localforage_js; + + },{"3":3}]},{},[4])(4) + }); +} (localforage$1, localforage$1.exports)); + +var localforageExports = localforage$1.exports; +var localforage = /*@__PURE__*/getDefaultExportFromCjs(localforageExports); + +/** Simpler wrapper for a file-backed cache for arbitrary metadata. */ +class LocalStorageCache { + appId; + version; + persister; + constructor(appId, version) { + this.appId = appId; + this.version = version; + this.persister = localforage.createInstance({ + name: "dataview/cache/" + appId, + driver: [localforage.INDEXEDDB], + description: "Cache metadata about files and sections in the dataview index.", + }); + } + /** Drop the entire cache instance and re-create a new fresh instance. */ + async recreate() { + await localforage.dropInstance({ name: "dataview/cache/" + this.appId }); + this.persister = localforage.createInstance({ + name: "dataview/cache/" + this.appId, + driver: [localforage.INDEXEDDB], + description: "Cache metadata about files and sections in the dataview index.", + }); + } + /** Load file metadata by path. */ + async loadFile(path) { + return this.persister.getItem(this.fileKey(path)).then(raw => { + let result = raw; + if (result) + result.data = Transferable.value(result.data); + return result; + }); + } + /** Store file metadata by path. */ + async storeFile(path, data) { + await this.persister.setItem(this.fileKey(path), { + version: this.version, + time: Date.now(), + data: Transferable.transferable(data), + }); + } + /** Drop old file keys that no longer exist. */ + async synchronize(existing) { + let keys = new Set(await this.allFiles()); + for (let exist of existing) + keys.delete(exist); + // Any keys remaining after deleting existing keys are non-existent keys that should be cleared from cache. + for (let key of keys) + await this.persister.removeItem(this.fileKey(key)); + return keys; + } + /** Obtain a list of all metadata keys. */ + async allKeys() { + return this.persister.keys(); + } + /** Obtain a list of all persisted files. */ + async allFiles() { + let keys = await this.allKeys(); + return keys.filter(k => k.startsWith("file:")).map(k => k.substring(5)); + } + fileKey(path) { + return "file:" + path; + } +} + +function decodeBase64(base64, enableUnicode) { + var binaryString = atob(base64); + if (enableUnicode) { + var binaryView = new Uint8Array(binaryString.length); + for (var i = 0, n = binaryString.length; i < n; ++i) { + binaryView[i] = binaryString.charCodeAt(i); + } + return String.fromCharCode.apply(null, new Uint16Array(binaryView.buffer)); + } + return binaryString; +} + +function createURL(base64, sourcemapArg, enableUnicodeArg) { + var sourcemap = sourcemapArg === undefined ? null : sourcemapArg; + var enableUnicode = enableUnicodeArg === undefined ? false : enableUnicodeArg; + var source = decodeBase64(base64, enableUnicode); + var start = source.indexOf('\n', 10) + 1; + var body = source.substring(start) + (sourcemap ? '\/\/# sourceMappingURL=' + sourcemap : ''); + var blob = new Blob([body], { type: 'application/javascript' }); + return URL.createObjectURL(blob); +} + +function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) { + var url; + return function WorkerFactory(options) { + url = url || createURL(base64, sourcemapArg, enableUnicodeArg); + return new Worker(url, options); + }; +} + +var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewogICd1c2Ugc3RyaWN0JzsKCiAgLy8gdGhlc2UgYXJlbid0IHJlYWxseSBwcml2YXRlLCBidXQgbm9yIGFyZSB0aGV5IHJlYWxseSB1c2VmdWwgdG8gZG9jdW1lbnQKCiAgLyoqCiAgICogQHByaXZhdGUKICAgKi8KICBjbGFzcyBMdXhvbkVycm9yIGV4dGVuZHMgRXJyb3Ige30KCiAgLyoqCiAgICogQHByaXZhdGUKICAgKi8KICBjbGFzcyBJbnZhbGlkRGF0ZVRpbWVFcnJvciBleHRlbmRzIEx1eG9uRXJyb3IgewogICAgY29uc3RydWN0b3IocmVhc29uKSB7CiAgICAgIHN1cGVyKGBJbnZhbGlkIERhdGVUaW1lOiAke3JlYXNvbi50b01lc3NhZ2UoKX1gKTsKICAgIH0KICB9CgogIC8qKgogICAqIEBwcml2YXRlCiAgICovCiAgY2xhc3MgSW52YWxpZEludGVydmFsRXJyb3IgZXh0ZW5kcyBMdXhvbkVycm9yIHsKICAgIGNvbnN0cnVjdG9yKHJlYXNvbikgewogICAgICBzdXBlcihgSW52YWxpZCBJbnRlcnZhbDogJHtyZWFzb24udG9NZXNzYWdlKCl9YCk7CiAgICB9CiAgfQoKICAvKioKICAgKiBAcHJpdmF0ZQogICAqLwogIGNsYXNzIEludmFsaWREdXJhdGlvbkVycm9yIGV4dGVuZHMgTHV4b25FcnJvciB7CiAgICBjb25zdHJ1Y3RvcihyZWFzb24pIHsKICAgICAgc3VwZXIoYEludmFsaWQgRHVyYXRpb246ICR7cmVhc29uLnRvTWVzc2FnZSgpfWApOwogICAgfQogIH0KCiAgLyoqCiAgICogQHByaXZhdGUKICAgKi8KICBjbGFzcyBDb25mbGljdGluZ1NwZWNpZmljYXRpb25FcnJvciBleHRlbmRzIEx1eG9uRXJyb3Ige30KCiAgLyoqCiAgICogQHByaXZhdGUKICAgKi8KICBjbGFzcyBJbnZhbGlkVW5pdEVycm9yIGV4dGVuZHMgTHV4b25FcnJvciB7CiAgICBjb25zdHJ1Y3Rvcih1bml0KSB7CiAgICAgIHN1cGVyKGBJbnZhbGlkIHVuaXQgJHt1bml0fWApOwogICAgfQogIH0KCiAgLyoqCiAgICogQHByaXZhdGUKICAgKi8KICBjbGFzcyBJbnZhbGlkQXJndW1lbnRFcnJvciBleHRlbmRzIEx1eG9uRXJyb3Ige30KCiAgLyoqCiAgICogQHByaXZhdGUKICAgKi8KICBjbGFzcyBab25lSXNBYnN0cmFjdEVycm9yIGV4dGVuZHMgTHV4b25FcnJvciB7CiAgICBjb25zdHJ1Y3RvcigpIHsKICAgICAgc3VwZXIoIlpvbmUgaXMgYW4gYWJzdHJhY3QgY2xhc3MiKTsKICAgIH0KICB9CgogIC8qKgogICAqIEBwcml2YXRlCiAgICovCgogIGNvbnN0IG4gPSAibnVtZXJpYyIsCiAgICBzID0gInNob3J0IiwKICAgIGwgPSAibG9uZyI7CgogIGNvbnN0IERBVEVfU0hPUlQgPSB7CiAgICB5ZWFyOiBuLAogICAgbW9udGg6IG4sCiAgICBkYXk6IG4sCiAgfTsKCiAgY29uc3QgREFURV9NRUQgPSB7CiAgICB5ZWFyOiBuLAogICAgbW9udGg6IHMsCiAgICBkYXk6IG4sCiAgfTsKCiAgY29uc3QgREFURV9NRURfV0lUSF9XRUVLREFZID0gewogICAgeWVhcjogbiwKICAgIG1vbnRoOiBzLAogICAgZGF5OiBuLAogICAgd2Vla2RheTogcywKICB9OwoKICBjb25zdCBEQVRFX0ZVTEwgPSB7CiAgICB5ZWFyOiBuLAogICAgbW9udGg6IGwsCiAgICBkYXk6IG4sCiAgfTsKCiAgY29uc3QgREFURV9IVUdFID0gewogICAgeWVhcjogbiwKICAgIG1vbnRoOiBsLAogICAgZGF5OiBuLAogICAgd2Vla2RheTogbCwKICB9OwoKICBjb25zdCBUSU1FX1NJTVBMRSA9IHsKICAgIGhvdXI6IG4sCiAgICBtaW51dGU6IG4sCiAgfTsKCiAgY29uc3QgVElNRV9XSVRIX1NFQ09ORFMgPSB7CiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogICAgc2Vjb25kOiBuLAogIH07CgogIGNvbnN0IFRJTUVfV0lUSF9TSE9SVF9PRkZTRVQgPSB7CiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogICAgc2Vjb25kOiBuLAogICAgdGltZVpvbmVOYW1lOiBzLAogIH07CgogIGNvbnN0IFRJTUVfV0lUSF9MT05HX09GRlNFVCA9IHsKICAgIGhvdXI6IG4sCiAgICBtaW51dGU6IG4sCiAgICBzZWNvbmQ6IG4sCiAgICB0aW1lWm9uZU5hbWU6IGwsCiAgfTsKCiAgY29uc3QgVElNRV8yNF9TSU1QTEUgPSB7CiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogICAgaG91ckN5Y2xlOiAiaDIzIiwKICB9OwoKICBjb25zdCBUSU1FXzI0X1dJVEhfU0VDT05EUyA9IHsKICAgIGhvdXI6IG4sCiAgICBtaW51dGU6IG4sCiAgICBzZWNvbmQ6IG4sCiAgICBob3VyQ3ljbGU6ICJoMjMiLAogIH07CgogIGNvbnN0IFRJTUVfMjRfV0lUSF9TSE9SVF9PRkZTRVQgPSB7CiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogICAgc2Vjb25kOiBuLAogICAgaG91ckN5Y2xlOiAiaDIzIiwKICAgIHRpbWVab25lTmFtZTogcywKICB9OwoKICBjb25zdCBUSU1FXzI0X1dJVEhfTE9OR19PRkZTRVQgPSB7CiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogICAgc2Vjb25kOiBuLAogICAgaG91ckN5Y2xlOiAiaDIzIiwKICAgIHRpbWVab25lTmFtZTogbCwKICB9OwoKICBjb25zdCBEQVRFVElNRV9TSE9SVCA9IHsKICAgIHllYXI6IG4sCiAgICBtb250aDogbiwKICAgIGRheTogbiwKICAgIGhvdXI6IG4sCiAgICBtaW51dGU6IG4sCiAgfTsKCiAgY29uc3QgREFURVRJTUVfU0hPUlRfV0lUSF9TRUNPTkRTID0gewogICAgeWVhcjogbiwKICAgIG1vbnRoOiBuLAogICAgZGF5OiBuLAogICAgaG91cjogbiwKICAgIG1pbnV0ZTogbiwKICAgIHNlY29uZDogbiwKICB9OwoKICBjb25zdCBEQVRFVElNRV9NRUQgPSB7CiAgICB5ZWFyOiBuLAogICAgbW9udGg6IHMsCiAgICBkYXk6IG4sCiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogIH07CgogIGNvbnN0IERBVEVUSU1FX01FRF9XSVRIX1NFQ09ORFMgPSB7CiAgICB5ZWFyOiBuLAogICAgbW9udGg6IHMsCiAgICBkYXk6IG4sCiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogICAgc2Vjb25kOiBuLAogIH07CgogIGNvbnN0IERBVEVUSU1FX01FRF9XSVRIX1dFRUtEQVkgPSB7CiAgICB5ZWFyOiBuLAogICAgbW9udGg6IHMsCiAgICBkYXk6IG4sCiAgICB3ZWVrZGF5OiBzLAogICAgaG91cjogbiwKICAgIG1pbnV0ZTogbiwKICB9OwoKICBjb25zdCBEQVRFVElNRV9GVUxMID0gewogICAgeWVhcjogbiwKICAgIG1vbnRoOiBsLAogICAgZGF5OiBuLAogICAgaG91cjogbiwKICAgIG1pbnV0ZTogbiwKICAgIHRpbWVab25lTmFtZTogcywKICB9OwoKICBjb25zdCBEQVRFVElNRV9GVUxMX1dJVEhfU0VDT05EUyA9IHsKICAgIHllYXI6IG4sCiAgICBtb250aDogbCwKICAgIGRheTogbiwKICAgIGhvdXI6IG4sCiAgICBtaW51dGU6IG4sCiAgICBzZWNvbmQ6IG4sCiAgICB0aW1lWm9uZU5hbWU6IHMsCiAgfTsKCiAgY29uc3QgREFURVRJTUVfSFVHRSA9IHsKICAgIHllYXI6IG4sCiAgICBtb250aDogbCwKICAgIGRheTogbiwKICAgIHdlZWtkYXk6IGwsCiAgICBob3VyOiBuLAogICAgbWludXRlOiBuLAogICAgdGltZVpvbmVOYW1lOiBsLAogIH07CgogIGNvbnN0IERBVEVUSU1FX0hVR0VfV0lUSF9TRUNPTkRTID0gewogICAgeWVhcjogbiwKICAgIG1vbnRoOiBsLAogICAgZGF5OiBuLAogICAgd2Vla2RheTogbCwKICAgIGhvdXI6IG4sCiAgICBtaW51dGU6IG4sCiAgICBzZWNvbmQ6IG4sCiAgICB0aW1lWm9uZU5hbWU6IGwsCiAgfTsKCiAgLyoqCiAgICogQGludGVyZmFjZQogICAqLwogIGNsYXNzIFpvbmUgewogICAgLyoqCiAgICAgKiBUaGUgdHlwZSBvZiB6b25lCiAgICAgKiBAYWJzdHJhY3QKICAgIC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KICAgICAgfQogICAgICByZXR1cm4gc2luZ2xldG9uJDE7CiAgICB9CgogICAgLyoqIEBvdmVycmlkZSAqKi8KICAgIGdldCB0eXBlKCkgewogICAgICByZXR1cm4gInN5c3RlbSI7CiAgICB9CgogICAgLyoqIEBvdmVycmlkZSAqKi8KICAgIGdldCBuYW1lKCkgewogICAgICByZXR1cm4gbmV3IEludGwuRGF0ZVRpbWVGb3JtYXQoKS5yZXNvbHZlZE9wdGlvbnMoKS50aW1lWm9uZTsKICAgIH0KCiAgICAvKiogQG92ZXJyaWRlICoqLwogICAgZ2V0IGlzVW5pdmVyc2FsKCkgewogICAgICByZXR1cm4gZmFsc2U7CiAgICB9CgogICAgLyoqIEBvdmVycmlkZSAqKi8KICAgIG9mZnNldE5hbWUodHMsIHsgZm9ybWF0LCBsb2NhbGUgfSkgewogICAgICByZXR1cm4gcGFyc2Vab25lSW5mbyh0cywgZm9ybWF0LCBsb2NhbGUpOwogICAgfQoKICAgIC8qKiBAb3ZlcnJpZGUgKiovCiAgICBmb3JtYXRPZmZzZXQodHMsIGZvcm1hdCkgewogICAgICByZXR1cm4gZm9ybWF0T2Zmc2V0KHRoaXMub2Zmc2V0KHRzKSwgZm9ybWF0KTsKICAgIH0KCiAgICAvKiogQG92ZXJyaWRlICoqLwogICAgb2Zmc2V0KHRzKSB7CiAgICAgIHJldHVybiAtbmV3IERhdGUodHMpLmdldFRpbWV6b25lT2Zmc2V0KCk7CiAgICB9CgogICAgLyoqIEBvdmVycmlkZSAqKi8KICAgIGVxdWFscyhvdGhlclpvbmUpIHsKICAgICAgcmV0dXJuIG90aGVyWm9uZS50eXBlID09PSAic3lzdGVtIjsKICAgIH0KCiAgICAvKiogQG92ZXJyaWRlICoqLwogICAgZ2V0IGlzVmFsaWQoKSB7CiAgICAgIHJldHVybiB0cnVlOwogICAgfQogIH0KCiAgbGV0IGR0ZkNhY2hlID0ge307CiAgZnVuY3Rpb24gbWFrZURURih6b25lKSB7CiAgICBpZiAoIWR0Zk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cHV0Q2FsZW5kYXIgfHwgbnVtYmVyaW5nU3lzdGVtKSB7CiAgICAgIGlmICghbG9jYWxlU3RyLmluY2x1ZGVzKCItdS0iKSkgewogICAgICAgIGxvY2FsZVN0ciArPSAiLXUiOwogICAgICB9CgogICAgICBpZiAob3V0cHV0Q2FsZW5kYXIpIHsKICAgICAgICBsb2NhbGVTdHIgKz0gYC1jYS0ke291dHB1dENhbGVuZGFyfWA7CiAgICAgIH0KCiAgICAgIGlmIChudW1iZXJpbmdTeXN0ZW0pIHsKICAgICAgICBsb2NhbGVTdHIgKz0gYC1udS0ke251bWJlcmluZ1N5c3RlbX1gOwogICAgICB9CiAgICAgIHJldHVybiBsb2NhbGVTdHI7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gbG9jYWxlU3RyOwogICAgfQogIH0KCiAgZnVuY3Rpb24gbWFwTW9udGhzKGYpIHsKICAgIGNvbnN0IG1zID0gW107CiAgICBmb3IgKGxldCBpID0gMTsgaSA8PSAxMjsgaSsrKSB7CiAgICAgIGNvbnN0IGR0ID0gRGF0ZVRpbWUudXRjKDIwMDksIGksIDEpOwogICAgICBtcy5wdXNoKGYoZHQpKTsKICAgIH0KICAgIHJldHVybiBtczsKICB9CgogIGZ1bmN0aW9uIG1hcFdlZWtkYXlzKGYpIHsKICAgIGNvbnN0IG1zID0gW107CiAgICBmb3IgKGxldCBpID0gMTsgaSA8PSA3OyBpKyspIHsKICAgICAgY29uc3QgZHQgPSBEYXRlVGltZS51dGMoMjAxNiwgMTEsIDEzICsgaSk7CiAgICAgIG1zLnB1c2goZihkdCkpOwogICAgfQogICAgcmV0dXJuIG1zOwogIH0KCiAgZnVuY3Rpb24gbGlzdFN0dWZmKGxvYywgbGVuZ3RoLCBlbmdsaXNoRm4sIGludGxGbikgewogICAgY29uc3QgbW9kZSA9IGxvYy5saXN0aW5nTW9kZSgpOwoKICAgIGlmIChtb2RlID09PSAiZXJyb3IiKSB7CiAgICAgIHJldHVybiBudWxsOwogICAgfSBl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ic3RpdHV0ZSBpbiB0aGUgYWN0dWFsIHpvbmUgbmFtZSwgd2UgaGF2ZSB0byB1c2UKICAgICAgICAvLyBmb3JtYXRUb1BhcnRzIHNvIHRoYXQgdGhlIHRpbWV6b25lIGNhbiBiZSByZXBsYWNlZC4KICAgICAgICByZXR1cm4gdGhpcy5mb3JtYXRUb1BhcnRzKCkKICAgICAgICAgIC5tYXAoKHsgdmFsdWUgfSkgPT4gdmFsdWUpCiAgICAgICAgICAuam9pbigiIik7CiAgICAgIH0KICAgICAgcmV0dXJuIHRoaXMuZHRmLmZvcm1hdCh0aGlzLmR0LnRvSlNEYXRlKCkpOwogICAgfQoKICAgIGZvcm1hdFRvUGFydHMoKSB7CiAgICAgIGNvbnN0IHBhcnRzID0gdGhpcy5kdGYuZm9ybWF0VG9QYXJ0cyh0aGlzLmR0LnRvSlNEYXRlKCkpOwogICAgICBpZiAodGhpcy5vcmlnaW5hbFpvbmUpIHsKICAgICAgICByZXR1cm4gcGFydHMubWFwKChwYXJ0KSA9PiB7CiAgICAgICAgICBpZiAocGFydC50eXBlID09PSAidGltZVpvbmVOYW1lIikgewogICAgICAgICAgICBjb25zdCBvZmZzZXROYW1lID0gdGhpcy5vcmlnaW5hbFpvbmUub2Zmc2V0TmFtZSh0aGlzLmR0LnRzLCB7CiAgICAgICAgICAgICAgbG9jYWxlOiB0aGlzLmR0LmxvY2FsZSwKICAgICAgICAgICAgICBmb3JtYXQ6IHRoaXMub3B0cy50aW1lWm9uZU5hbWUsCiAgICAgICAgICAgIH0pOwogICAgICAgICAgICByZXR1cm4gewogICAgICAgICAgICAgIC4uLnBhcnQsCiAgICAgICAgICAgICAgdmFsdWU6IG9mZnNldE5hbWUsCiAgICAgICAgICAgIH07CiAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICByZXR1cm4gcGFydDsKICAgICAgICAgIH0KICAgICAgICB9KTsKICAgICAgfQogICAgICByZXR1cm4gcGFydHM7CiAgICB9CgogICAgcmVzb2x2ZWRPcHR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IG90aGVyWm9uZS50eXBlID09PSAiZml4ZWQiICYmIG90aGVyWm9uZS5maXhlZCA9PT0gdGhpcy5maXhlZDsKICAgIH0KCiAgICAvKiogQG92ZXJyaWRlICoqLwogICAgZ2V0IGlzVmFsaWQoKSB7CiAgICAgIHJldHVybiB0cnVlOwogICAgfQogIH0KCiAgLyoqCiAgICogQSB6b25lIHRoYXQgZmFpbGVkIHRvIHBhcnNlLiBZb3Ugc2hvdWxkIG5ldmVyIG5lZWQgdG8gaW5zdGFudGlhdGUgdGhpcy4KICAgKiBAaW1wbGVtZW50cyB7Wm9uZX0KICAgKi8KICBjbGFzcyBJbnZhbGlkWm9uZSBleHRlbmRzIFpvbmUgewogICAgY29uc3RydWN0b3Ioem9uZU5hbWUpIHsKICAgICAgc3VwZXIoKTsKICAgICAgLyoqICBAcHJpdmF0ZSAqLwogICAgICB0aGlzLnpvbmVOYW1lID0gem9uZU5hbWU7CiAgICB9CgogICAgLyoqIEBvdmVycmlkZSAqKi8KICAgIGdldCB0eXBlKCkgewogICAgICByZXR1cm4gImludmFsaWQiOwogICAgfQoKICAgIC8qKiBAb3ZlcnJpZGUgKiovCiAgICBnZXQgbmFtZSgpIHsKICAgICAgcmV0dXJuIHRoaXMuem9uZU5hbWU7CiAgICB9CgogICAgLyoqIEBvdmVycmlkZSAqKi8KICAgIGdldCBpc1VuaXZlcnNhbCgpIHsKICAgICAgcmV0dXJuIGZhbHNlOwogICAgfQoKICAgIC8qKiBAb3ZlcnJpZGUgKiovCiAgICBvZmZzZXROYW1lKCkgewogICAgICByZXR1cm4gbnVsbDsKICAgIH0KCiAgICAvKiogQG92ZXJyaWRlICoqLwogICAgZm9ybWF0T2Zmc2V0KCkgewogICAgICByZXR1cm4gIiI7CiAgICB9CgogICAgLyoqIEBvdmVycmlkZSAqKi8KICAgIG9mZnNldCgpIHsKICAgICAgcmV0dXJuIE5hTjsKICAgIH0KCiAgICAvKiogQG92ZXJyaWRlICoqLwogICAgZXF1YWxzKCkgewogIC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hbmdlIGZvciBwcm9wZXJ0eSBmb3JtYXRgKTsKICAgIH0KICB9CgogIGZ1bmN0aW9uIHRpbWVPYmplY3Qob2JqKSB7CiAgICByZXR1cm4gcGljayhvYmosIFsiaG91ciIsICJtaW51dGUiLCAic2Vjb25kIiwgIm1pbGxpc2Vjb25kIl0pOwogIH0KCiAgLyoqCiAgICogQHByaXZhdGUKICAgKi8KCiAgY29uc3QgbW9udGhzTG9uZyA9IFsKICAgICJKYW51YXJ5IiwKICAgICJGZWJydWFyeSIsCiAgICAiTWFyY2giLAogICAgIkFwcmlsIiwKICAgICJNYXkiLAogICAgIkp1bmUiLAogICAgIkp1bHkiLAogICAgIkF1Z3VzdCIsCiAgICAiU2VwdGVtYmVyIiwKICAgICJPY3RvYmVyIiwKICAgICJOb3ZlbWJlciIsCiAgICAiRGVjZW1iZXIiLAogIF07CgogIGNvbnN0IG1vbnRoc1Nob3J0ID0gWwogICAgIkphbiIsCiAgICAiRmViIiwKICAgICJNYXIiLAogICAgIkFwciIsCiAgICAiTWF5IiwKICAgICJKdW4iLAogICAgIkp1bCIsCiAgICAiQXVnIiwKICAgICJTZXAiLAogICAgIk9jdCIsCiAgICAiTm92IiwKICAgICJEZWMiLAogIF07CgogIGNvbnN0IG1vbnRoc05hcnJvdyA9IFsiSiIsICJGIiwgIk0iLCAiQSIsICJNIiwgIkoiLCAiSiIsICJBIiwgIlMiLCAiTyIsICJOIiwgIkQiXTsKCiAgZnVuY3Rpb24gbW9udGhzKGxlbmd0aCkgewogICAgc3dpdGNoIChsZW5ndGgpIHsKICAgICAgY2FzZSAibmFycm93IjoKICAgICAgICByZXR1cm4gWy4uLm1vbnRoc05hcnJvd107CiAgICAgIGNhc2UgInNob3J0IjoKICAgICAgICByZXR1cm4gWy4uLm1vbnRoc1Nob3J0XTsKICAgICAgY2FzZSAibG9uZyI6CiAgICAgICAgcmV0dXJuIFsuLi5tb250aHNMb25nXTsKICAgICAgY2FzZSAibnVtZXJpYyI6CiAgICAgICAg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cyIsIG5hcnJvdyA9IGZhbHNlKSB7CiAgICBjb25zdCB1bml0cyA9IHsKICAgICAgeWVhcnM6IFsieWVhciIsICJ5ci4iXSwKICAgICAgcXVhcnRlcnM6IFsicXVhcnRlciIsICJxdHIuIl0sCiAgICAgIG1vbnRoczogWyJtb250aCIsICJtby4iXSwKICAgICAgd2Vla3M6IFsid2VlayIsICJ3ay4iXSwKICAgICAgZGF5czogWyJkYXkiLCAiZGF5IiwgImRheXMiXSwKICAgICAgaG91cnM6IFsiaG91ciIsICJoci4iXSwKICAgICAgbWludXRlczogWyJtaW51dGUiLCAibWluLiJdLAogICAgICBzZWNvbmRzOiBbInNlY29uZCIsICJzZWMuIl0sCiAgICB9OwoKICAgIGNvbnN0IGxhc3RhYmxlID0gWyJob3VycyIsICJtaW51dGVzIiwgInNlY29uZHMiXS5pbmRleE9mKHVuaXQpID09PSAtMTsKCiAgICBpZiAobnVtZXJpYyA9PT0gImF1dG8iICYmIGxhc3RhYmxlKSB7CiAgICAgIGNvbnN0IGlzRGF5ID0gdW5pdCA9PT0gImRheXMiOwogICAgICBzd2l0Y2ggKGNvdW50KSB7CiAgICAgICAgY2FzZSAxOgogICAgICAgICAgcmV0dXJuIGlzRGF5ID8gInRvbW9ycm93IiA6IGBuZXh0ICR7dW5pdHNbdW5pdF1bMF19YDsKICAgICAgICBjYXNlIC0xOgogICAgICAgICAgcmV0dXJuIGlzRGF5ID8gInllc3RlcmRheSIgOiBgbGFzdCAke3VuaXRzW3VuaXRdWzBdfWA7CiAgICAgICAgY2FzZSAwOgogICAgICAgICAgcmV0dXJuIGlzRGF5ID8gInRvZGF5IiA6IGB0aGlzICR7dW5pdHNbdW5pdF1bMF19YDsKICAgICAgfQogICAgfQoKICAgIGNvbnN0IGlzSW5QYXN0ID0gT2JqZWN0LmlzKGNvdW50LCAtMCkgfHwgY291bnQgPCAwLAogICAgICBmbXRWYWx1ZSA9IE1hdGguYWJzKGNvdW50KSwKICAgICAgc2luZ3VsYXIgPSBmbXRWYWx1ZSA9PT0gMSwKICAgICAgbGlsVW5pdHMgPSB1bml0c1t1bml0XSwKICAgICAgZm10VW5pdCA9IG5hcnJvdwogICAgICAgID8gc2luZ3VsYXIKICAgICAgICAgID8gbGlsVW5pdHNbMV0KICAgICAgICAgIDogbGlsVW5pdHNbMl0gfHwgbGlsVW5pdHNbMV0KICAgICAgICA6IHNpbmd1bGFyCiAgICAgICAgPyB1bml0c1t1bml0XVswXQogICAgICAgIDogdW5pdDsKICAgIHJldHVybiBpc0luUGFzdCA/IGAke2ZtdFZhbHVlfSAke2ZtdFVuaXR9IGFnb2AgOiBgaW4gJHtmbXRWYWx1ZX0gJHtmbXRVbml0fWA7CiAgfQoKICBmdW5jdGlvbiBzdHJpbmdpZnlUb2tlbnMoc3BsaXRzLCB0b2tlblRvU3RyaW5nKSB7CiAgICBsZXQgcyA9ICIiOwogICAgZm9yIChjb25zdCB0b2tlbiBvZiBzcGxpdHMpIHsKICAgICAgaWYgKHRva2VuLmxpdGVyYWwpIHsKICAgICAgICBzICs9IHRva2VuLnZhbDsKICAgICAgfSBlbHNlIHsKICAgICAgICBzICs9IHRva2VuVG9TdHJpbmcodG9rZW4udmFsKTsKICAgICAgfQogICAgfQogICAgcmV0dXJuIHM7CiAgfQoKICBjb25zdCBtYWNyb1Rva2VuVG9Gb3JtYXRPcHRzID0gewogICAgRDogREFURV9TSE9SVCwKICAgIEREOiBEQVRFX01FRCwKICAgIERERDogREFURV9GVUxMLAogICAgRERERDogREFURV9IVUdFLAogICAgdDogVElNRV9TSU1QTEUsCiAgICB0dDogVElNRV9XSVRIX1NFQ09ORFMsCiAgICB0dHQ6IFRJTUVfV0lUSF9TSE9SVF9PRkZTRVQsCiAgICB0dHR0OiBUSU1FX1dJVEhfTE9OR19PRkZTRVQsCiAgICBUOiBUSU1FXzI0X1NJTVBMRSwKICAgIFRUOiBUSU1FXzI0X1dJVEhfU0VDT05EUywKICAgIFRUVDogVElNRV8yNF9XSVRIX1NIT1JUX09G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IH0KCiAgICByZXNvbHZlZE9wdGlvbnMoZHQsIG9wdHMpIHsKICAgICAgcmV0dXJuIHRoaXMuZHRGb3JtYXR0ZXIoZHQsIG9wdHMpLnJlc29sdmVkT3B0aW9ucygpOwogICAgfQoKICAgIG51bShuLCBwID0gMCkgewogICAgICAvLyB3ZSBnZXQgc29tZSBwZXJmIG91dCBvZiBkb2luZyB0aGlzIGhlcmUsIGFubm95aW5nbHkKICAgICAgaWYgKHRoaXMub3B0cy5mb3JjZVNpbXBsZSkgewogICAgICAgIHJldHVybiBwYWRTdGFydChuLCBwKTsKICAgICAgfQoKICAgICAgY29uc3Qgb3B0cyA9IHsgLi4udGhpcy5vcHRzIH07CgogICAgICBpZiAocCA+IDApIHsKICAgICAgICBvcHRzLnBhZFRvID0gcDsKICAgICAgfQoKICAgICAgcmV0dXJuIHRoaXMubG9jLm51bWJlckZvcm1hdHRlcihvcHRzKS5mb3JtYXQobik7CiAgICB9CgogICAgZm9ybWF0RGF0ZVRpbWVGcm9tU3RyaW5nKGR0LCBmbXQpIHsKICAgICAgY29uc3Qga25vd25FbmdsaXNoID0gdGhpcy5sb2MubGlzdGluZ01vZGUoKSA9PT0gImVuIiwKICAgICAgICB1c2VEYXRlVGltZUZvcm1hdHRlciA9IHRoaXMubG9jLm91dHB1dENhbGVuZGFyICYmIHRoaXMubG9jLm91dHB1dENhbGVuZGFyICE9PSAiZ3JlZ29yeSIsCiAgICAgICAgc3RyaW5nID0gKG9wdHMsIGV4dHJhY3QpID0+IHRoaXMubG9jLmV4dHJhY3QoZHQsIG9wdHMsIGV4dHJhY3QpLAogICAgICAgIGZvcm1hdE9mZnNldCA9IChvcHRzKSA9PiB7CiAgICAgICAgICBpZiAoZHQuaXNPZmZzZXRGaXhlZCAmJiBkdC5vZmZzZXQgPT09IDAgJiYgb3B0cy5hbGxvd1opIHsKICAgICAgICAgICAgcmV0dXJuICJaIjsKICAgICAgICAgIH0KCiAgICAgICAgICByZXR1cm4gZHQuaXNWYWxpZCA/IGR0LnpvbmUuZm9ybWF0T2Zmc2V0KGR0LnRzLCBvcHRzLmZvcm1hdCkgOiAiIjsKICAgICAgICB9LAogICAgICAgIG1lcmlkaWVtID0gKCkgPT4KICAgICAgICAgIGtub3duRW5nbGlzaAogICAgICAgICAgICA/IG1lcmlkaWVtRm9yRGF0ZVRpbWUoZHQpCiAgICAgICAgICAgIDogc3RyaW5nKHsgaG91cjogIm51bWVyaWMiLCBob3VyQ3ljbGU6ICJoMTIiIH0sICJkYXlwZXJpb2QiKSwKICAgICAgICBtb250aCA9IChsZW5ndGgsIHN0YW5kYWxvbmUpID0+CiAgICAgICAgICBrbm93bkVuZ2xpc2gKICAgICAgICAgICAgPyBtb250aEZvckRhdGVUaW1lKGR0LCBsZW5ndGgpCiAgICAgICAgICAgIDogc3RyaW5nKHN0YW5kYWxvbmUgPyB7IG1vbnRoOiBsZW5ndGggfSA6IHsgbW9udGg6IGxlbmd0aCwgZGF5OiAibnVtZXJpYyIgfSwgIm1vbnRoIiksCiAgICAgICAgd2Vla2RheSA9IChsZW5ndGgsIHN0YW5kYWxvbmUpID0+CiAgICAgICAgICBrbm93bkVuZ2xpc2gKICAgICAgICAgICAgPyB3ZWVrZGF5Rm9yRGF0ZVRpbWUoZHQsIGxlbmd0aCkKICAgICAgICAgICAgOiBzdHJpbmcoCiAgICAgICAgICAgICAgICBzdGFuZGFsb25lID8geyB3ZWVrZGF5OiBsZW5ndGggfSA6IHsgd2Vla2RheTogbGVuZ3RoLCBtb250aDogImxvbmciLCBkYXk6ICJudW1lcmljIiB9LAogICAgICAgICAgICAgICAgIndlZWtkYXkiCiAgICAgICAgICAgICAgKSwKICAgICAgICBtYXliZU1hY3JvID0gKHRva2VuKSA9PiB7CiAgICAgICAgICBjb25zdCBmb3JtYXRPcHRzID0gRm9ybWF0dGVyLm1hY3JvVG9rZW5Ub0Zvcm1hdE9wdHModG9rZW4pOwogICAgICAgICAgaWYgKGZvcm1hdE9wdHMpIHsKICAgICAgICAgICAgcmV0dXJuIHRoaXMuZm9ybWF0V2l0aFN5c3RlbURlZmF1bHQoZHQsIGZvcm1hdE9wdHMpOwogICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgcmV0dXJuIHRva2VuOwogICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICAgZXJhID0gKGxlbmd0aCkgPT4KICAgICAgICAgIGtub3duRW5nbGlzaCA/IGVyYUZvckRhdGVUaW1lKGR0LCBsZW5ndGgpIDogc3RyaW5nKHsgZXJhOiBsZW5ndGggfSwgImVyYSIpLAogICAgICAgIHRva2VuVG9TdHJpbmcgPSAodG9rZW4pID0+IHsKICAgICAgICAgIC8vIFdoZXJlIHBvc3NpYmxlOiBodHRwczovL2NsZHIudW5pY29kZS5vcmcvdHJhbnNsYXRpb24vZGF0ZS10aW1lL2RhdGUtdGltZS1zeW1ib2xzCiAgICAgICAgICBzd2l0Y2ggKHRva2VuKSB7CiAgICAgICAgICAgIC8vIG1zCiAgICAgICAgICAgIGNhc2UgIlMiOgogICAgICAgICAgICAgIHJldHVybiB0aGlzLm51bShkdC5taWxsaXNlY29uZCk7CiAgICAgICAgICAgIGNhc2UgInUiOgogICAgICAgICAgICAvLyBmYWxscyB0aHJvdWdoCiAgICAgICAgICAgIGNhc2UgIlNTUyI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0Lm1pbGxpc2Vjb25kLCAzKTsKICAgICAgICAgICAgLy8gc2Vjb25kcwogICAgICAgICAgICBjYXNlICJzIjoKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oZHQuc2Vjb25kKTsKICAgICAgICAgICAgY2FzZSAic3MiOgogICAgICAgICAgICAgIHJldHVybiB0aGlzLm51bShkdC5zZWNvbmQsIDIpOwogICAgICAgICAgICAvLyBmcmFjdGlvbmFsIHNlY29uZHMKICAgICAgICAgICAgY2FzZSAidXUiOgogICAgICAgICAgICAgIHJldHVybiB0aGlzLm51bShNYXRoLmZsb29yKGR0Lm1pbGxpc2Vjb25kIC8gMTApLCAyKTsKICAgICAgICAgICAgY2FzZSAidXV1IjoKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oTWF0aC5mbG9vcihkdC5taWxsaXNlY29uZCAvIDEwMCkpOwogICAgICAgICAgICAvLyBtaW51dGVzCiAgICAgICAgICAgIGNhc2UgIm0iOgogICAgICAgICAgICAgIHJldHVybiB0aGlzLm51bShkdC5taW51dGUpOwogICAgICAgICAgICBjYXNlICJtbSI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0Lm1pbnV0ZSwgMik7CiAgICAgICAgICAgIC8vIGhvdXJzCiAgICAgICAgICAgIGNhc2UgImgiOgogICAgICAgICAgICAgIHJldHVybiB0aGlzLm51bShkdC5ob3VyICUgMTIgPT09IDAgPyAxMiA6IGR0LmhvdXIgJSAxMik7CiAgICAgICAgICAgIGNhc2UgImhoIjoKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oZHQuaG91ciAlIDEyID09PSAwID8gMTIgOiBkdC5ob3VyICUgMTIsIDIpOwogICAgICAgICAgICBjYXNlICJIIjoKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oZHQuaG91cik7CiAgICAgICAgICAgIGNhc2UgIkhIIjoKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oZHQuaG91ciwgMik7CiAgICAgICAgICAgIC8vIG9mZnNldAogICAgICAgICAgICBjYXNlICJaIjoKICAgICAgICAgICAgICAvLyBsaWtlICs2CiAgICAgICAgICAgICAgcmV0dXJuIGZvcm1hdE9mZnNldCh7IGZvcm1hdDogIm5hcnJvdyIsIGFsbG93WjogdGhpcy5vcHRzLmFsbG93WiB9KTsKICAgICAgICAgICAgY2FzZSAiWloiOgogICAgICAgICAgICAgIC8vIGxpa2UgKzA2OjAwCiAgICAgICAgICAgICAgcmV0dXJuIGZvcm1hdE9mZnNldCh7IGZvcm1hdDogInNob3J0IiwgYWxsb3daOiB0aGlzLm9wdHMuYWxsb3daIH0pOwogICAgICAgICAgICBjYXNlICJaWloiOgogICAgICAgICAgICAgIC8vIGxpa2UgKzA2MDAKICAgICAgICAgICAgICByZXR1cm4gZm9ybWF0T2Zmc2V0KHsgZm9ybWF0OiAidGVjaGllIiwgYWxsb3daOiB0aGlzLm9wdHMuYWxsb3daIH0pOwogICAgICAgICAgICBjYXNlICJaWlpaIjoKICAgICAgICAgICAgICAvLyBsaWtlIEVTVAogICAgICAgICAgICAgIHJldHVybiBkdC56b25lLm9mZnNldE5hbWUoZHQudHMsIHsgZm9ybWF0OiAic2hvcnQiLCBsb2NhbGU6IHRoaXMubG9jLmxvY2FsZSB9KTsKICAgICAgICAgICAgY2FzZSAiWlpaWloiOgogICAgICAgICAgICAgIC8vIGxpa2UgRWFzdGVybiBTdGFuZGFyZCBUaW1lCiAgICAgICAgICAgICAgcmV0dXJuIGR0LnpvbmUub2Zmc2V0TmFtZShkdC50cywgeyBmb3JtYXQ6ICJsb25nIiwgbG9jYWxlOiB0aGlzLmxvYy5sb2NhbGUgfSk7CiAgICAgICAgICAgIC8vIHpvbmUKICAgICAgICAgICAgY2FzZSAieiI6CiAgICAgICAgICAgICAgLy8gbGlrZSBBbWVyaWNhL05ld19Zb3JrCiAgICAgICAgICAgICAgcmV0dXJuIGR0LnpvbmVOYW1lOwogICAgICAgICAgICAvLyBtZXJpZGllbXMKICAgICAgICAgICAgY2FzZSAiYSI6CiAgICAgICAgICAgICAgcmV0dXJuIG1lcmlkaWVtKCk7CiAgICAgICAgICAgIC8vIGRhdGVzCiAgICAgICAgICAgIGNhc2UgImQiOgogICAgICAgICAgICAgIHJldHVybiB1c2VEYXRlVGltZUZvcm1hdHRlciA/IHN0cmluZyh7IGRheTogIm51bWVyaWMiIH0sICJkYXkiKSA6IHRoaXMubnVtKGR0LmRheSk7CiAgICAgICAgICAgIGNhc2UgImRkIjoKICAgICAgICAgICAgICByZXR1cm4gdXNlRGF0ZVRpbWVGb3JtYXR0ZXIgPyBzdHJpbmcoeyBkYXk6ICIyLWRpZ2l0IiB9LCAiZGF5IikgOiB0aGlzLm51bShkdC5kYXksIDIpOwogICAgICAgICAgICAvLyB3ZWVrZGF5cyAtIHN0YW5kYWxvbmUKICAgICAgICAgICAgY2FzZSAiYyI6CiAgICAgICAgICAgICAgLy8gbGlrZSAxCiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0LndlZWtkYXkpOwogICAgICAgICAgICBjYXNlICJjY2MiOgogICAgICAgICAgICAgIC8vIGxpa2UgJ1R1ZXMnCiAgICAgICAgICAgICAgcmV0dXJuIHdlZWtkYXkoInNob3J0IiwgdHJ1ZSk7CiAgICAgICAgICAgIGNhc2UgImNjY2MiOgogICAgICAgICAgICAgIC8vIGxpa2UgJ1R1ZXNkYXknCiAgICAgICAgICAgICAgcmV0dXJuIHdlZWtkYXkoImxvbmciLCB0cnVlKTsKICAgICAgICAgICAgY2FzZSAiY2NjY2MiOgogICAgICAgICAgICAgIC8vIGxpa2UgJ1QnCiAgICAgICAgICAgICAgcmV0dXJuIHdlZWtkYXkoIm5hcnJvdyIsIHRydWUpOwogICAgICAgICAgICAvLyB3ZWVrZGF5cyAtIGZvcm1hdAogICAgICAgICAgICBjYXNlICJFIjoKICAgICAgICAgICAgICAvLyBsaWtlIDEKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oZHQud2Vla2RheSk7CiAgICAgICAgICAgIGNhc2UgIkVFRSI6CiAgICAgICAgICAgICAgLy8gbGlrZSAnVHVlcycKICAgICAgICAgICAgICByZXR1cm4gd2Vla2RheSgic2hvcnQiLCBmYWxzZSk7CiAgICAgICAgICAgIGNhc2UgIkVFRUUiOgogICAgICAgICAgICAgIC8vIGxpa2UgJ1R1ZXNkYXknCiAgICAgICAgICAgICAgcmV0dXJuIHdlZWtkYXkoImxvbmciLCBmYWxzZSk7CiAgICAgICAgICAgIGNhc2UgIkVFRUVFIjoKICAgICAgICAgICAgICAvLyBsaWtlICdUJwogICAgICAgICAgICAgIHJldHVybiB3ZWVrZGF5KCJuYXJyb3ciLCBmYWxzZSk7CiAgICAgICAgICAgIC8vIG1vbnRocyAtIHN0YW5kYWxvbmUKICAgICAgICAgICAgY2FzZSAiTCI6CiAgICAgICAgICAgICAgLy8gbGlrZSAxCiAgICAgICAgICAgICAgcmV0dXJuIHVzZURhdGVUaW1lRm9ybWF0dGVyCiAgICAgICAgICAgICAgICA/IHN0cmluZyh7IG1vbnRoOiAibnVtZXJpYyIsIGRheTogIm51bWVyaWMiIH0sICJtb250aCIpCiAgICAgICAgICAgICAgICA6IHRoaXMubnVtKGR0Lm1vbnRoKTsKICAgICAgICAgICAgY2FzZSAiTEwiOgogICAgICAgICAgICAgIC8vIGxpa2UgMDEsIGRvZXNuJ3Qgc2VlbSB0byB3b3JrCiAgICAgICAgICAgICAgcmV0dXJuIHVzZURhdGVUaW1lRm9ybWF0dGVyCiAgICAgICAgICAgICAgICA/IHN0cmluZyh7IG1vbnRoOiAiMi1kaWdpdCIsIGRheTogIm51bWVyaWMiIH0sICJtb250aCIpCiAgICAgICAgICAgICAgICA6IHRoaXMubnVtKGR0Lm1vbnRoLCAyKTsKICAgICAgICAgICAgY2FzZSAiTExMIjoKICAgICAgICAgICAgICAvLyBsaWtlIEphbgogICAgICAgICAgICAgIHJldHVybiBtb250aCgic2hvcnQiLCB0cnVlKTsKICAgICAgICAgICAgY2FzZSAiTExMTCI6CiAgICAgICAgICAgICAgLy8gbGlrZSBKYW51YXJ5CiAgICAgICAgICAgICAgcmV0dXJuIG1vbnRoKCJsb25nIiwgdHJ1ZSk7CiAgICAgICAgICAgIGNhc2UgIkxMTExMIjoKICAgICAgICAgICAgICAvLyBsaWtlIEoKICAgICAgICAgICAgICByZXR1cm4gbW9udGgoIm5hcnJvdyIsIHRydWUpOwogICAgICAgICAgICAvLyBtb250aHMgLSBmb3JtYXQKICAgICAgICAgICAgY2FzZSAiTSI6CiAgICAgICAgICAgICAgLy8gbGlrZSAxCiAgICAgICAgICAgICAgcmV0dXJuIHVzZURhdGVUaW1lRm9ybWF0dGVyCiAgICAgICAgICAgICAgICA/IHN0cmluZyh7IG1vbnRoOiAibnVtZXJpYyIgfSwgIm1vbnRoIikKICAgICAgICAgICAgICAgIDogdGhpcy5udW0oZHQubW9udGgpOwogICAgICAgICAgICBjYXNlICJNTSI6CiAgICAgICAgICAgICAgLy8gbGlrZSAwMQogICAgICAgICAgICAgIHJldHVybiB1c2VEYXRlVGltZUZvcm1hdHRlcgogICAgICAgICAgICAgICAgPyBzdHJpbmcoeyBtb250aDogIjItZGlnaXQiIH0sICJtb250aCIpCiAgICAgICAgICAgICAgICA6IHRoaXMubnVtKGR0Lm1vbnRoLCAyKTsKICAgICAgICAgICAgY2FzZSAiTU1NIjoKICAgICAgICAgICAgICAvLyBsaWtlIEphbgogICAgICAgICAgICAgIHJldHVybiBtb250aCgic2hvcnQiLCBmYWxzZSk7CiAgICAgICAgICAgIGNhc2UgIk1NTU0iOgogICAgICAgICAgICAgIC8vIGxpa2UgSmFudWFyeQogICAgICAgICAgICAgIHJldHVybiBtb250aCgibG9uZyIsIGZhbHNlKTsKICAgICAgICAgICAgY2FzZSAiTU1NTU0iOgogICAgICAgICAgICAgIC8vIGxpa2UgSgogICAgICAgICAgICAgIHJldHVybiBtb250aCgibmFycm93IiwgZmFsc2UpOwogICAgICAgICAgICAvLyB5ZWFycwogICAgICAgICAgICBjYXNlICJ5IjoKICAgICAgICAgICAgICAvLyBsaWtlIDIwMTQKICAgICAgICAgICAgICByZXR1cm4gdXNlRGF0ZVRpbWVGb3JtYXR0ZXIgPyBzdHJpbmcoeyB5ZWFyOiAibnVtZXJpYyIgfSwgInllYXIiKSA6IHRoaXMubnVtKGR0LnllYXIpOwogICAgICAgICAgICBjYXNlICJ5eSI6CiAgICAgICAgICAgICAgLy8gbGlrZSAxNAogICAgICAgICAgICAgIHJldHVybiB1c2VEYXRlVGltZUZvcm1hdHRlcgogICAgICAgICAgICAgICAgPyBzdHJpbmcoeyB5ZWFyOiAiMi1kaWdpdCIgfSwgInllYXIiKQogICAgICAgICAgICAgICAgOiB0aGlzLm51bShkdC55ZWFyLnRvU3RyaW5nKCkuc2xpY2UoLTIpLCAyKTsKICAgICAgICAgICAgY2FzZSAieXl5eSI6CiAgICAgICAgICAgICAgLy8gbGlrZSAwMDEyCiAgICAgICAgICAgICAgcmV0dXJuIHVzZURhdGVUaW1lRm9ybWF0dGVyCiAgICAgICAgICAgICAgICA/IHN0cmluZyh7IHllYXI6ICJudW1lcmljIiB9LCAieWVhciIpCiAgICAgICAgICAgICAgICA6IHRoaXMubnVtKGR0LnllYXIsIDQpOwogICAgICAgICAgICBjYXNlICJ5eXl5eXkiOgogICAgICAgICAgICAgIC8vIGxpa2UgMDAwMDEyCiAgICAgICAgICAgICAgcmV0dXJuIHVzZURhdGVUaW1lRm9ybWF0dGVyCiAgICAgICAgICAgICAgICA/IHN0cmluZyh7IHllYXI6ICJudW1lcmljIiB9LCAieWVhciIpCiAgICAgICAgICAgICAgICA6IHRoaXMubnVtKGR0LnllYXIsIDYpOwogICAgICAgICAgICAvLyBlcmFzCiAgICAgICAgICAgIGNhc2UgIkciOgogICAgICAgICAgICAgIC8vIGxpa2UgQUQKICAgICAgICAgICAgICByZXR1cm4gZXJhKCJzaG9ydCIpOwogICAgICAgICAgICBjYXNlICJHRyI6CiAgICAgICAgICAgICAgLy8gbGlrZSBBbm5vIERvbWluaQogICAgICAgICAgICAgIHJldHVybiBlcmEoImxvbmciKTsKICAgICAgICAgICAgY2FzZSAiR0dHR0ciOgogICAgICAgICAgICAgIHJldHVybiBlcmEoIm5hcnJvdyIpOwogICAgICAgICAgICBjYXNlICJrayI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0LndlZWtZZWFyLnRvU3RyaW5nKCkuc2xpY2UoLTIpLCAyKTsKICAgICAgICAgICAgY2FzZSAia2trayI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0LndlZWtZZWFyLCA0KTsKICAgICAgICAgICAgY2FzZSAiVyI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0LndlZWtOdW1iZXIpOwogICAgICAgICAgICBjYXNlICJXVyI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0LndlZWtOdW1iZXIsIDIpOwogICAgICAgICAgICBjYXNlICJvIjoKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oZHQub3JkaW5hbCk7CiAgICAgICAgICAgIGNhc2UgIm9vbyI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0Lm9yZGluYWwsIDMpOwogICAgICAgICAgICBjYXNlICJxIjoKICAgICAgICAgICAgICAvLyBsaWtlIDEKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oZHQucXVhcnRlcik7CiAgICAgICAgICAgIGNhc2UgInFxIjoKICAgICAgICAgICAgICAvLyBsaWtlIDAxCiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0LnF1YXJ0ZXIsIDIpOwogICAgICAgICAgICBjYXNlICJYIjoKICAgICAgICAgICAgICByZXR1cm4gdGhpcy5udW0oTWF0aC5mbG9vcihkdC50cyAvIDEwMDApKTsKICAgICAgICAgICAgY2FzZSAieCI6CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGR0LnRzKTsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICByZXR1cm4gbWF5YmVNYWNybyh0b2tlbik7CiAgICAgICAgICB9CiAgICAgICAgfTsKCiAgICAgIHJldHVybiBzdHJpbmdpZnlUb2tlbnMoRm9ybWF0dGVyLnBhcnNlRm9ybWF0KGZtdCksIHRva2VuVG9TdHJpbmcpOwogICAgfQoKICAgIGZvcm1hdER1cmF0aW9uRnJvbVN0cmluZyhkdXIsIGZtdCkgewogICAgICBjb25zdCB0b2tlblRvRmllbGQgPSAodG9rZW4pID0+IHsKICAgICAgICAgIHN3aXRjaCAodG9rZW5bMF0pIHsKICAgICAgICAgICAgY2FzZSAiUyI6CiAgICAgICAgICAgICAgcmV0dXJuICJtaWxsaXNlY29uZCI7CiAgICAgICAgICAgIGNhc2UgInMiOgogICAgICAgICAgICAgIHJldHVybiAic2Vjb25kIjsKICAgICAgICAgICAgY2FzZSAibSI6CiAgICAgICAgICAgICAgcmV0dXJuICJtaW51dGUiOwogICAgICAgICAgICBjYXNlICJoIjoKICAgICAgICAgICAgICByZXR1cm4gImhvdXIiOwogICAgICAgICAgICBjYXNlICJkIjoKICAgICAgICAgICAgICByZXR1cm4gImRheSI7CiAgICAgICAgICAgIGNhc2UgInciOgogICAgICAgICAgICAgIHJldHVybiAid2VlayI7CiAgICAgICAgICAgIGNhc2UgIk0iOgogICAgICAgICAgICAgIHJldHVybiAibW9udGgiOwogICAgICAgICAgICBjYXNlICJ5IjoKICAgICAgICAgICAgICByZXR1cm4gInllYXIiOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgIHJldHVybiBudWxsOwogICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICAgdG9rZW5Ub1N0cmluZyA9IChsaWxkdXIpID0+ICh0b2tlbikgPT4gewogICAgICAgICAgY29uc3QgbWFwcGVkID0gdG9rZW5Ub0ZpZWxkKHRva2VuKTsKICAgICAgICAgIGlmIChtYXBwZWQpIHsKICAgICAgICAgICAgcmV0dXJuIHRoaXMubnVtKGxpbGR1ci5nZXQobWFwcGVkKSwgdG9rZW4ubGVuZ3RoKTsKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHJldHVybiB0b2tlbjsKICAgICAgICAgIH0KICAgICAgICB9LAogICAgICAgIHRva2VucyA9IEZvcm1hdHRlci5wYXJzZUZvcm1hdChmbXQpLAogICAgICAgIHJlYWxUb2tlbnMgPSB0b2tlbnMucmVkdWNlKAogICAgICAgICAgKGZvdW5kLCB7IGxpdGVyYWwsIHZhbCB9KSA9PiAobGl0ZXJhbCA/IGZvdW5kIDogZm91bmQuY29uY2F0KHZhbCkpLAogICAgICAgICAgW10KICAgIC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ICAgICAgICBjb25zdCBbdmFsLCB6b25lLCBuZXh0XSA9IGV4KG0sIGN1cnNvcik7CiAgICAgICAgICAgIHJldHVybiBbeyAuLi5tZXJnZWRWYWxzLCAuLi52YWwgfSwgem9uZSB8fCBtZXJnZWRab25lLCBuZXh0XTsKICAgICAgICAgIH0sCiAgICAgICAgICBbe30sIG51bGwsIDFdCiAgICAgICAgKQogICAgICAgIC5zbGljZSgwLCAyKTsKICB9CgogIGZ1bmN0aW9uIHBhcnNlKHMsIC4uLnBhdHRlcm5zKSB7CiAgICBpZiAocyA9PSBudWxsKSB7CiAgICAgIHJldHVybiBbbnVsbCwgbnVsbF07CiAgICB9CgogICAgZm9yIChjb25zdCBbcmVnZXgsIGV4dHJhY3Rvcl0gb2YgcGF0dGVybnMpIHsKICAgICAgY29uc3QgbSA9IHJlZ2V4LmV4ZWMocyk7CiAgICAgIGlmIChtKSB7CiAgICAgICAgcmV0dXJuIGV4dHJhY3RvcihtKTsKICAgICAgfQogICAgfQogICAgcmV0dXJuIFtudWxsLCBudWxsXTsKICB9CgogIGZ1bmN0aW9uIHNpbXBsZVBhcnNlKC4uLmtleXMpIHsKICAgIHJldHVybiAobWF0Y2gsIGN1cnNvcikgPT4gewogICAgICBjb25zdCByZXQgPSB7fTsKICAgICAgbGV0IGk7CgogICAgICBmb3IgKGkgPSAwOyBpIDwga2V5cy5sZW5ndGg7IGkrKykgewogICAgICAgIHJldFtrZXlzW2ldXSA9IHBhcnNlSW50ZWdlcihtYXRjaFtjdXJzb3IgKyBpXSk7CiAgICAgIH0KICAgICAgcmV0dXJuIFtyZXQsIG51bGwsIGN1cnNvciArIGldOwogICAgfTsKICB9CgogIC8vIElTTyBhbmQgU1FMIHBhcnNpbmcKICBjb25zdCBvZmZzZXRSZWdleCA9IC8oPzooWil8KFsrLV1cZFxkKSg/Ojo/KFxkXGQpKT8pLzsKICBjb25zdCBpc29FeHRlbmRlZFpvbmUgPSBgKD86JHtvZmZzZXRSZWdleC5zb3VyY2V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aXNlY29uZHM6IDI0ICogNjAgKiA2MCAqIDEwMDAsCiAgICAgIH0sCiAgICAgIGhvdXJzOiB7IG1pbnV0ZXM6IDYwLCBzZWNvbmRzOiA2MCAqIDYwLCBtaWxsaXNlY29uZHM6IDYwICogNjAgKiAxMDAwIH0sCiAgICAgIG1pbnV0ZXM6IHsgc2Vjb25kczogNjAsIG1pbGxpc2Vjb25kczogNjAgKiAxMDAwIH0sCiAgICAgIHNlY29uZHM6IHsgbWlsbGlzZWNvbmRzOiAxMDAwIH0sCiAgICB9LAogICAgY2FzdWFsTWF0cml4ID0gewogICAgICB5ZWFyczogewogICAgICAgIHF1YXJ0ZXJzOiA0LAogICAgICAgIG1vbnRoczogMTIsCiAgICAgICAgd2Vla3M6IDUyLAogICAgICAgIGRheXM6IDM2NSwKICAgICAgICBob3VyczogMzY1ICogMjQsCiAgICAgICAgbWludXRlczogMzY1ICogMjQgKiA2MCwKICAgICAgICBzZWNvbmRzOiAzNjUgKiAyNCAqIDYwICogNjAsCiAgICAgICAgbWlsbGlzZWNvbmRzOiAzNjUgKiAyNCAqIDYwICogNjAgKiAxMDAwLAogICAgICB9LAogICAgICBxdWFydGVyczogewogICAgICAgIG1vbnRoczogMywKICAgICAgICB3ZWVrczogMTMsCiAgICAgICAgZGF5czogOTEsCiAgICAgICAgaG91cnM6IDkxICogMjQsCiAgICAgICAgbWludXRlczogOTEgKiAyNCAqIDYwLAogICAgICAgIHNlY29uZHM6IDkxICogMjQgKiA2MCAqIDYwLAogICAgICAgIG1pbGxpc2Vjb25kczogOTEgKiAyNCAqIDYwICogNjAgKiAxMDAwLAogICAgICB9LAogICAgICBtb250aHM6IHsKICAgICAgICB3ZWVrczogNCwKICAgICAgICBkYXlzOiAzMCwKICAgICAgICBob3VyczogMzAgKiAyNCwKICAgICAgICBtaW51dGVzOiAzMCAqIDI0ICogNjAsCiAgICAgICAgc2Vjb25kczogMzAgKiAyNCAqIDYwICogNjAsCiAgICAgICAgbWlsbGlzZWNvbmRzOiAzMCAqIDI0ICogNjAgKiA2MCAqIDEwMDAsCiAgICAgIH0sCgogICAgICAuLi5sb3dPcmRlck1hdHJpeCwKICAgIH0sCiAgICBkYXlzSW5ZZWFyQWNjdXJhdGUgPSAxNDYwOTcuMCAvIDQwMCwKICAgIGRheXNJbk1vbnRoQWNjdXJhdGUgPSAxNDYwOTcuMCAvIDQ4MDAsCiAgICBhY2N1cmF0ZU1hdHJpeCA9IHsKICAgICAgeWVhcnM6IHsKICAgICAgICBxdWFydGVyczogNCwKICAgICAgICBtb250aHM6IDEyLAogICAgICAgIHdlZWtzOiBkYXlzSW5ZZWFyQWNjdXJhdGUgLyA3LAogICAgICAgIGRheXM6IGRheXNJblllYXJBY2N1cmF0ZSwKICAgICAgICBob3VyczogZGF5c0luWWVhckFjY3VyYXRlICogMjQsCiAgICAgICAgbWludXRlczogZGF5c0luWWVhckFjY3VyYXRlICogMjQgKiA2MCwKICAgICAgICBzZWNvbmRzOiBkYXlzSW5ZZWFyQWNjdXJhdGUgKiAyNCAqIDYwICogNjAsCiAgICAgICAgbWlsbGlzZWNvbmRzOiBkYXlzSW5ZZWFyQWNjdXJhdGUgKiAyNCAqIDYwICogNjAgKiAxMDAwLAogICAgICB9LAogICAgICBxdWFydGVyczogewogICAgICAgIG1vbnRoczogMywKICAgICAgICB3ZWVrczogZGF5c0luWWVhckFjY3VyYXRlIC8gMjgsCiAgICAgICAgZGF5czogZGF5c0luWWVhckFjY3VyYXRlIC8gNCwKICAgICAgICBob3VyczogKGRheXNJblllYXJBY2N1cmF0ZSAqIDI0KSAvIDQsCiAgICAgICAgbWludXRlczogKGRheXNJblllYXJBY2N1cmF0ZSAqIDI0ICogNjApIC8gNCwKICAgICAgICBzZWNvbmRzOiAoZGF5c0luWWVhckFjY3VyYXRlICogMjQgKiA2MCAqIDYwKSAvIDQsCiAgICAgICAgbWlsbGlzZWNvbmRzOiAoZGF5c0luWWVhckFjY3VyYXRlICogMjQgKiA2MCAqIDYwICogMTAwMCkg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b3NzaWJsZSBmcm9tIHRoZSBsb3dlciBvcmRlciB1bml0IGludG8KICAgICAgICAgIC8vIHRoZSBoaWdoZXIgb3JkZXIgb25lCiAgICAgICAgICAvLwogICAgICAgICAgLy8gTWF0aC5mbG9vciB0YWtlcyBjYXJlIG9mIGJvdGggb2YgdGhlc2UgY2FzZXMsIHJvdW5kaW5nIGF3YXkgZnJvbSAwCiAgICAgICAgICAvLyBpZiBwcmV2aW91c1ZhbCA8IDAgaXQgbWFrZXMgdGhlIGFic29sdXRlIHZhbHVlIGxhcmdlcgogICAgICAgICAgLy8gaWYgcHJldmlvdXNWYWwgPj0gaXQgbWFrZXMgdGhlIGFic29sdXRlIHZhbHVlIHNtYWxsZXIKICAgICAgICAgIGNvbnN0IHJvbGxVcCA9IE1hdGguZmxvb3IocHJldmlvdXNWYWwgLyBjb252KTsKICAgICAgICAgIHZhbHNbY3VycmVudF0gKz0gcm9sbFVwICogZmFjdG9yOwogICAgICAgICAgdmFsc1twcmV2aW91c10gLT0gcm9sbFVwICogY29udiAqIGZhY3RvcjsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGN1cnJlbnQ7CiAgICAgIH0gZWxzZSB7CiAgICAgICAgcmV0dXJuIHByZXZpb3VzOwogICAgICB9CiAgICB9LCBudWxsKTsKCiAgICAvLyB0cnkgdG8gY29udmVydCBhbnkgZGVjaW1hbHMgaW50byBzbWFsbGVyIHVuaXRzIGlmIHBvc3NpYmxlCiAgICAvLyBmb3IgZXhhbXBsZSBmb3IgeyB5ZWFyczogMi41LCBkYXlzOiAwLCBzZWNvbmRzOiAwIH0gd2Ugd2FudCB0byBnZXQgeyB5ZWFyczogMiwgZGF5czogMTgyLCBob3VyczogMTIgfQogICAgb3JkZXJlZFVuaXRzJDEucmVkdWNlKChwcmV2aW91cywgY3VycmVudCkgPT4gewogICAgICBpZiAoIWlzVW5kZWZpbmVkKHZhbHNbY3VycmVudF0pKSB7CiAgICAgICAgaWYgKHByZXZpb3VzKSB7CiAgICAgICAgICBjb25zdCBmcmFjdGlvbiA9IHZhbHNbcHJldmlvdXNdICUgMTsKICAgICAgICAgIHZhbHNbcHJldmlvdXNdIC09IGZyYWN0aW9uOwogICAgICAgICAgdmFsc1tjdXJyZW50XSArPSBmcmFjdGlvbiAqIG1hdHJpeFtwcmV2aW91c11bY3VycmVudF07CiAgICAgICAgfQogICAgICAgIHJldHVybiBjdXJyZW50OwogICAgICB9IGVsc2UgewogICAgICAgIHJldHVybiBwcmV2aW91czsKICAgICAgfQogICAgfSwgbnVsbCk7CiAgfQoKICAvLyBSZW1vdmUgYWxsIHByb3BlcnRpZXMgd2l0aCBhIHZhbHVlIG9mIDAgZnJvbSBhbiBvYmplY3QKICBmdW5jdGlvbiByZW1vdmVaZXJvZXModmFscykgewogICAgY29uc3QgbmV3VmFscyA9IHt9OwogICAgZm9yIChjb25zdCBba2V5LCB2YWx1ZV0gb2YgT2JqZWN0LmVudHJpZXModmFscykpIHsKICAgICAgaWYgKHZhbHVlICE9PSAwKSB7CiAgICAgICAgbmV3VmFsc1trZXldID0gdmFsdWU7CiAgICAgIH0KICAgIH0KICAgIHJldHVybiBuZXdWYWxzOwogIH0KCiAgLyoqCiAgICogQSBEdXJhdGlvbiBvYmplY3QgcmVwcmVzZW50cyBhIHBlcmlvZCBvZiB0aW1lLCBsaWtlICIyIG1vbnRocyIgb3IgIjEgZGF5LCAxIGhvdXIiLiBDb25jZXB0dWFsbHksIGl0J3MganVzdCBhIG1hcCBvZiB1bml0cyB0byB0aGVpciBxdWFudGl0aWVzLCBhY2NvbXBhbmllZCBieSBzb21lIGFkZGl0aW9uYWwgY29uZmlndXJhdGlvbiBhbmQgbWV0aG9kcyBmb3IgY3JlYXRpbmcsIHBhcnNpbmcsIGludGVycm9nYXRpbmcsIHRyYW5zZm9ybWluZywgYW5kIGZvcm1hdHRpbmcgdGhlbS4gVGhleSBjYW4gYmUgdXNlZCBvbiB0aGVpciBvd24gb3IgaW4gY29uanVuY3Rpb24gd2l0aCBvd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BxdWFydGVyOiAicXVhcnRlcnMiLAogICAgICAgIHF1YXJ0ZXJzOiAicXVhcnRlcnMiLAogICAgICAgIG1vbnRoOiAibW9udGhzIiwKICAgICAgICBtb250aHM6ICJtb250aHMiLAogICAgICAgIHdlZWs6ICJ3ZWVrcyIsCiAgICAgICAgd2Vla3M6ICJ3ZWVrcyIsCiAgICAgICAgZGF5OiAiZGF5cyIsCiAgICAgICAgZGF5czogImRheXMiLAogICAgICAgIGhvdXI6ICJob3VycyIsCiAgICAgICAgaG91cnM6ICJob3VycyIsCiAgICAgICAgbWludXRlOiAibWludXRlcyIsCiAgICAgICAgbWludXRlczogIm1pbnV0ZXMiLAogICAgICAgIHNlY29uZDogInNlY29uZHMiLAogICAgICAgIHNlY29uZHM6ICJzZWNvbmRzIiwKICAgICAgICBtaWxsaXNlY29uZDogIm1pbGxpc2Vjb25kcyIsCiAgICAgICAgbWlsbGlzZWNvbmRzOiAibWlsbGlzZWNvbmRzIiwKICAgICAgfVt1bml0ID8gdW5pdC50b0xvd2VyQ2FzZSgpIDogdW5pdF07CgogICAgICBpZiAoIW5vcm1hbGl6ZWQpIHRocm93IG5ldyBJbnZhbGlkVW5pdEVycm9yKHVuaXQpOwoKICAgICAgcmV0dXJuIG5vcm1hbGl6ZWQ7CiAgICB9CgogICAgLyoqCiAgICAgKiBDaGVjayBpZiBhbiBvYmplY3QgaXMgYSBEdXJhdGlvbi4gV29ya3MgYWNyb3NzIGNvbnRleHQgYm91bmRhcmllcwogICAgICogQHBhcmFtIHtvYmplY3R9IG8KICAgICAqIEByZXR1cm4ge2Jvb2xlYW59CiAgICAgKi8KICAgIHN0YXRpYyBpc0R1cmF0aW9uKG8pIHsKICAgICAgcmV0dXJuIChvICYmIG8uaXNMdXhvbkR1cmF0aW9uKSB8fCBmYWxzZTsKICAgIH0KCiAgICAvKioKICAgICAqIEdldCAgdGhlIGxvY2FsZSBvZiBhIER1cmF0aW9uLCBzdWNoICdlbi1HQicKICAgICAqIEB0eXBlI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AgKiB2YXIgZHVyID0gRHVyYXRpb24uZnJvbU9iamVjdCh7IGRheXM6IDEsIGhvdXJzOiA1LCBtaW51dGVzOiA2IH0pCiAgICAgKiBkdXIudG9IdW1hbigpIC8vPT4gJzEgZGF5LCA1IGhvdXJzLCA2IG1pbnV0ZXMnCiAgICAgKiBkdXIudG9IdW1hbih7IGxpc3RTdHlsZTogImxvbmciIH0pIC8vPT4gJzEgZGF5LCA1IGhvdXJzLCBhbmQgNiBtaW51dGVzJwogICAgICogZHVyLnRvSHVtYW4oeyB1bml0RGlzcGxheTogInNob3J0IiB9KSAvLz0+ICcxIGRheSwgNSBociwgNiBtaW4nCiAgICAgKiBgYGAKICAgICAqLwogICAgdG9IdW1hbihvcHRzID0ge30pIHsKICAgICAgaWYgKCF0aGlzLmlzVmFsaWQpIHJldHVybiBJTlZBTElEJDI7CgogICAgICBjb25zdCBsID0gb3JkZXJlZFVuaXRzJDEKICAgICAgICAubWFwKCh1bml0KSA9PiB7CiAgICAgICAgICBjb25zdCB2YWwgPSB0aGlzLnZhbHVlc1t1bml0XTsKICAgICAgICAgIGlmIChpc1VuZGVmaW5lZCh2YWwpKSB7CiAgICAgICAgICAgIHJldHVybiBudWxsOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuIHRoaXMubG9jCiAgICAgICAgICAgIC5udW1iZXJGb3JtYXR0ZXIoeyBzdHlsZTogInVuaXQiLCB1bml0RGlzcGxheTogImxvbmciLCAuLi5vcHRzLCB1bml0OiB1bml0LnNsaWNlKDAsIC0xKSB9KQogICAgICAgICAgICAuZm9ybWF0KHZhbCk7CiAgICAgICAgfSkKICAgICAgICAuZmlsdGVyKChuKSA9PiBuKTsKCiAgICAgIHJldHVybiB0aGlzLmxvYwogICAgICAgIC5saXN0Rm9ybWF0dGVyKHsgdHlwZTogImNvbmp1bmN0aW9uIiwgc3R5bGU6IG9wdHMubGlzdFN0eWxlIHx8ICJuYXJyb3ciLCAuLi5vcHRzIH0pCiAgICAgICAgLmZvcm1hdChsKTsKICAgIH0KCiAgICAvKioKICAgICAqIFJldHVybnMgYSBKYXZhU2NyaXB0IG9iamVjdCB3aXRoIHRoaXMgRHVyYXRpb24ncyB2YWx1ZXMuCiAgICAgKiBAZXhhbXBsZSBEdXJhdGlvbi5mcm9tT2JqZWN0KHsgeWVhcnM6IDEsIGRheXM6IDYsIHNlY29uZHM6IDIgfSkudG9PYmplY3QoKSAvLz0+IHsgeWVhcnM6IDEsIGRheXM6IDYsIHNlY29uZHM6IDIgfQogICAgICogQHJldHVybiB7T2JqZWN0fQogICAgICovCiAgICB0b09iamVjdCgpIHsKICAgICAgaWYgKCF0aGlzLmlzVmFsaWQpIHJldHVybiB7fTsKICAgICAgcmV0dXJuIHsgLi4udGhpcy52YWx1ZXMgfTsKICAgIH0KCiAgICAvKioKICAgICAqIFJldHVybnMgYW4gSVNPIDg2MDEtY29tcGxpYW50IHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiB0aGlzIER1cmF0aW9uLgogICAgICogQHNlZSBodHRwczovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9JU09fODYwMSNEdXJhdGlvbnMKICAgICAqIEBleGFtcGxlIER1cmF0aW9uLmZyb21PYmplY3QoeyB5ZWFyczogMywgc2Vjb25kczogNDUgfSkudG9JU08oKSAvLz0+ICdQM1lUNDVTJwogICAgICogQGV4YW1wbGUgRHVyYXRpb24uZnJvbU9iamVjdCh7IG1vbnRoczogNCwgc2Vjb25kczogNDUgfSkudG9JU08oKSAvLz0+ICdQNE1UNDVTJwogICAgICogQGV4YW1wbGUgRHVyYXRpb24uZnJvbU9iamVjdCh7IG1vbnRoczogNSB9KS50b0lTTygpIC8vPT4gJ1A1TScKICAgICAqIEBleGFtcGxlIER1cmF0aW9uLmZyb21PYmplY3QoeyBtaW51dGVzOiA1IH0pLnRvSVNPKCkgLy89PiAnUFQ1TScKICAgICAqIEBleGFtcGxlIER1cmF0aW9uLmZyb21PYmplY3QoeyBtaWxsaXNlY29uZHM6IDYgfS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M6IGZhbHNlLAogICAgICAgIHN1cHByZXNzU2Vjb25kczogZmFsc2UsCiAgICAgICAgaW5jbHVkZVByZWZpeDogZmFsc2UsCiAgICAgICAgZm9ybWF0OiAiZXh0ZW5kZWQiLAogICAgICAgIC4uLm9wdHMsCiAgICAgICAgaW5jbHVkZU9mZnNldDogZmFsc2UsCiAgICAgIH07CgogICAgICBjb25zdCBkYXRlVGltZSA9IERhdGVUaW1lLmZyb21NaWxsaXMobWlsbGlzLCB7IHpvbmU6ICJVVEMiIH0pOwogICAgICByZXR1cm4gZGF0ZVRpbWUudG9JU09UaW1lKG9wdHMpOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJucyBhbiBJU08gODYwMSByZXByZXNlbnRhdGlvbiBvZiB0aGlzIER1cmF0aW9uIGFwcHJvcHJpYXRlIGZvciB1c2UgaW4gSlNPTi4KICAgICAqIEByZXR1cm4ge3N0cmluZ30KICAgICAqLwogICAgdG9KU09OKCkgewogICAgICByZXR1cm4gdGhpcy50b0lTTygpOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJucyBhbiBJU08gODYwMSByZXByZXNlbnRhdGlvbiBvZiB0aGlzIER1cmF0aW9uIGFwcHJvcHJpYXRlIGZvciB1c2UgaW4gZGVidWdnaW5nLgogICAgICogQHJldHVybiB7c3RyaW5nfQogICAgICovCiAgICB0b1N0cmluZygpIHsKICAgICAgcmV0dXJuIHRoaXMudG9JU08oKTsKICAgIH0KCiAgICAvKioKICAgICAqIFJldHVybnMgYW4gbWlsbGlzZWNvbmRzIHZhbHVlIG9mIHRoaXMgRHVyYXRpb24uCiAgICAgKiBAcmV0dXJuIHtudW1iZXJ9CiAgICAgKi8KICAgIHRvTWlsbGlzKCkgewogICAgICBpZiAoIXRoaXMuaXNWYWxpZCkgcmV0dXJuIE5hTjsKCiAgICAgIHJldHVybiBkdXJhdGlvblRvTWlsbGlzKHRoaXMubWF0cml4LCB0aGlzLnZhbHVlcyk7CiAgICB9CgogICAgLyoqCiAgIC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pemUoKS50b09iamVjdCgpIC8vPT4geyBob3VyczogMTEsIG1pbnV0ZXM6IDE1IH0KICAgICAqIEBleGFtcGxlIER1cmF0aW9uLmZyb21PYmplY3QoeyB5ZWFyczogMi41LCBkYXlzOiAwLCBob3VyczogMCB9KS5ub3JtYWxpemUoKS50b09iamVjdCgpIC8vPT4geyB5ZWFyczogMiwgZGF5czogMTgyLCBob3VyczogMTIgfQogICAgICogQHJldHVybiB7RHVyYXRpb259CiAgICAgKi8KICAgIG5vcm1hbGl6ZSgpIHsKICAgICAgaWYgKCF0aGlzLmlzVmFsaWQpIHJldHVybiB0aGlzOwogICAgICBjb25zdCB2YWxzID0gdGhpcy50b09iamVjdCgpOwogICAgICBub3JtYWxpemVWYWx1ZXModGhpcy5tYXRyaXgsIHZhbHMpOwogICAgICByZXR1cm4gY2xvbmUkMSh0aGlzLCB7IHZhbHVlczogdmFscyB9LCB0cnVlKTsKICAgIH0KCiAgICAvKioKICAgICAqIFJlc2NhbGUgdW5pdHMgdG8gaXRzIGxhcmdlc3QgcmVwcmVzZW50YXRpb24KICAgICAqIEBleGFtcGxlIER1cmF0aW9uLmZyb21PYmplY3QoeyBtaWxsaXNlY29uZHM6IDkwMDAwIH0pLnJlc2NhbGUoKS50b09iamVjdCgpIC8vPT4geyBtaW51dGVzOiAxLCBzZWNvbmRzOiAzMCB9CiAgICAgKiBAcmV0dXJuIHtEdXJhdGlvbn0KICAgICAqLwogICAgcmVzY2FsZSgpIHsKICAgICAgaWYgKCF0aGlzLmlzVmFsaWQpIHJldHVybiB0aGlzOwogICAgICBjb25zdCB2YWxzID0gcmVtb3ZlWmVyb2VzKHRoaXMubm9ybWFsaXplKCkuc2hpZnRUb0FsbCgpLnRvT2JqZWN0KCkpOwogICAgICByZXR1cm4gY2xvbmUkMSh0aGlzLCB7IHZhbHVlczogdmFscyB9LCB0cnVlKTsKICAgIH0KCiAgICAvKioKICAgICAqIENvbnZlcnQgdGhpcyBEdXJhdGlvbiBpbnRvIGl0cyByZXByZXNlbnRhdGlvbiBpbiBhIGRpZmZlcmVudCBzZXQgb2YgdW5pdHMuCiAgICAgKiBAZXhhbXBsZSBEdXJhdGlvbi5mcm9tT2JqZWN0KHsgaG91cnM6IDEsIHNlY29uZHM6IDMwIH0pLnNoaWZ0VG8oJ21pbnV0ZXMnLCAnbWlsbGlzZWNvbmRzJykudG9PYmplY3QoKSAvLz0+IHsgbWludXRlczogNjAsIG1pbGxpc2Vjb25kczogMzAwMDAgfQogICAgICogQHJldHVybiB7RHVyYXRpb259CiAgICAgKi8KICAgIHNoaWZ0VG8oLi4udW5pdHMpIHsKICAgICAgaWYgKCF0aGlzLmlzVmFsaWQpIHJldHVybiB0aGlzOwoKICAgICAgaWYgKHVuaXRzLmxlbmd0aCA9PT0gMCkgewogICAgICAgIHJldHVybiB0aGlzOwogICAgICB9CgogICAgICB1bml0cyA9IHVuaXRzLm1hcCgodSkgPT4gRHVyYXRpb24ubm9ybWFsaXplVW5pdCh1KSk7CgogICAgICBjb25zdCBidWlsdCA9IHt9LAogICAgICAgIGFjY3VtdWxhdGVkID0ge30sCiAgICAgICAgdmFscyA9IHRoaXMudG9PYmplY3QoKTsKICAgICAgbGV0IGxhc3RVbml0OwoKICAgICAgZm9yIChjb25zdCBrIG9mIG9yZGVyZWRVbml0cyQxKSB7CiAgICAgICAgaWYgKHVuaXRzLmluZGV4T2YoaykgPj0gMCkgewogICAgICAgICAgbGFzdFVuaXQgPSBrOwoKICAgICAgICAgIGxldCBvd24gPSAwOwoKICAgICAgICAgIC8vIGFueXRoaW5nIHdlIGhhdmVuJ3QgYm9pbGVkIGRvd24geWV0IHNob3VsZCBnZXQgYm9pbGVkIHRvIHRoaXMgdW5pdAogICAgICAgICAgZm9yIChjb25zdCBhayBpbiBhY2N1bXVsYXRlZCkgewogICAgICAgICAgICBvd24gKz0gdGhpcy5tYXRyaXhbYWtdW2tdICogYWNjdW11bGF0ZWRbYWtdOwogICAgICAgICAgICBhY2N1bXVsYXRlZFtha10gPSAwOwogICAgICAgICAgfQoKICAgICAgICAgIC8vIHBsdXMgYW55dGhpbmcgdGhhdCdzIGFscmVhZHkgaW4gdGhpcyB1bml0CiAgICAgICAgICBpZiAoaXNOdW1iZXIodmFsc1trXSkpIHsKICAgICAgICAgICAgb3duICs9IHZhbHNba107CiAgICAgICAgICB9CgogICAgICAgICAgLy8gb25seSBrZWVwIHRoZSBpbnRlZ2VyIHBhcnQgZm9yIG5vdyBpbiB0aGUgaG9wZXMgb2YgcHV0dGluZyBhbnkgZGVjaW1hbCBwYXJ0CiAgICAgICAgICAvLyBpbnRvIGEgc21hbGxlciB1bml0IGxhdGVyCiAgICAgICAgICBjb25zdCBpID0gTWF0aC50cnVuYyhvd24pOwogICAgICAgICAgYnVpbHRba10gPSBpOwogICAgICAgICAgYWNjdW11bGF0ZWRba10gPSAob3duICogMTAwMCAtIGkgKiAxMDAwKSAvIDEwMDA7CgogICAgICAgICAgLy8gb3RoZXJ3aXNlLCBrZWVwIGl0IGluIHRoZSB3aW5ncyB0byBib2lsIGl0IGxhdGVyCiAgICAgICAgfSBlbHNlIGlmIChpc051bWJlcih2YWxzW2tdKSkgewogICAgICAgICAgYWNjdW11bGF0ZWRba10gPSB2YWxzW2tdOwogICAgICAgIH0KICAgICAgfQoKICAgICAgLy8gYW55dGhpbmcgbGVmdG92ZXIgYmVjb21lcyB0aGUgZGVjaW1hbCBmb3IgdGhlIGxhc3QgdW5pdAogICAgICAvLyBsYXN0VW5pdCBtdXN0IGJlIGRlZmluZWQgc2luY2UgdW5pdHMgaXMgbm90IGVtcHR5CiAgICAgIGZvciAoY29uc3Qga2V5IGluIGFjY3VtdWxhdGVkKSB7CiAgICAgICAgaWYgKGFjY3VtdWxhdGVkW2tleV0gIT09IDApIHsKICAgICAgICAgIGJ1aWx0W2xhc3RVbml0XSArPQogICAgICAgICAgICBrZXkgPT09IGxhc3RVbml0ID8gYWNjdW11bGF0ZWRba2V5XSA6IGFjY3VtdWxhdGVkW2tleV0gLyB0a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RoaXM7CiAgICAgIGNvbnN0IG5lZ2F0ZWQgPSB7fTsKICAgICAgZm9yIChjb25zdCBrIG9mIE9iamVjdC5rZXlzKHRoaXMudmFsdWVzKSkgewogICAgICAgIG5lZ2F0ZWRba10gPSB0aGlzLnZhbHVlc1trXSA9PT0gMCA/IDAgOiAtdGhpcy52YWx1ZXNba107CiAgICAgIH0KICAgICAgcmV0dXJuIGNsb25lJDEodGhpcywgeyB2YWx1ZXM6IG5lZ2F0ZWQgfSwgdHJ1ZSk7CiAgICB9CgogICAgLyoqCiAgICAgKiBHZXQgdGhlIHllYXJzLgogICAgICogQHR5cGUge251bWJlcn0KICAgICAqLwogICAgZ2V0IHllYXJzKCkgewogICAgICByZXR1cm4gdGhpcy5pc1ZhbGlkID8gdGhpcy52YWx1ZXMueWVhcnMgfHwgMCA6IE5hTjsKICAgIH0KCiAgICAvKioKICAgICAqIEdldCB0aGUgcXVhcnRlcnMuCiAgICAgKiBAdHlwZSB7bnVtYmVyfQogICAgICovCiAgICBnZXQgcXVhcnRlcnMoKSB7CiAgICAgIHJldHVybiB0aGlzLmlzVmFsaWQgPyB0aGlzLnZhbHVlcy5xdWFydGVycyB8fCAwIDogTmFOOwogICAgfQoKICAgIC8qKgogICAgICogR2V0IHRoZSBtb250aHMuCiAgICAgKiBAdHlwZSB7bnVtYmVyfQogICAgICovCiAgICBnZXQgbW9udGhzKCkgewogICAgICByZXR1cm4gdGhpcy5pc1ZhbGlkID8gdGhpcy52YWx1ZXMubW9udGhzIHx8IDAgOiBOYU47CiAgICB9CgogICAgLyoqCiAgICAgKiBHZXQgdGhlIHdlZWtzCiAgICAgKiBAdHlwZSB7bnVtYmVyfQogICAgICovCiAgICBnZXQgd2Vla3MoKSB7CiAgICAgIHJldHVybiB0aGlzLmlzVmFsaWQgPyB0aGlzLnZhbHVlcy53ZWVrcyB8fCAwIDogTmFOOwogICAgfQoKICAgIC8qKgogICAgICogR2V0IHRoZSBkYXlzLgogICAgICogQHR5cGUge251bWJlcn0KICAgICAqLwogICAgZ2V0IGRheXMoKSB7CiAgICAgIHJldHVybiB0aGlzLmlzVmFsaWQgPyB0aGlzLnZhbHVlcy5kYXlzIHx8IDAgOiBOYU47CiAgICB9CgogICAgLyoqCiAgICAgKiBHZXQgdGhlIGhvdXJzLgogICAgICogQHR5cGUge251bWJlcn0KICAgICAqLwogICAgZ2V0IGhvdXJzKCkgewogICAgICByZXR1cm4gdGhpcy5pc1ZhbGlkID8gdGhpcy52YWx1ZXMuaG91cnMgfHwgMCA6IE5hTjsKICAgIH0KCiAgICAvKioKICAgICAqIEdldCB0aGUgbWludXRlcy4KICAgICAqIEB0eXBlIHtudW1iZXJ9CiAgICAgKi8KICAgIGdldCBtaW51dGVzKCkgewogICAgICByZXR1cm4gdGhpcy5pc1ZhbGlkID8gdGhpcy52YWx1ZXMubWludXRlcyB8fCAwIDogTmFOOwogICAgfQoKICAgIC8qKgogICAgICogR2V0IHRoZSBzZWNvbmRzLgogICAgICogQHJldHVybiB7bnVtYmVyfQogICAgICovCiAgICBnZXQgc2Vjb25kcygpIHsKICAgICAgcmV0dXJuIHRoaXMuaXNWYWxpZCA/IHRoaXMudmFsdWVzLnNlY29uZHMgfHwgMCA6IE5hTjsKICAgIH0KCiAgICAvKioKICAgICAqIEdldCB0aGUgbWlsbGlzZWNvbmRzLgogICAgICogQHJldHVybiB7bnVtYmVyfQogICAgICovCiAgICBnZXQgbWlsbGlzZWNvbmRzKCkgewogICAgICByZXR1cm4gdGhpcy5pc1ZhbGlkID8gdGhpcy52YWx1ZXMubWlsbGlzZWNvbmRzIHx8IDAgOiBOYU47CiAgICB9CgogICAgLyoqCiAgICAgKiBSZXR1cm5zIHdoZXRoZXIgdGhlIER1cmF0aW9uIGlzIGludmFsaWQuIEludmFsaWQgZHVyYXRpb25zIGFyZSByZXR1cm5lZCBieSBkaWZmIG9wZXJhdGlvbnMKICAgICAqIG9uIGludmFsaWQgRGF0ZVRpbWVzIG9yIEludGVydmFscy4KICAgICAqIEBy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WYgKHMgJiYgZSkgewogICAgICAgIGxldCBzdGFydCwgc3RhcnRJc1ZhbGlkOwogICAgICAgIHRyeSB7CiAgICAgICAgICBzdGFydCA9IERhdGVUaW1lLmZyb21JU08ocywgb3B0cyk7CiAgICAgICAgICBzdGFydElzVmFsaWQgPSBzdGFydC5pc1ZhbGlkOwogICAgICAgIH0gY2F0Y2ggKGUpIHsKICAgICAgICAgIHN0YXJ0SXNWYWxpZCA9IGZhbHNlOwogICAgICAgIH0KCiAgICAgICAgbGV0IGVuZCwgZW5kSXNWYWxpZDsKICAgICAgICB0cnkgewogICAgICAgICAgZW5kID0gRGF0ZVRpbWUuZnJvbUlTTyhlLCBvcHRzKTsKICAgICAgICAgIGVuZElzVmFsaWQgPSBlbmQuaXNWYWxpZDsKICAgICAgICB9IGNhdGNoIChlKSB7CiAgICAgICAgICBlbmRJc1ZhbGlkID0gZmFsc2U7CiAgICAgICAgfQoKICAgICAgICBpZiAoc3RhcnRJc1ZhbGlkICYmIGVuZElzVmFsaWQpIHsKICAgICAgICAgIHJldHVybiBJbnRlcnZhbC5mcm9tRGF0ZVRpbWVzKHN0YXJ0LCBlbmQpOwogICAgICAgIH0KCiAgICAgICAgaWYgKHN0YXJ0SXNWYWxpZCkgewogICAgICAgICAgY29uc3QgZHVyID0gRHVyYXRpb24uZnJvbUlTTyhlLCBvcHRzKTsKICAgICAgICAgIGlmIChkdXIuaXNWYWxpZCkgewogICAgICAgICAgICByZXR1cm4gSW50ZXJ2YWwuYWZ0ZXIoc3RhcnQsIGR1cik7CiAgICAgICAgICB9CiAgICAgICAgfSBlbHNlIGlmIChlbmRJc1ZhbGlkKSB7CiAgICAgICAgICBjb25zdCBkdXIgPSBEdXJhdGlvbi5mcm9tSVNPKHMsIG9wdHMpOwogICAgICAgICAgaWYgKGR1ci5pc1ZhbGlkKSB7CiAgICAgICAgICAgIHJldHVybiBJbnRlcnZhbC5iZWZvcmUoZW5kLCBkdXIpOwogICAgICAgICAgfQogICAgICAgIH0KICAgICAgfQogICAgICByZXR1cm4gSW50ZXJ2YWwuaW52YWxpZCgidW5wYXJzYWJsZSIsIGB0aGUgaW5wdXQgIiR7dGV4dH0iIGNhbid0IGJlIHBhcnNlZCBhcyBJU08gODYwMWApOwogICAgfQoKICAgIC8qKgogICAgICogQ2hlY2sgaWYgYW4gb2JqZWN0IGlzIGFuIEludGVydmFsLiBXb3JrcyBhY3Jvc3MgY29udGV4dCBib3VuZGFyaWVzCiAgICAgKiBAcGFyYW0ge29iamVjdH0gbwogICAgICogQHJldHVybiB7Ym9vbGVhbn0KICAgICAqLwogICAgc3RhdGljIGlzSW50ZXJ2YWwobykgewogICAgICByZXR1cm4gKG8gJiYgby5pc0x1eG9uSW50ZXJ2YWwpIHx8IGZhbHNlOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJucyB0aGUgc3RhcnQgb2YgdGhlIEludGVydmFsCiAgICAgKiBAdHlwZSB7RGF0ZVRpbWV9CiAgICAgKi8KICAgIGdldCBzdGFydCgpIHsKICAgICAgcmV0dXJuIHRoaXMuaXNWYWxpZCA/IHRoaXMucyA6IG51bGw7CiAgICB9CgogICAgLyoqCiAgICAgKiBSZXR1cm5zIHRoZSBlbmQgb2YgdGhlIEludGVydmFsCiAgICAgKiBAdHlwZSB7RGF0ZVRpbWV9CiAgICAgKi8KICAgIGdldCBlbmQoKSB7CiAgICAgIHJldHVybiB0aGlzLmlzVmFsaWQgPyB0aGlzLmUgOiBudWxsOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJucyB3aGV0aGVyIHRoaXMgSW50ZXJ2YWwncyBlbmQgaXMgYXQgbGVhc3QgaXRzIHN0YXJ0LCBtZWFuaW5nIHRoYXQgdGhlIEludGVydmFsIGlzbid0ICdiYWNrd2FyZHMnLgogICAgICogQHR5cGUge2Jvb2xlYW59CiAgICAgKi8KICAgIGdldCBpc1ZhbGlkKCkgewogICAgICByZXR1cm4gdGhpcy5pbnZhbGlkUmVhc29uID09PSBudWxsOwogICAgfQo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pbWVzIC0gdGhlIHVuaXQgb2YgdGltZSB0byBjb3VudC4KICAgICAqIEByZXR1cm4ge0FycmF5fQogICAgICovCiAgICBzcGxpdEF0KC4uLmRhdGVUaW1lcykgewogICAgICBpZiAoIXRoaXMuaXNWYWxpZCkgcmV0dXJuIFtdOwogICAgICBjb25zdCBzb3J0ZWQgPSBkYXRlVGltZXMKICAgICAgICAgIC5tYXAoZnJpZW5kbHlEYXRlVGltZSkKICAgICAgICAgIC5maWx0ZXIoKGQpID0+IHRoaXMuY29udGFpbnMoZCkpCiAgICAgICAgICAuc29ydCgpLAogICAgICAgIHJlc3VsdHMgPSBbXTsKICAgICAgbGV0IHsgcyB9ID0gdGhpcywKICAgICAgICBpID0gMDsKCiAgICAgIHdoaWxlIChzIDwgdGhpcy5lKSB7CiAgICAgICAgY29uc3QgYWRkZWQgPSBzb3J0ZWRbaV0gfHwgdGhpcy5lLAogICAgICAgICAgbmV4dCA9ICthZGRlZCA+ICt0aGlzLmUgPyB0aGlzLmUgOiBhZGRlZDsKICAgICAgICByZXN1bHRzLnB1c2goSW50ZXJ2YWwuZnJvbURhdGVUaW1lcyhzLCBuZXh0KSk7CiAgICAgICAgcyA9IG5leHQ7CiAgICAgICAgaSArPSAxOwogICAgICB9CgogICAgICByZXR1cm4gcmVzdWx0czsKICAgIH0KCiAgICAvKioKICAgICAqIFNwbGl0IHRoaXMgSW50ZXJ2YWwgaW50byBzbWFsbGVyIEludGVydmFscywgZWFjaCBvZiB0aGUgc3BlY2lmaWVkIGxlbmd0aC4KICAgICAqIExlZnQgb3ZlciB0aW1lIGlzIGdyb3VwZWQgaW50byBhIHNtYWxsZXIgaW50ZXJ2YWwKICAgICAqIEBwYXJhbSB7RHVyYXRpb258T2JqZWN0fG51bWJlcn0gZHVyYXRpb24gLSBUaGUgbGVuZ3RoIG9mIGVhY2ggcmVzdWx0aW5nIGludGVydmFsLgogICAgICogQHJldHVybiB7QXJyYXl9CiAgICAgKi8KICAgIHNwbGl0QnkoZH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vIG51bWJlck9mUGFydHMpLnNsaWNlKDAsIG51bWJlck9mUGFydHMpOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJuIHdoZXRoZXIgdGhpcyBJbnRlcnZhbCBvdmVybGFwcyB3aXRoIHRoZSBzcGVjaWZpZWQgSW50ZXJ2YWwKICAgICAqIEBwYXJhbSB7SW50ZXJ2YWx9IG90aGVyCiAgICAgKiBAcmV0dXJuIHtib29sZWFufQogICAgICovCiAgICBvdmVybGFwcyhvdGhlcikgewogICAgICByZXR1cm4gdGhpcy5lID4gb3RoZXIucyAmJiB0aGlzLnMgPCBvdGhlci5lOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJuIHdoZXRoZXIgdGhpcyBJbnRlcnZhbCdzIGVuZCBpcyBhZGphY2VudCB0byB0aGUgc3BlY2lmaWVkIEludGVydmFsJ3Mgc3RhcnQuCiAgICAgKiBAcGFyYW0ge0ludGVydmFsfSBvdGhlcgogICAgICogQHJldHVybiB7Ym9vbGVhbn0KICAgICAqLwogICAgYWJ1dHNTdGFydChvdGhlcikgewogICAgICBpZiAoIXRoaXMuaXNWYWxpZCkgcmV0dXJuIGZhbHNlOwogICAgICByZXR1cm4gK3RoaXMuZSA9PT0gK290aGVyLnM7CiAgICB9CgogICAgLyoqCiAgICAgKiBSZXR1cm4gd2hldGhlciB0aGlzIEludGVydmFsJ3Mgc3RhcnQgaXMgYWRqYWNlbnQgdG8gdGhlIHNwZWNpZmllZCBJbnRlcnZhbCdzIGVuZC4KICAgICAqIEBwYXJhbSB7SW50ZXJ2YWx9IG90aGVyCiAgICAgKiBAcmV0dXJuIHtib29sZWFufQogICAgICovCiAgICBhYnV0c0VuZChvdGhlcikgewogICAgICBpZiAoIXRoaXMuaXNWYWxpZCkgcmV0dXJuIGZhbHNlOwogICAgICByZXR1cm4gK290aGVyLmUgPT09ICt0aGlzLnM7CiAgICB9CgogICAgLyoqCiAgICAgKiBSZXR1cm4gd2hldGhlciB0aGlzIEludGVydmFsIGVuZ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uZSA6IG90aGVyLmU7CiAgICAgIHJldHVybiBJbnRlcnZhbC5mcm9tRGF0ZVRpbWVzKHMsIGUpOwogICAgfQoKICAgIC8qKgogICAgICogTWVyZ2UgYW4gYXJyYXkgb2YgSW50ZXJ2YWxzIGludG8gYSBlcXVpdmFsZW50IG1pbmltYWwgc2V0IG9mIEludGVydmFscy4KICAgICAqIENvbWJpbmVzIG92ZXJsYXBwaW5nIGFuZCBhZGphY2VudCBJbnRlcnZhbHMuCiAgICAgKiBAcGFyYW0ge0FycmF5fSBpbnRlcnZhbHMKICAgICAqIEByZXR1cm4ge0FycmF5fQogICAgICovCiAgICBzdGF0aWMgbWVyZ2UoaW50ZXJ2YWxzKSB7CiAgICAgIGNvbnN0IFtmb3VuZCwgZmluYWxdID0gaW50ZXJ2YWxzCiAgICAgICAgLnNvcnQoKGEsIGIpID0+IGEucyAtIGIucykKICAgICAgICAucmVkdWNlKAogICAgICAgICAgKFtzb2ZhciwgY3VycmVudF0sIGl0ZW0pID0+IHsKICAgICAgICAgICAgaWYgKCFjdXJyZW50KSB7CiAgICAgICAgICAgICAgcmV0dXJuIFtzb2ZhciwgaXRlbV07CiAgICAgICAgICAgIH0gZWxzZSBpZiAoY3VycmVudC5vdmVybGFwcyhpdGVtKSB8fCBjdXJyZW50LmFidXRzU3RhcnQoaXRlbSkpIHsKICAgICAgICAgICAgICByZXR1cm4gW3NvZmFyLCBjdXJyZW50LnVuaW9uKGl0ZW0pXTsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICByZXR1cm4gW3NvZmFyLmNvbmNhdChbY3VycmVudF0pLCBpdGVtXTsKICAgICAgICAgICAgfQogICAgICAgICAgfSwKICAgICAgICAgIFtbXSwgbnVsbF0KICAgICAgICApOwogICAgICBpZiAoZmluYWwpIHsKICAgICAgICBmb3VuZC5wdXNoKGZpbmFsKTsKICAgICAgfQogICAgICByZXR1cm4gZm91bmQ7CiAgICB9CgogICAgLyoqCiAgICAgKiBSZXR1cm4gYW4gYXJyYXkgb2YgSW50ZXJ2YWxzIHJlcHJlc2VudGluZyB0aGUgc3BhbnMgb2YgdGltZSB0aGF0IG9ubHkgYXBwZWFyIGluIG9uZSBvZiB0aGUgc3BlY2lmaWVkIEludGVydmFscy4KICAgICAqIEBwYXJhbSB7QXJyYXl9IGludGVydmFscwogICAgICogQHJldHVybiB7QXJyYXl9CiAgICAgKi8KICAgIHN0YXRpYyB4b3IoaW50ZXJ2YWxzKSB7CiAgICAgIGxldCBzdGFydCA9IG51bGwsCiAgICAgICAgY3VycmVudENvdW50ID0gMDsKICAgICAgY29uc3QgcmVzdWx0cyA9IFtdLAogICAgICAgIGVuZHMgPSBpbnRlcnZhbHMubWFwKChpKSA9PiBbCiAgICAgICAgICB7IHRpbWU6IGkucywgdHlwZTogInMiIH0sCiAgICAgICAgICB7IHRpbWU6IGkuZSwgdHlwZTogImUiIH0sCiAgICAgICAgXSksCiAgICAgICAgZmxhdHRlbmVkID0gQXJyYXkucHJvdG90eXBlLmNvbmNhdCguLi5lbmRzKSwKICAgICAgICBhcnIgPSBmbGF0dGVuZWQuc29ydCgoYSwgYikgPT4gYS50aW1lIC0gYi50aW1lKTsKCiAgICAgIGZvciAoY29uc3QgaSBvZiBhcnIpIHsKICAgICAgICBjdXJyZW50Q291bnQgKz0gaS50eXBlID09PSAicyIgPyAxIDogLTE7CgogICAgICAgIGlmIChjdXJyZW50Q291bnQgPT09IDEpIHsKICAgICAgICAgIHN0YXJ0ID0gaS50aW1lOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICBpZiAoc3RhcnQgJiYgK3N0YXJ0ICE9PSAraS50aW1lKSB7CiAgICAgICAgICAgIHJlc3VsdHMucHVzaChJbnRlcnZhbC5mcm9tRGF0ZVRpbWVzKHN0YXJ0LCBpLnRpbWUpKTsKICAgICAgICAgIH0KCiAgICAgICAgICBzdGFydCA9IG51bGw7CiAgICAgICAgfQogICAgICB9CgogICAgICByZXR1cm4gSW50ZXJ2YWwubWVyZ2U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FJldHVybnMgYW4gSVNPIDg2MDEtY29tcGxpYW50IHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiB0aGlzIEludGVydmFsLgogICAgICogQHNlZSBodHRwczovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9JU09fODYwMSNUaW1lX2ludGVydmFscwogICAgICogQHBhcmFtIHtPYmplY3R9IG9wdHMgLSBUaGUgc2FtZSBvcHRpb25zIGFzIHtAbGluayBEYXRlVGltZSN0b0lTT30KICAgICAqIEByZXR1cm4ge3N0cmluZ30KICAgICAqLwogICAgdG9JU08ob3B0cykgewogICAgICBpZiAoIXRoaXMuaXNWYWxpZCkgcmV0dXJuIElOVkFMSUQkMTsKICAgICAgcmV0dXJuIGAke3RoaXMucy50b0lTTyhvcHRzKX0vJHt0aGlzLmUudG9JU08ob3B0cyl9YDsKICAgIH0KCiAgICAvKioKICAgICAqIFJldHVybnMgYW4gSVNPIDg2MDEtY29tcGxpYW50IHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiBkYXRlIG9mIHRoaXMgSW50ZXJ2YWwuCiAgICAgKiBUaGUgdGltZSBjb21wb25lbnRzIGFyZSBpZ25vcmVkLgogICAgICogQHNlZSBodHRwczovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9JU09fODYwMSNUaW1lX2ludGVydmFscwogICAgICogQHJldHVybiB7c3RyaW5nfQogICAgICovCiAgICB0b0lTT0RhdGUoKSB7CiAgICAgIGlmICghdGhpcy5pc1ZhbGlkKSByZXR1cm4gSU5WQUxJRCQxOwogICAgICByZXR1cm4gYCR7dGhpcy5zLnRvSVNPRGF0ZSgpfS8ke3RoaXMuZS50b0lTT0RhdGUoKX1gOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJucyBhbiBJU08gODYwMS1jb21wbGlhbnQgc3RyaW5nIHJlcHJlc2VudGF0aW9uIG9mIHRpbWUgb2YgdGhpcyBJbnRlcnZhbC4KICAgICAqIFRoZSBkYXRlIGNvbXBvbmVudHMgYXJlIGlnbm9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sb2MsICJ7Miw0fSIpLAogICAgICBmb3VyVG9TaXggPSBkaWdpdFJlZ2V4KGxvYywgIns0LDZ9IiksCiAgICAgIGxpdGVyYWwgPSAodCkgPT4gKHsgcmVnZXg6IFJlZ0V4cChlc2NhcGVUb2tlbih0LnZhbCkpLCBkZXNlcjogKFtzXSkgPT4gcywgbGl0ZXJhbDogdHJ1ZSB9KSwKICAgICAgdW5pdGF0ZSA9ICh0KSA9PiB7CiAgICAgICAgaWYgKHRva2VuLmxpdGVyYWwpIHsKICAgICAgICAgIHJldHVybiBsaXRlcmFsKHQpOwogICAgICAgIH0KICAgICAgICBzd2l0Y2ggKHQudmFsKSB7CiAgICAgICAgICAvLyBlcmEKICAgICAgICAgIGNhc2UgIkciOgogICAgICAgICAgICByZXR1cm4gb25lT2YobG9jLmVyYXMoInNob3J0IiksIDApOwogICAgICAgICAgY2FzZSAiR0ciOgogICAgICAgICAgICByZXR1cm4gb25lT2YobG9jLmVyYXMoImxvbmciKSwgMCk7CiAgICAgICAgICAvLyB5ZWFycwogICAgICAgICAgY2FzZSAieSI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KG9uZVRvU2l4KTsKICAgICAgICAgIGNhc2UgInl5IjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQodHdvVG9Gb3VyLCB1bnRydW5jYXRlWWVhcik7CiAgICAgICAgICBjYXNlICJ5eXl5IjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQoZm91cik7CiAgICAgICAgICBjYXNlICJ5eXl5eSI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KGZvdXJUb1NpeCk7CiAgICAgICAgICBjYXNlICJ5eXl5eXkiOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdChzaXgpOwogICAgICAgICAgLy8gbW9udGhzCiAgICAgICAgICBjYXNlICJNIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQob25lT3JUd28pOwogICAgICAgICAgY2FzZSAiTU0iOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdCh0d28pOwogICAgICAgICAgY2FzZSAiTU1NIjoKICAgICAgICAgICAgcmV0dXJuIG9uZU9mKGxvYy5tb250aHMoInNob3J0IiwgdHJ1ZSksIDEpOwogICAgICAgICAgY2FzZSAiTU1NTSI6CiAgICAgICAgICAgIHJldHVybiBvbmVPZihsb2MubW9udGhzKCJsb25nIiwgdHJ1ZSksIDEpOwogICAgICAgICAgY2FzZSAiTCI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KG9uZU9yVHdvKTsKICAgICAgICAgIGNhc2UgIkxMIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQodHdvKTsKICAgICAgICAgIGNhc2UgIkxMTCI6CiAgICAgICAgICAgIHJldHVybiBvbmVPZihsb2MubW9udGhzKCJzaG9ydCIsIGZhbHNlKSwgMSk7CiAgICAgICAgICBjYXNlICJMTExMIjoKICAgICAgICAgICAgcmV0dXJuIG9uZU9mKGxvYy5tb250aHMoImxvbmciLCBmYWxzZSksIDEpOwogICAgICAgICAgLy8gZGF0ZXMKICAgICAgICAgIGNhc2UgImQiOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdChvbmVPclR3byk7CiAgICAgICAgICBjYXNlICJkZCI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KHR3byk7CiAgICAgICAgICAvLyBvcmRpbmFscwogICAgICAgICAgY2FzZSAibyI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KG9uZVRvVGhyZWUpOwogICAgICAgICAgY2FzZSAib29vIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQodGhyZWUpOwogICAgICAgICAgLy8gdGltZQogICAgICAgICAgY2FzZSAiSEgiOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdCh0d28pOwogICAgICAgICAgY2FzZSAiSCI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KG9uZU9yVHdvKTsKICAgICAgICAgIGNhc2UgImhoIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQodHdvKTsKICAgICAgICAgIGNhc2UgImgiOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdChvbmVPclR3byk7CiAgICAgICAgICBjYXNlICJtbSI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KHR3byk7CiAgICAgICAgICBjYXNlICJtIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQob25lT3JUd28pOwogICAgICAgICAgY2FzZSAicSI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KG9uZU9yVHdvKTsKICAgICAgICAgIGNhc2UgInFxIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQodHdvKTsKICAgICAgICAgIGNhc2UgInMiOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdChvbmVPclR3byk7CiAgICAgICAgICBjYXNlICJzcyI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KHR3byk7CiAgICAgICAgICBjYXNlICJTIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQob25lVG9UaHJlZSk7CiAgICAgICAgICBjYXNlICJTU1MiOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdCh0aHJlZSk7CiAgICAgICAgICBjYXNlICJ1IjoKICAgICAgICAgICAgcmV0dXJuIHNpbXBsZShvbmVUb05pbmUpOwogICAgICAgICAgY2FzZSAidXUiOgogICAgICAgICAgICByZXR1cm4gc2ltcGxlKG9uZU9yVHdvKTsKICAgICAgICAgIGNhc2UgInV1dSI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KG9uZSk7CiAgICAgICAgICAvLyBtZXJpZGllbQogICAgICAgICAgY2FzZSAiYSI6CiAgICAgICAgICAgIHJldHVybiBvbmVPZihsb2MubWVyaWRpZW1zKCksIDApOwogICAgICAgICAgLy8gd2Vla1llYXIgKGspCiAgICAgICAgICBjYXNlICJra2trIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQoZm91cik7CiAgICAgICAgICBjYXNlICJrayI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KHR3b1RvRm91ciwgdW50cnVuY2F0ZVllYXIpOwogICAgICAgICAgLy8gd2Vla051bWJlciAoVykKICAgICAgICAgIGNhc2UgIlciOgogICAgICAgICAgICByZXR1cm4gaW50VW5pdChvbmVPclR3byk7CiAgICAgICAgICBjYXNlICJXVyI6CiAgICAgICAgICAgIHJldHVybiBpbnRVbml0KHR3byk7CiAgICAgICAgICAvLyB3ZWVrZGF5cwogICAgICAgICAgY2FzZSAiRSI6CiAgICAgICAgICBjYXNlICJjIjoKICAgICAgICAgICAgcmV0dXJuIGludFVuaXQob25lKTsKICAgICAgICAgIGNhc2UgIkVFRSI6CiAgICAgICAgICAgIHJldHVybiBvbmVPZihsb2Mud2Vla2RheXMoInNob3J0IiwgZmFsc2UpLCAxKTsKICAgICAgICAgIGNhc2UgIkVFRUUiOgogICAgICAgICAgICByZXR1cm4gb25lT2YobG9jLndlZWtkYXlzKCJsb25nIiwgZmFsc2UpLCAxKTsKICAgICAgICAgIGNhc2UgImNjYyI6CiAgICAgICAgICAgIHJldHVybiBvbmVPZihsb2Mud2Vla2RheXMoInNob3J0IiwgdHJ1ZSksIDEpOwogICAgICAgICAgY2FzZSAiY2NjYyI6CiAgICAgICAgICAgIHJldHVybiBvbmVPZihsb2Mud2Vla2RheXMoImxvbmciLCB0cnVlKSwgMSk7CiAgICAgICAgICAvLyBvZmZzZXQvem9uZQogICAgICAgICAgY2FzZSAiWiI6CiAgICAgICAgICBjYXNlICJaWiI6CiAgICAgICAgICAgIHJldHVybiBvZmZzZXQobmV3IFJlZ0V4cChgKFsrLV0ke29uZU9yVHdvLnNvdXJjZX0pKD86Oigke3R3by5zb3VyY2V9KSk/YCksIDIpOwogICAgICAgICAgY2FzZSAiWlpaIjoKICAgICAgICAgICAgcmV0dXJuIG9mZnNldChuZXcgUmVnRXhwKGAoWystXSR7b25lT3JUd28uc291cmNlfSkoJHt0d28uc291cmNlfSk/YCksIDIpOwogICAgICAgICAgLy8gd2UgZG9uJ3Qgc3VwcG9ydC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3QiKSB7CiAgICAgIHZhbCA9IHZhbFtzdHlsZV07CiAgICB9CgogICAgaWYgKHZhbCkgewogICAgICByZXR1cm4gewogICAgICAgIGxpdGVyYWw6IGZhbHNlLAogICAgICAgIHZhbCwKICAgICAgfTsKICAgIH0KCiAgICByZXR1cm4gdW5kZWZpbmVkOwogIH0KCiAgZnVuY3Rpb24gYnVpbGRSZWdleCh1bml0cykgewogICAgY29uc3QgcmUgPSB1bml0cy5tYXAoKHUpID0+IHUucmVnZXgpLnJlZHVjZSgoZiwgcikgPT4gYCR7Zn0oJHtyLnNvdXJjZX0pYCwgIiIpOwogICAgcmV0dXJuIFtgXiR7cmV9JGAsIHVuaXRzXTsKICB9CgogIGZ1bmN0aW9uIG1hdGNoKGlucHV0LCByZWdleCwgaGFuZGxlcnMpIHsKICAgIGNvbnN0IG1hdGNoZXMgPSBpbnB1dC5tYXRjaChyZWdleCk7CgogICAgaWYgKG1hdGNoZXMpIHsKICAgICAgY29uc3QgYWxsID0ge307CiAgICAgIGxldCBtYXRjaEluZGV4ID0gMTsKICAgICAgZm9yIChjb25zdCBpIGluIGhhbmRsZXJzKSB7CiAgICAgICAgaWYgKGhhc093blByb3BlcnR5KGhhbmRsZXJzLCBpKSkgewogICAgICAgICAgY29uc3QgaCA9IGhhbmRsZXJzW2ldLAogICAgICAgICAgICBncm91cHMgPSBoLmdyb3VwcyA/IGguZ3JvdXBzICsgMSA6IDE7CiAgICAgICAgICBpZiAoIWgubGl0ZXJhbCAmJiBoLnRva2VuKSB7CiAgICAgICAgICAgIGFsbFtoLnRva2VuLnZhbFswXV0gPSBoLmRlc2VyKG1hdGNoZXMuc2xpY2UobWF0Y2hJbmRleCwgbWF0Y2hJbmRleCArIGdyb3VwcykpOwogICAgICAgICAgfQogICAgICAgICAgbWF0Y2hJbmRleCArPSBncm91cHM7CiAgICAgICAgfQogICAgICB9CiAgICAgIHJldHVybiBbbWF0Y2hlcywgYWxsXTsKICAgIH0gZWxzZSB7CiAgICAgIHJldHVybiBbbWF0Y2hlcywge31dOwogICAgfQogIH0KCiAgZnVuY3Rpb24gZGF0ZVRpbWVGcm9tTWF0Y2hlcyhtYXRjaGVzKSB7CiAgICBjb25zdCB0b0ZpZWxkID0gKHRva2VuKSA9PiB7CiAgICAgIHN3aXRjaCAodG9rZW4pIHsKICAgICAgICBjYXNlICJTIjoKICAgICAgICAgIHJldHVybiAibWlsbGlzZWNvbmQiOwogICAgICAgIGNhc2UgInMiOgogICAgICAgICAgcmV0dXJuICJzZWNvbmQiOwogICAgICAgIGNhc2UgIm0iOgogICAgICAgICAgcmV0dXJuICJtaW51dGUiOwogICAgICAgIGNhc2UgImgiOgogICAgICAgIGNhc2UgIkgiOgogICAgICAgICAgcmV0dXJuICJob3VyIjsKICAgICAgICBjYXNlICJkIjoKICAgICAgICAgIHJldHVybiAiZGF5IjsKICAgICAgICBjYXNlICJvIjoKICAgICAgICAgIHJldHVybiAib3JkaW5hbCI7CiAgICAgICAgY2FzZSAiTCI6CiAgICAgICAgY2FzZSAiTSI6CiAgICAgICAgICByZXR1cm4gIm1vbnRoIjsKICAgICAgICBjYXNlICJ5IjoKICAgICAgICAgIHJldHVybiAieWVhciI7CiAgICAgICAgY2FzZSAiRSI6CiAgICAgICAgY2FzZSAiYyI6CiAgICAgICAgICByZXR1cm4gIndlZWtkYXkiOwogICAgICAgIGNhc2UgIlciOgogICAgICAgICAgcmV0dXJuICJ3ZWVrTnVtYmVyIjsKICAgICAgICBjYXNlICJrIjoKICAgICAgICAgIHJldHVybiAid2Vla1llYXIiOwogICAgICAgIGNhc2UgInEiOgogICAgICAgICAgcmV0dXJuICJxdWFydGVyIjsKICAgICAgICBkZWZhdWx0OgogICAgICAgICAgcmV0dXJuIG51bGw7CiAgICAgIH0KICAgIH07CgogICAgbGV0IHpvbmUgPSBudWxsOwogICAgbGV0IHNwZWNpZmljT2Zmc2V0OwogICAgaWYgKCFpc1VuZGVmaW5lZChtYXRjaGVzLnopKSB7CiAgICAgIHpvbmUgPS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nZXRVVENNaW51dGVzKCksCiAgICAgIHNlY29uZDogZC5nZXRVVENTZWNvbmRzKCksCiAgICAgIG1pbGxpc2Vjb25kOiBkLmdldFVUQ01pbGxpc2Vjb25kcygpLAogICAgfTsKICB9CgogIC8vIGNvbnZlcnQgYSBjYWxlbmRhciBvYmplY3QgdG8gYSBlcG9jaCB0aW1lc3RhbXAKICBmdW5jdGlvbiBvYmpUb1RTKG9iaiwgb2Zmc2V0LCB6b25lKSB7CiAgICByZXR1cm4gZml4T2Zmc2V0KG9ialRvTG9jYWxUUyhvYmopLCBvZmZzZXQsIHpvbmUpOwogIH0KCiAgLy8gY3JlYXRlIGEgbmV3IERUIGluc3RhbmNlIGJ5IGFkZGluZyBhIGR1cmF0aW9uLCBhZGp1c3RpbmcgZm9yIERTVHMKICBmdW5jdGlvbiBhZGp1c3RUaW1lKGluc3QsIGR1cikgewogICAgY29uc3Qgb1ByZSA9IGluc3QubywKICAgICAgeWVhciA9IGluc3QuYy55ZWFyICsgTWF0aC50cnVuYyhkdXIueWVhcnMpLAogICAgICBtb250aCA9IGluc3QuYy5tb250aCArIE1hdGgudHJ1bmMoZHVyLm1vbnRocykgKyBNYXRoLnRydW5jKGR1ci5xdWFydGVycykgKiAzLAogICAgICBjID0gewogICAgICAgIC4uLmluc3QuYywKICAgICAgICB5ZWFyLAogICAgICAgIG1vbnRoLAogICAgICAgIGRheToKICAgICAgICAgIE1hdGgubWluKGluc3QuYy5kYXksIGRheXNJbk1vbnRoKHllYXIsIG1vbnRoKSkgKwogICAgICAgICAgTWF0aC50cnVuYyhkdXIuZGF5cykgKwogICAgICAgICAgTWF0aC50cnVuYyhkdXIud2Vla3MpICogNywKICAgICAgfSwKICAgICAgbWlsbGlzVG9BZGQgPSBEdXJhdGlvbi5mcm9tT2JqZWN0KHsKICAgICAgICB5ZWFyczogZHVyLnllYXJzIC0gTWF0aC50cnVuYyhkdXIueWVhcnMpLAogICAgICAgIHF1YXJ0ZXJzOiBkdXIucXVhcnRlc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dG9yKGNvbmZpZykgewogICAgICBjb25zdCB6b25lID0gY29uZmlnLnpvbmUgfHwgU2V0dGluZ3MuZGVmYXVsdFpvbmU7CgogICAgICBsZXQgaW52YWxpZCA9CiAgICAgICAgY29uZmlnLmludmFsaWQgfHwKICAgICAgICAoTnVtYmVyLmlzTmFOKGNvbmZpZy50cykgPyBuZXcgSW52YWxpZCgiaW52YWxpZCBpbnB1dCIpIDogbnVsbCkgfHwKICAgICAgICAoIXpvbmUuaXNWYWxpZCA/IHVuc3VwcG9ydGVkWm9uZSh6b25lKSA6IG51bGwpOwogICAgICAvKioKICAgICAgICogQGFjY2VzcyBwcml2YXRlCiAgICAgICAqLwogICAgICB0aGlzLnRzID0gaXNVbmRlZmluZWQoY29uZmlnLnRzKSA/IFNldHRpbmdzLm5vdygpIDogY29uZmlnLnRzOwoKICAgICAgbGV0IGMgPSBudWxsLAogICAgICAgIG8gPSBudWxsOwogICAgICBpZiAoIWludmFsaWQpIHsKICAgICAgICBjb25zdCB1bmNoYW5nZWQgPSBjb25maWcub2xkICYmIGNvbmZpZy5vbGQudHMgPT09IHRoaXMudHMgJiYgY29uZmlnLm9sZC56b25lLmVxdWFscyh6b25lKTsKCiAgICAgICAgaWYgKHVuY2hhbmdlZCkgewogICAgICAgICAgW2MsIG9dID0gW2NvbmZpZy5vbGQuYywgY29uZmlnLm9sZC5vXTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgY29uc3Qgb3QgPSB6b25lLm9mZnNldCh0aGlzLnRzKTsKICAgICAgICAgIGMgPSB0c1RvT2JqKHRoaXMudHMsIG90KTsKICAgICAgICAgIGludmFsaWQgPSBOdW1iZXIuaXNOYU4oYy55ZWFyKSA/IG5ldyBJbnZhbGlkKCJpbnZhbGlkIGlucHV0IikgOiBudWxsOwogICAgICAgICAgYyA9IGludmFsaWQgPyBudWxsIDogYzsKICAgICAgICAgIG8gPSBpbnZhbGlkID8gbnVsbCA6IG90OwogICAgICAgIH0KICAgICAgfQoKICAgICAgLyoqCiAgICAgICAqIEBhY2Nlc3MgcHJpdmF0ZQogICAgICAgKi8KICAgICAgdGhpcy5fem9uZSA9IHpvbmU7CiAgICAgIC8qKgogICAgICAgKiBAYWNjZXNzIHByaXZhdGUKICAgICAgICovCiAgICAgIHRoaXMubG9jID0gY29uZmlnLmxvYyB8fCBMb2NhbGUuY3JlYXRlKCk7CiAgICAgIC8qKgogICAgICAgKiBAYWNjZXNzIHByaXZhdGUKICAgICAgICovCiAgICAgIHRoaXMuaW52YWxpZCA9IGludmFsaWQ7CiAgICAgIC8qKgogICAgICAgKiBAYWNjZXNzIHByaXZhdGUKICAgICAgICovCiAgICAgIHRoaXMud2Vla0RhdGEgPSBudWxsOwogICAgICAvKioKICAgICAgICogQGFjY2VzcyBwcml2YXRlCiAgICAgICAqLwogICAgICB0aGlzLmMgPSBjOwogICAgICAvKioKICAgICAgICogQGFjY2VzcyBwcml2YXRlCiAgICAgICAqLwogICAgICB0aGlzLm8gPSBvOwogICAgICAvKioKICAgICAgICogQGFjY2VzcyBwcml2YXRlCiAgICAgICAqLwogICAgICB0aGlzLmlzTHV4b25EYXRlVGltZSA9IHRydWU7CiAgICB9CgogICAgLy8gQ09OU1RSVUNUCgogICAgLyoqCiAgICAgKiBDcmVhdGUgYSBEYXRlVGltZSBmb3IgdGhlIGN1cnJlbnQgaW5zdGFudCwgaW4gdGhlIHN5c3RlbSdzIHRpbWUgem9uZS4KICAgICAqCiAgICAgKiBVc2UgU2V0dGluZ3MgdG8gb3ZlcnJpZGUgdGhlc2UgZGVmYXVsdCB2YWx1ZXMgaWYgbmVlZGVkLgogICAgICogQGV4YW1wbGUgRGF0ZVRpbWUubm93KCkudG9JU08oKSAvL34+IG5vdyBpbiB0aGUgSVNPIGZvcm1hdAogICAgICogQHJldHVybiB7RGF0ZVRpbWV9CiAgICAgKi8KICAgIHN0YXRpYyBub3coKSB7CiAgICAgIHJldHVybiBuZXcgRGF0ZVRpbWUoe30pOwogICAgfQoKICAgIC8qKgogICAg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gb3Igd2Vla051bWJlcikgLT4gZXJyb3IKICAgICAgLy8gKGdyZWdvcmlhbiBtb250aCBvciBkYXkpICsgb3JkaW5hbCAtPiBlcnJvcgogICAgICAvLyBvdGhlcndpc2UganVzdCB1c2Ugd2Vla3Mgb3Igb3JkaW5hbHMgb3IgZ3JlZ29yaWFuLCBkZXBlbmRpbmcgb24gd2hhdCdzIHNwZWNpZmllZAoKICAgICAgaWYgKChjb250YWluc0dyZWdvciB8fCBjb250YWluc09yZGluYWwpICYmIGRlZmluaXRlV2Vla0RlZikgewogICAgICAgIHRocm93IG5ldyBDb25mbGljdGluZ1NwZWNpZmljYXRpb25FcnJvcigKICAgICAgICAgICJDYW4ndCBtaXggd2Vla1llYXIvd2Vla051bWJlciB1bml0cyB3aXRoIHllYXIvbW9udGgvZGF5IG9yIG9yZGluYWxzIgogICAgICAgICk7CiAgICAgIH0KCiAgICAgIGlmIChjb250YWluc0dyZWdvck1EICYmIGNvbnRhaW5zT3JkaW5hbCkgewogICAgICAgIHRocm93IG5ldyBDb25mbGljdGluZ1NwZWNpZmljYXRpb25FcnJvcigiQ2FuJ3QgbWl4IG9yZGluYWwgZGF0ZXMgd2l0aCBtb250aC9kYXkiKTsKICAgICAgfQoKICAgICAgY29uc3QgdXNlV2Vla0RhdGEgPSBkZWZpbml0ZVdlZWtEZWYgfHwgKG5vcm1hbGl6ZWQud2Vla2RheSAmJiAhY29udGFpbnNHcmVnb3IpOwoKICAgICAgLy8gY29uZmlndXJlIG91cnNlbHZlcyB0byBkZWFsIHdpdGggZ3JlZ29yaWFuIGRhdGVzIG9yIHdlZWsgc3R1ZmYKICAgICAgbGV0IHVuaXRzLAogICAgICAgIGRlZmF1bHRWYWx1ZXMsCiAgICAgICAgb2JqTm93ID0gdHNUb09iaih0c05vdywgb2Zmc2V0UHJvdmlzKTsKICAgICAgaWYgKHVzZVdlZWtEYXRhKSB7CiAgICAgICAgdW5pdHMgPSBvcmRlcmVkV2Vla1VuaXRzOwogICAgICAgI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F0YShub3JtYWxpemVkKQogICAgICAgICAgOiBjb250YWluc09yZGluYWwKICAgICAgICAgID8gaGFzSW52YWxpZE9yZGluYWxEYXRhKG5vcm1hbGl6ZWQpCiAgICAgICAgICA6IGhhc0ludmFsaWRHcmVnb3JpYW5EYXRhKG5vcm1hbGl6ZWQpLAogICAgICAgIGludmFsaWQgPSBoaWdoZXJPcmRlckludmFsaWQgfHwgaGFzSW52YWxpZFRpbWVEYXRhKG5vcm1hbGl6ZWQpOwoKICAgICAgaWYgKGludmFsaWQpIHsKICAgICAgICByZXR1cm4gRGF0ZVRpbWUuaW52YWxpZChpbnZhbGlkKTsKICAgICAgfQoKICAgICAgLy8gY29tcHV0ZSB0aGUgYWN0dWFsIHRpbWUKICAgICAgY29uc3QgZ3JlZ29yaWFuID0gdXNlV2Vla0RhdGEKICAgICAgICAgID8gd2Vla1RvR3JlZ29yaWFuKG5vcm1hbGl6ZWQpCiAgICAgICAgICA6IGNvbnRhaW5zT3JkaW5hbAogICAgICAgICAgPyBvcmRpbmFsVG9HcmVnb3JpYW4obm9ybWFsaXplZCkKICAgICAgICAgIDogbm9ybWFsaXplZCwKICAgICAgICBbdHNGaW5hbCwgb2Zmc2V0RmluYWxdID0gb2JqVG9UUyhncmVnb3JpYW4sIG9mZnNldFByb3Zpcywgem9uZVRvVXNlKSwKICAgICAgICBpbnN0ID0gbmV3IERhdGVUaW1lKHsKICAgICAgICAgIHRzOiB0c0ZpbmFsLAogICAgICAgICAgem9uZTogem9uZVRvVXNlLAogICAgICAgICAgbzogb2Zmc2V0RmluYWwsCiAgICAgICAgICBsb2MsCiAgICAgICAgfSk7CgogICAgICAvLyBncmVnb3JpYW4gZGF0YSArIHdlZWtkYXkgc2VydmVzIG9ubHkgdG8gdmFsaWRhdGUKICAgICAgaWYgKG5vcm1hbGl6ZWQud2Vla2RheSAmJiBjb250YWluc0dyZWdvciAmJiBvYmoud2Vla2RheSAhPT0gaW5zdC53ZWVrZGF5KSB7CiAgICAgICAgcmV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IXRoaXMuaXNWYWxpZCkgcmV0dXJuIHRoaXM7CgogICAgICBjb25zdCBub3JtYWxpemVkID0gbm9ybWFsaXplT2JqZWN0KHZhbHVlcywgbm9ybWFsaXplVW5pdCksCiAgICAgICAgc2V0dGluZ1dlZWtTdHVmZiA9CiAgICAgICAgICAhaXNVbmRlZmluZWQobm9ybWFsaXplZC53ZWVrWWVhcikgfHwKICAgICAgICAgICFpc1VuZGVmaW5lZChub3JtYWxpemVkLndlZWtOdW1iZXIpIHx8CiAgICAgICAgICAhaXNVbmRlZmluZWQobm9ybWFsaXplZC53ZWVrZGF5KSwKICAgICAgICBjb250YWluc09yZGluYWwgPSAhaXNVbmRlZmluZWQobm9ybWFsaXplZC5vcmRpbmFsKSwKICAgICAgICBjb250YWluc0dyZWdvclllYXIgPSAhaXNVbmRlZmluZWQobm9ybWFsaXplZC55ZWFyKSwKICAgICAgICBjb250YWluc0dyZWdvck1EID0gIWlzVW5kZWZpbmVkKG5vcm1hbGl6ZWQubW9udGgpIHx8ICFpc1VuZGVmaW5lZChub3JtYWxpemVkLmRheSksCiAgICAgICAgY29udGFpbnNHcmVnb3IgPSBjb250YWluc0dyZWdvclllYXIgfHwgY29udGFpbnNHcmVnb3JNRCwKICAgICAgICBkZWZpbml0ZVdlZWtEZWYgPSBub3JtYWxpemVkLndlZWtZZWFyIHx8IG5vcm1hbGl6ZWQud2Vla051bWJlcjsKCiAgICAgIGlmICgoY29udGFpbnNHcmVnb3IgfHwgY29udGFpbnNPcmRpbmFsKSAmJiBkZWZpbml0ZVdlZWtEZWYpIHsKICAgICAgICB0aHJvdyBuZXcgQ29uZmxpY3RpbmdTcGVjaWZpY2F0aW9uRXJyb3IoCiAgICAgICAgICAiQ2FuJ3QgbWl4IHdlZWtZZWFyL3dlZWtOdW1iZXIgdW5pdHMgd2l0aCB5ZWFyL21vbnRoL2RheSBvciBvcmRpbmFscyIKICAgICAgICApOwogICAgICB9CgogICAgICBpZiAoY29udGFpbnNHcmVnb3JNRC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ywgNSwgMzApLnN0YXJ0T2YoJ2hvdXInKS50b0lTT1RpbWUoKTsgLy89PiAnMDU6MDA6MDAuMDAwLTA1OjAwJwogICAgICogQHJldHVybiB7RGF0ZVRpbWV9CiAgICAgKi8KICAgIHN0YXJ0T2YodW5pdCkgewogICAgICBpZiAoIXRoaXMuaXNWYWxpZCkgcmV0dXJuIHRoaXM7CiAgICAgIGNvbnN0IG8gPSB7fSwKICAgICAgICBub3JtYWxpemVkVW5pdCA9IER1cmF0aW9uLm5vcm1hbGl6ZVVuaXQodW5pdCk7CiAgICAgIHN3aXRjaCAobm9ybWFsaXplZFVuaXQpIHsKICAgICAgICBjYXNlICJ5ZWFycyI6CiAgICAgICAgICBvLm1vbnRoID0gMTsKICAgICAgICAvLyBmYWxscyB0aHJvdWdoCiAgICAgICAgY2FzZSAicXVhcnRlcnMiOgogICAgICAgIGNhc2UgIm1vbnRocyI6CiAgICAgICAgICBvLmRheSA9IDE7CiAgICAgICAgLy8gZmFsbHMgdGhyb3VnaAogICAgICAgIGNhc2UgIndlZWtzIjoKICAgICAgICBjYXNlICJkYXlzIjoKICAgICAgICAgIG8uaG91ciA9IDA7CiAgICAgICAgLy8gZmFsbHMgdGhyb3VnaAogICAgICAgIGNhc2UgImhvdXJzIjoKICAgICAgICAgIG8ubWludXRlID0gMDsKICAgICAgICAvLyBmYWxscyB0aHJvdWdoCiAgICAgICAgY2FzZSAibWludXRlcyI6CiAgICAgICAgICBvLnNlY29uZCA9IDA7CiAgICAgICAgLy8gZmFsbHMgdGhyb3VnaAogICAgICAgIGNhc2UgInNlY29uZHMiOgogICAgICAgICAgby5taWxsaXNlY29uZCA9IDA7CiAgICAgICAgICBicmVhazsKICAgICAgICAvLyBubyBkZWZhdWx0LCBpbnZhbGlkIHVuaXRzIHRocm93IGluIG5vcm1hbGl6ZVVuaXQoKQogICAgICB9CgogICAgICBpZiAobm9ybWFsaXplZFVuaXQgPT09ICJ3ZWVrcyIpIHsKICAgICAgICBvLndlZWtkYX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kWm9uZSA9IGZhbHNlLAogICAgICBmb3JtYXQgPSAiZXh0ZW5kZWQiLAogICAgfSA9IHt9KSB7CiAgICAgIGlmICghdGhpcy5pc1ZhbGlkKSB7CiAgICAgICAgcmV0dXJuIG51bGw7CiAgICAgIH0KCiAgICAgIGxldCBjID0gaW5jbHVkZVByZWZpeCA/ICJUIiA6ICIiOwogICAgICByZXR1cm4gKAogICAgICAgIGMgKwogICAgICAgIHRvSVNPVGltZSgKICAgICAgICAgIHRoaXMsCiAgICAgICAgICBmb3JtYXQgPT09ICJleHRlbmRlZCIsCiAgICAgICAgICBzdXBwcmVzc1NlY29uZHMsCiAgICAgICAgICBzdXBwcmVzc01pbGxpc2Vjb25kcywKICAgICAgICAgIGluY2x1ZGVPZmZzZXQsCiAgICAgICAgICBleHRlbmRlZFpvbmUKICAgICAgICApCiAgICAgICk7CiAgICB9CgogICAgLyoqCiAgICAgKiBSZXR1cm5zIGFuIFJGQyAyODIyLWNvbXBhdGlibGUgc3RyaW5nIHJlcHJlc2VudGF0aW9uIG9mIHRoaXMgRGF0ZVRpbWUKICAgICAqIEBleGFtcGxlIERhdGVUaW1lLnV0YygyMDE0LCA3LCAxMykudG9SRkMyODIyKCkgLy89PiAnU3VuLCAxMyBKdWwgMjAxNCAwMDowMDowMCArMDAwMCcKICAgICAqIEBleGFtcGxlIERhdGVUaW1lLmxvY2FsKDIwMTQsIDcsIDEzKS50b1JGQzI4MjIoKSAvLz0+ICdTdW4sIDEzIEp1bCAyMDE0IDAwOjAwOjAwIC0wNDAwJwogICAgICogQHJldHVybiB7c3RyaW5nfQogICAgICovCiAgICB0b1JGQzI4MjIoKSB7CiAgICAgIHJldHVybiB0b1RlY2hGb3JtYXQodGhpcywgIkVFRSwgZGQgTExMIHl5eXkgSEg6bW06c3MgWlpaIiwgZmFsc2UpOwogICAgfQoKICAgIC8qKgogICAgICogUmV0dXJucyBhIHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiB0aGlzIERhdGVUaW1lIGF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zZQogICAgICogQGV4YW1wbGUKICAgICAqIHZhciBpMSA9IERhdGVUaW1lLmZyb21JU08oJzE5ODItMDUtMjVUMDk6NDUnKSwKICAgICAqICAgICBpMiA9IERhdGVUaW1lLmZyb21JU08oJzE5ODMtMTAtMTRUMTA6MzAnKTsKICAgICAqIGkyLmRpZmYoaTEpLnRvT2JqZWN0KCkgLy89PiB7IG1pbGxpc2Vjb25kczogNDM4MDc1MDAwMDAgfQogICAgICogaTIuZGlmZihpMSwgJ2hvdXJzJykudG9PYmplY3QoKSAvLz0+IHsgaG91cnM6IDEyMTY4Ljc1IH0KICAgICAqIGkyLmRpZmYoaTEsIFsnbW9udGhzJywgJ2RheXMnXSkudG9PYmplY3QoKSAvLz0+IHsgbW9udGhzOiAxNiwgZGF5czogMTkuMDMxMjUgfQogICAgICogaTIuZGlmZihpMSwgWydtb250aHMnLCAnZGF5cycsICdob3VycyddKS50b09iamVjdCgpIC8vPT4geyBtb250aHM6IDE2LCBkYXlzOiAxOSwgaG91cnM6IDAuNzUgfQogICAgICogQHJldHVybiB7RHVyYXRpb259CiAgICAgKi8KICAgIGRpZmYob3RoZXJEYXRlVGltZSwgdW5pdCA9ICJtaWxsaXNlY29uZHMiLCBvcHRzID0ge30pIHsKICAgICAgaWYgKCF0aGlzLmlzVmFsaWQgfHwgIW90aGVyRGF0ZVRpbWUuaXNWYWxpZCkgewogICAgICAgIHJldHVybiBEdXJhdGlvbi5pbnZhbGlkKCJjcmVhdGVkIGJ5IGRpZmZpbmcgYW4gaW52YWxpZCBEYXRlVGltZSIpOwogICAgICB9CgogICAgICBjb25zdCBkdXJPcHRzID0geyBsb2NhbGU6IHRoaXMubG9jYWxlLCBudW1iZXJpbmdTeXN0ZW06IHRoaXMubnVtYmVyaW5nU3lzdGVtLCAuLi5vcHRzIH07CgogICAgICBjb25zdCB1bml0cyA9IG1heWJlQXJyYXkodW5pdCkubWFwKER1cmF0aW9uLm5vcm1hbGl6ZVVuaXQpLAogICAgICAgIG90aGV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pb25zID0ge30pIHsKICAgICAgcmV0dXJuIERhdGVUaW1lLmZyb21Gb3JtYXRFeHBsYWluKHRleHQsIGZtdCwgb3B0aW9ucyk7CiAgICB9CgogICAgLy8gRk9STUFUIFBSRVNFVFMKCiAgICAvKioKICAgICAqIHtAbGluayBEYXRlVGltZSN0b0xvY2FsZVN0cmluZ30gZm9ybWF0IGxpa2UgMTAvMTQvMTk4MwogICAgICogQHR5cGUge09iamVjdH0KICAgICAqLwogICAgc3RhdGljIGdldCBEQVRFX1NIT1JUKCkgewogICAgICByZXR1cm4gREFURV9TSE9SVDsKICAgIH0KCiAgICAvKioKICAgICAqIHtAbGluayBEYXRlVGltZSN0b0xvY2FsZVN0cmluZ30gZm9ybWF0IGxpa2UgJ09jdCAxNCwgMTk4MycKICAgICAqIEB0eXBlIHtPYmplY3R9CiAgICAgKi8KICAgIHN0YXRpYyBnZXQgREFURV9NRUQoKSB7CiAgICAgIHJldHVybiBEQVRFX01FRDsKICAgIH0KCiAgICAvKioKICAgICAqIHtAbGluayBEYXRlVGltZSN0b0xvY2FsZVN0cmluZ30gZm9ybWF0IGxpa2UgJ0ZyaSwgT2N0IDE0LCAxOTgzJwogICAgICogQHR5cGUge09iamVjdH0KICAgICAqLwogICAgc3RhdGljIGdldCBEQVRFX01FRF9XSVRIX1dFRUtEQVkoKSB7CiAgICAgIHJldHVybiBEQVRFX01FRF9XSVRIX1dFRUtEQVk7CiAgICB9CgogICAgLyoqCiAgICAgKiB7QGxpbmsgRGF0ZVRpbWUjdG9Mb2NhbGVTdHJpbmd9IGZvcm1hdCBsaWtlICdPY3RvYmVyIDE0LCAxOTgzJwogICAgICogQHR5cGUge09iamVjdH0KICAgICAqLwogICAgc3RhdGljIGdldCBEQVRFX0ZVTEwoKSB7CiAgICAgIHJldHVybiBEQVRFX0ZVTEw7CiAgICB9CgogICAgLyoqCiAgICAgKiB7QGxpbmsgRGF0ZVRpbWUjdG9Mb2NhbGVTdHJpbmd9IGZvcm1hdCBsaWtl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wogICAgICBzdWNjZXNzZnVsOwogICAgICBjb25zdHJ1Y3Rvcih2YWx1ZSkgewogICAgICAgICAgdGhpcy52YWx1ZSA9IHZhbHVlOwogICAgICAgICAgdGhpcy5zdWNjZXNzZnVsID0gdHJ1ZTsKICAgICAgfQogICAgICBtYXAoZikgewogICAgICAgICAgcmV0dXJuIG5ldyBTdWNjZXNzKGYodGhpcy52YWx1ZSkpOwogICAgICB9CiAgICAgIGZsYXRNYXAoZikgewogICAgICAgICAgcmV0dXJuIGYodGhpcy52YWx1ZSk7CiAgICAgIH0KICAgICAgbWFwRXJyKGYpIHsKICAgICAgICAgIHJldHVybiB0aGlzOwogICAgICB9CiAgICAgIGJpbWFwKHN1Y2MsIF9mYWlsKSB7CiAgICAgICAgICByZXR1cm4gdGhpcy5tYXAoc3VjYyk7CiAgICAgIH0KICAgICAgb3JFbHNlKF92YWx1ZSkgewogICAgICAgICAgcmV0dXJuIHRoaXMudmFsdWU7CiAgICAgIH0KICAgICAgY2FzdCgpIHsKICAgICAgICAgIHJldHVybiB0aGlzOwogICAgICB9CiAgICAgIG9yRWxzZVRocm93KF9tZXNzYWdlKSB7CiAgICAgICAgICByZXR1cm4gdGhpcy52YWx1ZTsKICAgICAgfQogIH0KICAvKiogRnVuY3Rpb25hbCByZXR1cm4gdHlwZSBmb3IgZXJyb3IgaGFuZGxpbmcuICovCiAgY2xhc3MgRmFpbHVyZSB7CiAgICAgIGVycm9yOwogICAgICBzdWNjZXNzZnVsOwogICAgICBjb25zdHJ1Y3RvcihlcnJvcikgewogICAgICAgICAgdGhpcy5lcnJvciA9IGVycm9yOwogICAgICAgICAgdGhpcy5zdWNjZXNzZnVsID0gZmFsc2U7CiAgICAgIH0KICAgICAgbWFwKF9mKSB7CiAgICAgICAgICByZXR1cm4gdGhpczsKICAgICAgfQogICAgICBmbGF0TWFwKF9mKSB7CiAgICAgICAgICByZXR1cm4gdGhpczsKICAgICAgfQogICAgICBtYXBFcnIoZikgewogICAgICAgICAgcmV0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jJELVx1REYzNVx1REYzNy1cdURGN0NcdURGN0UtXHVERjg0XHVERjg2LVx1REY5M1x1REZBMC1cdURGQzFcdURGQzVcdURGQzZcdURGQzhcdURGQzlcdURGQ0YtXHVERkQzXHVERkUwLVx1REZGMFx1REZGOC1cdURGRkZdfFx1RERFNlx1RDgzQ1tcdURERTgtXHVEREVDXHVEREVFXHVEREYxXHVEREYyXHVEREY0XHVEREY2LVx1RERGQVx1RERGQ1x1RERGRFx1RERGRl18XHVEREU3XHVEODNDW1x1RERFNlx1RERFN1x1RERFOS1cdURERUZcdURERjEtXHVEREY0XHVEREY2LVx1RERGOVx1RERGQlx1RERGQ1x1RERGRVx1RERGRl18XHVEREU4XHVEODNDW1x1RERFNlx1RERFOFx1RERFOVx1RERFQi1cdURERUVcdURERjAtXHVEREY1XHVEREY3XHVEREZBLVx1RERGRl18XHVEREU5XHVEODNDW1x1RERFQVx1RERFQ1x1RERFRlx1RERGMFx1RERGMlx1RERGNFx1RERGRl18XHVEREVBXHVEODNDW1x1RERFNlx1RERFOFx1RERFQVx1RERFQ1x1RERFRFx1RERGNy1cdURERkFdfFx1RERFQlx1RDgzQ1tcdURERUUtXHVEREYwXHVEREYyXHVEREY0XHVEREY3XXxcdURERUNcdUQ4M0NbXHVEREU2XHVEREU3XHVEREU5LVx1RERFRVx1RERGMS1cdURERjNcdURERjUtXHVEREZBXHVEREZDXHVEREZFXXxcdURERURcdUQ4M0NbXHVEREYwXHVEREYyXHVEREYzXHVEREY3XHVEREY5XHVEREZBXXxcdURERUVcdUQ4M0NbXHVEREU4LVx1RERFQVx1RERGMS1cdURERjRcdURERjYtXHVEREY5XXxcdURERUZcdUQ4M0NbXHVEREVBXHVEREYyXHVEREY0XHVEREY1XXxcdURERjBcdUQ4M0NbXHVEREVBXHVEREVDLVx1RERFRVx1RERGMlx1RERGM1x1RERGNVx1RERGN1x1RERGQ1x1RERGRVx1RERGRl18XHVEREYxXHVEODNDW1x1RERFNi1cdURERThcdURERUVcdURERjBcdURERjctXHVEREZCXHVEREZFXXxcdURERjJcdUQ4M0NbXHVEREU2XHVEREU4LVx1RERFRFx1RERGMC1cdURERkZdfFx1RERGM1x1RDgzQ1tcdURERTZcdURERThcdURERUEtXHVEREVDXHVEREVFXHVEREYxXHVEREY0XHVEREY1XHVEREY3XHVEREZBXHVEREZGXXxcdURERjRcdUQ4M0NcdURERjJ8XHVEREY1XHVEODNDW1x1RERFNlx1RERFQS1cdURERURcdURERjAtXHVEREYzXHVEREY3LVx1RERGOVx1RERGQ1x1RERGRV18XHVEREY2XHVEODNDXHVEREU2fFx1RERGN1x1RDgzQ1tcdURERUFcdURERjRcdURERjhcdURERkFcdURERkNdfFx1RERGOFx1RDgzQ1tcdURERTYtXHVEREVBXHVEREVDLVx1RERGNFx1RERGNy1cdURERjlcdURERkJcdURERkQtXHVEREZGXXxcdURERjlcdUQ4M0NbXHVEREU2XHVEREU4XHVEREU5XHVEREVCLVx1RERFRFx1RERFRi1cdURERjRcdURERjdcdURERjlcdURERkJcdURERkNcdURERkZdfFx1RERGQVx1RDgzQ1tcdURERTZcdURERUNcdURERjJcdURERjNcdURERjhcdURERkVcdURERkZdfFx1RERGQlx1RDgzQ1tcdURERTZcdURERThcdURERUFcdURERUNcdURERUVcdURERjNcdURERkFdfFx1RERGQ1x1RDgzQ1tcdURERUJcdURERjhdfFx1RERGRFx1RDgzQ1x1RERGMHxcdURERkVcdUQ4M0NbXHVEREVBXHVEREY5XXxcdURERkZcdUQ4M0NbXHVEREU2XHVEREYyXHVEREZDXXxcdURGRjNcdUZFMEY/KD86XHUyMDBEKD86XHUyNkE3XHVGRTBGP3xcdUQ4M0NcdURGMDgpKT98XHVERkY0KD86XHUyMDBEXHUyNjIwXHVGRTBGP3xcdURCNDBcdURDNjdcdURCNDBcdURDNjJcdURCNDAoPzpcdURDNjVcdURCNDBcdURDNkVcdURCNDBcdURDNjd8XHVEQzczXHVEQjQwXHVEQzYzXHVEQjQwXHVEQzc0fFx1REM3N1x1REI0MFx1REM2Q1x1REI0MFx1REM3MylcdURCNDBcdURDN0YpPyl8XHVEODNEKD86W1x1REMwOFx1REMyNl0oPzpcdTIwMERcdTJCMUIpP3xbXHVEQzNGXHVEQ0ZEXHVERDQ5XHVERDRBXHVERDZGXHVERDcwXHVERDczXHVERDc2LVx1REQ3OVx1REQ4N1x1REQ4QS1cdUREOERcdUREQTVcdUREQThcdUREQjFcdUREQjJcdUREQkNcdUREQzItXHVEREM0XHVEREQxLVx1REREM1x1REREQy1cdUREREVcdURERTFcdURERTNcdURERThcdURERUZcdURERjNcdURERkFcdURFQ0JcdURFQ0QtXHVERUNGXHVERUUwLVx1REVFNVx1REVFOVx1REVGMFx1REVGM11cdUZFMEY/fFtcdURDNDJcdURDNDNcdURDNDYtXHVEQzUwXHVEQzY2XHVEQzY3XHVEQzZCLVx1REM2RFx1REM3Mlx1REM3NC1cdURDNzZcdURDNzhcdURDN0NcdURDODNcdURDODVcdURDOEZcdURDOTFcdURDQUFcdUREN0FcdUREOTVcdUREOTZcdURFNENcdURFNEZcdURFQzBcdURFQ0NdKD86XHVEODNDW1x1REZGQi1cdURGRkZdKT98W1x1REM2RVx1REM3MFx1REM3MVx1REM3M1x1REM3N1x1REM4MVx1REM4Mlx1REM4Nlx1REM4N1x1REU0NS1cdURFNDdcdURFNEJcdURFNERcdURFNEVcdURFQTNcdURFQjQtXHVERUI2XSg/Olx1RDgzQ1tcdURGRkItXHVERkZGXSk/KD86XHUyMDBEW1x1MjY0MFx1MjY0Ml1cdUZFMEY/KT98W1x1REQ3NFx1REQ5MF0oPzpcdUZFMEZ8XHVEODNDW1x1REZGQi1cdURGRkZdKT98W1x1REMwMC1cdURDMDdcdURDMDktXHVEQzE0XHVEQzE2LVx1REMyNVx1REMyNy1cdURDM0FcdURDM0MtXHVEQzNFXHVEQzQwXHVEQzQ0XHVEQzQ1XHVEQzUxLVx1REM2NVx1REM2QVx1REM3OS1cdURDN0JcdURDN0QtXHVEQzgwXHVEQzg0XHVEQzg4LV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dXJuIHNldHRpbmcucmVuZGVyTnVsbEFzOwogICAgICAgICAgICAgIGNhc2UgInN0cmluZyI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB3cmFwcGVkLnZhbHVlOwogICAgICAgICAgICAgIGNhc2UgIm51bWJlciI6CiAgICAgICAgICAgICAgY2FzZSAiYm9vbGVhbiI6CiAgICAgICAgICAgICAgICAgIHJldHVybiAiIiArIHdyYXBwZWQudmFsdWU7CiAgICAgICAgICAgICAgY2FzZSAiaHRtbCI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB3cmFwcGVkLnZhbHVlLm91dGVySFRNTDsKICAgICAgICAgICAgICBjYXNlICJ3aWRnZXQiOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcHBlZC52YWx1ZS5tYXJrZG93bigpOwogICAgICAgICAgICAgIGNhc2UgImxpbmsiOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcHBlZC52YWx1ZS5tYXJrZG93bigpOwogICAgICAgICAgICAgIGNhc2UgImZ1bmN0aW9uIjoKICAgICAgICAgICAgICAgICAgcmV0dXJuICI8ZnVuY3Rpb24+IjsKICAgICAgICAgICAgICBjYXNlICJhcnJheSI6CiAgICAgICAgICAgICAgICAgIGxldCByZXN1bHQgPSAiIjsKICAgICAgICAgICAgICAgICAgaWYgKHJlY3Vyc2l2ZSkKICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdCArPSAiWyI7CiAgICAgICAgICAgICAgICAgIHJlc3VsdCArPSB3cmFwcGVkLnZhbHVlLm1hcChmID0+IHRvU3RyaW5nKGYsIHNldHRpbmcsIHRydWUpKS5qb2luKCIsICIpOwogICAgICAgICAgICAgICAgICBpZiAocmVjdXJzaXZlKQogICAgICAgICAgICAgICAgICAgICAgcmVzdWx0ICs9ICJdIjsKICAgICAgICAgICAgICAgICAgcmV0dXJuIHJlc3VsdDsKICAgICAgICAgICAgICBjYXNlICJvYmplY3QiOgogICAgICAgICAgICAgICAgICByZXR1cm4gKCJ7ICIgKwogICAgICAgICAgICAgICAgICAgICAgT2JqZWN0LmVudHJpZXMod3JhcHBlZC52YWx1ZSkKICAgICAgICAgICAgICAgICAgICAgICAgICAubWFwKGUgPT4gZVswXSArICI6ICIgKyB0b1N0cmluZyhlWzFdLCBzZXR0aW5nLCB0cnVlKSkKICAgICAgICAgICAgICAgICAgICAgICAgICAuam9pbigiLCAiKSArCiAgICAgICAgICAgICAgICAgICAgICAiIH0iKTsKICAgICAgICAgICAgICBjYXNlICJkYXRlIjoKICAgICAgICAgICAgICAgICAgaWYgKHdyYXBwZWQudmFsdWUuc2Vjb25kID09IDAgJiYgd3JhcHBlZC52YWx1ZS5ob3VyID09IDAgJiYgd3JhcHBlZC52YWx1ZS5taW51dGUgPT0gMCkgewogICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdyYXBwZWQudmFsdWUudG9Gb3JtYXQoc2V0dGluZy5kZWZhdWx0RGF0ZUZvcm1hdCk7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgcmV0dXJuIHdyYXBwZWQudmFsdWUudG9Gb3JtYXQoc2V0dGluZy5kZWZhdWx0RGF0ZVRpbWVGb3JtYXQpOwogICAgICAgICAgICAgIGNhc2UgImR1cmF0aW9uIjoKICAgICAgICAgICAgICAgICAgcmV0dXJuIHJlbmRlck1pbmltYWxEdXJhdGlvbih3cmFwcGVkLnZhbHVlKTsKICAgICAgICAgIH0KICAgICAgfQogICAgICBWYWx1ZXMudG9TdHJpbmcgPSB0b1N0cmluZzsKICAgICAgLyoqIFdyYXAgYSBsaXRlcmFsIHZhbHVlIHNvIHlvdSBjYW4gc3dpdGNoIG9uIGl0IGVhc2lseS4gKi8KICAgICAgZnVuY3Rpb24gd3JhcFZhbHVlKHZhbCkgewogICAgICAgICAgaWYgKGlzTnVsbCh2YWwpKQogICAgICAgICAgICAgIHJldHVybiB7IHR5cGU6ICJudWxsIiwgdmFsdWU6IHZhbCB9OwogICAgICAgICAgZWxzZSBpZiAoaXNOdW1iZXIodmFsKSkKICAgICAgICAgICAgICByZXR1cm4geyB0eXBlOiAibnVtYmVyIiwgdmFsdWU6IHZhbCB9OwogICAgICAgICAgZWxzZSBpZiAoaXNTdHJpbmcodmFsKSkKICAgICAgICAgICAgICByZXR1cm4geyB0eXBlOiAic3RyaW5nIiwgdmFsdWU6IHZhbCB9OwogICAgICAgICAgZWxzZSBpZiAoaXNCb29sZWFuKHZhbCkpCiAgICAgICAgICAgICAgcmV0dXJuIHsgdHlwZTogImJvb2xlYW4iLCB2YWx1ZTogdmFsIH07CiAgICAgICAgICBlbHNlIGlmIChpc0R1cmF0aW9uKHZhbCkpCiAgICAgICAgICAgICAgcmV0dXJuIHsgdHlwZTogImR1cmF0aW9uIiwgdmFsdWU6IHZhbCB9OwogICAgICAgICAgZWxzZSBpZiAoaXNEYXRlKHZhbCkpCiAgICAgICAgICAgICAgcmV0dXJuIHsgdHlwZTogImRhdGUiLCB2YWx1ZTogdmFsIH07CiAgICAgICAgICBlbHNlIGlmIChpc1dpZGdldCh2YWwpKQogICAgICAgICAgICAgIHJldHVybiB7IHR5cGU6ICJ3aWRnZXQiLCB2YWx1ZTogdmFsIH07CiAgICAgICAgICBlbHNlIGlmIChpc0FycmF5KHZhbCkpCiAgICAgICAgICAgICAgcmV0dXJuIHsgdHlwZTogImFycmF5IiwgdmFsdWU6IHZhbCB9OwogICAgICAgICAgZWxzZSBpZiAoaXNMaW5rKHZhbCkpCiAgICAgICAgICAgICAgcmV0dXJuIHsgdHlwZTogImxpbmsiLCB2YWx1ZTogdmFsIH07CiAgICAgICAgICBlbHNlIGlmIChpc0Z1bmN0aW9uKHZhbCkpCiAgICAgICAgICAgICAgcmV0dXJuIHsgdHlwZTogImZ1bmN0aW9uIiwgdmFsdWU6IHZhbCB9OwogICAgICAgICAgZWxzZSBpZiAoaXNIdG1sKHZhbCkpCiAgICAgICAgICAgICAgcmV0dXJuIHsgdHlwZTogImh0bWwiLCB2YWx1ZTogdmFsIH07CiAgICAgICAgICBlbHNlIGlmIChpc09iamVjdCh2YWwpKQogICAgICAgICAgICAgIHJldHVybiB7IHR5cGU6ICJvYmplY3QiLCB2YWx1ZTogdmFsIH07CiAgICAgICAgICBlbHNlCiAgICAgICAgICAgICAgcmV0dXJuIHVuZGVmaW5lZDsKICAgICAgfQogICAgICBWYWx1ZXMud3JhcFZhbHVlID0gd3JhcFZhbHVlOwogICAgICAvKiogUmVjdXJzaXZlbHkgbWFwIGNvbXBsZXggb2JqZWN0cyBhdCB0aGUgbGVhdmVzLiAqLwogICAgICBmdW5jdGlvbiBtYXBMZWF2ZXModmFsLCBmdW5jKSB7CiAgICAgICAgICBpZiAoaXNPYmplY3QodmFsKSkgewogICAgICAgICAgICAgIGxldCByZXN1bHQgPSB7fTsKICAgICAgICAgICAgICBmb3IgKGxldCBba2V5LCB2YWx1ZV0gb2YgT2JqZWN0LmVudHJpZXModmFsKSkKICAgICAgICAgICAgICAgICAgcmVzdWx0W2tleV0gPSBtYXBMZWF2ZXModmFsdWUsIGZ1bmMpOwogICAgICAgICAgICAgIHJldHVybiByZXN1bHQ7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIGlmIChpc0FycmF5KHZhbCkpIHsKICAgICAgICAgICAgICBsZXQgcmVzdWx0ID0gW107CiAgICAgICAgICAgICAgZm9yIChsZXQgdmFsdWUgb2YgdmFsKQogICAgICAgICAgICAgICAgICByZXN1bHQucHVzaChtYXBMZWF2ZXModmFsdWUsIGZ1bmMpKTsKICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0OwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgcmV0dXJuIGZ1bmModmFsKTsKICAgICAgICAgIH0KICAgICAgfQogICAgICBWYWx1ZXMubWFwTGVhdmVzID0gbWFwTGVhdmVzOwogICAgICAvKiogQ29tcGFyZSB0d28gYXJiaXRyYXJ5IEphdmFTY3JpcHQgdmFsdWVzLiBQcm9kdWNlcyBhIHRvdGFsIG9yZGVyaW5nIG92ZXIgQU5ZIHBvc3NpYmxlIGRhdGF2aWV3IHZhbHVlLiAqLwogICAgICBmdW5jdGlvbiBjb21wYXJlVmFsdWUodmFsMSwgdmFsMiwgbGlua05vcm1hbGl6ZXIpIHsKICAgICAgICAgIC8vIEhhbmRsZSB1bmRlZmluZWQvbnVsbHMgZmlyc3QuCiAgICAgICAgICBpZiAodmFsMSA9PT0gdW5kZWZpbmVkKQogICAgICAgICAgICAgIHZhbDEgPSBudWxsOwogICAgICAgICAgaWYgKHZhbDIgPT09IHVuZGVmaW5lZCkKICAgICAgICAgICAgICB2YWwyID0gbnVsbDsKICAgICAgICAgIGlmICh2YWwxID09PSBudWxsICYmIHZhbDIgPT09IG51bGwpCiAgICAgICAgICAgICAgcmV0dXJuIDA7CiAgICAgICAgICBlbHNlIGlmICh2YWwxID09PSBudWxsKQogICAgICAgICAgICAgIHJldHVybiAtMTsKICAgICAgICAgIGVsc2UgaWYgKHZhbDIgPT09IG51bGwpCiAgICAgICAgICAgICAgcmV0dXJuIDE7CiAgICAgICAgICAvLyBBIG5vbi1udWxsIHZhbHVlIG5vdyB3aGljaCB3ZSBjYW4gd3JhcCAmIGNvbXBhcmUgb24uCiAgICAgICAgICBsZXQgd3JhcDEgPSB3cmFwVmFsdWUodmFsMSk7CiAgICAgICAgICBsZXQgd3JhcDIgPSB3cmFwVmFsdWUodmFsMik7CiAgICAgICAgICBpZiAod3JhcDEgPT09IHVuZGVmaW5lZCAmJiB3cmFwMiA9PT0gdW5kZWZpbmVkKQogICAgICAgICAgICAgIHJldHVybiAwOwogICAgICAgICAgZWxzZSBpZiAod3JhcDEgPT09IHVuZGVmaW5lZCkKICAgICAgICAgICAgICByZXR1cm4gLTE7CiAgICAgICAgICBlbHNlIGlmICh3cmFwMiA9PT0gdW5kZWZpbmVkKQogICAgICAgICAgICAgIHJldHVybiAxOwogICAgICAgICAgLy8gU2hvcnQtY2lyY3VpdCBvbiBkaWZmZXJlbnQgdHlwZXMgb3Igb24gcmVmZXJlbmNlIGVxdWFsaXR5LgogICAgICAgICAgaWYgKHdyYXAxLnR5cGUgIT0gd3JhcDIudHlwZSkKICAgICAgICAgICAgICByZXR1cm4gd3JhcDEudHlwZS5sb2NhbGVDb21wYXJlKHdyYXAyLnR5cGUpOwogICAgICAgICAgaWYgKHdyYXAxLnZhbHVlID09PSB3cmFwMi52YWx1ZSkKICAgICAgICAgICAgICByZXR1cm4gMDsKICAgICAgICAgIHN3aXRjaCAod3JhcDEudHlwZSkgewogICAgICAgICAgICAgIGNhc2UgInN0cmluZyI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB3cmFwMS52YWx1ZS5sb2NhbGVDb21wYXJlKHdyYXAyLnZhbHVlKTsKICAgICAgICAgICAgICBjYXNlICJudW1iZXIiOgogICAgICAgICAgICAgICAgICBpZiAod3JhcDEudmFsdWUgPCB3cmFwMi52YWx1ZSkKICAgICAgICAgICAgICAgICAgICAgIHJldHVybiAtMTsKICAgICAgICAgICAgICAgICAgZWxzZSBpZiAod3JhcDEudmFsdWUgPT0gd3JhcDIudmFsdWUpCiAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gMDsKICAgICAgICAgICAgICAgICAgcmV0dXJuIDE7CiAgICAgICAgICAgICAgY2FzZSAibnVsbCI6CiAgICAgICAgICAgICAgICAgIHJldHVybiAwOwogICAgICAgICAgICAgIGNhc2UgImJvb2xlYW4iOgogICAgICAgICAgICAgICAgICBpZiAod3JhcDEudmFsdWUgPT0gd3JhcDIudmFsdWUpCiAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gMDsKICAgICAgICAgICAgICAgICAgZWxzZQogICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHdyYXAxLnZhbHVlID8gMSA6IC0xOwogICAgICAgICAgICAgIGNhc2UgImxpbmsiOgogICAgICAgICAgICAgICAgICBsZXQgbGluazEgPSB3cmFwMS52YWx1ZTsKICAgICAgICAgICAgICAgICAgbGV0IGxpbmsyID0gd3JhcDIudmFsdWU7CiAgICAgICAgICAgICAgICAgIGxldCBub3JtYWxpemUgPSBsaW5rTm9ybWFsaXplciA/PyAoKHgpID0+IHgpOwogICAgICAgICAgICAgICAgICAvLyBXZSBjYW4ndCBjb21wYXJlIGJ5IGZpbGUgbmFtZSBvciBkaXNwbGF5LCBzaW5jZSB0aGF0IHdvdWxkIGJyZWFrIGxpbmsgZXF1YWxpdHkuIENvbXBhcmUgYnkgcGF0aC4KICAgICAgICAgICAgICAgICAgbGV0IHBhdGhDb21wYXJlID0gbm9ybWFsaXplKGxpbmsxLnBhdGgpLmxvY2FsZUNvbXBhcmUobm9ybWFsaXplKGxpbmsyLnBhdGgpKTsKICAgICAgICAgICAgICAgICAgaWYgKHBhdGhDb21wYXJlICE9IDApCiAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gcGF0aENvbXBhcmU7CiAgICAgICAgICAgICAgICAgIC8vIFRoZW4gY29tcGFyZSBieSB0eXBlLgogICAgICAgICAgICAgICAgICBsZXQgdHlwZUNvbXBhcmUgPSBsaW5rMS50eXBlLmxvY2FsZUNvbXBhcmUobGluazIudHlwZSk7CiAgICAgICAgICAgICAgICAgIGlmICh0eXBlQ29tcGFyZSAhPSAwKQogICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHR5cGVDb21wYXJlOwogICAgICAgICAgICAgICAgICAvLyBUaGVuIGNvbXBhcmUgYnkgc3VicGF0aCBleGlzdGVuY2UuCiAgICAgICAgICAgICAgICAgIGlmIChsaW5rMS5zdWJwYXRoICYmICFsaW5rMi5zdWJwYXRoKQogICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIDE7CiAgICAgICAgICAgICAgICAgIGlmICghbGluazEuc3VicGF0aCAmJiBsaW5rMi5zdWJwYXRoKQogICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIC0xOwogICAgICAgICAgICAgICAgICBpZiAoIWxpbmsxLnN1YnBhdGggJiYgIWxpbmsyLnN1YnBhdGgpCiAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gMDsKICAgICAgICAgICAgICAgICAgLy8gU2luY2UgYm90aCBoYXZlIGEgc3VicGF0aCwgY29tcGFyZSBieSBzdWJwYXRoLgogICAgICAgICAgICAgICAgICByZXR1cm4gKGxpbmsxLnN1YnBhdGggPz8gIiIpLmxvY2FsZUNvbXBhcmUobGluazIuc3VicGF0aCA/PyAiIik7CiAgICAgICAgICAgICAgY2FzZSAiZGF0ZSI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB3cmFwMS52YWx1ZSA8IHdyYXAyLnZhbHVlCiAgICAgICAgICAgICAgICAgICAgICA/IC0xCiAgICAgICAgICAgICAgICAgICAgICA6IHdyYXAxLnZhbHVlLmVxdWFscyh3cmFwMi52YWx1ZSkKICAgICAgICAgICAgICAgICAgICAgICAgICA/IDAKICAgICAgICAgICAgICAgICAgICAgICAgICA6IDE7CiAgICAgICAgICAgICAgY2FzZSAiZHVyYXRpb24iOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcDEudmFsdWUgPCB3cmFwMi52YWx1ZQogICAgICAgICAgICAgICAgICAgICAgPyAtMQogICAgICAgICAgICAgICAgICAgICAgOiB3cmFwMS52YWx1ZS5lcXVhbHMod3JhcDIudmFsdWUpCiAgICAgICAgICAgICAgICAgICAgICAgICAgPyAwCiAgICAgICAgICAgICAgICAgICAgICAgICAgOiAxOwogICAgICAgICAgICAgIGNhc2UgImFycmF5IjoKICAgICAgICAgICAgICAgICAgbGV0IGYxID0gd3JhcDEudmFsdWU7CiAgICAgICAgICAgICAgICAgIGxldCBmMiA9IHdyYXAyLnZhbHVlOwogICAgICAgICAgICAgICAgICBmb3IgKGxldCBpbmRleCA9IDA7IGluZGV4IDwgTWF0aC5taW4oZjEubGVuZ3RoLCBmMi5sZW5ndGgpOyBpbmRleCsrKSB7CiAgICAgICAgICAgICAgICAgICAgICBsZXQgY29tcCA9IGNvbXBhcmVWYWx1ZShmMVtpbmRleF0sIGYyW2luZGV4XSk7CiAgICAgICAgICAgICAgICAgICAgICBpZiAoY29tcCAhPSAwKQogICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBjb21wOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIHJldHVybiBmMS5sZW5ndGggLSBmMi5sZW5ndGg7CiAgICAgICAgICAgICAgY2FzZSAib2JqZWN0IjoKICAgICAgICAgICAgICAgICAgbGV0IG8xID0gd3JhcDEudmFsdWU7CiAgICAgICAgICAgICAgICAgIGxldCBvMiA9IHdyYXAyLnZhbHVlOwogICAgICAgICAgICAgICAgICBsZXQgazEgPSBBcnJheS5mcm9tKE9iamVjdC5rZXlzKG8xKSk7CiAgICAgICAgICAgICAgICAgIGxldCBrMiA9IEFycmF5LmZyb20oT2JqZWN0LmtleXMobzIpKTsKICAgICAgICAgICAgICAgICAgazEuc29ydCgpOwogICAgICAgICAgICAgICAgICBrMi5zb3J0KCk7CiAgICAgICAgICAgICAgICAgIGxldCBrZXlDb21wYXJlID0gY29tcGFyZVZhbHVlKGsxLCBrMik7CiAgICAgICAgICAgICAgICAgIGlmIChrZXlDb21wYXJlICE9IDApCiAgICAgICAgICAgICAgICAgICAgICByZXR1cm4ga2V5Q29tcGFyZTsKICAgICAgICAgICAgICAgICAgZm9yIChsZXQga2V5IG9mIGsxKSB7CiAgICAgICAgICAgICAgICAgICAgICBsZXQgY29tcCA9IGNvbXBhcmVWYWx1ZShvMVtrZXldLCBvMltrZXldKTsKICAgICAgICAgICAgICAgICAgICAgIGlmIChjb21wICE9IDApCiAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGNvbXA7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgcmV0dXJuIDA7CiAgICAgICAgICAgICAgY2FzZSAid2lkZ2V0IjoKICAgICAgICAgICAgICBjYXNlICJodG1sIjoKICAgICAgICAgICAgICBjYXNlICJmdW5jdGlvbiI6CiAgICAgICAgICAgICAgICAgIHJldHVybiAwOwogICAgICAgICAgfQogICAgICB9CiAgICAgIFZhbHVlcy5jb21wYXJlVmFsdWUgPSBjb21wYXJlVmFsdWU7CiAgICAgIC8qKiBGaW5kIHRoZSBjb3JyZXNwb25kaW5nIERhdGF2aWV3IHR5cGUgZm9yIGFuIGFyYml0cmFyeSB2YWx1ZS4gKi8KICAgICAgZnVuY3Rpb24gdHlwZU9mKHZhbCkgewogICAgICAgICAgcmV0dXJuIHdyYXBWYWx1ZSh2YWwpPy50eXBlOwogICAgICB9CiAgICAgIFZhbHVlcy50eXBlT2YgPSB0eXBlT2Y7CiAgICAgIC8qKiBEZXRlcm1pbmUgaWYgdGhlIGdpdmVuIHZhbHVlIGlzICJ0cnV0aHkiIChpLmUuLCBpcyBub24tbnVsbCBhbmQgaGFzIGRhdGEgaW4gaXQpLiAqLwogICAgICBmdW5jdGlvbiBpc1RydXRoeShmaWVsZCkgewogICAgICAgICAgbGV0IHdyYXBwZWQgPSB3cmFwVmFsdWUoZmllbGQpOwogICAgICAgICAgaWYgKCF3cmFwcGVkKQogICAgICAgICAgICAgIHJldHVybiBmYWxzZTsKICAgICAgICAgIHN3aXRjaCAod3JhcHBlZC50eXBlKSB7CiAgICAgICAgICAgICAgY2FzZSAibnVtYmVyIjoKICAgICAgICAgICAgICAgICAgcmV0dXJuIHdyYXBwZWQudmFsdWUgIT0gMDsKICAgICAgICAgICAgICBjYXNlICJzdHJpbmciOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcHBlZC52YWx1ZS5sZW5ndGggPiAwOwogICAgICAgICAgICAgIGNhc2UgImJvb2xlYW4iOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcHBlZC52YWx1ZTsKICAgICAgICAgICAgICBjYXNlICJsaW5rIjoKICAgICAgICAgICAgICAgICAgcmV0dXJuICEhd3JhcHBlZC52YWx1ZS5wYXRoOwogICAgICAgICAgICAgIGNhc2UgImRhdGUiOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcHBlZC52YWx1ZS50b01pbGxpcygpICE9IDA7CiAgICAgICAgICAgICAgY2FzZSAiZHVyYXRpb24iOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcHBlZC52YWx1ZS5hcygic2Vjb25kcyIpICE9IDA7CiAgICAgICAgICAgICAgY2FzZSAib2JqZWN0IjoKICAgICAgICAgICAgICAgICAgcmV0dXJuIE9iamVjdC5rZXlzKHdyYXBwZWQudmFsdWUpLmxlbmd0aCA+IDA7CiAgICAgICAgICAgICAgY2FzZSAiYXJyYXkiOgogICAgICAgICAgICAgICAgICByZXR1cm4gd3JhcHBlZC52YWx1ZS5sZW5ndGggPiAwOwogICAgICAgICAgICAgIGNhc2UgIm51bGwiOgogICAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7CiAgICAgICAgICAgICAgY2FzZSAiaHRtbCI6CiAgICAgICAgICAgICAgY2FzZSAid2lkZ2V0IjoKICAgICAgICAgICAgICBjYXNlICJmdW5jdGlvbiI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB0cnVlOwogICAgICAgICAgfQogICAgICB9CiAgICAgIFZhbHVlcy5pc1RydXRoeSA9IGlzVHJ1dGh5OwogICAgICAvKiogRGVlcCBjb3B5IGEgZmllbGQuICovCiAgICAgIGZ1bmN0aW9uIGRlZXBDb3B5KGZpZWxkKSB7CiAgICAgICAgICBpZiAoZmllbGQgPT09IG51bGwgfHwgZmllbGQgPT09IHVuZGVmaW5lZCkKICAgICAgICAgICAgICByZXR1cm4gZmllbGQ7CiAgICAgICAgICBpZiAoVmFsdWVzLmlzQXJyYXkoZmllbGQpKSB7CiAgICAgICAgICAgICAgcmV0dXJuIFtdLmNvbmNhdChmaWVsZC5tYXAodiA9PiBkZWVwQ29weSh2KSkpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSBpZiAoVmFsdWVzLmlzT2JqZWN0KGZpZWxkKSkgewogICAgICAgICAgICAgIGxldCByZXN1bHQgPSB7fTsKICAgICAgICAgICAgICBmb3IgKGxldCBba2V5LCB2YWx1ZV0gb2YgT2JqZWN0LmVudHJpZXMoZmllbGQpKQogICAgICAgICAgICAgICAgICByZXN1bHRba2V5XSA9IGRlZXBDb3B5KHZhbHVlKTsKICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0OwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgcmV0dXJuIGZpZWxkOwogICAgICAgICAgfQogICAgICB9CiAgICAgIFZhbHVlcy5kZWVwQ29weSA9IGRlZXBDb3B5OwogICAgICBmdW5jdGlvbiBpc1N0cmluZyh2YWwpIHsKICAgICAgICAgIHJldHVybiB0eXBlb2YgdmFsID09ICJzdHJpbmciOwogICAgICB9CiAgICAgIFZhbHVlcy5pc1N0cmluZyA9IGlzU3RyaW5nOwogICAgICBmdW5jdGlvbiBpc051bWJlcih2YWwpIHsKICAgICAgICAgIHJldHVybiB0eXBlb2YgdmFsID09ICJudW1iZXIiOwogICAgICB9CiAgICAgIFZhbHVlcy5pc051bWJlciA9IGlzTnVtYmVyOwogICAgICBmdW5jdGlvbiBpc0RhdGUodmFsKSB7CiAgICAgICAgICByZXR1cm4gdmFsIGluc3RhbmNlb2YgRGF0ZVRpbWU7CiAgICAgIH0KICAgICAgVmFsdWVzLmlzRGF0ZSA9IGlzRGF0ZTsKICAgICAgZnVuY3Rpb24gaXNEdXJhdGlvbih2YWwpIHsKICAgICAgICAgIHJldHVybiB2YWwgaW5zdGFuY2VvZiBEdXJhdGlvbjsKICAgICAgfQogICAgICBWYWx1ZXMuaXNEdXJhdGlvbiA9IGlzRHVyYXRpb247CiAgICAgIGZ1bmN0aW9uIGlzTnVsbCh2YWwpIHsKICAgICAgICAgIHJldHVybiB2YWwgPT09IG51bGwgfHwgdmFsID09PSB1bmRlZmluZWQ7CiAgICAgIH0KICAgICAgVmFsdWVzLmlzTnVsbCA9IGlzTnVsbDsKICAgICAgZnVuY3Rpb24gaXNBcnJheSh2YWwpIHsKICAgICAgICAgIHJldHVybiBBcnJheS5pc0FycmF5KHZhbCk7CiAgICAgIH0KICAgICAgVmFsdWVzLmlzQXJyYXkgPSBpc0FycmF5OwogICAgICBmdW5jdGlvbiBpc0Jvb2xlYW4odmFsKSB7CiAgICAgICAgICByZXR1cm4gdHlwZW9mIHZhbCA9PT0gImJvb2xlYW4iOwogICAgICB9CiAgICAgIFZhbHVlcy5pc0Jvb2xlYW4gPSBpc0Jvb2xlYW47CiAgICAgIGZ1bmN0aW9uIGlzTGluayh2YWwpIHsKICAgICAgICAgIHJldHVybiB2YWwgaW5zdGFuY2VvZiBMaW5rOwogICAgICB9CiAgICAgIFZhbHVlcy5pc0xpbmsgPSBpc0xpbms7CiAgICAgIGZ1bmN0aW9uIGlzV2lkZ2V0KHZhbCkgewogICAgICAgICAgcmV0dXJuIHZhbCBpbnN0YW5jZW9mIFdpZGdldDsKICAgICAgfQogICAgICBWYWx1ZXMuaXNXaWRnZXQgPSBpc1dpZGdldDsKICAgICAgZnVuY3Rpb24gaXNIdG1sKHZhbCkgewogICAgICAgICAgaWYgKHR5cGVvZiBIVE1MRWxlbWVudCAhPT0gInVuZGVmaW5lZCIpIHsKICAgICAgICAgICAgICByZXR1cm4gdmFsIGluc3RhbmNlb2YgSFRNTEVsZW1lbnQ7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7CiAgICAgICAgICB9CiAgICAgIH0KICAgICAgVmFsdWVzLmlzSHRtbCA9IGlzSHRtbDsKICAgICAgLyoqIENoZWNrcyBpZiB0aGUgZ2l2ZW4gdmFsdWUgaXMgYW4gb2JqZWN0IChhbmQgbm90IGFueSBvdGhlciBkYXRhdmlldy1yZWNvZ25pemVkIG9iamVjdC1saWtlIHR5cGUpLiAqLwogICAgICBmdW5jdGlvbiBpc09iamVjdCh2YWwpIHsKICAgICAgICAgIHJldHVybiAodHlwZW9mIHZhbCA9PSAib2JqZWN0IiAmJgogICAgICAgICAgICAgICFpc0h0bWwodmFsKSAmJgogICAgICAgICAgICAgICFpc1dpZGdldCh2YWwpICYmCiAgICAgICAgICAgICAgIWlzQ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XkuICovCiAgICAgIGZ1bmN0aW9uIGlzR3JvdXBpbmcoZW50cnkpIHsKICAgICAgICAgIGZvciAobGV0IGVsZW1lbnQgb2YgZW50cnkpCiAgICAgICAgICAgICAgaWYgKCFpc0VsZW1lbnRHcm91cChlbGVtZW50KSkKICAgICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlOwogICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgIH0KICAgICAgR3JvdXBpbmdzLmlzR3JvdXBpbmcgPSBpc0dyb3VwaW5nOwogICAgICAvKiogQ291bnQgdGhlIHRvdGFsIG51bWJlciBvZiBlbGVtZW50cyBpbiBhIHJlY3Vyc2l2ZSBncm91cGluZy4gKi8KICAgICAgZnVuY3Rpb24gY291bnQoZWxlbWVudHMpIHsKICAgICAgICAgIGlmIChpc0dyb3VwaW5nKGVsZW1lbnRzKSkgewogICAgICAgICAgICAgIGxldCByZXN1bHQgPSAwOwogICAgICAgICAgICAgIGZvciAobGV0IHN1Ymdyb3VwIG9mIGVsZW1lbnRzKQogICAgICAgICAgICAgICAgICByZXN1bHQgKz0gY291bnQoc3ViZ3JvdXAucm93cyk7CiAgICAgICAgICAgICAgcmV0dXJuIHJlc3VsdDsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIHJldHVybiBlbGVtZW50cy5sZW5ndGg7CiAgICAgICAgICB9CiAgICAgIH0KICAgICAgR3JvdXBpbmdzLmNvdW50ID0gY291bnQ7CiAgfSkoR3JvdXBpbmdzIHx8IChHcm91cGluZ3MgPSB7fSkpOwogIC8vLy8vLy8vLy8KICAvLyBMSU5LIC8vCiAgLy8vLy8vLy8vLwogIC8qKiBUaGUgT2JzaWRpYW4gJ2xpbmsnLCB1c2VkIGZvciB1bmlxdWVseSBkZXNjcmliaW5nIGEgZmlsZSwgaGVhZGVyLCBvciBibG9jay4gKi8KICBjbGFzcyBMaW5rIHsKICAgICAgLyoqIFRoZSBmaWxlIHBhdGggdGhpcyBsaW5rIHBvaW50cyB0by4gKi8KICAgICAgcGF0aDsKICAgICAgLyoqIFRoZSBkaXNwbGF5IG5hbWUgYXNzb2NpYXRlZCB3aXRoIHRoZSBsaW5rLiAqLwogICAgICBkaXNwbGF5OwogICAgICAvKiogVGhlIGJsb2NrIElEIG9yIGhlYWRlciB0aGlzIGxpbmsgcG9pbnRzIHRvIHdpdGhpbiBhIGZpbGUsIGlmIHJlbGV2YW50LiAqLwogICAgICBzdWJwYXRoOwogICAgICAvKiogSXMgdGhpcyBsaW5rIGFuIGVtYmVkZGVkIGxpbmsgKCEpPyAqLwogICAgICBlbWJlZDsKICAgICAgLyoqIFRoZSB0eXBlIG9mIHRoaXMgbGluaywgd2hpY2ggZGV0ZXJtaW5lcyB3aGF0ICdzdWJwYXRoJyByZWZlcnMgdG8sIGlmIGFueXRoaW5nLiAqLwogICAgICB0eXBlOwogICAgICAvKiogQ3JlYXRlIGEgbGluayB0byBhIHNwZWNpZmljIGZpbGUuICovCiAgICAgIHN0YXRpYyBmaWxlKHBhdGgsIGVtYmVkID0gZmFsc2UsIGRpc3BsYXkpIHsKICAgICAgICAgIHJldHVybiBuZXcgTGluayh7CiAgICAgICAgICAgICAgcGF0aCwKICAgICAgICAgICAgICBlbWJlZCwKICAgICAgICAgICAgICBkaXNwbGF5LAogICAgICAgICAgICAgIHN1YnBhdGg6IHVuZGVmaW5lZCwKICAgICAgICAgICAgICB0eXBlOiAiZmlsZSIsCiAgICAgICAgICB9KTsKICAgICAgfQogICAgICBzdGF0aWMgaW5mZXIobGlua3BhdGgsIGVtYmVkID0gZmFsc2UsIGRpc3BsYXkpIHsKICAgICAgICAgIGlmIChsaW5rcGF0aC5pbmNsdWRlcygiI14iKSkgewogICAgICAgICAgICAgIGxldCBzcGxpdCA9IGxpbmtwYXRoLnNwbGl0KCIjXiIpOwogICAgICAgICAgICAgIHJldHVybiBMaW5rLmJsb2NrKHNwbGl0WzBdLCBzcGxpdFsxXSwgZW1iZWQsIGRpc3BsYXkpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSBpZiAobGlua3BhdGguaW5jbHVkZXMoIiMiKSkgewogICAgICAgICAgICAgIGxldCBzcGxpdCA9IGxpbmtwYXRoLnNwbGl0KCIjIik7CiAgICAgICAgICAgICAgcmV0dXJuIExpbmsuaGVhZGVyKHNwbGl0WzBdLCBzcGxpdFsxXSwgZW1iZWQsIGRpc3BsYXkpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZQogICAgICAgICAgICAgIHJldHVybiBMaW5rLmZpbGUobGlua3BhdGgsIGVtYmVkLCBkaXNwbGF5KTsKICAgICAgfQogICAgICAvKiogQ3JlYXRlIGEgbGluayB0byBhIHNwZWNpZmljIGZpbGUgYW5kIGhlYWRlciBpbiB0aGF0IGZpbGUuICovCiAgICAgIHN0YXRpYyBoZWFkZXIocGF0aCwgaGVhZGVyLCBlbWJlZCwgZGlzcGxheSkgewogICAgICAgICAgLy8gSGVhZGVycyBuZWVkIHRvIGJlIG5vcm1hbGl6ZWQgdG8gYWxwaGEtbnVtZXJpYyAmIHdpdGggZXh0cmEgc3BhY2luZyByZW1vdmVkLgogICAgICAgICAgcmV0dXJuIG5ldyBMaW5rKHsKICAgICAgICAgICAgICBwYXRoLAogICAgICAgICAgICAgIGVtYmVkLAogICAgICAgICAgICAgIGRpc3BsYXksCiAgICAgICAgICAgICAgc3VicGF0aDogbm9ybWFsaXplSGVhZGVyRm9yTGluayhoZWFkZXIpLAogICAgICAgICAgICAgIHR5cGU6ICJoZWFkZXIiLAogICAgICAgICAgfSk7CiAgICAgIH0KICAgICAgLyoqIENyZWF0ZSBhIGxpbmsgdG8gYSBzcGVjaWZpYyBmaWxlIGFuZCBibG9jayBpbiB0aGF0IGZpbGUuICovCiAgICAgIHN0YXRpYyBibG9jayhwYXRoLCBibG9ja0lkLCBlbWJlZCwgZGlzcGxheSkgewogICAgICAgICAgcmV0dXJuIG5ldyBMaW5rKHsKICAgICAgICAgICAgICBwYXRoLAogICAgICAgICAgICAgIGVtYmVkLAogICAgICAgICAgICAgIGRpc3BsYXksCiAgICAgICAgICAgICAgc3VicGF0aDogYmxvY2tJZCwKICAgICAgICAgICAgICB0eXBlOiAiYmxvY2siLAogICAgICAgICAgfSk7CiAgICAgIH0KICAgICAgc3RhdGljIGZyb21PYmplY3Qob2JqZWN0KSB7CiAgICAgICAgICByZXR1cm4gbmV3IExpbmsob2JqZWN0KTsKICAgICAgfQogICAgICBjb25zdHJ1Y3RvcihmaWVsZHMpIHsKICAgICAgICAgIE9iamVjdC5hc3NpZ24odGhpcywgZmllbGRzKTsKICAgICAgfQogICAgICAvKiogQ2hlY2tzIGZvciBsaW5rIGVxdWFsaXR5IChpLmUuLCB0aGF0IHRoZSBsaW5rcyBhcmUgcG9pbnRpbmcgdG8gdGhlIHNhbWUgZXhhY3QgbG9jYXRpb24pLiAqLwogICAgICBlcXVhbHMob3RoZXIpIHsKICAgICAgICAgIGlmIChvdGhlciA9PSB1bmRlZmluZWQgfHwgb3RoZXIgPT0gbnVsbCkKICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7CiAgICAgICAgICByZXR1cm4gdGhpcy5wYXRoID09IG90aGVyLnBhdGggJiYgdGhpcy50eXBlID09IG90aGVyLnR5cGUgJiYgdGhpcy5zdWJwYXRoID09IG90aGVyLnN1YnBhdGg7CiAgICAgIH0KICAgICAgLyoqIENvbnZlcnQgdGhpcyBsaW5rIHRvIGl0J3MgbWFya2Rvd24gcmVwcmVzZW50YXRpb24uICovCiAgICAgIHRvU3RyaW5nKCkgewogICAgICAgICAgcmV0dXJuIHRoaXMubWFya2Rvd24oKTsKICAgICAgfQogICAgICAvKiogQ29udmVydCB0aGlzIGxpbmsgdG8gYSByYXcgb2JqZWN0IHdoaWNoIGlzIHNlcmlhbGl6YXRpb24tZnJpZW5kbHkuICovCiAgICAgIHRvT2JqZWN0KCkgewogICAgICAgICAgcmV0dXJuIHsgcGF0aDogdGhpcy5wYXRoLCB0eXBlOiB0aGlzLnR5cGUsIHN1YnBhdGg6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kaXNwbGF5KTsKICAgICAgfQogICAgICAvKiogQ29udmVydCB0aGlzIGxpbmsgaW50byBhbiBlbWJlZGRlZCBsaW5rLiAqLwogICAgICB0b0VtYmVkKCkgewogICAgICAgICAgaWYgKHRoaXMuZW1iZWQpIHsKICAgICAgICAgICAgICByZXR1cm4gdGhpczsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGxldCBsaW5rID0gbmV3IExpbmsodGhpcyk7CiAgICAgICAgICAgICAgbGluay5lbWJlZCA9IHRydWU7CiAgICAgICAgICAgICAgcmV0dXJuIGxpbms7CiAgICAgICAgICB9CiAgICAgIH0KICAgICAgLyoqIENvbnZlcnQgdGhpcyBsaW5rIGludG8gYSBub24tZW1iZWRkZWQgbGluay4gKi8KICAgICAgZnJvbUVtYmVkKCkgewogICAgICAgICAgaWYgKCF0aGlzLmVtYmVkKSB7CiAgICAgICAgICAgICAgcmV0dXJuIHRoaXM7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICBsZXQgbGluayA9IG5ldyBMaW5rKHRoaXMpOwogICAgICAgICAgICAgIGxpbmsuZW1iZWQgPSBmYWxzZTsKICAgICAgICAgICAgICByZXR1cm4gbGluazsKICAgICAgICAgIH0KICAgICAgfQogICAgICAvKiogQ29udmVydCB0aGlzIGxpbmsgdG8gbWFya2Rvd24gc28gaXQgY2FuIGJlIHJlbmRlcmVkLiAqLwogICAgICBtYXJrZG93bigpIHsKICAgICAgICAgIGxldCByZXN1bHQgPSAodGhpcy5lbWJlZCA/ICIhIiA6ICIiKSArICJbWyIgKyB0aGlzLm9ic2lkaWFuTGluaygpOwogICAgICAgICAgaWYgKHRoaXMuZGlzcGxheSkgewogICAgICAgICAgICAgIHJlc3VsdCArPSAifCIgKyB0aGlzLmRpc3BsYXk7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICByZXN1bHQgKz0gInwiICsgZ2V0RmlsZVRpdGxl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azogRHVyYXRpb24uZnJvbU9iamVjdCh7IHdlZWtzOiAxIH0pLAogICAgICB3ZWVrczogRHVyYXRpb24uZnJvbU9iamVjdCh7IHdlZWtzOiAxIH0pLAogICAgICB3azogRHVyYXRpb24uZnJvbU9iamVjdCh7IHdlZWtzOiAxIH0pLAogICAgICB3a3M6IER1cmF0aW9uLmZyb21PYmplY3QoeyB3ZWVrczogMSB9KSwKICAgICAgdzogRHVyYXRpb24uZnJvbU9iamVjdCh7IHdlZWtzOiAxIH0pLAogICAgICBkYXk6IER1cmF0aW9uLmZyb21PYmplY3QoeyBkYXlzOiAxIH0pLAogICAgICBkYXlzOiBEdXJhdGlvbi5mcm9tT2JqZWN0KHsgZGF5czogMSB9KSwKICAgICAgZDogRHVyYXRpb24uZnJvbU9iamVjdCh7IGRheXM6IDEgfSksCiAgICAgIGhvdXI6IER1cmF0aW9uLmZyb21PYmplY3QoeyBob3VyczogMSB9KSwKICAgICAgaG91cnM6IER1cmF0aW9uLmZyb21PYmplY3QoeyBob3VyczogMSB9KSwKICAgICAgaHI6IER1cmF0aW9uLmZyb21PYmplY3QoeyBob3VyczogMSB9KSwKICAgICAgaHJzOiBEdXJhdGlvbi5mcm9tT2JqZWN0KHsgaG91cnM6IDEgfSksCiAgICAgIGg6IER1cmF0aW9uLmZyb21PYmplY3QoeyBob3VyczogMSB9KSwKICAgICAgbWludXRlOiBEdXJhdGlvbi5mcm9tT2JqZWN0KHsgbWludXRlczogMSB9KSwKICAgICAgbWludXRlczogRHVyYXRpb24uZnJvbU9iamVjdCh7IG1pbnV0ZXM6IDEgfSksCiAgICAgIG1pbjogRHVyYXRpb24uZnJvbU9iamVjdCh7IG1pbnV0ZXM6IDEgfSksCiAgICAgIG1pbnM6IER1cmF0aW9uLmZyb21PYmplY3QoeyBtaW51dGVzOiAxIH0pLAogICAgICBtOiBEdXJhdGlvbi5mcm9tT2JqZWN0KHsgbWludXRlczogMSB9KSwKICAgICAgc2Vjb25kOiBEdXJhdGlvbi5m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5zZXEocGFyc2ltbW9uX3VtZF9taW5FeHBvcnRzLm9wdFdoaXRlc3BhY2UsIHNlcCwgcGFyc2ltbW9uX3VtZF9taW5FeHBvcnRzLm9wdFdoaXRlc3BhY2UsIGNoaWxkKS5tYW55KCksIChmaXJzdCwgcmVzdCkgPT4gewogICAgICAgICAgaWYgKHJlc3QubGVuZ3RoID09IDApCiAgICAgICAgICAgICAgcmV0dXJuIGZpcnN0OwogICAgICAgICAgbGV0IG5vZGUgPSBjb21iaW5lKGZpcnN0LCByZXN0WzBdWzFdLCByZXN0WzBdWzNdKTsKICAgICAgICAgIGZvciAobGV0IGluZGV4ID0gMTsgaW5kZXggPCByZXN0Lmxlbmd0aDsgaW5kZXgrKykgewogICAgICAgICAgICAgIG5vZGUgPSBjb21iaW5lKG5vZGUsIHJlc3RbaW5kZXhdWzFdLCByZXN0W2luZGV4XVszXSk7CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gbm9kZTsKICAgICAgfSk7CiAgfQogIGZ1bmN0aW9uIGNoYWluT3B0KGJhc2UsIC4uLmZ1bmNzKSB7CiAgICAgIHJldHVybiBwYXJzaW1tb25fdW1kX21pbkV4cG9ydHMuY3VzdG9tKChzdWNjZXNzLCBmYWlsdXJlKSA9PiB7CiAgICAgICAgICByZXR1cm4gKGlucHV0LCBpKSA9PiB7CiAgICAgICAgICAgICAgbGV0IHJlc3VsdCA9IGJhc2UuXyhpbnB1dCwgaSk7CiAgICAgICAgICAgICAgaWYgKCFyZXN1bHQuc3RhdHVzKQogICAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0OwogICAgICAgICAgICAgIGZvciAobGV0IGZ1bmMgb2YgZnVuY3MpIHsKICAgICAgICAgICAgICAgICAgbGV0IG5leHQgPSBmdW5jKHJlc3VsdC52YWx1ZSkuXyhpbnB1dCwgcmVzdWx0LmluZGV4KTsKICAgICAgICAgICAgICAgICAgaWYgKCFuZXh0LnN0YXR1cykKICAgICAgICAgICAgICAgICAgICAgIHJldH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VzYygiJz49JyBvciAnPD0nIG9yICchPScgb3IgJz0nIG9yICc+JyBvciAnPCciKSwKICAgICAgLy8gQmluYXJ5IGJvb2xlYW4gY29tYmluYXRpb24gb3BlcmF0b3IuCiAgICAgIGJpbmFyeUJvb2xlYW5PcDogXyA9PiBwYXJzaW1tb25fdW1kX21pbkV4cG9ydHMucmVnZXhwKC9hbmR8b3J8JnxcfC9pKQogICAgICAgICAgLm1hcChzdHIgPT4gewogICAgICAgICAgaWYgKHN0ci50b0xvd2VyQ2FzZSgpID09ICJhbmQiKQogICAgICAgICAgICAgIHJldHVybiAiJiI7CiAgICAgICAgICBlbHNlIGlmIChzdHIudG9Mb3dlckNhc2UoKSA9PSAib3IiKQogICAgICAgICAgICAgIHJldHVybiAifCI7CiAgICAgICAgICBlbHNlCiAgICAgICAgICAgICAgcmV0dXJuIHN0cjsKICAgICAgfSkKICAgICAgICAgIC5kZXNjKCInYW5kJyBvciAnb3InIiksCiAgICAgIC8vIEEgZGF0ZSB3aGljaCBjYW4gYmUgWVlZWS1NTVstRERUSEg6bW06c3NdLgogICAgICByb290RGF0ZTogXyA9PiBwYXJzaW1tb25fdW1kX21pbkV4cG9ydHMuc2VxTWFwKHBhcnNpbW1vbl91bWRfbWluRXhwb3J0cy5yZWdleHAoL1xkezR9LyksIHBhcnNpbW1vbl91bWRfbWluRXhwb3J0cy5zdHJpbmcoIi0iKSwgcGFyc2ltbW9uX3VtZF9taW5FeHBvcnRzLnJlZ2V4cCgvXGR7Mn0vKSwgKHllYXIsIF8sIG1vbnRoKSA9PiB7CiAgICAgICAgICByZXR1cm4gRGF0ZVRpbWUuZnJvbU9iamVjdCh7IHllYXI6IE51bWJlci5wYXJzZUludCh5ZWFyKSwgbW9udGg6IE51bWJlci5wYXJzZUludChtb250aCkgfSk7CiAgICAgIH0pLmRlc2MoImRhdGUgaW4gZm9ybWF0IFlZWVktTU1bLUREVEhILU1NLVNTLk1TXSIpLAogICAgICBkYXRlU2hvcnRoYW5kOiBfID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OiBxID0+IHBhcnNpbW1vbl91bWRfbWluRXhwb3J0cy5hbHQocS5wYXJlbnNTb3VyY2UsIHEubmVnYXRlU291cmNlLCBxLmxpbmtPdXRnb2luZ1NvdXJjZSwgcS5saW5rSW5jb21pbmdTb3VyY2UsIHEuZm9sZGVyU291cmNlLCBxLnRhZ1NvdXJjZSwgcS5jc3ZTb3VyY2UpLAogICAgICBiaW5hcnlPcFNvdXJjZTogcSA9PiBjcmVhdGVCaW5hcnlQYXJzZXIocS5hdG9tU291cmNlLCBxLmJpbmFyeUJvb2xlYW5PcC5tYXAocyA9PiBzKSwgU291cmNlcy5iaW5hcnlPcCksCiAgICAgIHNvdXJjZTogcSA9PiBxLmJpbmFyeU9wU291cmNlLAogICAgICAvLyBGaWVsZCBwYXJzaW5nLgogICAgICB2YXJpYWJsZUZpZWxkOiBxID0+IHEuaWRlbnRpZmllcgogICAgICAgICAgLmNoYWluKHIgPT4gewogICAgICAgICAgaWYgKEtFWVdPUkRTLmluY2x1ZGVzKHIudG9VcHBlckNhc2UoKSkpIHsKICAgICAgICAgICAgICByZXR1cm4gcGFyc2ltbW9uX3VtZF9taW5FeHBvcnRzLmZhaWwoIlZhcmlhYmxlIGZpZWxkcyBjYW5ub3QgYmUgYSBrZXl3b3JkICgiICsgS0VZV09SRFMuam9pbigiIG9yICIpICsgIikiKTsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIHJldHVybiBwYXJzaW1tb25fdW1kX21pbkV4cG9ydHMuc3VjY2VlZChGaWVsZHMudmFyaWFibGUocikpOwogICAgICAgICAgfQogICAgICB9KQogICAgICAgICAgLmRlc2MoInZhcmlhYmxlIiksCiAgICAgIG51bWJlckZpZWxkOiBxID0+IHEubnVtYmVyLm1hcCh2YWwgPT4gRmllbGRzLmxpdGVyYWwodmFsKSkuZGVzYygibnVtYmVyIiksCiAgICAgIHN0cmluZ0ZpZWxkOiBxID0+IHEuc3RyaW5nLm1hcCh2YWwgPT4gRmllb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0ID0gRmllbGRzLmluZGV4KHJlc3VsdCwgRmllbGRzLmxpdGVyYWwocG9zdC5maWVsZCkpOwogICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgICAgIGNhc2UgImluZGV4IjoKICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdCA9IEZpZWxkcy5pbmRleChyZXN1bHQsIHBvc3QuZmllbGQpOwogICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgICAgIGNhc2UgImZ1bmN0aW9uIjoKICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdCA9IEZpZWxkcy5mdW5jKHJlc3VsdCwgcG9zdC5maWVsZHMpOwogICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuIHJlc3VsdDsKICAgICAgfSksCiAgICAgIG5lZ2F0ZWRGaWVsZDogcSA9PiBwYXJzaW1tb25fdW1kX21pbkV4cG9ydHMuc2VxTWFwKHBhcnNpbW1vbl91bWRfbWluRXhwb3J0cy5zdHJpbmcoIiEiKSwgcS5pbmRleEZpZWxkLCAoXywgZmllbGQpID0+IEZpZWxkcy5uZWdhdGUoZmllbGQpKS5kZXNjKCJuZWdhdGVkIGZpZWxkIiksCiAgICAgIHBhcmVuc0ZpZWxkOiBxID0+IHBhcnNpbW1vbl91bWRfbWluRXhwb3J0cy5zZXFNYXAocGFyc2ltbW9uX3VtZF9taW5FeHBvcnRzLnN0cmluZygiKCIpLCBwYXJzaW1tb25fdW1kX21pbkV4cG9ydHMub3B0V2hpdGVzcGFjZSwgcS5maWVsZCwgcGFyc2ltbW9uX3VtZF9taW5FeHBvcnRzLm9wdFdoaXRlc3BhY2UsIHBhcnNpbW1vbl91bWRfbWluRXhwb3J0cy5zdHJpbmcoIikiKSwgKF8xLCBfMiwgZmllbGQsIF8zLCBfNCkgPT4gZmllbGQpLAogICAgICBsYW1iZGFGaWVsZDogcSA9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IGluZGV4IGFmdGVyIHRoZSBlbmQgb2YgdGhlIHZhbHVlLgogICAqLwogIGZ1bmN0aW9uIGZpbmRDbG9zaW5nKGxpbmUsIHN0YXJ0LCBvcGVuLCBjbG9zZSkgewogICAgICBsZXQgbmVzdGluZyA9IDA7CiAgICAgIGxldCBlc2NhcGVkID0gZmFsc2U7CiAgICAgIGZvciAobGV0IGluZGV4ID0gc3RhcnQ7IGluZGV4IDwgbGluZS5sZW5ndGg7IGluZGV4KyspIHsKICAgICAgICAgIGxldCBjaGFyID0gbGluZS5jaGFyQXQoaW5kZXgpOwogICAgICAgICAgLy8gQWxsb3dzIGZvciBkb3VibGUgZXNjYXBlcyBsaWtlICdcXCcgdG8gYmUgcmVuZGVyZWQgbm9ybWFsbHkuCiAgICAgICAgICBpZiAoY2hhciA9PSAiXFwiKSB7CiAgICAgICAgICAgICAgZXNjYXBlZCA9ICFlc2NhcGVkOwogICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgfQogICAgICAgICAgLy8gSWYgZXNjYXBlZCwgaWdub3JlIHRoZSBuZXh0IGNoYXJhY3RlciBmb3IgY29tcHV0aW5nIG5lc3RpbmcsIHJlZ2FyZGxlc3Mgb2Ygd2hhdCBpdCBpcy4KICAgICAgICAgIGlmIChlc2NhcGVkKSB7CiAgICAgICAgICAgICAgZXNjYXBlZCA9IGZhbHNlOwogICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgfQogICAgICAgICAgaWYgKGNoYXIgPT0gb3BlbikKICAgICAgICAgICAgICBuZXN0aW5nKys7CiAgICAgICAgICBlbHNlIGlmIChjaGFyID09IGNsb3NlKQogICAgICAgICAgICAgIG5lc3RpbmctLTsKICAgICAgICAgIC8vIE9ubHkgb2NjdXJzIGlmIHdlIGFyZSBvbiBhIGNsb3NlIGNoYXJhY3RlciBhbmQgdGhlcmUgaXMgbm8gbW9yZSBuZXN0aW5nLgogICAgICAgICAgaWYgKG5lc3RpbmcgPCAwKQogICAgICAgICA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0Y2hpbmcgZW5kIGJyYWNrZXQsIGFuZCBwYXJzZSB3aGF0ZXZlciByZW1haW5zIGFzIGFuIGlubGluZSB2YWx1ZS4KICAgKi8KICBmdW5jdGlvbiBleHRyYWN0SW5saW5lRmllbGRzKGxpbmUsIGluY2x1ZGVUYXNrRmllbGRzID0gZmFsc2UpIHsKICAgICAgbGV0IGZpZWxkcyA9IFtdOwogICAgICBmb3IgKGxldCB3cmFwcGVyIG9mIE9iamVjdC5rZXlzKElOTElORV9GSUVMRF9XUkFQUEVSUykpIHsKICAgICAgICAgIGxldCBmb3VuZEluZGV4ID0gbGluZS5pbmRleE9mKHdyYXBwZXIpOwogICAgICAgICAgd2hpbGUgKGZvdW5kSW5kZXggPj0gMCkgewogICAgICAgICAgICAgIGxldCBwYXJzZWRGaWVsZCA9IGZpbmRTcGVjaWZpY0lubGluZUZpZWxkKGxpbmUsIGZvdW5kSW5kZXgpOwogICAgICAgICAgICAgIGlmICghcGFyc2VkRmllbGQpIHsKICAgICAgICAgICAgICAgICAgZm91bmRJbmRleCA9IGxpbmUuaW5kZXhPZih3cmFwcGVyLCBmb3VuZEluZGV4ICsgMSk7CiAgICAgICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBmaWVsZHMucHVzaChwYXJzZWRGaWVsZCk7CiAgICAgICAgICAgICAgZm91bmRJbmRleCA9IGxpbmUuaW5kZXhPZih3cmFwcGVyLCBwYXJzZWRGaWVsZC5lbmQpOwogICAgICAgICAgfQogICAgICB9CiAgICAgIGlmIChpbmNsdWRlVGFza0ZpZWxkcykKICAgICAgICAgIGZpZWxkcyA9IGZpZWxkcy5jb25jYXQoZXh0cmFjdFNwZWNpYWxUYXNrRmllbGRzKGxpbmUpKTsKICAgICAgZmllbGRzLnNvcnQoKGEsIGIpID0+IGEuc3RhcnQgLSBiLnN0YXJ0KTsKICAgICAgbGV0IGZpbHRlcmVkRmllbGRzID0gW107CiAgICAgIGZvciAobGV0I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ZXIpIHsKICAgICAgICAgIC8vIE11dGF0ZSB0aGUgZGF0YSBmb3Igbm93LCB3aGljaCBpcyBwcm9iYWJseSBhIGJhZCBpZGVhIGJ1dC4uLiBhbGwgd2VsbC4KICAgICAgICAgIGlmIChkYXRhLmZyb250bWF0dGVyKSB7CiAgICAgICAgICAgICAgZGF0YS5mcm9udG1hdHRlciA9IFZhbHVlcy5tYXBMZWF2ZXMoZGF0YS5mcm9udG1hdHRlciwgdCA9PiBWYWx1ZXMuaXNMaW5rKHQpID8gbGlua05vcm1hbGl6ZXIodCkgOiB0KTsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChkYXRhLmZpZWxkcykgewogICAgICAgICAgICAgIGZvciAobGV0IFtrZXksIHZhbHVlXSBvZiBkYXRhLmZpZWxkcy5lbnRyaWVzKCkpIHsKICAgICAgICAgICAgICAgICAgZGF0YS5maWVsZHMuc2V0KGtleSwgVmFsdWVzLm1hcExlYXZlcyh2YWx1ZSwgdCA9PiAoVmFsdWVzLmlzTGluayh0KSA/IGxpbmtOb3JtYWxpemVyKHQpIDogdCkpKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBpZiAoZGF0YS5saXN0cykgewogICAgICAgICAgICAgIGZvciAobGV0IGl0ZW0gb2YgZGF0YS5saXN0cykgewogICAgICAgICAgICAgICAgICBmb3IgKGxldCBba2V5LCB2YWx1ZV0gb2YgaXRlbS5maWVsZHMuZW50cmllcygpKSB7CiAgICAgICAgICAgICAgICAgICAgICBpdGVtLmZpZWxkcy5zZXQoa2V5LCB2YWx1ZS5tYXAoeCA9PiBWYWx1ZXMubWFwTGVhdmVzKHgsIHQgPT4gKFZhbHVlcy5pc0xpbmsodCkgPyBsaW5rTm9ybWFsaXplcih0KSA6IHQpKSkpOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgICAgaWYgKGRhdGEubGlua3MpIHsKICAgICAgICAgICAgICBkYXRhLmxpbmt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2hlID8/IG5ldyBMaXN0U2VyaWFsaXphdGlvbkNhY2hlKHRoaXMubGlzdHMpOwogICAgICAgICAgbGV0IHJlc3VsdCA9IHsKICAgICAgICAgICAgICBmaWxlOiB7CiAgICAgICAgICAgICAgICAgIHBhdGg6IHRoaXMucGF0aCwKICAgICAgICAgICAgICAgICAgZm9sZGVyOiB0aGlzLmZvbGRlcigpLAogICAgICAgICAgICAgICAgICBuYW1lOiB0aGlzLm5hbWUoKSwKICAgICAgICAgICAgICAgICAgbGluazogTGluay5maWxlKHRoaXMucGF0aCksCiAgICAgICAgICAgICAgICAgIG91dGxpbmtzOiB0aGlzLmZpbGVMaW5rcygpLAogICAgICAgICAgICAgICAgICBpbmxpbmtzOiBBcnJheS5mcm9tKGluZGV4LmxpbmtzLmdldEludmVyc2UodGhpcy5wYXRoKSkubWFwKGwgPT4gTGluay5maWxlKGwpKSwKICAgICAgICAgICAgICAgICAgZXRhZ3M6IEFycmF5LmZyb20odGhpcy50YWdzKSwKICAgICAgICAgICAgICAgICAgdGFnczogQXJyYXkuZnJvbSh0aGlzLmZ1bGxUYWdzKCkpLAogICAgICAgICAgICAgICAgICBhbGlhc2VzOiBBcnJheS5mcm9tKHRoaXMuYWxpYXNlcyksCiAgICAgICAgICAgICAgICAgIGxpc3RzOiB0aGlzLmxpc3RzLm1hcChsID0+IHJlYWxDYWNoZS5nZXQobC5saW5lKSksCiAgICAgICAgICAgICAgICAgIHRhc2tzOiB0aGlzLmxpc3RzLmZpbHRlcihsID0+ICEhbC50YXNrKS5tYXAobCA9PiByZWFsQ2FjaGUuZ2V0KGwubGluZSkpLAogICAgICAgICAgICAgICAgICBjdGltZTogdGhpcy5jdGltZSwKICAgICAgICAgICAgICAgICAgY2RheTogc3RyaXBUaW1lKHRoaXMuY3RpbWUpLAogICAgICAgICAgICAgICAgICBtdGltZTogdGhpcy5tdGltZSwKICAgICAgICAgICAgICAgICAgbWRheTogc3RyaXBUaW1lKHRoaXMubXRpbWUpLAogICAgICAgICAgICAgICAgICBzaXplOiB0aGlzLnNpemUsCiAgICAgICAgICAgICAgICAgIHN0YXJyZWQ6IGluZGV4LnN0YXJyZWQuc3RhcnJlZCh0aGlzLnBhdGgpLAogICAgICAgICAgICAgICAgICBmcm9udG1hdHRlcjogVmFsdWVzLmRlZXBDb3B5KHRoaXMuZnJvbnRtYXR0ZXIpLAogICAgICAgICAgICAgICAgICBleHQ6IHRoaXMuZXh0ZW5zaW9uKCksCiAgICAgICAgICAgICAgfSwKICAgICAgICAgIH07CiAgICAgICAgICAvLyBBZGQgdGhlIGN1cnJlbnQgZGF5IGlmIHByZXNlbnQuCiAgICAgICAgICBpZiAodGhpcy5kYXkpCiAgICAgICAgICAgICAgcmVzdWx0LmZpbGUuZGF5ID0gdGhpcy5kYXk7CiAgICAgICAgICAvLyBUaGVuIGFwcGVuZCB0aGUgY29tcHV0ZWQgZmllbGRzLgogICAgICAgICAgZm9yIChsZXQgW2tleSwgdmFsdWVdIG9mIHRoaXMuZmllbGRzLmVudHJpZXMoKSkgewogICAgICAgICAgICAgIGlmIChrZXkgaW4gcmVzdWx0KQogICAgICAgICAgICAgICAgICBjb250aW51ZTsgLy8gRG9uJ3QgYWxsb3cgZmllbGRzIHRvIG92ZXJyaWRlIGV4aXN0aW5nIGtleXMuCiAgICAgICAgICAgICAgcmVzdWx0W2tleV0gPSB2YWx1ZTsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiByZXN1bHQ7CiAgICAgIH0KICB9CiAgLyoqIEEgbGlzdCBpdGVtIGluc2lkZSBvZiBhIGxpc3QuICovCiAgY2xhc3MgTGlzdEl0ZW0gewogICAgICAvKiogVGhlIHN5bWJvbCAoJyonLCAnLScsICcxLicpIHVzZWQgdG8gZGVmaW5lIHRoaXMgbGlzdCBpdGVtLiAqLwogICAgICBzeW1ib2w7CiAgICAgIC8qKiBBIGxpbmsgd2hpY2ggcG9pbnRzIHRvIHRoaXMgdGFzaywgb3IgdG8gdGhlIGNsb3Nlc3QgYmxv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9XSAke3RoaXMudGV4dH1gOwogICAgICAgICAgZWxzZQogICAgICAgICAgICAgIHJldHVybiBgJHt0aGlzLnN5bWJvbH0gJHt0aGlzLnRleHR9YDsKICAgICAgfQogICAgICBjcmVhdGVkKCkgewogICAgICAgICAgcmV0dXJuICh0aGlzLmZpZWxkcy5nZXQoImNyZWF0ZWQiKSA/PyB0aGlzLmZpZWxkcy5nZXQoImN0aW1lIikgPz8gdGhpcy5maWVsZHMuZ2V0KCJjZGF5IikpPy5bMF07CiAgICAgIH0KICAgICAgZHVlKCkgewogICAgICAgICAgcmV0dXJuICh0aGlzLmZpZWxkcy5nZXQoImR1ZSIpID8/IHRoaXMuZmllbGRzLmdldCgiZHVldGltZSIpID8/IHRoaXMuZmllbGRzLmdldCgiZHVlZGF5IikpPy5bMF07CiAgICAgIH0KICAgICAgY29tcGxldGVkKCkgewogICAgICAgICAgcmV0dXJuICh0aGlzLmZpZWxkcy5nZXQoImNvbXBsZXRlZCIpID8/CiAgICAgICAgICAgICAgdGhpcy5maWVsZHMuZ2V0KCJjb21wbGV0aW9uIikgPz8KICAgICAgICAgICAgICB0aGlzLmZpZWxkcy5nZXQoImNvbXB0aW1lIikgPz8KICAgICAgICAgICAgICB0aGlzLmZpZWxkcy5nZXQoImNvbXBkYXkiKSk/LlswXTsKICAgICAgfQogICAgICBzdGFydCgpIHsKICAgICAgICAgIHJldHVybiB0aGlzLmZpZWxkcy5nZXQoInN0YXJ0Iik/LlswXTsKICAgICAgfQogICAgICBzY2hlZHVsZWQoKSB7CiAgICAgICAgICByZXR1cm4gdGhpcy5maWVsZHMuZ2V0KCJzY2hlZHVsZWQiKT8uWzBdOwogICAgICB9CiAgICAgIC8qKiBDcmVhdGUgYW4gQVBJLWZyaWVuZGx5IGNvcHkgb2YgdGhpcyBsaXN0IGl0ZW0uIERlLWR1cGxpY2F0aW9uIGlzIGRvbmUgdmlhIHRoZSBwcm92aWRlZCBjYWNoZS4gKi8KICAgICAgc2VyaWFsaXplKGNhY2hlKSB7CiAgICAgICAgICAvLyBNYXAgY2hpbGRyZW4gdG8gdGhlaXIgc2VyaWFsaXplZC9kZS1kdXBsaWNhdGVkIGVxdWl2YWxlbnRzIHJpZ2h0IGF3YXkuCiAgICAgICAgICBsZXQgY2hpbGRyZW4gPSB0aGlzLmNoaWxkcmVuLm1hcChsID0+IGNhY2hlLmdldChsKSkuZmlsdGVyKChsKSA9PiBsICE9PSB1bmRlZmluZWQpOwogICAgICAgICAgbGV0IHJlc3VsdCA9IHsKICAgICAgICAgICAgICBzeW1ib2w6IHRoaXMuc3ltYm9sLAogICAgICAgICAgICAgIGxpbms6IHRoaXMubGluaywKICAgICAgICAgICAgICBzZWN0aW9uOiB0aGlzLnNlY3Rpb24sCiAgICAgICAgICAgICAgdGV4dDogdGhpcy50ZXh0LAogICAgICAgICAgICAgIHRhZ3M6IEFycmF5LmZyb20odGhpcy50YWdzKSwKICAgICAgICAgICAgICBsaW5lOiB0aGlzLmxpbmUsCiAgICAgICAgICAgICAgbGluZUNvdW50OiB0aGlzLmxpbmVDb3VudCwKICAgICAgICAgICAgICBsaXN0OiB0aGlzLmxpc3QsCiAgICAgICAgICAgICAgb3V0bGlua3M6IEFycmF5LmZyb20odGhpcy5saW5rcyksCiAgICAgICAgICAgICAgcGF0aDogdGhpcy5saW5rLnBhdGgsCiAgICAgICAgICAgICAgY2hpbGRyZW46IGNoaWxkcmVuLAogICAgICAgICAgICAgIHRhc2s6ICEhdGhpcy50YXNrLAogICAgICAgICAgICAgIGFubm90YXRlZDogdGhpcy5maWVsZHMuc2l6ZSA+IDAsCiAgICAgICAgICAgICAgcG9zaXRpb246IFZhbHVlcy5kZWVwQ29weSh0aGlzLnBvc2l0aW9uKSwKICAgICAgICAgICAgICBzdWJ0YXNrczogY2hpbGRyZW4sCiAgICAgICAgICAgICAgcmVhbDogISF0aGlzLnRhc2ssCiAgICAgICAgICAgICAgaGVhZGVyOiB0aGlzLnNlY3Rpb24sIC8vIEBkZXByZWNhdGVkLCB1c2UgJ2l0ZW0uc2VjdGlvbicgaW5zdGVhZC4KICAgICAgICAgIH07CiAgICAgICAgICBpZiAodGhpcy5wYXJlbnQgfHwgdGhpcy5wYXJlbnQgPT09IDApCiAgICAgICAgICAgICAgcmVzdWx0LnBhcmVudCA9IHRoaXMucGFyZW50OwogICAgICAgICAgaWYgKHRoaXMuYmxvY2tJZCkKICAgICAgICAgICAgICByZXN1bHQuYmxvY2tJZCA9IHRoaXMuYmxvY2tJZDsKICAgICAgICAgIGFkZEZpZWxkcyh0aGlzLmZpZWxkcywgcmVzdWx0KTsKICAgICAgICAgIGlmICh0aGlzLnRhc2spIHsKICAgICAgICAgICAgICByZXN1bHQuc3RhdHVzID0gdGhpcy50YXNrLnN0YXR1czsKICAgICAgICAgICAgICByZXN1bHQuY2hlY2tlZCA9IHRoaXMudGFzay5jaGVja2VkOwogICAgICAgICAgICAgIHJlc3VsdC5jb21wbGV0ZWQgPSB0aGlzLnRhc2suY29tcGxldGVkOwogICAgICAgICAgICAgIHJlc3VsdC5mdWxseUNvbXBsZXRlZCA9IHRoaXMudGFzay5mdWxseUNvbXBsZXRlZDsKICAgICAgICAgICAgICBsZXQgY3JlYXRlZCA9IHRoaXMuY3JlYXRlZCgpLCBkdWUgPSB0aGlzLmR1ZSgpLCBjb21wbGV0ZWQgPSB0aGlzLmNvbXBsZXRlZCgpLCBzdGFydCA9IHRoaXMuc3RhcnQoKSwgc2NoZWR1bGVkID0gdGhpcy5zY2hlZHVsZWQoKTsKICAgICAgICAgICAgICBpZiAoY3JlYXRlZCkKICAgICAgICAgICAgICAgICAgcmVzdWx0LmNyZWF0ZWQgPSBWYWx1ZXMuZGVlcENvcHkoY3JlYXRlZCk7CiAgICAgICAgICAgICAgaWYgKGR1ZSkKICAgICAgICAgICAgICAgICAgcmVzdWx0LmR1ZSA9IFZhbHVlcy5kZWVwQ29weShkdWUpOwogICAgICAgICAgICAgIGlmIChjb21wbGV0ZWQpCiAgICAgICAgICAgICAgICAgIHJl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KQogICAgICAgICAgICAgIHJldHVybiB0aGlzLmNhY2hlW2xpbmVub107CiAgICAgICAgICBlbHNlIGlmICh0aGlzLnNlZW4uaGFzKGxpbmVubykpIHsKICAgICAgICAgICAgICBjb25zb2xlLmxvZyhgRGF0YXZpZXc6IEVuY291bnRlcmVkIGEgY2lyY3VsYXIgbGlzdCAobGluZSBudW1iZXIgJHtsaW5lbm99OyBjaGlsZHJlbiAke3RoaXMubGlzdEl0ZW1zW2xpbmVub10uY2hpbGRyZW4uam9pbigiLCAiKX0pYCk7CiAgICAgICAgICAgICAgcmV0dXJuIHVuZGVmaW5lZDsKICAgICAgICAgIH0KICAgICAgICAgIHRoaXMuc2Vlbi5hZGQobGluZW5vKTsKICAgICAgICAgIGxldCByZXN1bHQgPSB0aGlzLmxpc3RJdGVtc1tsaW5lbm9dLnNlcmlhbGl6ZSh0aGlzKTsKICAgICAgICAgIHRoaXMuY2FjaGVbbGluZW5vXSA9IHJlc3VsdDsKICAgICAgICAgIHJldHVybiByZXN1bHQ7CiAgICAgIH0KICB9CiAgZnVuY3Rpb24gYWRkRmllbGRzKGZpZWxkcywgdGFyZ2V0KSB7CiAgICAgIGZvciAobGV0IFtrZXksIHZhbHVlc10gb2YgZmllbGRzLmVudHJpZXMoKSkgewogICAgICAgICAgaWYgKGtleSBpbiB0YXJnZXQpCiAgICAgICAgICAgICAgY29udGludWU7CiAgICAgICAgICB0YXJnZXRba2V5XSA9IHZhbHVlcy5sZW5ndGggPT0gMSA/IHZhbHVlc1swXSA6IHZhbHVlczsKICAgICAgfQogICAgICByZXR1cm4gdGFyZ2V0OwogIH0KCiAgLyoqIENvbW1vbiB1dGlsaXRpZXMgZm9yIGV4dHJhY3RpbmcgdGFncywgbGlua3MsIGFuZCBvdGhlciBidXNpbmVzcyBmcm9tIG1ldGFkYXRhLiAqLwogIGNvbnN0IFBPVEVOVElBTF9UQUdfTUFUQ0hFUiA9IC8jW15ccyw7XC46IVw/JyJgKClcW1xdXHtcfV0rL2dp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IC8vIEZyb250LW1hdHRlciBmaWxlIHRhZ3MsIGFsaWFzZXMsIEFORCBmcm9udG1hdHRlciBwcm9wZXJ0aWVzLgogICAgICBpZiAobWV0YWRhdGEuZnJvbnRtYXR0ZXIpIHsKICAgICAgICAgIGZvciAobGV0IHRhZyBvZiBleHRyYWN0VGFncyhtZXRhZGF0YS5mcm9udG1hdHRlcikpIHsKICAgICAgICAgICAgICBpZiAoIXRhZy5zdGFydHNXaXRoKCIjIikpCiAgICAgICAgICAgICAgICAgIHRhZyA9ICIjIiArIHRhZzsKICAgICAgICAgICAgICB0YWdzLmFkZCh0YWcpOwogICAgICAgICAgfQogICAgICAgICAgZm9yIChsZXQgYWxpYXMgb2YgZXh0cmFjdEFsaWFzZXMobWV0YWRhdGEuZnJvbnRtYXR0ZXIpIHx8IFtdKQogICAgICAgICAgICAgIGFsaWFzZXMuYWRkKGFsaWFzKTsKICAgICAgICAgIGxldCBmcm9udEZpZWxkcyA9IHBhcnNlRnJvbnRtYXR0ZXIobWV0YWRhdGEuZnJvbnRtYXR0ZXIpOwogICAgICAgICAgZm9yIChsZXQgW2tleSwgdmFsdWVdIG9mIE9iamVjdC5lbnRyaWVzKGZyb250RmllbGRzKSkgewogICAgICAgICAgICAgIGlmIChrZXkgPT0gInBvc2l0aW9uIikKICAgICAgICAgICAgICAgICAgY29udGludWU7CiAgICAgICAgICAgICAgYWRkSW5saW5lRmllbGQoa2V5LCB2YWx1ZSwgZmllbGRzKTsKICAgICAgICAgIH0KICAgICAgfQogICAgICAvLyBBZGQgZnJvbnRtYXR0ZXIgbGlua3MgdG8gbGlua3MuCiAgICAgIGlmIChtZXRhZGF0YS5mcm9udG1hdHRlckxpbmtzKSB7CiAgICAgICAgICBmb3IgKGxldCByYXdMaW5rIG9mIG1ldGFkYXRhLmZyb250bWF0dGVyTGlua3MgfHwgW10pIHsKICAgICAgICAgICAgICBjb25zdCBsaW5rID0gTGluay5pbmZlcihyYXdMaW5rLmxpbmssIGZhbHNlLCByYXdMaW5rLmRpc3BsYXlUZXh0KTsKICAgICAgICAgICAgICBsaW5rcy5wdXNoKGxpbmspOwogICAgICAgICAgfQogICAgICB9CiAgICAgIC8vIExpbmtzIGluIG1ldGFkYXRhLgogICAgICBjb25zdCBsaW5rc0J5TGluZSA9IHt9OwogICAgICBmb3IgKGxldCByYXdMaW5rIG9mIG1ldGFkYXRhLmxpbmtzIHx8IFtdKSB7CiAgICAgICAgICBjb25zdCBsaW5rID0gTGluay5pbmZlcihyYXdMaW5rLmxpbmssIGZhbHNlLCByYXdMaW5rLmRpc3BsYXlUZXh0KTsKICAgICAgICAgIGNvbnN0IGxpbmUgPSByYXdMaW5rLnBvc2l0aW9uLnN0YXJ0LmxpbmU7CiAgICAgICAgICBsaW5rcy5wdXNoKGxpbmspOwogICAgICAgICAgaWYgKCEobGluZSBpbiBsaW5rc0J5TGluZSkpCiAgICAgICAgICAgICAgbGlua3NCeUxpbmVbbGluZV0gPSBbbGlua107CiAgICAgICAgICBlbHNlCiAgICAgICAgICAgICAgbGlua3NCeUxpbmVbbGluZV0ucHVzaChsaW5rKTsKICAgICAgfQogICAgICAvLyBFbWJlZCBMaW5rcyBpbiBtZXRhZGF0YS4KICAgICAgZm9yIChsZXQgcmF3RW1iZWQgb2YgbWV0YWRhdGEuZW1iZWRzIHx8IFtdKSB7CiAgICAgICAgICBjb25zdCBsaW5rID0gTGluay5pbmZlcihyYXdFbWJlZC5saW5rLCB0cnVlLCByYXdFbWJlZC5kaXNwbGF5VGV4dCk7CiAgICAgICAgICBjb25zdCBsaW5lID0gcmF3RW1iZWQucG9zaXRpb24uc3RhcnQubGluZTsKICAgICAgICAgIGxpbmtzLnB1c2gobGluayk7CiAgICAgICAgICBpZiAoIShsaW5lIGluIGxpbmtzQnlMaW5lKSkKICAgICAgICAgICAgICBsaW5rc0J5TGluZVtsaW5lXSA9IFtsaW5rXTsKICAgICAgICAgIGVsc2UKICAgICAgICAgICAgICBsaW5rc0J5TGluZVtsaW5lXS5wdXN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nVlOwogICAgICAgICAgaWYgKEFycmF5LmlzQXJyYXkodmFsdWUpKQogICAgICAgICAgICAgIHJlc3VsdC5wdXNoKC4uLnZhbHVlLm1hcCh2ID0+ICgiIiArIHYpLnRyaW0oKSkpOwogICAgICAgICAgZWxzZQogICAgICAgICAgICAgIHJlc3VsdC5wdXNoKC4uLnNwbGl0RnJvbnRtYXR0ZXJUYWdPckFsaWFzKHZhbHVlLCAvLC8pKTsKICAgICAgfQogICAgICByZXR1cm4gcmVzdWx0OwogIH0KICAvKiogU3BsaXQgYSBmcm9udG1hdHRlciBsaXN0IGludG8gc2VwYXJhdGUgZWxlbWVudHM7IGhhbmRsZXMgYWN0dWFsIGxpc3RzLCBjb21tYSBzZXBhcmF0ZWQgbGlzdHMsIGFuZCBzaW5nbGUgZWxlbWVudHMuICovCiAgZnVuY3Rpb24gc3BsaXRGcm9udG1hdHRlclRhZ09yQWxpYXMoZGF0YSwgb24pIHsKICAgICAgaWYgKGRhdGEgPT0gbnVsbCB8fCBkYXRhID09IHVuZGVmaW5lZCkKICAgICAgICAgIHJldHVybiBbXTsKICAgICAgaWYgKEFycmF5LmlzQXJyYXkoZGF0YSkpIHsKICAgICAgICAgIHJldHVybiBkYXRhCiAgICAgICAgICAgICAgLmZpbHRlcihzID0+ICEhcykKICAgICAgICAgICAgICAubWFwKHMgPT4gc3BsaXRGcm9udG1hdHRlclRhZ09yQWxpYXMocywgb24pKQogICAgICAgICAgICAgIC5yZWR1Y2UoKHAsIGMpID0+IHAuY29uY2F0KGMpLCBbXSk7CiAgICAgIH0KICAgICAgLy8gRm9yY2UgdG8gYSBzdHJpbmcgdG8gaGFuZGxlIG51bWJlcnMgYW5kIHNvIG9uLgogICAgICByZXR1cm4gKCIiICsgZGF0YSkKICAgICAgICAgIC5zcGxpdChvbikKICAgICAgICAgIC5maWx0ZXIodCA9PiAhIXQpCiAgICAgICAgICAubWFwKHQgPT4gdC50cmltKCkpCiAgICAgICAgICAuZmlsdGVyKHQgPT4gdC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vbnN0IGxpc3RMaW5lc1RvU2tpcCA9IG5ldyBTZXQoKTsKICAgICAgZm9yIChjb25zdCBsaW5lIG9mIGxpc3RzKSB7CiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IGxpbmUubGluZUNvdW50OyBpKyspCiAgICAgICAgICAgICAgbGlzdExpbmVzVG9Ta2lwLmFkZChsaW5lLmxpbmUgKyBpKTsKICAgICAgfQogICAgICAvLyBPbmx5IHBhcnNlIGhlYWRpbmcgYW5kIHBhcmFncmFwaCBlbGVtZW50cyBmb3IgaW5saW5lIGZpZWxkczsgd2Ugd2lsbCBwYXJzZSBsaXN0IG1ldGFkYXRhIHNlcGFyYXRlbHkuCiAgICAgIGZvciAobGV0IHNlY3Rpb24gb2YgbWV0YWRhdGEuc2VjdGlvbnMgfHwgW10pIHsKICAgICAgICAgIGlmIChzZWN0aW9uLnR5cGUgPT0gImxpc3QiIHx8IHNlY3Rpb24udHlwZSA9PSAicnVsaW5nIikKICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgIGZvciAobGV0IGxpbmVubyA9IHNlY3Rpb24ucG9zaXRpb24uc3RhcnQubGluZTsgbGluZW5vIDw9IHNlY3Rpb24ucG9zaXRpb24uZW5kLmxpbmU7IGxpbmVubysrKSB7CiAgICAgICAgICAgICAgbGV0IGxpbmUgPSBjb250ZW50c1tsaW5lbm9dOwogICAgICAgICAgICAgIGlmIChsaW5lID09IHVuZGVmaW5lZCB8fCBsaW5lID09IG51bGwpCiAgICAgICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgICAgIGlmIChsaXN0TGluZXNUb1NraXAuaGFzKGxpbmVubykpCiAgICAgICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgICAgIC8vIEZhc3QgYmFpbC1vdXQgZm9yIGxpbmVzIHRoYXQgYXJlIHRvbyBsb25nIG9yIGRvIG5vdCBjb250YWluICc6OicuCiAgICAgICAgICAgICAgaWYgKGxpbmUubGVuZ3RoID4gMzI3NjggfHwgIWxpbmUuaW5jbHVkZXMoIjo6IikpCiAgICAgICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgICAgIGxpbmUgPSBsaW5lLnRyaW0oKTsKICAgICAgICAgICAgICBsZXQgaW5saW5lRmllbGRzID0gZXh0cmFjdElubGluZUZpZWxkcyhsaW5lKTsKICAgICAgICAgICAgICBpZiAoaW5saW5lRmllbGRzLmxlbmd0aCA+IDApIHsKICAgICAgICAgICAgICAgICAgZm9yIChsZXQgaWZpZWxkIG9mIGlubGluZUZpZWxkcykKICAgICAgICAgICAgICAgICAgICAgIGFkZFJhd0lubGluZUZpZWxkKGlmaWVsZCwgZmllbGRzKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgIGxldCBmdWxsTGluZSA9IGV4dHJhY3RGdWxsTGluZUZpZWxkKGxpbmUpOwogICAgICAgICAgICAgICAgICBpZiAoZnVsbExpbmUpCiAgICAgICAgICAgICAgICAgICAgICBhZGRSYXdJbmxpbmVGaWVsZChmdWxsTGluZSwgZmllbGRzKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgIH0KICAgICAgcmV0dXJuIHsgZmllbGRzLCBsaXN0cyB9OwogIH0KICAvLyBUT0RPOiBDb25zaWRlciB1c2luZyBhbiBhY3R1YWwgcGFyc2VyIGluIGxpZXUgb2YgYSBtb3JlIGV4cGVuc2l2ZSByZWdleC4KICBjb25zdCBMSVNUX0lURU1fUkVHRVggPSAvXltccz5dKihcZCtcLnxcZCtcKXxcKnwtfFwrKVxzKihcWy57MCwxfVxdKT9ccyooLiopJC9tdTsKICAvKioKICAgKiBQYXJzZSBsaXN0IGl0ZW1zIGZyb20gdGhlIHBhZ2UgKyBtZXRhZGF0YS4gVGhpcyByZXF1aXJlcyBzb21lIGFkZGl0aW9uYWwgcGFyc2luZyBhYm92ZSB3aGF0ZXZlciBPYnNpZGlhbiBwcm92aWRlcywKICAgKiBzaW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3NpdGlvbi5zdGFydC5saW5lOyBsaW5lIDw9IHJhd0VsZW1lbnQucG9zaXRpb24uZW5kLmxpbmU7IGxpbmUrKykgewogICAgICAgICAgICAgIGlmIChsaW5rc0J5TGluZVtsaW5lXSkKICAgICAgICAgICAgICAgICAgbGlua3MucHVzaCguLi5saW5rc0J5TGluZVtsaW5lXSk7CiAgICAgICAgICB9CiAgICAgICAgICAvLyBDb25zdHJ1Y3QgdW5pdmVyc2FsIGluZm9ybWF0aW9uIGFib3V0IHRoaXMgZWxlbWVudCAoYmVmb3JlIHRhc2tzKS4KICAgICAgICAgIGxldCBpdGVtID0gbmV3IExpc3RJdGVtKHsKICAgICAgICAgICAgICBzeW1ib2w6IHJhd01hdGNoWzFdLAogICAgICAgICAgICAgIGxpbms6IGNsb3Nlc3RMaW5rLAogICAgICAgICAgICAgIGxpbmtzOiBsaW5rcywKICAgICAgICAgICAgICBzZWN0aW9uOiBzZWN0aW9uTGluaywKICAgICAgICAgICAgICB0ZXh0OiB0ZXh0V2l0aE5ld2xpbmUsCiAgICAgICAgICAgICAgdGFnczogZXh0cmFjdFRhZ3MkMSh0ZXh0Tm9OZXdsaW5lKSwKICAgICAgICAgICAgICBsaW5lOiByYXdFbGVtZW50LnBvc2l0aW9uLnN0YXJ0LmxpbmUsCiAgICAgICAgICAgICAgbGluZUNvdW50OiByYXdFbGVtZW50LnBvc2l0aW9uLmVuZC5saW5lIC0gcmF3RWxlbWVudC5wb3NpdGlvbi5zdGFydC5saW5lICsgMSwKICAgICAgICAgICAgICBsaXN0OiBjb250YWluaW5nTGlzdElkID09IC0xID8gLTEgOiAobWV0YWRhdGEuc2VjdGlvbnMgfHwgW10pW2NvbnRhaW5pbmdMaXN0SWRdLnBvc2l0aW9uLnN0YXJ0LmxpbmUsCiAgICAgICAgICAgICAgcG9zaXRpb246IHJhd0VsZW1lbnQucG9zaXRpb24sCiAgICAgICAgICAgICAgY2hpbGRyZW46IFtdLAogICAgICAgICAgICAgIGJsb2NrSWQ6IHJhd0VsZW1lbnQuaWQsCiAgICAgICAgICB9KTsKICAgICAgICAgIGlmIChyYXdFbGVtZW50LnBhcmVudCA+PSAwICYmIHJhd0VsZW1lbnQucGFyZW50ICE9IGl0ZW0ubGluZSkKICAgICAgICAgICAgICBpdGVtLnBhcmVudCA9IHJhd0VsZW1lbnQucGFyZW50OwogICAgICAgICAgLy8gU2V0IHVwIHRoZSBiYXNpYyB0YXNrIGluZm9ybWF0aW9uIGZvciBub3csIHRob3VnaCB3ZSBoYXZlIHRvIHJlY29tcHV0ZSBgZnVsbHlDb21wdXRlZGAgbGF0ZXIuCiAgICAgICAgICBpZiAocmF3RWxlbWVudC50YXNrKSB7CiAgICAgICAgICAgICAgaXRlbS50YXNrID0gewogICAgICAgICAgICAgICAgICBzdGF0dXM6IHJhd0VsZW1lbnQudGFzaywKICAgICAgICAgICAgICAgICAgY2hlY2tlZDogcmF3RWxlbWVudC50YXNrICE9ICIiICYmIHJhd0VsZW1lbnQudGFzayAhPSAiICIsCiAgICAgICAgICAgICAgICAgIGNvbXBsZXRlZDogcmF3RWxlbWVudC50YXNrID09ICJYIiB8fCByYXdFbGVtZW50LnRhc2sgPT0gIngiLAogICAgICAgICAgICAgICAgICBmdWxseUNvbXBsZXRlZDogcmF3RWxlbWVudC50YXNrID09ICJYIiB8fCByYXdFbGVtZW50LnRhc2sgPT0gIngiLAogICAgICAgICAgICAgIH07CiAgICAgICAgICB9CiAgICAgICAgICAvLyBFeHRyYWN0IGlubGluZSBmaWVsZHM7IGV4dHJhY3QgZnVsbC1saW5lIGZpZWxkcyBvbmx5IGlmIHdlIGFyZSBOT1QgYSB0YXNrLgogICAgICAgICAgaXRlbS5maWVsZHMgPSBuZXcgTWFwKCk7CiAgICAgICAgICBmb3IgKGxldCBlbGVtZW50IG9mIGV4dHJhY3RJbmxpbmVGaWVsZHModGV4dE5vTmV3bGluZSwgdHJ1ZSkpCiAgICAgICAgICAgICAgYWRkUmF3SW5saW5lRmllbGQoZWxlbWV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gZmluZS4KICAgICAgICAgIGlmIChsaXN0SXRlbS50YXNrKSB7CiAgICAgICAgICAgICAgbGV0IGN1cnIgPSBsaXN0SXRlbTsKICAgICAgICAgICAgICB3aGlsZSAoISFjdXJyKSB7CiAgICAgICAgICAgICAgICAgIGlmIChjdXJyLnRhc2spCiAgICAgICAgICAgICAgICAgICAgICBjdXJyLnRhc2suZnVsbHlDb21wbGV0ZWQgPSBjdXJyLnRhc2suZnVsbHlDb21wbGV0ZWQgJiYgbGlzdEl0ZW0udGFzay5jb21wbGV0ZWQ7CiAgICAgICAgICAgICAgICAgIGN1cnIgPSBjYWNoZVtjdXJyLnBhcmVudCA/PyAtMV07CiAgICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICB9CiAgICAgIHJldHVybiBbT2JqZWN0LnZhbHVlcyhjYWNoZSksIGxpdGVyYWxzXTsKICB9CiAgLyoqIEF0dGVtcHQgdG8gZmluZCBhIGRhdGUgYXNzb2NpYXRlZCB3aXRoIHRoZSBnaXZlbiBwYWdlIGZyb20gbWV0YWRhdGEgb3IgZmlsZW5hbWVzLiAqLwogIGZ1bmN0aW9uIGZpbmREYXRlKGZpbGUsIGZpZWxkcykgewogICAgICBmb3IgKGxldCBrZXkgb2YgZmllbGRzLmtleXMoKSkgewogICAgICAgICAgaWYgKCEoa2V5LnRvTG9jYWxlTG93ZXJDYXNlKCkgPT0gImRhdGUiIHx8IGtleS50b0xvY2FsZUxvd2VyQ2FzZSgpID09ICJkYXkiKSkKICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgIGxldCB2YWx1ZSA9IGZpZWxkcy5nZXQoa2V5KTsKICAgICAgICAgIGlmIChWYWx1ZXMuaXNEYXRlKHZhbHVlKSkgewogICAgICAgICAgICAgIHJldHVybiB2YWx1ZTsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKFZhbHVlcy5pc0FycmF5KHZhbHVlKSAmJiB2YWx1ZS5sZW5ndGggPiAwICYmIFZhbHVlcy5pc0RhdGUodmFsdWVbMF0pKSB7CiAgICAgICAgICAgICAgcmV0dXJuIHZhbHVlWzBdOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSBpZiAoVmFsdWVzLmlzTGluayh2YWx1ZSkpIHsKICAgICAgICAgICAgICBsZXQgZGF0ZSA9IGV4dHJhY3REYXRlKHZhbHVlLnBhdGgpID8/IGV4dHJhY3REYXRlKHZhbHVlLnN1YnBhdGggPz8gIiIpID8/IGV4dHJhY3REYXRlKHZhbHVlLmRpc3BsYXkgPz8gIiIpOwogICAgICAgICAgICAgIGlmIChkYXRlKQogICAgICAgICAgICAgICAgICByZXR1cm4gZGF0ZTsKICAgICAgICAgIH0KICAgICAgfQogICAgICByZXR1cm4gZXh0cmFjdERhdGUoZ2V0RmlsZVRpdGxlKGZpbGUpKTsKICB9CiAgLyoqIFJlY3Vyc2l2ZWx5IGNvbnZlcnQgZnJvbnRtYXR0ZXIgaW50byBmaWVsZHMuIFdlIGhhdmUgdG8gZGFuY2UgYXJvdW5kIFlBTUwgc3RydWN0dXJlLiAqLwogIGZ1bmN0aW9uIHBhcnNlRnJvbnRtYXR0ZXIodmFsdWUpIHsKICAgICAgaWYgKHZhbHVlID09IG51bGwpIHsKICAgICAgICAgIHJldHVybiBudWxsOwogICAgICB9CiAgICAgIGVsc2UgaWYgKHR5cGVvZiB2YWx1ZSA9PT0gIm9iamVjdCIpIHsKICAgICAgICAgIGlmIChBcnJheS5pc0FycmF5KHZhbHVlKSkgewogICAgICAgICAgICAgIGxldCByZXN1bHQgPSBbXTsKICAgICAgICAgICAgICBmb3IgKGxldCBjaGlsZCBvZiB2YWx1ZSkgewogICAgICAgICAgICAgICAgICByZXN1bHQucHVzaChwYXJzZUZyb250bWF0dGVyKGNoaWxkKSk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIHJldHVybiByZXN1bHQ7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIGlmICh2YWx1ZSBpbnN0YW5jZW9mIERhdGUpIHsKICAgICAgICAgICAgICBsZXQgZGF0ZVBhcnNlID0gRGF0ZVRpbWUuZnJvbUpTRGF0ZSh2YWx1ZSk7CiAgICAgICAgICAgICAgcmV0dXJuIGRhdGVQYXJzZTsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGxldCBvYmplY3QgPSB2YWx1ZTsKICAgICAgICAgICAgICBsZXQgcmVzdWx0ID0ge307CiAgICAgICAgICAgICAgZm9yIChsZXQga2V5IGluIG9iamVjdCkgewogICAgICAgICAgICAgICAgICByZXN1bHRba2V5XSA9IHBhcnNlRnJvbnRtYXR0ZXIob2JqZWN0W2tleV0pOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0OwogICAgICAgICAgfQogICAgICB9CiAgICAgIGVsc2UgaWYgKHR5cGVvZiB2YWx1ZSA9PT0gIm51bWJlciIpIHsKICAgICAgICAgIHJldHVybiB2YWx1ZTsKICAgICAgfQogICAgICBlbHNlIGlmICh0eXBlb2YgdmFsdWUgPT09ICJib29sZWFuIikgewogICAgICAgICAgcmV0dXJuIHZhbHVlOwogICAgICB9CiAgICAgIGVsc2UgaWYgKHR5cGVvZiB2YWx1ZSA9PT0gInN0cmluZyIpIHsKICAgICAgICAgIGxldCBkYXRlUGFyc2UgPSBFWFBSRVNTSU9OLmRhdGUucGFyc2UodmFsdWUpOwogICAgICAgICAgaWYgKGRhdGVQYXJzZS5zdGF0dXMpCiAgICAgICAgICAgICAgcmV0dXJuIGRhdGVQYXJzZS52YWx1ZTsKICAgICAgICAgIGxldCBkdXJhdGlvblBhcnNlID0gRVhQUkVTU0lPTi5kdXJhdGlvbi5wYXJzZSh2YWx1ZSk7CiAgICAgICAgICBpZiAoZHVyYXRpb25QYXJzZS5zdGF0dXMpCiAgICAgICAgICAgICAgcmV0dXJuIGR1cmF0aW9uUGFyc2UudmFsdWU7CiAgICAgICAgICBsZXQgbGlua1BhcnNlID0gRVhQUkVTU0lPTi5lbWJlZExpb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ZlcmFibGUodmFsKSk7CiAgICAgICAgICAgICAgcmV0dXJuIGNvcGllZDsKICAgICAgICAgIH0KICAgICAgICAgIGxldCB3cmFwcGVkID0gVmFsdWVzLndyYXBWYWx1ZSh2YWx1ZSk7CiAgICAgICAgICBpZiAod3JhcHBlZCA9PT0gdW5kZWZpbmVkKQogICAgICAgICAgICAgIHRocm93IEVycm9yKCJVbnJlY29nbml6ZWQgdHJhbnNmZXJhYmxlIHZhbHVlOiAiICsgdmFsdWUpOwogICAgICAgICAgc3dpdGNoICh3cmFwcGVkLnR5cGUpIHsKICAgICAgICAgICAgICBjYXNlICJudWxsIjoKICAgICAgICAgICAgICBjYXNlICJudW1iZXIiOgogICAgICAgICAgICAgIGNhc2UgInN0cmluZyI6CiAgICAgICAgICAgICAgY2FzZSAiYm9vbGVhbiI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB3cmFwcGVkLnZhbHVlOwogICAgICAgICAgICAgIGNhc2UgImRhdGUiOgogICAgICAgICAgICAgICAgICByZXR1cm4gewogICAgICAgICAgICAgICAgICAgICAgIl9fX3RyYW5zZmVyLXR5cGUiOiAiZGF0ZSIsCiAgICAgICAgICAgICAgICAgICAgICB2YWx1ZTogdHJhbnNmZXJhYmxlKHdyYXBwZWQudmFsdWUudG9PYmplY3QoKSksCiAgICAgICAgICAgICAgICAgICAgICBvcHRpb25zOiB7CiAgICAgICAgICAgICAgICAgICAgICAgICAgem9uZTogd3JhcHBlZC52YWx1ZS56b25lLmVxdWFscyhTeXN0ZW1ab25lLmluc3RhbmNlKSA/IHVuZGVmaW5lZCA6IHdyYXBwZWQudmFsdWUuem9uZU5hbWUsCiAgICAgICAgICAgICAgICAgICAgICB9LAogICAgICAgICAgICAgICAgICB9OwogICAgICAgICAgICAgIGNhc2UgImR1cmF0aW9uIjoKICAgICAgICAgICAgICAgICAgcmV0dXJuIHsgIl9fX3RyYW5zZmVyLXR5cGUiOiAiZHVyYXRpb24iLCB2YWx1ZTogdHJhbnNmZXJhYmxlKHdyYXBwZWQudmFsdWUudG9PYmplY3QoKSkgfTsKICAgICAgICAgICAgICBjYXNlICJhcnJheSI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB3cmFwcGVkLnZhbHVlLm1hcCh2ID0+IHRyYW5zZmVyYWJsZSh2KSk7CiAgICAgICAgICAgICAgY2FzZSAibGluayI6CiAgICAgICAgICAgICAgICAgIHJldHVybiB7ICJfX190cmFuc2Zlci10eXBlIjogImxpbmsiLCB2YWx1ZTogdHJhbnNmZXJhYmxlKHdyYXBwZWQudmFsdWUudG9PYmplY3QoKSkgfTsKICAgICAgICAgICAgICBjYXNlICJvYmplY3QiOgogICAgICAgICAgICAgICAgICBsZXQgcmVzdWx0ID0ge307CiAgICAgICAgICAgICAgICAgIGZvciAobGV0IFtrZXksIHZhbHVlXSBvZiBPYmplY3QuZW50cmllcyh3cmFwcGVkLnZhbHVlKSkKICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFtrZXldID0gdHJhbnNmZXJhYmxlKHZhbHVlKTsKICAgICAgICAgICAgICAgICAgcmV0dXJuIHJlc3VsdDsKICAgICAgICAgIH0KICAgICAgfQogICAgICBUcmFuc2ZlcmFibGUudHJhbnNmZXJhYmxlID0gdHJhbnNmZXJhYmxlOwogICAgICAvKiogQ29udmVydCBhIHRyYW5zZmVyYWJsZSB2YWx1ZSBiYWNrIHRvIGEgbGl0ZXJhbCB2YWx1ZSB3ZSBjYW4gd29yayB3aXRoLiAqLwogICAgICBmdW5jdGlvbiB2YWx1ZSh0cmFuc2ZlcmFibGUpIHsKICAgICAgICAgIGlmICh0cmFuc2ZlcmFibGUgPT09IG51bGwpIHsKICAgICAgICAgICAgICByZXR1cm4gbnVsbDsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKHRyYW5zZmVyYWJsZSA9PT0gdW5kZWZpbmVkKSB7CiAgICAgICAgICAgICAgcmV0dXJuIHVuZGVmaW5lZDsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKHRyYW5zZmVyYWJsZSBpbnN0YW5jZW9mIE1hcCkgewogICAgICAgICAgICAgIGxldCByZWFsID0gbmV3IE1hcCgpOwogICAgICAgICAgICAgIGZvciAobGV0IFtrZXksIHZhbF0gb2YgdHJhbnNmZXJhYmxlLmVudHJpZXMoKSkKICAgICAgICAgICAgICAgICAgcmVhbC5zZXQodmFsdWUoa2V5KSwgdmFsdWUodmFsKSk7CiAgICAgICAgICAgICAgcmV0dXJuIHJlYWw7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIGlmICh0cmFuc2ZlcmFibGUgaW5zdGFuY2VvZiBTZXQpIHsKICAgICAgICAgICAgICBsZXQgcmVhbCA9IG5ldyBTZXQoKTsKICAgICAgICAgICAgICBmb3IgKGxldCB2YWwgb2YgdHJhbnNmZXJhYmxlKQogICAgICAgICAgICAgICAgICByZWFsLmFkZCh2YWx1ZSh2YWwpKTsKICAgICAgICAgICAgICByZXR1cm4gcmVhbDsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKEFycmF5LmlzQXJyYXkodHJhbnNmZXJhYmxlKSkgewogICAgICAgICAgICAgIHJldHVybiB0cmFuc2ZlcmFibGUubWFwKHYgPT4gdmFsdWUodikpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSBpZiAodHlwZW9mIHRyYW5zZmVyYWJsZSA9PT0gIm9iamVjdCIpIHsKICAgICAgICAgICAgICBpZiAoIl9fX3RyYW5zZmVyLXR5cGUiIGluIHRyYW5zZmVyYWJsZSkgewogICAgICAgICAgICAgICAgICBzd2l0Y2ggKHRyYW5zZmVyYWJsZVsiX19fdHJhbnNmZXItdHlwZSJdKSB7CiAgICAgICAgICAgICAgICAgICAgICBjYXNlICJkYXRlIjoKICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgZGF0ZU9wdHMgPSB2YWx1ZSh0cmFuc2ZlcmFibGUub3B0aW9ucyk7CiAgICAgICAgICAgICAgICAgICAgICAgICAgbGV0IGRhdGVEYXRhID0gdmFsdWUodHJhbnNmZXJhYmxlLnZhbHVlKTsKICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gRGF0ZVRpbWUuZnJvbU9iamVjdChkYXRlRGF0YSwgeyB6b25lOiBkYXRlT3B0cy56b25lIH0pOwogICAgICAgICAgICAgICAgICAgICAgY2FzZSAiZHVyYXRpb24iOgogICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBEdXJhdGlvbi5mcm9tT2JqZWN0KHZhbHVlKHRyYW5zZmVyYWJsZS52YWx1ZSkpOwogICAgICAgICAgICAgICAgICAgICAgY2FzZSAibGluayI6CiAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIExpbmsuZnJvbU9iamVjdCh2YWx1ZSh0cmFuc2ZlcmFibGUudmFsdWUpKTsKICAgICAgICAgICAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICAgICAgICAgICAgdGhyb3cgRXJyb3IoYFVucmVjb2duaXplZCB0cmFuc2ZlciB0eXBlICcke3RyYW5zZmVyYWJsZVsiX19fdHJhbnNmZXItdHlwZSJdfSdgKTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBsZXQgcmVzdWx0ID0ge307CiAgICAgICAgICAgICAgZm9yIChsZXQgW2tleSwgdmFsXSBvZiBPYmplY3QuZW50cmllcyh0cmFuc2ZlcmFibGUpKQogICAgICAgICAgICAgICAgICByZXN1bHRba2V5XSA9IHZhbHVlKHZhbCk7CiAgICAgICAgICAgICAgcmV0dXJuIHJlc3VsdDsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiB0cmFuc2ZlcmFibGU7CiAgICAgIH0KICAgICAgVHJhbnNmZXJhYmxlLnZhbHVlID0gdmFsdWU7CiAgfSkoVHJhbnNmZXJhYmxlIHx8IChUcmFuc2ZlcmFibGUgPSB7fSkpOwoKICAvKiogRW50cnktcG9pbnQgc2NyaXB0IHVzZWQgYnkgdGhlIGluZGV4IGFzIGEg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IHRvIGluZGV4IGZpbGU6ICR7ZXZ0LmRhdGEucGF0aH06ICR7ZXJyb3J9YCwKICAgICAgICAgICAgICB9LAogICAgICAgICAgfSk7CiAgICAgIH0KICB9OwoKfSkoKTsKCg==', null, false); +/* eslint-enable */ + +/** Controls and creates Dataview file importers, allowing for asynchronous loading and parsing of files. */ +/** Multi-threaded file parser which debounces rapid file requests automatically. */ +class FileImporter extends obsidian.Component { + numWorkers; + vault; + metadataCache; + /* Background workers which do the actual file parsing. */ + workers; + /** Tracks which workers are actively parsing a file, to make sure we properly delegate results. */ + busy; + /** List of files which have been queued for a reload. */ + reloadQueue; + /** Fast-access set which holds the list of files queued to be reloaded; used for debouncing. */ + reloadSet; + /** Paths -> promises for file reloads which have not yet been queued. */ + callbacks; + constructor(numWorkers, vault, metadataCache) { + super(); + this.numWorkers = numWorkers; + this.vault = vault; + this.metadataCache = metadataCache; + this.workers = []; + this.busy = []; + this.reloadQueue = []; + this.reloadSet = new Set(); + this.callbacks = new Map(); + for (let index = 0; index < numWorkers; index++) { + let worker = new WorkerFactory({ name: "Dataview Indexer " + (index + 1) }); + worker.onmessage = evt => this.finish(evt.data.path, Transferable.value(evt.data.result), index); + this.workers.push(worker); + this.register(() => worker.terminate()); + this.busy.push(false); + } + } + /** + * Queue the given file for reloading. Multiple reload requests for the same file in a short time period will be de-bounced + * and all be resolved by a single actual file reload. + */ + reload(file) { + let promise = new Promise((resolve, reject) => { + if (this.callbacks.has(file.path)) + this.callbacks.get(file.path)?.push([resolve, reject]); + else + this.callbacks.set(file.path, [[resolve, reject]]); + }); + // De-bounce repeated requests for the same file. + if (this.reloadSet.has(file.path)) + return promise; + this.reloadSet.add(file.path); + // Immediately run this task if there are available workers; otherwise, add it to the queue. + let workerId = this.nextAvailableWorker(); + if (workerId !== undefined) { + this.send(file, workerId); + } + else { + this.reloadQueue.push(file); + } + return promise; + } + /** Finish the parsing of a file, potentially queueing a new file. */ + finish(path, data, index) { + // Cache the callbacks before we do book-keeping. + let calls = [].concat(this.callbacks.get(path) ?? []); + // Book-keeping to clear metadata & allow the file to be re-loaded again. + this.reloadSet.delete(path); + this.callbacks.delete(path); + // Notify the queue this file is available for new work. + this.busy[index] = false; + // Queue a new job onto this worker. + let job = this.reloadQueue.shift(); + if (job !== undefined) + this.send(job, index); + // Resolve promises to let users know this file has finished. + if ("$error" in data) { + for (let [_, reject] of calls) + reject(data["$error"]); + } + else { + for (let [callback, _] of calls) + callback(data); + } + } + /** Send a new task to the given worker ID. */ + send(file, workerId) { + this.busy[workerId] = true; + this.vault.cachedRead(file).then(c => this.workers[workerId].postMessage({ + path: file.path, + contents: c, + stat: file.stat, + metadata: this.metadataCache.getFileCache(file), + })); + } + /** Find the next available, non-busy worker; return undefined if all workers are busy. */ + nextAvailableWorker() { + let index = this.busy.indexOf(false); + return index == -1 ? undefined : index; + } +} + +/** Stores various indices on all files in the vault to make dataview generation fast. */ +/** Aggregate index which has several sub-indices and will initialize all of them. */ +class FullIndex extends obsidian.Component { + app; + indexVersion; + onChange; + /** Generate a full index from the given vault. */ + static create(app, indexVersion, onChange) { + return new FullIndex(app, indexVersion, onChange); + } + /** Whether all files in the vault have been indexed at least once. */ + initialized; + /** I/O access to the Obsidian vault contents. */ + vault; + /** Access to in-memory metadata, useful for parsing and metadata lookups. */ + metadataCache; + /** Persistent IndexedDB backing store, used for faster startup. */ + persister; + /* Maps path -> markdown metadata for all markdown pages. */ + pages; + /** Map files -> tags in that file, and tags -> files. This version includes subtags. */ + tags; + /** Map files -> exact tags in that file, and tags -> files. This version does not automatically add subtags. */ + etags; + /** Map files -> linked files in that file, and linked file -> files that link to it. */ + links; + /** Search files by path prefix. */ + prefix; + /** Allows for efficient lookups of whether a file is starred or not. */ + starred; + /** Caches data in CSV files. */ + // TODO: CSV parsing should be done by a worker thread asynchronously to avoid frontend stalls. + csv; + /** + * The current "revision" of the index, which monotonically increases for every index change. Use this to determine + * if you are up to date. + */ + revision; + /** Asynchronously parses files in the background using web workers. */ + importer; + /** Construct a new index using the app data and a current data version. */ + constructor(app, indexVersion, onChange) { + super(); + this.app = app; + this.indexVersion = indexVersion; + this.onChange = onChange; + this.initialized = false; + this.vault = app.vault; + this.metadataCache = app.metadataCache; + this.pages = new Map(); + this.tags = new ValueCaseInsensitiveIndexMap(); + this.etags = new ValueCaseInsensitiveIndexMap(); + this.links = new IndexMap(); + this.revision = 0; + // Caches metadata via durable storage to speed up cache initialization when Obsidian restarts. + this.persister = new LocalStorageCache(app.appId || "shared", indexVersion); + // Handles asynchronous reloading of files on web workers. + this.addChild((this.importer = new FileImporter(2, this.vault, this.metadataCache))); + // Prefix listens to file creation/deletion/rename, and not modifies, so we let it set up it's own listeners. + this.addChild((this.prefix = PrefixIndex.create(this.vault, () => this.touch()))); + // The CSV cache also needs to listen to filesystem events for cache invalidation. + this.addChild((this.csv = new CsvCache(this.vault))); + // The starred cache fetches starred entries semi-regularly via an interval. + this.addChild((this.starred = new StarredCache(this.app, () => this.touch()))); + } + /** Trigger a metadata event on the metadata cache. */ + trigger(...args) { + this.metadataCache.trigger("dataview:metadata-change", ...args); + } + /** "Touch" the index, incrementing the revision number and causing downstream views to reload. */ + touch() { + this.revision += 1; + this.onChange(); + } + /** Runs through the whole vault to set up initial file metadata. */ + initialize() { + // The metadata cache is updated on initial file index and file loads. + this.registerEvent(this.metadataCache.on("resolve", file => this.reload(file))); + // Renames do not set off the metadata cache; catch these explicitly. + this.registerEvent(this.vault.on("rename", this.rename, this)); + // File creation does cause a metadata change, but deletes do not. Clear the caches for this. + this.registerEvent(this.vault.on("delete", af => { + if (!(af instanceof obsidian.TFile) || !PathFilters.markdown(af.path)) + return; + let file = af; + this.pages.delete(file.path); + this.tags.delete(file.path); + this.etags.delete(file.path); + this.links.delete(file.path); + this.touch(); + this.trigger("delete", file); + })); + // Asynchronously initialize actual content in the background. + this._initialize(this.vault.getMarkdownFiles()); + } + /** Drops the local storage cache and re-indexes all files; this should generally be used if you expect cache issues. */ + async reinitialize() { + await this.persister.recreate(); + const files = this.vault.getMarkdownFiles(); + const start = Date.now(); + let promises = files.map(file => this.reload(file)); + await Promise.all(promises); + console.log(`Dataview: re-initialized index with ${files.length} files (${(Date.now() - start) / 1000.0}s)`); + } + /** Internal asynchronous initializer. */ + async _initialize(files) { + let reloadStart = Date.now(); + let promises = files.map(l => this.reload(l)); + let results = await Promise.all(promises); + let cached = 0, skipped = 0; + for (let item of results) { + if (item.skipped) { + skipped += 1; + continue; + } + if (item.cached) + cached += 1; + } + this.initialized = true; + this.metadataCache.trigger("dataview:index-ready"); + console.log(`Dataview: all ${files.length} files have been indexed in ${(Date.now() - reloadStart) / 1000.0}s (${cached} cached, ${skipped} skipped).`); + // Drop keys for files which do not exist anymore. + let remaining = await this.persister.synchronize(files.map(l => l.path)); + if (remaining.size > 0) { + console.log(`Dataview: Dropped cache entries for ${remaining.size} deleted files.`); + } + } + rename(file, oldPath) { + if (!(file instanceof obsidian.TFile) || !PathFilters.markdown(file.path)) + return; + if (this.pages.has(oldPath)) { + const oldMeta = this.pages.get(oldPath); + this.pages.delete(oldPath); + if (oldMeta) { + oldMeta.path = file.path; + this.pages.set(file.path, oldMeta); + } + } + this.tags.rename(oldPath, file.path); + this.links.rename(oldPath, file.path); + this.etags.rename(oldPath, file.path); + this.touch(); + this.trigger("rename", file, oldPath); + } + /** Queue a file for reloading; this is done asynchronously in the background and may take a few seconds. */ + async reload(file) { + if (!PathFilters.markdown(file.path)) + return { cached: false, skipped: true }; + // The first load of a file is attempted from persisted cache; subsequent loads just use the importer. + if (this.pages.has(file.path) || this.initialized) { + await this.import(file); + return { cached: false, skipped: false }; + } + else { + // Check the cache for the latest data; if it is out of date or non-existent, then reload. + return this.persister.loadFile(file.path).then(async (cached) => { + if (!cached || cached.time < file.stat.mtime || cached.version != this.indexVersion) { + // This cache value is out of data, reload via the importer and update the cache. + // We will skip files with no active file metadata - they will be caught by a later reload + // via the 'resolve' metadata event. + let fileCache = this.metadataCache.getFileCache(file); + if (fileCache === undefined || fileCache === null) + return { cached: false, skipped: true }; + await this.import(file); + return { cached: false, skipped: false }; + } + else { + // Use the cached data since it is up to date and on the same version. + this.finish(file, cached.data); + return { cached: true, skipped: false }; + } + }); + } + } + /** Import a file directly from disk, skipping the cache. */ + async import(file) { + return this.importer.reload(file).then(r => { + this.finish(file, r); + this.persister.storeFile(file.path, r); + }); + } + /** Finish the reloading of file metadata by adding it to in memory indexes. */ + finish(file, parsed) { + let meta = PageMetadata.canonicalize(parsed, link => { + let realPath = this.metadataCache.getFirstLinkpathDest(link.path, file.path); + if (realPath) + return link.withPath(realPath.path); + else + return link; + }); + this.pages.set(file.path, meta); + this.tags.set(file.path, meta.fullTags()); + this.etags.set(file.path, meta.tags); + this.links.set(file.path, new Set(meta.links.map(l => l.path))); + this.touch(); + this.trigger("update", file); + } +} +/** Indexes files by their full prefix - essentially a simple prefix tree. */ +class PrefixIndex extends obsidian.Component { + vault; + updateRevision; + static create(vault, updateRevision) { + return new PrefixIndex(vault, updateRevision); + } + constructor(vault, updateRevision) { + super(); + this.vault = vault; + this.updateRevision = updateRevision; + } + *walk(folder, filter) { + for (const file of folder.children) { + if (file instanceof obsidian.TFolder) { + yield* this.walk(file, filter); + } + else if (filter ? filter(file.path) : true) { + yield file.path; + } + } + } + /** Get the list of all files under the given path. */ + get(prefix, filter) { + let folder = this.vault.getAbstractFileByPath(prefix || "/"); + return new Set(folder instanceof obsidian.TFolder ? this.walk(folder, filter) : []); + } + /** Determines if the given path exists in the prefix index. */ + pathExists(path) { + return this.vault.getAbstractFileByPath(path || "/") != null; + } + /** Determines if the given prefix exists in the prefix index. */ + nodeExists(prefix) { + return this.vault.getAbstractFileByPath(prefix || "/") instanceof obsidian.TFolder; + } + /** + * Use the in-memory prefix index to convert a relative path to an absolute one. + */ + resolveRelative(path, origin) { + if (!origin) + return path; + else if (path.startsWith("/")) + return path.substring(1); + let relativePath = getParentFolder(origin) + "/" + path; + if (this.pathExists(relativePath)) + return relativePath; + else + return path; + } +} +/** Simple path filters which filter file types. */ +var PathFilters; +(function (PathFilters) { + function csv(path) { + return path.toLowerCase().endsWith(".csv"); + } + PathFilters.csv = csv; + function markdown(path) { + let lcPath = path.toLowerCase(); + return lcPath.endsWith(".md") || lcPath.endsWith(".markdown"); + } + PathFilters.markdown = markdown; +})(PathFilters || (PathFilters = {})); +/** + * Caches in-use CSVs to make high-frequency reloads (such as actively looking at a document + * that uses CSV) fast. + */ +class CsvCache extends obsidian.Component { + vault; + static CACHE_EXPIRY_SECONDS = 5 * 60; + // Cache of loaded CSVs; old entries will periodically be removed + cache; + // Periodic job which clears out the cache based on time. + cacheClearInterval; + constructor(vault) { + super(); + this.vault = vault; + this.cache = new Map(); + // Force-flush the cache on CSV file deletions or modifications. + this.registerEvent(this.vault.on("modify", file => { + if (file instanceof obsidian.TFile && PathFilters.csv(file.path)) + this.cache.delete(file.path); + })); + this.registerEvent(this.vault.on("delete", file => { + if (file instanceof obsidian.TFile && PathFilters.csv(file.path)) + this.cache.delete(file.path); + })); + } + /** Load a CSV file from the cache, doing a fresh load if it has not been loaded. */ + async get(path) { + // Clear old entries on every fresh load, since the path being loaded may be stale. + this.clearOldEntries(); + let existing = this.cache.get(path); + if (existing) + return Result.success(existing.data); + else { + let value = await this.loadInternal(path); + if (value.successful) + this.cache.set(path, { data: value.value, loadTime: DateTime.now() }); + return value; + } + } + /** Do the actual raw loading of a CSV path (which is either local or an HTTP request). */ + async loadInternal(path) { + // Allow http://, https://, and file:// prefixes which use AJAX. + if (path.startsWith("http://") || path.startsWith("https://") || path.startsWith("file://")) { + try { + let result = await fetch(path, { + method: "GET", + mode: "no-cors", + redirect: "follow", + }); + return Result.success(parseCsv(await result.text())); + } + catch (ex) { + return Result.failure("" + ex + "\n\n" + ex.stack); + } + } + // Otherwise, assume it is a fully-qualified file path. + try { + let fileData = await this.vault.adapter.read(path); + return Result.success(parseCsv(fileData)); + } + catch (ex) { + return Result.failure(`Failed to load data from path '${path}'.`); + } + } + /** Clear old entries in the cache (as measured by insertion time). */ + clearOldEntries() { + let currentTime = DateTime.now(); + let keysToRemove = new Set(); + for (let [key, value] of this.cache.entries()) { + let entryAge = Math.abs(currentTime.diff(value.loadTime, "seconds").seconds); + if (entryAge > CsvCache.CACHE_EXPIRY_SECONDS) + keysToRemove.add(key); + } + keysToRemove.forEach(key => this.cache.delete(key)); + } +} +/** Optional connector to the Obsidian 'Starred' plugin which allows for efficiently querying if a file is starred or not. */ +class StarredCache extends obsidian.Component { + app; + onUpdate; + /** Initial delay before checking the cache; we need to wait for it to asynchronously load the initial stars. */ + static INITIAL_DELAY = 4 * 1000; + /** How frequently to check for star updates. */ + static REFRESH_INTERVAL = 30 * 1000; + /** Set of all starred file paths. */ + stars; + constructor(app, onUpdate) { + super(); + this.app = app; + this.onUpdate = onUpdate; + this.stars = StarredCache.fetch(this.app); + this.registerInterval(window.setInterval(() => this.reload(), StarredCache.REFRESH_INTERVAL)); + const initialHandler = window.setTimeout(() => this.reload(), StarredCache.INITIAL_DELAY); + this.register(() => window.clearTimeout(initialHandler)); + } + /** Determines if the given path is starred. */ + starred(path) { + return this.stars.has(path); + } + reload() { + let newStars = StarredCache.fetch(this.app); + if (!setsEqual(this.stars, newStars)) { + this.stars = newStars; + this.onUpdate(); + } + } + /** Fetch all starred files from the stars plugin, if present. */ + static fetch(app) { + let items = app?.internalPlugins?.plugins?.bookmarks?.instance?.items; + if (items == undefined) + return new Set(); + // Retrieve all grouped (nested) items, returning a flat array + const flattenItems = (items) => { + let children = []; + return items + .map(i => { + if (i.type == "group" && i.items && i.items.length) { + children = [...children, ...i.items]; + } + return i; + }) + .concat(children.length ? flattenItems(children) : children); + }; + items = flattenItems(items); + return new Set(items.filter((l) => l.type === "file").map(l => l.path)); + } +} +/** A generic index which indexes variables of the form key -> value[], allowing both forward and reverse lookups. */ +class IndexMap { + /** Maps key -> values for that key. */ + map; + /** Cached inverse map; maps value -> keys that reference that value. */ + invMap; + /** Create a new, empty index map. */ + constructor() { + this.map = new Map(); + this.invMap = new Map(); + } + /** Returns all values for the given key. */ + get(key) { + let result = this.map.get(key); + if (result) { + return new Set(result); + } + else { + return new Set(); + } + } + /** Returns all keys that reference the given key. Mutating the returned set is not allowed. */ + getInverse(value) { + return this.invMap.get(value) || IndexMap.EMPTY_SET; + } + /** Sets the key to the given values; this will delete the old mapping for the key if one was present. */ + set(key, values) { + if (!values.size) { + // no need to store if no values + this.delete(key); + return this; + } + let oldValues = this.map.get(key); + if (oldValues) { + for (let value of oldValues) { + // Only delete the ones we're not adding back + if (!values.has(key)) + this.invMap.get(value)?.delete(key); + } + } + this.map.set(key, values); + for (let value of values) { + if (!this.invMap.has(value)) + this.invMap.set(value, new Set([key])); + else + this.invMap.get(value)?.add(key); + } + return this; + } + /** Clears all values for the given key so they can be re-added. */ + delete(key) { + let oldValues = this.map.get(key); + if (!oldValues) + return false; + this.map.delete(key); + for (let value of oldValues) { + this.invMap.get(value)?.delete(key); + } + return true; + } + /** Rename all references to the given key to a new value. */ + rename(oldKey, newKey) { + let oldValues = this.map.get(oldKey); + if (!oldValues) + return false; + this.delete(oldKey); + this.set(newKey, oldValues); + return true; + } + /** Clear the entire index. */ + clear() { + this.map.clear(); + this.invMap.clear(); + } + static EMPTY_SET = Object.freeze(new Set()); +} +/** Index map wrapper which is case-insensitive in the key. */ +class ValueCaseInsensitiveIndexMap { + delegate; + /** Create a new, empty case insensitive index map. */ + constructor(delegate = new IndexMap()) { + this.delegate = delegate; + } + /** Returns all values for the given key. */ + get(key) { + return this.delegate.get(key); + } + /** Returns all keys that reference the given value. Mutating the returned set is not allowed. */ + getInverse(value) { + return this.delegate.getInverse(value.toLocaleLowerCase()); + } + /** Sets the key to the given values; this will delete the old mapping for the key if one was present. */ + set(key, values) { + this.delegate.set(key, new Set(Array.from(values).map(v => v.toLocaleLowerCase()))); + return this; + } + /** Clears all values for the given key so they can be re-added. */ + delete(key) { + return this.delegate.delete(key); + } + /** Rename all references to the given key to a new value. */ + rename(oldKey, newKey) { + return this.delegate.rename(oldKey, newKey); + } + /** Clear the entire index. */ + clear() { + this.delegate.clear(); + } +} + +/** Collect data matching a source query. */ +/** Find source paths which match the given source. */ +function matchingSourcePaths(source, index, originFile = "") { + switch (source.type) { + case "empty": + return Result.success(new Set()); + case "tag": + return Result.success(index.tags.getInverse(source.tag)); + case "csv": + return Result.success(new Set([index.prefix.resolveRelative(source.path, originFile)])); + case "folder": + // Prefer loading from the folder at the given path. + if (index.prefix.nodeExists(source.folder)) + return Result.success(index.prefix.get(source.folder, PathFilters.markdown)); + // But allow for loading individual files if they exist. + if (index.prefix.pathExists(source.folder)) + return Result.success(new Set([source.folder])); + else if (index.prefix.pathExists(source.folder + ".md")) + return Result.success(new Set([source.folder + ".md"])); + // For backwards-compat, return an empty result even if the folder does not exist. + return Result.success(new Set()); + case "link": + let fullPath = index.metadataCache.getFirstLinkpathDest(source.file, originFile)?.path; + if (!fullPath) { + // Look in links which includes unresolved links + return Result.success(index.links.getInverse(source.file)); + } + if (source.direction === "incoming") { + // To find all incoming links (i.e., things that link to this), use the index that Obsidian provides. + // TODO: Use an actual index so this isn't a fullscan. + let resolved = index.metadataCache.resolvedLinks; + let incoming = new Set(); + for (let [key, value] of Object.entries(resolved)) { + if (fullPath in value) + incoming.add(key); + } + return Result.success(incoming); + } + else { + let resolved = index.metadataCache.resolvedLinks; + if (!(fullPath in resolved)) + return Result.failure(`Could not find file "${source.file}" during link lookup - does it exist?`); + return Result.success(new Set(Object.keys(index.metadataCache.resolvedLinks[fullPath]))); + } + case "binaryop": + return Result.flatMap2(matchingSourcePaths(source.left, index, originFile), matchingSourcePaths(source.right, index, originFile), (left, right) => { + if (source.op == "&") { + let result = new Set(); + for (let elem of right) { + if (left.has(elem)) + result.add(elem); + } + return Result.success(result); + } + else if (source.op == "|") { + let result = new Set(left); + for (let elem of right) + result.add(elem); + return Result.success(result); + } + else { + return Result.failure(`Unrecognized operator '${source.op}'.`); + } + }); + case "negate": + return matchingSourcePaths(source.child, index, originFile).map(child => { + // TODO: This is obviously very inefficient. Can be improved by complicating the + // return type of this function & optimizing 'and' / 'or'. + let allFiles = new Set(index.vault.getMarkdownFiles().map(f => f.path)); + child.forEach(f => allFiles.delete(f)); + return allFiles; + }); + } +} +/** Convert a path to the data for that path; usually markdown pages, but could also be other file types (like CSV). */ +async function resolvePathData(path, index) { + if (PathFilters.csv(path)) + return resolveCsvData(path, index); + else + return resolveMarkdownData(path, index); +} +// TODO: We shouldn't be doing path normalization here relative to an origin file, +/** Convert a CSV path to the data in the CSV (in dataview format). */ +async function resolveCsvData(path, index) { + let rawData = await index.csv.get(path); + return rawData.map(rows => { + return rows.map((row, index) => { + return { + id: `${path}#${index}`, + data: row, + }; + }); + }); +} +/** Convert a path pointing to a markdown page, into the associated metadata. */ +function resolveMarkdownData(path, index) { + let page = index.pages.get(path); + if (!page) + return Result.success([]); + return Result.success([ + { + id: Link.file(path), + data: page.serialize(index), + }, + ]); +} +/** Resolve a source to the collection of data rows that it matches. */ +async function resolveSource(source, index, originFile = "") { + let paths = matchingSourcePaths(source, index, originFile); + if (!paths.successful) + return Result.failure(paths.error); + let result = []; + for (let path of paths.value) { + let resolved = await resolvePathData(path, index); + if (!resolved.successful) + return resolved; + for (let val of resolved.value) + result.push(val); + } + return Result.success(result); +} + +// cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated. +// A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance. +// Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity. +// See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480 +// https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js +function cyrb53(str, seed = 0) { + let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed; + for (let i = 0, ch; i < str.length; i++) { + ch = str.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507); + h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909); + h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507); + h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909); + // For a full 64-bit value we could return + // [h2>>>0, h1>>>0] + return 4294967296 * (2097151 & h2) + (h1 >>> 0); // ; +} + +/** Default function implementations for the expression evaluator. */ +/** + * Allows for the creation of functions that check the number and type of their arguments, and dispatch + * to different implementations based on the types of the inputs. + */ +class FunctionBuilder { + name; + variants; + vectorized; + constructor(name) { + this.name = name; + this.variants = []; + this.vectorized = {}; + } + /** Add a general function variant which accepts any number of arguments of any type. */ + vararg(impl) { + this.variants.push({ args: [], varargs: true, impl }); + return this; + } + /** Add a function variant which takes in a single argument. */ + add1(argType, impl) { + this.variants.push({ + args: [argType], + varargs: false, + impl: (c, ...rest) => impl(rest[0], c), + }); + return this; + } + /** Add a function variant which takes in two typed arguments. */ + add2(arg1, arg2, impl) { + this.variants.push({ + args: [arg1, arg2], + varargs: false, + impl: (c, ...rest) => impl(rest[0], rest[1], c), + }); + return this; + } + /** Add a function variant which takes in three typed arguments. */ + add3(arg1, arg2, arg3, impl) { + this.variants.push({ + args: [arg1, arg2, arg3], + varargs: false, + impl: (c, ...rest) => impl(rest[0], rest[1], rest[2], c), + }); + return this; + } + /** Add vectorized variants which accept the given number of arguments and delegate. */ + vectorize(numArgs, positions) { + this.vectorized[numArgs] = positions; + return this; + } + /** Return a function which checks the number and type of arguments, passing them on to the first matching variant. */ + build() { + let self = (context, ...args) => { + let types = []; + for (let arg of args) { + let argType = Values.typeOf(arg); + if (!argType) + throw Error(`Unrecognized argument type for argument '${arg}'`); + types.push(argType); + } + // Handle vectorization, possibly in multiple fields. + if (this.vectorized[types.length]) { + let vectorizedPositions = this.vectorized[types.length].filter(k => types[k] == "array"); + if (vectorizedPositions.length > 0) { + let minLength = vectorizedPositions + .map(p => args[p].length) + .reduce((p, c) => Math.min(p, c)); + // Call the subfunction for each element in the longest array. + // If you call a vectorized function with different-length arrays, + // the output is limited by the length of the shortest array. + let result = []; + for (let vpos = 0; vpos < minLength; vpos++) { + let subargs = []; + for (let index = 0; index < args.length; index++) { + if (vectorizedPositions.includes(index)) { + let arr = args[index]; + subargs.push(arr[vpos]); + } + else { + subargs.push(args[index]); + } + } + result.push(self(context, ...subargs)); + } + return result; + } + } + outer: for (let variant of this.variants) { + if (variant.varargs) + return variant.impl(context, ...args); + if (variant.args.length != types.length) + continue; + for (let index = 0; index < variant.args.length; index++) { + if (variant.args[index] != "*" && variant.args[index] != types[index]) + continue outer; + } + return variant.impl(context, ...args); + } + throw Error(`No implementation of '${this.name}' found for arguments: ${types.join(", ")}`); + }; + return self; + } +} +/** Utilities for managing function implementations. */ +var Functions; +(function (Functions) { + /** Bind a context to a function implementation, yielding a function which does not need the context argument. */ + function bind(func, context) { + return (...args) => func(context, ...args); + } + Functions.bind = bind; + /** Bind a context to all functions in the given map, yielding a new map of bound functions. */ + function bindAll(funcs, context) { + let result = {}; + for (let [key, func] of Object.entries(funcs)) { + result[key] = Functions.bind(func, context); + } + return result; + } + Functions.bindAll = bindAll; +})(Functions || (Functions = {})); +/** + * Collection of all defined functions; defined here so that they can be called from within dataview, + * and test code. + */ +var DefaultFunctions; +(function (DefaultFunctions) { + DefaultFunctions.typeOf = new FunctionBuilder("type") + .add1("array", _ => "array") + .add1("boolean", _ => "boolean") + .add1("date", _ => "date") + .add1("duration", _ => "duration") + .add1("function", _ => "function") + .add1("widget", _ => "widget") + .add1("link", _ => "link") + .add1("null", _ => "null") + .add1("number", _ => "number") + .add1("object", _ => "object") + .add1("string", _ => "string") + .add1("*", _ => "unknown") + .build(); + /** Compute the length of a data type. */ + DefaultFunctions.length = new FunctionBuilder("length") + .add1("array", a => a.length) + .add1("object", a => Object.keys(a).length) + .add1("string", a => a.length) + .add1("null", _a => 0) + .build(); + /** List constructor function. */ + DefaultFunctions.list = (_context, ...args) => args; + /** Object constructor function. */ + DefaultFunctions.object = (_context, ...args) => { + if (args.length % 2 != 0) + throw Error("object() requires an even number of arguments"); + let result = {}; + for (let index = 0; index < args.length; index += 2) { + let key = args[index]; + if (!Values.isString(key)) + throw Error("keys should be of type string for object(key1, value1, ...)"); + result[key] = args[index + 1]; + } + return result; + }; + /** Internal link constructor function. */ + DefaultFunctions.link = new FunctionBuilder("link") + .add1("string", (a, c) => Link.file(c.linkHandler.normalize(a), false)) + .add1("link", a => a) + .add1("null", _a => null) + .vectorize(1, [0]) + .add2("string", "string", (t, d, c) => Link.file(c.linkHandler.normalize(t), false, d)) + .add3("string", "string", "boolean", (t, d, e, c) => Link.file(c.linkHandler.normalize(t), e, d)) + .add2("link", "string", (t, d) => t.withDisplay(d)) + .add2("null", "*", () => null) + .add2("*", "null", (t, _n, c) => DefaultFunctions.link(c, t)) + .vectorize(2, [0, 1]) + .build(); + /** Embed and un-embed a link. */ + DefaultFunctions.embed = new FunctionBuilder("embed") + .add1("link", l => l.toEmbed()) + .vectorize(1, [0]) + .add2("link", "boolean", (l, e, c) => (e ? l.toEmbed() : l.fromEmbed())) + .add1("null", () => null) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .vectorize(2, [0, 1]) + .build(); + /** External link constructor function. */ + DefaultFunctions.elink = new FunctionBuilder("elink") + .add2("string", "string", (a, d) => Widgets.externalLink(a, d)) + .add2("string", "null", (s, _n, c) => DefaultFunctions.elink(c, s, s)) + .add2("null", "*", () => null) + .vectorize(2, [0]) + .add1("string", (a, c) => DefaultFunctions.elink(c, a, a)) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + /** Date constructor function. */ + DefaultFunctions.date = new FunctionBuilder("date") + .add1("string", str => { + let parsedDate = EXPRESSION.datePlus.parse(str); + if (parsedDate.status) + return parsedDate.value; + else + return null; + }) + .add1("date", d => d) + .add1("link", (link, c) => { + // Try to parse from the display... + if (link.display) { + let parsedDate = EXPRESSION.date.parse(link.display); + if (parsedDate.status) + return parsedDate.value; + } + // Then try to parse from the path... + let parsedDate = EXPRESSION.date.parse(link.path); + if (parsedDate.status) + return parsedDate.value; + // Then pull it from the file. + let resolved = c.linkHandler.resolve(link.path); + if (resolved && resolved?.file?.day) { + return resolved?.file?.day; + } + return null; + }) + .add2("string", "string", (d, f) => { + if (f === "x" || f === "X") { + let match = NUMBER_REGEX.exec(d); + if (match) + return DateTime.fromMillis(Number.parseInt(match[0]) * (f === "X" ? 1000 : 1)); + else { + throw Error("Not a number for format( (${ f }): ${ d }"); + } + } + else { + let parsedDate = DateTime.fromFormat(d, f); + if (parsedDate.isValid) + return parsedDate; + else { + throw Error(`Can't handle format (${f}) on date string (${d})`); + } + } + }) + .add2("null", "string", () => null) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + /** Duration constructor function. */ + DefaultFunctions.dur = new FunctionBuilder("dur") + .add1("string", str => { + let parsedDur = EXPRESSION.duration.parse(str.trim()); + if (parsedDur.status) + return parsedDur.value; + else + return null; + }) + .add1("duration", d => d) + .add1("null", d => d) + .vectorize(1, [0]) + .build(); + /** Format a date using a luxon/moment-style date format. */ + DefaultFunctions.dateformat = new FunctionBuilder("dateformat") + .add2("date", "string", (date, format) => date.toFormat(format, { locale: currentLocale() })) + .add2("null", "string", (_nul, _format) => null) + .vectorize(2, [0]) + .build(); + DefaultFunctions.durationformat = new FunctionBuilder("durationformat") + .add2("duration", "string", (dur, format) => dur.toFormat(format)) + .add2("null", "string", (_nul, _format) => null) + .vectorize(2, [0]) + .build(); + DefaultFunctions.localtime = new FunctionBuilder("localtime") + .add1("date", d => d.toLocal()) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + const NUMBER_REGEX = /-?[0-9]+(\.[0-9]+)?/; + /** Number constructor function. */ + DefaultFunctions.number = new FunctionBuilder("number") + .add1("number", a => a) + .add1("string", str => { + let match = NUMBER_REGEX.exec(str); + if (match) + return Number.parseFloat(match[0]); + else + return null; + }) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + /** Format a number using a standard currency format. */ + DefaultFunctions.currencyformat = new FunctionBuilder("currencyformat") + .add2("number", "string", (num, format) => Intl.NumberFormat(currentLocale(), { style: "currency", currency: format }).format(num)) + .add2("null", "string", (_nul, _format) => null) + .add1("number", num => Intl.NumberFormat(currentLocale(), { style: "currency", currency: "USD" }).format(num)) + .add1("null", () => null) + .vectorize(2, [0]) + .build(); + /** + * Convert any value to a reasonable internal string representation. Most useful for dates, strings, numbers, and + * so on. + */ + DefaultFunctions.string = new FunctionBuilder("string").add1("*", (a, ctx) => Values.toString(a, ctx.settings)).build(); + DefaultFunctions.round = new FunctionBuilder("round") + .add1("number", n => Math.round(n)) + .add1("null", () => null) + .vectorize(1, [0]) + .add2("number", "number", (n, p) => { + if (p <= 0) + return Math.round(n); + return parseFloat(n.toFixed(p)); + }) + .add2("number", "null", n => Math.round(n)) + .add2("null", "*", () => null) + .vectorize(2, [0]) + .build(); + DefaultFunctions.trunc = new FunctionBuilder("trunc") + .add1("number", n => Math.trunc(n)) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + DefaultFunctions.floor = new FunctionBuilder("floor") + .add1("number", n => Math.floor(n)) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + DefaultFunctions.ceil = new FunctionBuilder("ceil") + .add1("number", n => Math.ceil(n)) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + DefaultFunctions.min = new FunctionBuilder("min") + .add2("*", "null", (a, _n) => a) + .add2("null", "*", (_n, a) => a) + .add2("*", "*", (a, b, ctx) => (Values.compareValue(a, b, ctx.linkHandler.normalize) <= 0 ? a : b)) + .add1("array", (a, ctx) => DefaultFunctions.min(ctx, ...a)) + .vararg((ctx, ...args) => (args.length == 0 ? null : args.reduce((p, c) => DefaultFunctions.min(ctx, p, c)))) + .build(); + DefaultFunctions.max = new FunctionBuilder("max") + .add2("*", "null", (a, _n) => a) + .add2("null", "*", (_n, a) => a) + .add2("*", "*", (a, b, ctx) => (Values.compareValue(a, b, ctx.linkHandler.normalize) > 0 ? a : b)) + .add1("array", (a, ctx) => DefaultFunctions.max(ctx, ...a)) + .vararg((ctx, ...args) => (args.length == 0 ? null : args.reduce((p, c) => DefaultFunctions.max(ctx, p, c)))) + .build(); + DefaultFunctions.minby = new FunctionBuilder("minby") + .add2("array", "function", (arr, func, ctx) => { + if (arr.length == 0) + return null; + let values = arr.map(v => { + return { value: v, mapped: func(ctx, v) }; + }); + let filtered = values.filter(v => !Values.isNull(v.mapped)); + if (filtered.length == 0) + return arr[0]; + return filtered.reduce((p, c) => { + if (Values.compareValue(p.mapped, c.mapped, ctx.linkHandler.normalize) <= 0) + return p; + else + return c; + }).value; + }) + .add2("null", "function", (_arr, _func, _ctx) => null) + .build(); + DefaultFunctions.maxby = new FunctionBuilder("maxby") + .add2("array", "function", (arr, func, ctx) => { + if (arr.length == 0) + return null; + let values = arr.map(v => { + return { value: v, mapped: func(ctx, v) }; + }); + let filtered = values.filter(v => !Values.isNull(v.mapped)); + if (filtered.length == 0) + return arr[0]; + return filtered.reduce((p, c) => { + if (Values.compareValue(p.mapped, c.mapped, ctx.linkHandler.normalize) > 0) + return p; + else + return c; + }).value; + }) + .add2("null", "function", (_arr, _func, _ctx) => null) + .build(); + DefaultFunctions.striptime = new FunctionBuilder("striptime") + .add1("date", d => DateTime.fromObject({ year: d.year, month: d.month, day: d.day })) + .add1("null", _n => null) + .vectorize(1, [0]) + .build(); + // Default contains, which looks through data structures recursively. + DefaultFunctions.contains = new FunctionBuilder("contains") + .add2("array", "*", (l, elem, context) => l.some(e => DefaultFunctions.contains(context, e, elem))) + .add2("string", "string", (haystack, needle) => haystack.includes(needle)) + .add2("object", "string", (obj, key) => key in obj) + .add2("*", "*", (elem1, elem2, context) => context.evaluate(Fields.binaryOp(Fields.literal(elem1), "=", Fields.literal(elem2))).orElseThrow()) + .vectorize(2, [1]) + .build(); + // Case insensitive version of contains. + DefaultFunctions.icontains = new FunctionBuilder("icontains") + .add2("array", "*", (l, elem, context) => l.some(e => DefaultFunctions.icontains(context, e, elem))) + .add2("string", "string", (haystack, needle) => haystack.toLocaleLowerCase().includes(needle.toLocaleLowerCase())) + .add2("object", "string", (obj, key) => key in obj) + .add2("*", "*", (elem1, elem2, context) => context.evaluate(Fields.binaryOp(Fields.literal(elem1), "=", Fields.literal(elem2))).orElseThrow()) + .vectorize(2, [1]) + .build(); + // "exact" contains, does not look recursively. + DefaultFunctions.econtains = new FunctionBuilder("econtains") + .add2("array", "*", (l, elem, context) => l.some(e => context.evaluate(Fields.binaryOp(Fields.literal(elem), "=", Fields.literal(e))).orElseThrow())) + .add2("string", "string", (haystack, needle) => haystack.includes(needle)) + .add2("object", "string", (obj, key) => key in obj) + .add2("*", "*", (elem1, elem2, context) => context.evaluate(Fields.binaryOp(Fields.literal(elem1), "=", Fields.literal(elem2))).orElseThrow()) + .vectorize(2, [1]) + .build(); + // Case insensitive contains which looks for exact word matches (i.e., boundary-to-boundary match). + DefaultFunctions.containsword = new FunctionBuilder("containsword") + .add2("string", "string", (hay, needle) => !!hay.match(new RegExp(".*\\b" + escapeRegex(needle) + "\\b.*", "i"))) + .add2("null", "*", (_a, _b) => null) + .add2("*", "null", (_a, _b) => null) + .vectorize(2, [0, 1]) + .build(); + /** Extract 0 or more keys from a given object via indexing. */ + DefaultFunctions.extract = (context, ...args) => { + if (args.length == 0) + return "extract(object, key1, ...) requires at least 1 argument"; + // Manually handle vectorization in the first argument. + let object = args[0]; + if (Values.isArray(object)) + return object.map(v => DefaultFunctions.extract(context, v, ...args.slice(1))); + let result = {}; + for (let index = 1; index < args.length; index++) { + let key = args[index]; + if (!Values.isString(key)) + throw Error("extract(object, key1, ...) must be called with string keys"); + result[key] = context.evaluate(Fields.index(Fields.literal(object), Fields.literal(key))).orElseThrow(); + } + return result; + }; + // Reverse an array or string. + DefaultFunctions.reverse = new FunctionBuilder("reverse") + .add1("array", l => { + let result = []; + for (let index = l.length - 1; index >= 0; index--) + result.push(l[index]); + return result; + }) + .add1("string", l => { + let result = ""; + for (let c = 0; c < l.length; c++) + result += l[l.length - c - 1]; + return result; + }) + .add1("*", e => e) + .build(); + // Sort an array; if given two arguments, sorts by the key returned. + DefaultFunctions.sort = new FunctionBuilder("sort") + .add1("array", (list, context) => DefaultFunctions.sort(context, list, (_ctx, a) => a)) + .add2("array", "function", (list, key, context) => { + let result = [].concat(list); + result.sort((a, b) => { + let akey = key(context, a); + let bkey = key(context, b); + let le = context + .evaluate(Fields.binaryOp(Fields.literal(akey), "<", Fields.literal(bkey))) + .orElseThrow(); + if (Values.isTruthy(le)) + return -1; + let eq = context + .evaluate(Fields.binaryOp(Fields.literal(akey), "=", Fields.literal(bkey))) + .orElseThrow(); + if (Values.isTruthy(eq)) + return 0; + return 1; + }); + return result; + }) + .add1("*", e => e) + .build(); + DefaultFunctions.regextest = new FunctionBuilder("regextest") + .add2("string", "string", (pattern, field) => RegExp(pattern).test(field)) + .add2("null", "*", (_n, _a) => false) + .add2("*", "null", (_a, _n) => false) + .vectorize(2, [0, 1]) + .build(); + DefaultFunctions.regexmatch = new FunctionBuilder("regexmatch") + .add2("string", "string", (pattern, field) => { + if (!pattern.startsWith("^") && !pattern.endsWith("$")) + pattern = "^" + pattern + "$"; + return !!field.match(pattern); + }) + .add2("null", "*", (_n, _a) => false) + .add2("*", "null", (_a, _n) => false) + .vectorize(2, [0, 1]) + .build(); + DefaultFunctions.regexreplace = new FunctionBuilder("regexreplace") + .add3("string", "string", "string", (field, pat, rep) => { + try { + let reg = new RegExp(pat, "g"); + return field.replace(reg, rep); + } + catch (ex) { + throw Error(`Invalid regexp '${pat}' in regexreplace`); + } + }) + .add3("null", "*", "*", () => null) + .add3("*", "null", "*", () => null) + .add3("*", "*", "null", () => null) + .vectorize(3, [0, 1, 2]) + .build(); + DefaultFunctions.lower = new FunctionBuilder("lower") + .add1("string", s => s.toLocaleLowerCase()) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + DefaultFunctions.upper = new FunctionBuilder("upper") + .add1("string", s => s.toLocaleUpperCase()) + .add1("null", () => null) + .vectorize(1, [0]) + .build(); + DefaultFunctions.replace = new FunctionBuilder("replace") + .add3("string", "string", "string", (str, pat, repr) => str.split(pat).join(repr)) + .add3("null", "*", "*", () => null) + .add3("*", "null", "*", () => null) + .add3("*", "*", "null", () => null) + .vectorize(3, [0, 1, 2]) + .build(); + // Ensure undefined matches turn into empty strings for split/2 and split/3. + const splitImpl = (str, delim, limit) => str.split(new RegExp(delim), limit).map(str => str || ""); + /** Split a string on a given string. */ + DefaultFunctions.split = new FunctionBuilder("split") + .add2("string", "string", (string, splitter) => splitImpl(string, splitter)) + .add3("string", "string", "number", (string, splitter, limit) => splitImpl(string, splitter, limit)) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .add3("*", "*", "null", () => null) + .add3("*", "null", "*", () => null) + .add3("null", "*", "*", () => null) + .build(); + DefaultFunctions.startswith = new FunctionBuilder("startswith") + .add2("string", "string", (str, starting) => str.startsWith(starting)) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .vectorize(2, [0, 1]) + .build(); + DefaultFunctions.endswith = new FunctionBuilder("endswith") + .add2("string", "string", (str, ending) => str.endsWith(ending)) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .vectorize(2, [0, 1]) + .build(); + DefaultFunctions.padleft = new FunctionBuilder("padleft") + .add2("string", "number", (str, len) => str.padStart(len, " ")) + .add3("string", "number", "string", (str, len, padding) => str.padStart(len, padding)) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .add3("null", "*", "*", () => null) + .add3("*", "null", "*", () => null) + .add3("*", "*", "null", () => null) + .vectorize(2, [0, 1]) + .vectorize(3, [0, 1, 2]) + .build(); + DefaultFunctions.padright = new FunctionBuilder("padright") + .add2("string", "number", (str, len) => str.padEnd(len, " ")) + .add3("string", "number", "string", (str, len, padding) => str.padEnd(len, padding)) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .add3("null", "*", "*", () => null) + .add3("*", "null", "*", () => null) + .add3("*", "*", "null", () => null) + .vectorize(2, [0, 1]) + .vectorize(3, [0, 1, 2]) + .build(); + DefaultFunctions.substring = new FunctionBuilder("substring") + .add2("string", "number", (str, start) => str.substring(start)) + .add3("string", "number", "number", (str, start, end) => str.substring(start, end)) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .add3("null", "*", "*", () => null) + .add3("*", "null", "*", () => null) + .add3("*", "*", "null", () => null) + .vectorize(2, [0, 1]) + .vectorize(3, [0, 1, 2]) + .build(); + DefaultFunctions.truncate = new FunctionBuilder("truncate") + .add3("string", "number", "string", (str, length, suffix) => { + if (str.length > length - suffix.length) { + return str.substring(0, Math.max(0, length - suffix.length)) + suffix; + } + else { + return str; + } + }) + .add2("string", "number", (str, length, ctx) => DefaultFunctions.truncate(ctx, str, length, "...")) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .add3("null", "*", "*", () => null) + .add3("*", "null", "*", () => null) + .add3("*", "*", "null", () => null) + .vectorize(2, [0, 1]) + .vectorize(3, [0, 1, 2]) + .build(); + DefaultFunctions.fdefault = new FunctionBuilder("default") + .add2("*", "*", (v, bk) => (Values.isNull(v) ? bk : v)) + .vectorize(2, [0, 1]) + .build(); + DefaultFunctions.ldefault = new FunctionBuilder("ldefault") + .add2("*", "*", (v, bk) => (Values.isNull(v) ? bk : v)) + .build(); + // Returns the display name of the element. + DefaultFunctions.display = new FunctionBuilder("display") + .add1("null", () => "") + .add1("array", (a, ctx) => { + return a.map(e => DefaultFunctions.display(ctx, e)).join(", "); + }) + .add1("string", (str) => normalizeMarkdown(str)) + .add1("link", (a, ctx) => { + if (a.display) { + return DefaultFunctions.display(ctx, a.display); + } + else { + return Values.toString(a, ctx.settings).replace(/\[\[.*\|(.*)\]\]/, "$1"); + } + }) + .add1("*", (a, ctx) => { + return Values.toString(a, ctx.settings); + }) + .build(); + DefaultFunctions.choice = new FunctionBuilder("choice") + .add3("*", "*", "*", (b, left, right) => (Values.isTruthy(b) ? left : right)) + .vectorize(3, [0]) + .build(); + DefaultFunctions.hash = new FunctionBuilder("hash") + .add2("string", "number", (seed, variant) => { + return cyrb53(seed, variant); + }) + .add2("string", "string", (seed, text) => { + return cyrb53(seed + text); + }) + .add3("string", "string", "number", (seed, text, variant) => { + return cyrb53(seed + text, variant); + }) + .build(); + DefaultFunctions.reduce = new FunctionBuilder("reduce") + .add2("array", "string", (lis, op, context) => { + if (lis.length == 0) + return null; + if (op != "+" && op != "-" && op != "*" && op != "/" && op != "&" && op != "|") + throw Error("reduce(array, op) supports '+', '-', '/', '*', '&', and '|'"); + let value = lis[0]; + for (let index = 1; index < lis.length; index++) { + value = context + .evaluate(Fields.binaryOp(Fields.literal(value), op, Fields.literal(lis[index]))) + .orElseThrow(); + } + return value; + }) + .add2("array", "function", (lis, op, context) => { + if (lis.length == 0) + return null; + let value = lis[0]; + for (let index = 1; index < lis.length; index++) { + // Skip null values to reduce the pain of summing over fields that may or may not exist. + if (Values.isNull(lis[index])) + continue; + value = op(context, value, lis[index]); + } + return value; + }) + .add2("null", "*", () => null) + .add2("*", "null", () => null) + .vectorize(2, [1]) + .build(); + DefaultFunctions.sum = new FunctionBuilder("sum") + .add1("array", (arr, c) => DefaultFunctions.reduce(c, arr, "+")) + .add1("*", e => e) + .build(); + DefaultFunctions.average = new FunctionBuilder("average") + .add1("array", (array, context) => { + if (array.length == 0) + return null; + const add = DefaultFunctions.sum(context, array); + if (add == null || add == undefined) + return null; + return context + .evaluate(Fields.binaryOp(Fields.literal(add), "/", Fields.literal(array.length))) + .orElseThrow(); + }) + .add1("*", e => e) + .build(); + DefaultFunctions.product = new FunctionBuilder("product") + .add1("array", (arr, c) => DefaultFunctions.reduce(c, arr, "*")) + .add1("*", e => e) + .build(); + DefaultFunctions.join = new FunctionBuilder("join") + .add2("array", "string", (arr, sep, ctx) => arr.map(e => Values.toString(e, ctx.settings)).join(sep)) + .add2("array", "null", (arr, _s, context) => DefaultFunctions.join(context, arr, ", ")) + .add2("*", "string", (elem, sep, ctx) => Values.toString(elem, ctx.settings)) + .add1("array", (arr, context) => DefaultFunctions.join(context, arr, ", ")) + .add1("*", (e, ctx) => Values.toString(e, ctx.settings)) + .vectorize(2, [1]) + .build(); + DefaultFunctions.any = new FunctionBuilder("any") + .add1("array", arr => arr.some(v => Values.isTruthy(v))) + .add2("array", "function", (arr, f, ctx) => arr.some(v => Values.isTruthy(f(ctx, v)))) + .vararg((_ctx, ...args) => args.some(v => Values.isTruthy(v))) + .build(); + DefaultFunctions.all = new FunctionBuilder("all") + .add1("array", arr => arr.every(v => Values.isTruthy(v))) + .add2("array", "function", (arr, f, ctx) => arr.every(v => Values.isTruthy(f(ctx, v)))) + .vararg((_ctx, ...args) => args.every(v => Values.isTruthy(v))) + .build(); + DefaultFunctions.none = new FunctionBuilder("all") + .add1("array", arr => !arr.some(v => Values.isTruthy(v))) + .add2("array", "function", (arr, f, ctx) => !arr.some(v => Values.isTruthy(f(ctx, v)))) + .vararg((_ctx, ...args) => !args.some(v => Values.isTruthy(v))) + .build(); + DefaultFunctions.filter = new FunctionBuilder("filter") + .add2("array", "function", (arr, f, ctx) => arr.filter(v => Values.isTruthy(f(ctx, v)))) + .add2("null", "*", () => null) + .build(); + DefaultFunctions.unique = new FunctionBuilder("unique") + .add1("array", (arr, ctx) => DataArray.wrap(arr, ctx.settings).distinct().array()) + .add1("null", () => null) + .build(); + DefaultFunctions.map = new FunctionBuilder("map") + .add2("array", "function", (arr, f, ctx) => arr.map(v => f(ctx, v))) + .add2("null", "*", () => null) + .build(); + DefaultFunctions.nonnull = new FunctionBuilder("nonnull") + .add1("array", arr => arr.filter(v => Values.typeOf(v) != "null")) + .vararg((_ctx, ...args) => args.filter(v => Values.typeOf(v) != "null")) + .build(); + /** Gets an object containing a link's own properties */ + DefaultFunctions.meta = new FunctionBuilder("meta") + .add1("link", link => ({ + display: link.display ?? null, + embed: link.embed, + path: link.path, + subpath: link.subpath ?? null, + type: link.type, + })) + .build(); + // Concatenates sub-array elements into a new array + DefaultFunctions.flat = new FunctionBuilder("flat") + .add1("array", a => { + return a.flat(); + }) + .add2("array", "number", (a, n) => { + // @ts-ignore + return a.flat(n); + }) + .add1("null", () => null) + .build(); + // Slices the array into a new array + DefaultFunctions.slice = new FunctionBuilder("slice") + .add1("array", a => { + return a.slice(); + }) + .add2("array", "number", (a, start) => { + return a.slice(start); + }) + .add3("array", "number", "number", (a, start, end) => { + return a.slice(start, end); + }) + .add1("null", () => null) + .build(); + // Returns the first non-null value from the array as a single element + DefaultFunctions.firstvalue = new FunctionBuilder("firstvalue") + .add1("array", a => { + let nonnull = a.filter(v => Values.typeOf(v) != "null"); + let res = nonnull.length != 0 ? nonnull[0] : null; + return res; + }) + .add1("null", () => null) + .build(); +})(DefaultFunctions || (DefaultFunctions = {})); +/** Default function implementations for the expression evaluator. */ +// Keep functions in same order as they're documented !! +const DEFAULT_FUNCTIONS = { + // Constructors + object: DefaultFunctions.object, + list: DefaultFunctions.list, + array: DefaultFunctions.list, + date: DefaultFunctions.date, + dur: DefaultFunctions.dur, + number: DefaultFunctions.number, + string: DefaultFunctions.string, + link: DefaultFunctions.link, + embed: DefaultFunctions.embed, + elink: DefaultFunctions.elink, + typeof: DefaultFunctions.typeOf, + // Numeric Operations + round: DefaultFunctions.round, + trunc: DefaultFunctions.trunc, + floor: DefaultFunctions.floor, + ceil: DefaultFunctions.ceil, + min: DefaultFunctions.min, + max: DefaultFunctions.max, + sum: DefaultFunctions.sum, + product: DefaultFunctions.product, + average: DefaultFunctions.average, + minby: DefaultFunctions.minby, + maxby: DefaultFunctions.maxby, + // Object, Arrays, and String operations + contains: DefaultFunctions.contains, + icontains: DefaultFunctions.icontains, + econtains: DefaultFunctions.econtains, + containsword: DefaultFunctions.containsword, + extract: DefaultFunctions.extract, + sort: DefaultFunctions.sort, + reverse: DefaultFunctions.reverse, + length: DefaultFunctions.length, + nonnull: DefaultFunctions.nonnull, + firstvalue: DefaultFunctions.firstvalue, + all: DefaultFunctions.all, + any: DefaultFunctions.any, + none: DefaultFunctions.none, + join: DefaultFunctions.join, + filter: DefaultFunctions.filter, + map: DefaultFunctions.map, + flat: DefaultFunctions.flat, + slice: DefaultFunctions.slice, + unique: DefaultFunctions.unique, + reduce: DefaultFunctions.reduce, + // String Operations + regextest: DefaultFunctions.regextest, + regexmatch: DefaultFunctions.regexmatch, + regexreplace: DefaultFunctions.regexreplace, + replace: DefaultFunctions.replace, + lower: DefaultFunctions.lower, + upper: DefaultFunctions.upper, + split: DefaultFunctions.split, + startswith: DefaultFunctions.startswith, + endswith: DefaultFunctions.endswith, + padleft: DefaultFunctions.padleft, + padright: DefaultFunctions.padright, + substring: DefaultFunctions.substring, + truncate: DefaultFunctions.truncate, + // Utility Operations + default: DefaultFunctions.fdefault, + ldefault: DefaultFunctions.ldefault, + display: DefaultFunctions.display, + choice: DefaultFunctions.choice, + striptime: DefaultFunctions.striptime, + dateformat: DefaultFunctions.dateformat, + durationformat: DefaultFunctions.durationformat, + currencyformat: DefaultFunctions.currencyformat, + localtime: DefaultFunctions.localtime, + hash: DefaultFunctions.hash, + meta: DefaultFunctions.meta, +}; + +/** Provides a global dispatch table for evaluating binary operators, including comparison. */ +/** Provides implementations for binary operators on two types using a registry. */ +class BinaryOpHandler { + map; + static create() { + return new BinaryOpHandler(); + } + constructor() { + this.map = new Map(); + } + register(left, op, right, func) { + this.map.set(BinaryOpHandler.repr(op, left, right), func); + return this; + } + registerComm(left, op, right, func) { + return this.register(left, op, right, func).register(right, op, left, (a, b, ctx) => func(b, a, ctx)); + } + /** Implement a comparison function. */ + compare(type, compare) { + return this.register(type, "<", type, (a, b, ctx) => compare(a, b, ctx) < 0) + .register(type, "<=", type, (a, b, ctx) => compare(a, b, ctx) <= 0) + .register(type, ">", type, (a, b, ctx) => compare(a, b, ctx) > 0) + .register(type, ">=", type, (a, b, ctx) => compare(a, b, ctx) >= 0) + .register(type, "=", type, (a, b, ctx) => compare(a, b, ctx) == 0) + .register(type, "!=", type, (a, b, ctx) => compare(a, b, ctx) != 0); + } + /** Attempt to evaluate the given binary operator on the two literal fields. */ + evaluate(op, left, right, ctx) { + let leftType = Values.typeOf(left); + let rightType = Values.typeOf(right); + if (!leftType) + return Result.failure(`Unrecognized value '${left}'`); + else if (!rightType) + return Result.failure(`Unrecognized value '${right}'`); + let handler = this.map.get(BinaryOpHandler.repr(op, leftType, rightType)); + if (handler) + return Result.success(handler(left, right, ctx)); + // Right-'*' fallback: + let handler2 = this.map.get(BinaryOpHandler.repr(op, leftType, "*")); + if (handler2) + return Result.success(handler2(left, right, ctx)); + // Left-'*' fallback: + let handler3 = this.map.get(BinaryOpHandler.repr(op, "*", rightType)); + if (handler3) + return Result.success(handler3(left, right, ctx)); + // Double '*' fallback. + let handler4 = this.map.get(BinaryOpHandler.repr(op, "*", "*")); + if (handler4) + return Result.success(handler4(left, right, ctx)); + return Result.failure(`No implementation found for '${leftType} ${op} ${rightType}'`); + } + /** Create a string representation of the given triplet for unique lookup in the map. */ + static repr(op, left, right) { + return `${left},${op},${right}`; + } +} +/** Configure and create a binary OP handler with the given parameters. */ +function createBinaryOps(linkNormalizer) { + return (BinaryOpHandler.create() + // TODO: Consider not using a universal comparison function. + .compare("*", (a, b) => Values.compareValue(a, b, linkNormalizer)) + // Global boolean operations. + .register("*", "&", "*", (a, b) => Values.isTruthy(a) && Values.isTruthy(b)) + .register("*", "|", "*", (a, b) => Values.isTruthy(a) || Values.isTruthy(b)) + // Number implementations. + .register("number", "+", "number", (a, b) => a + b) + .register("number", "-", "number", (a, b) => a - b) + .register("number", "*", "number", (a, b) => a * b) + .register("number", "/", "number", (a, b) => a / b) + .register("number", "%", "number", (a, b) => a % b) + // String implementations. + .register("string", "+", "*", (a, b, ctx) => a + Values.toString(b, ctx.settings)) + .register("*", "+", "string", (a, b, ctx) => Values.toString(a, ctx.settings) + b) + .registerComm("string", "*", "number", (a, b) => (b < 0 ? "" : a.repeat(b))) + // Date Operations. + .register("date", "-", "date", (a, b) => { + return normalizeDuration(a.diff(b, ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"])); + }) + .register("date", "-", "duration", (a, b) => a.minus(b)) + .registerComm("date", "+", "duration", (a, b) => a.plus(b)) + // Duration Operations. + .register("duration", "+", "duration", (a, b) => normalizeDuration(a.plus(b))) + .register("duration", "-", "duration", (a, b) => normalizeDuration(a.minus(b))) + .register("duration", "/", "number", (a, b) => normalizeDuration(a.mapUnits(x => x / b))) + .registerComm("duration", "*", "number", (a, b) => normalizeDuration(a.mapUnits(x => x * b))) + // Array operations. + .register("array", "+", "array", (a, b) => [].concat(a).concat(b)) + // Object operations. + .register("object", "+", "object", (a, b) => Object.assign({}, a, b)) + // Null handling operators. + .register("null", "+", "null", (_a, _b) => null) + .register("null", "-", "null", (_a, _b) => null) + .register("null", "*", "null", (_a, _b) => null) + .register("null", "/", "null", (_a, _b) => null) + .register("null", "%", "null", (_a, _b) => null) + .register("date", "+", "null", (_a, _b) => null) + .register("null", "+", "date", (_a, _b) => null) + .register("date", "-", "null", (_a, _b) => null) + .register("null", "-", "date", (_a, _b) => null)); +} + +/** Core implementation of the query language evaluation engine. */ +/** + * Evaluation context that expressions can be evaluated in. Includes global state, as well as available functions and a handler + * for binary operators. + */ +class Context { + linkHandler; + settings; + globals; + binaryOps; + functions; + /** + * Create a new context with the given namespace of globals, as well as optionally with custom binary operator, function, + * and link handlers. + */ + constructor(linkHandler, settings, globals = {}, binaryOps = createBinaryOps(linkHandler.normalize), functions = DEFAULT_FUNCTIONS) { + this.linkHandler = linkHandler; + this.settings = settings; + this.globals = globals; + this.binaryOps = binaryOps; + this.functions = functions; + } + /** Set a global value in this context. */ + set(name, value) { + this.globals[name] = value; + return this; + } + /** Get the value of a global variable by name. Returns null if not present. */ + get(name) { + return this.globals[name] ?? null; + } + /** Try to evaluate an arbitrary field in this context, raising an exception on failure. */ + tryEvaluate(field, data = {}) { + return this.evaluate(field, data).orElseThrow(); + } + /** Evaluate an arbitrary field in this context. */ + evaluate(field, data = {}) { + switch (field.type) { + case "literal": + return Result.success(field.value); + case "variable": + if (field.name in data) + return Result.success(data[field.name]); + else if (field.name in this.globals) + return Result.success(this.globals[field.name]); + else + return Result.success(null); + case "negated": + return this.evaluate(field.child, data).map(s => !Values.isTruthy(s)); + case "binaryop": + return Result.flatMap2(this.evaluate(field.left, data), this.evaluate(field.right, data), (a, b) => this.binaryOps.evaluate(field.op, a, b, this)); + case "list": + let result = []; + for (let child of field.values) { + let subeval = this.evaluate(child, data); + if (!subeval.successful) + return subeval; + result.push(subeval.value); + } + return Result.success(result); + case "object": + let objResult = {}; + for (let [key, child] of Object.entries(field.values)) { + let subeval = this.evaluate(child, data); + if (!subeval.successful) + return subeval; + objResult[key] = subeval.value; + } + return Result.success(objResult); + case "lambda": + // Just relying on JS to capture 'data' for us implicitly; unsure + // if this is correct thing to do. Could cause weird behaviors. + return Result.success((ctx, ...args) => { + let copy = Object.assign({}, data); + for (let arg = 0; arg < Math.min(args.length, field.arguments.length); arg++) { + copy[field.arguments[arg]] = args[arg]; + } + return ctx.evaluate(field.value, copy).orElseThrow(); + }); + case "function": + let rawFunc = field.func.type == "variable" + ? Result.success(field.func.name) + : this.evaluate(field.func, data); + if (!rawFunc.successful) + return rawFunc; + let func = rawFunc.value; + let args = []; + for (let arg of field.arguments) { + let resolved = this.evaluate(arg, data); + if (!resolved.successful) + return resolved; + args.push(resolved.value); + } + let call; + if (Values.isFunction(func)) + call = func; + else if (Values.isString(func) && func in this.functions) + call = this.functions[func]; + else if (Values.isString(func)) + return Result.failure(`Unrecognized function name '${func}'`); + else + return Result.failure(`Cannot call type '${Values.typeOf(func)}' as a function`); + try { + return Result.success(call(this, ...args)); + } + catch (e) { + return Result.failure(e.message); + } + case "index": + // TODO: Will move this out to an 'primitives' module and add more content to it. + let literalIndex = this.evaluate(field.index, data); + let checkedIndex = literalIndex.flatMap(s => Values.isString(s) || Values.isNumber(s) || Values.isNull(s) + ? Result.success(s) + : Result.failure("Can only index with a string or number")); + if (!checkedIndex.successful) + return checkedIndex; + let index = checkedIndex.value; + if (Values.isNull(index)) + return Result.success(null); + let checkedObject = field.object.type == "variable" && field.object.name == "row" + ? Result.success(Object.assign({}, this.globals, data)) + : this.evaluate(field.object, data); + if (!checkedObject.successful) + return checkedObject; + let object = Values.wrapValue(checkedObject.value); + if (!object) + return Result.failure("Unrecognized object to index into: " + object); + switch (object.type) { + case "object": + if (!Values.isString(index)) + return Result.failure('can only index into objects with strings (a.b or a["b"])'); + return Result.success(object.value[index] ?? null); + case "link": + if (!Values.isString(index)) + return Result.failure('can only index into links with strings (a.b or a["b"])'); + let linkValue = this.linkHandler.resolve(object.value.path); + if (Values.isNull(linkValue)) + return Result.success(null); + return Result.success(linkValue[index] ?? null); + case "array": + if (Values.isNumber(index)) { + if (index >= object.value.length || index < 0) + return Result.success(null); + else + return Result.success(object.value[index]); + } + else if (Values.isString(index)) { + let result = []; + for (let value of object.value) { + let next = this.evaluate(Fields.index(Fields.literal(value), Fields.literal(index))); + if (!next.successful) + continue; + result.push(next.value); + } + return Result.success(result); + } + else { + return Result.failure("Array indexing requires either a number (to get a specific element), or a string (to map all elements inside the array)"); + } + case "string": + if (!Values.isNumber(index)) + return Result.failure("string indexing requires a numeric index (string[index])"); + if (index >= object.value.length || index < 0) + return Result.success(null); + return Result.success(object.value[index]); + case "date": + if (!Values.isString(index)) + return Result.failure("date indexing requires a string representing the unit"); + switch (index) { + case "year": + return Result.success(object.value.year); + case "month": + return Result.success(object.value.month); + case "weekyear": + return Result.success(object.value.weekNumber); + case "week": + return Result.success(Math.floor(object.value.day / 7) + 1); + case "weekday": + return Result.success(object.value.weekday); + case "day": + return Result.success(object.value.day); + case "hour": + return Result.success(object.value.hour); + case "minute": + return Result.success(object.value.minute); + case "second": + return Result.success(object.value.second); + case "millisecond": + return Result.success(object.value.millisecond); + default: + return Result.success(null); + } + case "duration": + if (!Values.isString(index)) + return Result.failure("duration indexing requires a string representing the unit"); + switch (index) { + case "year": + case "years": + return Result.success(object.value.shiftTo("years").years); + case "month": + case "months": + return Result.success(object.value.shiftTo("months").months); + case "weeks": + return Result.success(object.value.shiftTo("weeks").weeks); + case "day": + case "days": + return Result.success(object.value.shiftTo("days").days); + case "hour": + case "hours": + return Result.success(object.value.shiftTo("hours").hours); + case "minute": + case "minutes": + return Result.success(object.value.shiftTo("minutes").minutes); + case "second": + case "seconds": + return Result.success(object.value.shiftTo("seconds").seconds); + case "millisecond": + case "milliseconds": + return Result.success(object.value.shiftTo("milliseconds").milliseconds); + default: + return Result.success(null); + } + default: + return Result.success(null); + } + } + } +} + +function iden(x) { + return x; +} +/** Shared execution code which just takes in arbitrary data, runs operations over it, and returns it + per-row errors. */ +function executeCore(rows, context, ops) { + let diagnostics = []; + let identMeaning = { type: "path" }; + let startTime = Date.now(); + for (let op of ops) { + let opStartTime = Date.now(); + let incomingRows = rows.length; + let errors = []; + switch (op.type) { + case "where": + let whereResult = []; + for (let index = 0; index < rows.length; index++) { + let row = rows[index]; + let value = context.evaluate(op.clause, row.data); + if (!value.successful) + errors.push({ index, message: value.error }); + else if (Values.isTruthy(value.value)) + whereResult.push(row); + } + rows = whereResult; + break; + case "sort": + let sortFields = op.fields; + let taggedData = []; + outer: for (let index = 0; index < rows.length; index++) { + let row = rows[index]; + let rowSorts = []; + for (let sIndex = 0; sIndex < sortFields.length; sIndex++) { + let value = context.evaluate(sortFields[sIndex].field, row.data); + if (!value.successful) { + errors.push({ index, message: value.error }); + continue outer; + } + rowSorts.push(value.value); + } + taggedData.push({ data: row, fields: rowSorts }); + } + // Sort rows by the sort fields, and then return the finished result. + taggedData.sort((a, b) => { + for (let index = 0; index < sortFields.length; index++) { + let factor = sortFields[index].direction === "ascending" ? 1 : -1; + let le = context.binaryOps + .evaluate("<", a.fields[index], b.fields[index], context) + .orElse(false); + if (Values.isTruthy(le)) + return factor * -1; + let ge = context.binaryOps + .evaluate(">", a.fields[index], b.fields[index], context) + .orElse(false); + if (Values.isTruthy(ge)) + return factor * 1; + } + return 0; + }); + rows = taggedData.map(v => v.data); + break; + case "limit": + let limiting = context.evaluate(op.amount); + if (!limiting.successful) + return Result.failure("Failed to execute 'limit' statement: " + limiting.error); + if (!Values.isNumber(limiting.value)) + return Result.failure(`Failed to execute 'limit' statement: limit should be a number, but got '${Values.typeOf(limiting.value)}' (${limiting.value})`); + rows = rows.slice(0, limiting.value); + break; + case "group": + let groupData = []; + for (let index = 0; index < rows.length; index++) { + let value = context.evaluate(op.field.field, rows[index].data); + if (!value.successful) { + errors.push({ index, message: value.error }); + continue; + } + groupData.push({ data: rows[index], key: value.value }); + } + // Sort by the key, which we will group on shortly. + groupData.sort((a, b) => { + let le = context.binaryOps.evaluate("<", a.key, b.key, context).orElse(false); + if (Values.isTruthy(le)) + return -1; + let ge = context.binaryOps.evaluate(">", a.key, b.key, context).orElse(false); + if (Values.isTruthy(ge)) + return 1; + return 0; + }); + // Then walk through and find fields that are equal. + let finalGroupData = []; + if (groupData.length > 0) + finalGroupData.push({ + key: groupData[0].key, + rows: [groupData[0].data.data], + [op.field.name]: groupData[0].key, + }); + for (let index = 1; index < groupData.length; index++) { + let curr = groupData[index], prev = groupData[index - 1]; + if (context.binaryOps.evaluate("=", curr.key, prev.key, context).orElse(false)) { + finalGroupData[finalGroupData.length - 1].rows.push(curr.data.data); + } + else { + finalGroupData.push({ + key: curr.key, + rows: [curr.data.data], + [op.field.name]: curr.key, + }); + } + } + rows = finalGroupData.map(d => { + return { id: d.key, data: d }; + }); + identMeaning = { type: "group", name: op.field.name, on: identMeaning }; + break; + case "flatten": + let flattenResult = []; + for (let index = 0; index < rows.length; index++) { + let row = rows[index]; + let value = context.evaluate(op.field.field, row.data); + if (!value.successful) { + errors.push({ index, message: value.error }); + continue; + } + let datapoints = Values.isArray(value.value) ? value.value : [value.value]; + for (let v of datapoints) { + let copy = Values.deepCopy(row); + copy.data[op.field.name] = v; + flattenResult.push(copy); + } + } + rows = flattenResult; + if (identMeaning.type == "group" && identMeaning.name == op.field.name) + identMeaning = identMeaning.on; + break; + default: + return Result.failure("Unrecognized query operation '" + op.type + "'"); + } + if (errors.length >= incomingRows && incomingRows > 0) { + return Result.failure(`Every row during operation '${op.type}' failed with an error; first ${Math.min(3, errors.length)}:\n + ${errors + .slice(0, 3) + .map(d => "- " + d.message) + .join("\n")}`); + } + diagnostics.push({ + incomingRows, + errors, + outgoingRows: rows.length, + timeMs: Date.now() - opStartTime, + }); + } + return Result.success({ + data: rows, + idMeaning: identMeaning, + ops, + diagnostics, + timeMs: Date.now() - startTime, + }); +} +/** Expanded version of executeCore which adds an additional "extraction" step to the pipeline. */ +function executeCoreExtract(rows, context, ops, fields) { + let internal = executeCore(rows, context, ops); + if (!internal.successful) + return internal; + let core = internal.value; + let startTime = Date.now(); + let errors = []; + let res = []; + outer: for (let index = 0; index < core.data.length; index++) { + let page = { id: core.data[index].id, data: {} }; + for (let [name, field] of Object.entries(fields)) { + let value = context.evaluate(field, core.data[index].data); + if (!value.successful) { + errors.push({ index: index, message: value.error }); + continue outer; + } + page.data[name] = value.value; + } + res.push(page); + } + if (errors.length >= core.data.length && core.data.length > 0) { + return Result.failure(`Every row during final data extraction failed with an error; first ${Math.max(errors.length, 3)}:\n + ${errors + .slice(0, 3) + .map(d => "- " + d.message) + .join("\n")}`); + } + let execTime = Date.now() - startTime; + return Result.success({ + data: res, + idMeaning: core.idMeaning, + diagnostics: core.diagnostics.concat([ + { + timeMs: execTime, + incomingRows: core.data.length, + outgoingRows: res.length, + errors, + }, + ]), + ops: core.ops.concat([{ type: "extract", fields }]), + timeMs: core.timeMs + execTime, + }); +} +/** Execute a list-based query, returning the final results. */ +async function executeList(query, index, origin, settings) { + // Start by collecting all of the files that match the 'from' queries. + let fileset = await resolveSource(query.source, index, origin); + if (!fileset.successful) + return Result.failure(fileset.error); + // Extract information about the origin page to add to the root context. + let rootContext = new Context(defaultLinkHandler(index, origin), settings, { + this: index.pages.get(origin)?.serialize(index) ?? {}, + }); + let targetField = query.header.format; + let showId = query.header.showId; + let fields = targetField ? { target: targetField } : {}; + return executeCoreExtract(fileset.value, rootContext, query.operations, fields).map(core => { + let data; + if (showId && targetField) { + data = core.data.map(p => Widgets.listPair(p.id, p.data["target"] ?? null)); + } + else if (targetField) { + data = core.data.map(p => p.data["target"] ?? null); + } + else { + data = core.data.map(p => p.id); + } + return { primaryMeaning: core.idMeaning, core, data }; + }); +} +/** Execute a table query. */ +async function executeTable(query, index, origin, settings) { + // Start by collecting all of the files that match the 'from' queries. + let fileset = await resolveSource(query.source, index, origin); + if (!fileset.successful) + return Result.failure(fileset.error); + // Extract information about the origin page to add to the root context. + let rootContext = new Context(defaultLinkHandler(index, origin), settings, { + this: index.pages.get(origin)?.serialize(index) ?? {}, + }); + let targetFields = query.header.fields; + let showId = query.header.showId; + let fields = {}; + for (let field of targetFields) + fields[field.name] = field.field; + return executeCoreExtract(fileset.value, rootContext, query.operations, fields).map(core => { + if (showId) { + const idName = core.idMeaning.type === "group" ? core.idMeaning.name : settings.tableIdColumnName; + let names = [idName].concat(targetFields.map(f => f.name)); + let data = core.data.map(p => [p.id].concat(targetFields.map(f => p.data[f.name]))); + return { core, names, data, idMeaning: core.idMeaning }; + } + else { + let names = targetFields.map(f => f.name); + let data = core.data.map(p => targetFields.map(f => p.data[f.name])); + return { core, names, data, idMeaning: core.idMeaning }; + } + }); +} +/** Maps a raw core execution result to a task grouping which is much easier to render. */ +function extractTaskGroupings(id, rows) { + switch (id.type) { + case "path": + return rows; + case "group": + let key = id.name; + return rows.map(r => iden({ + key: r[key], + rows: extractTaskGroupings(id.on, r.rows), + })); + } +} +/** Execute a task query, returning all matching tasks. */ +async function executeTask(query, origin, index, settings) { + let fileset = matchingSourcePaths(query.source, index, origin); + if (!fileset.successful) + return Result.failure(fileset.error); + // Collect tasks from pages which match. + let incomingTasks = []; + for (let path of fileset.value) { + let page = index.pages.get(path); + if (!page) + continue; + let pageData = page.serialize(index); + let pageTasks = pageData.file.tasks.map(t => { + const tcopy = Values.deepCopy(t); + // Add page data to this copy. + for (let [key, value] of Object.entries(pageData)) { + if (key in tcopy) + continue; + tcopy[key] = value; + } + return { id: `${pageData.path}#${t.line}`, data: tcopy }; + }); + for (let task of pageTasks) + incomingTasks.push(task); + } + // Extract information about the origin page to add to the root context. + let rootContext = new Context(defaultLinkHandler(index, origin), settings, { + this: index.pages.get(origin)?.serialize(index) ?? {}, + }); + return executeCore(incomingTasks, rootContext, query.operations).map(core => { + return { + core, + tasks: extractTaskGroupings(core.idMeaning, core.data.map(r => r.data)), + }; + }); +} +/** Execute a single field inline a file, returning the evaluated result. */ +function executeInline(field, origin, index, settings) { + return new Context(defaultLinkHandler(index, origin), settings, { + this: index.pages.get(origin)?.serialize(index) ?? {}, + }).evaluate(field); +} +/** The default link resolver used when creating contexts. */ +function defaultLinkHandler(index, origin) { + return { + resolve: link => { + let realFile = index.metadataCache.getFirstLinkpathDest(link, origin); + if (!realFile) + return null; + let realPage = index.pages.get(realFile.path); + if (!realPage) + return null; + return realPage.serialize(index); + }, + normalize: link => { + let realFile = index.metadataCache.getFirstLinkpathDest(link, origin); + return realFile?.path ?? link; + }, + exists: link => { + let realFile = index.metadataCache.getFirstLinkpathDest(link, origin); + return !!realFile; + }, + }; +} +/** Execute a calendar-based query, returning the final results. */ +async function executeCalendar(query, index, origin, settings) { + // Start by collecting all of the files that match the 'from' queries. + let fileset = await resolveSource(query.source, index, origin); + if (!fileset.successful) + return Result.failure(fileset.error); + // Extract information about the origin page to add to the root context. + let rootContext = new Context(defaultLinkHandler(index, origin), settings, { + this: index.pages.get(origin)?.serialize(index) ?? {}, + }); + let targetField = query.header.field.field; + let fields = { + target: targetField, + link: Fields.indexVariable("file.link"), + }; + return executeCoreExtract(fileset.value, rootContext, query.operations, fields).map(core => { + let data = core.data.map(p => iden({ + date: p.data["target"], + link: p.data["link"], + })); + return { core, data }; + }); +} + +function compareVersions(v1, v2) { + // validate input and split into segments + const n1 = validateAndParse(v1); + const n2 = validateAndParse(v2); + + // pop off the patch + const p1 = n1.pop(); + const p2 = n2.pop(); + + // validate numbers + const r = compareSegments(n1, n2); + if (r !== 0) return r; + + // validate pre-release + if (p1 && p2) { + return compareSegments(p1.split('.'), p2.split('.')); + } else if (p1 || p2) { + return p1 ? -1 : 1; + } + + return 0; +} + +const validate = (v) => + typeof v === 'string' && /^[v\d]/.test(v) && semver.test(v); + +const compare = (v1, v2, operator) => { + // validate input operator + assertValidOperator(operator); + + // since result of compareVersions can only be -1 or 0 or 1 + // a simple map can be used to replace switch + const res = compareVersions(v1, v2); + + return operatorResMap[operator].includes(res); +}; + +const satisfies = (v, r) => { + // if no range operator then "=" + const m = r.match(/^([<>=~^]+)/); + const op = m ? m[1] : '='; + + // if gt/lt/eq then operator compare + if (op !== '^' && op !== '~') return compare(v, r, op); + + // else range of either "~" or "^" is assumed + const [v1, v2, v3] = validateAndParse(v); + const [r1, r2, r3] = validateAndParse(r); + if (compareStrings(v1, r1) !== 0) return false; + if (op === '^') { + return compareSegments([v2, v3], [r2, r3]) >= 0; + } + if (compareStrings(v2, r2) !== 0) return false; + return compareStrings(v3, r3) >= 0; +}; + +// export CJS style for parity +compareVersions.validate = validate; +compareVersions.compare = compare; +compareVersions.satisfies = satisfies; + +const semver = + /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; + +const validateAndParse = (v) => { + if (typeof v !== 'string') { + throw new TypeError('Invalid argument expected string'); + } + const match = v.match(semver); + if (!match) { + throw new Error(`Invalid argument not valid semver ('${v}' received)`); + } + match.shift(); + return match; +}; + +const isWildcard = (s) => s === '*' || s === 'x' || s === 'X'; + +const tryParse = (v) => { + const n = parseInt(v, 10); + return isNaN(n) ? v : n; +}; + +const forceType = (a, b) => + typeof a !== typeof b ? [String(a), String(b)] : [a, b]; + +const compareStrings = (a, b) => { + if (isWildcard(a) || isWildcard(b)) return 0; + const [ap, bp] = forceType(tryParse(a), tryParse(b)); + if (ap > bp) return 1; + if (ap < bp) return -1; + return 0; +}; + +const compareSegments = (a, b) => { + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const r = compareStrings(a[i] || 0, b[i] || 0); + if (r !== 0) return r; + } + return 0; +}; + +const operatorResMap = { + '>': [1], + '>=': [0, 1], + '=': [0], + '<=': [-1, 0], + '<': [-1], +}; + +const allowedOperators = Object.keys(operatorResMap); + +const assertValidOperator = (op) => { + if (typeof op !== 'string') { + throw new TypeError( + `Invalid operator type, expected string but got ${typeof op}` + ); + } + if (allowedOperators.indexOf(op) === -1) { + throw new Error( + `Invalid operator, expected one of ${allowedOperators.join('|')}` + ); + } +}; + +var n,l$1,u$1,i$1,o$1,r$1,f$1,e$1,c$1={},s$1=[],a$1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,h$1=Array.isArray;function v$1(n,l){for(var u in l)n[u]=l[u];return n}function p$1(n){var l=n.parentNode;l&&l.removeChild(n);}function y$1(l,u,t){var i,o,r,f={};for(r in u)"key"==r?i=u[r]:"ref"==r?o=u[r]:f[r]=u[r];if(arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),"function"==typeof l&&null!=l.defaultProps)for(r in l.defaultProps)void 0===f[r]&&(f[r]=l.defaultProps[r]);return d$1(l,f,i,o,null)}function d$1(n,t,i,o,r){var f={type:n,props:t,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==r?++u$1:r};return null==r&&null!=l$1.vnode&&l$1.vnode(f),f}function _$1(){return {current:null}}function k$2(n){return n.children}function b$1(n,l){this.props=n,this.context=l;}function g$2(n,l){if(null==l)return n.__?g$2(n.__,n.__.__k.indexOf(n)+1):null;for(var u;ll&&i$1.sort(f$1));x$2.__r=0;}function P$1(n,l,u,t,i,o,r,f,e,a,v){var p,y,_,b,m,w,x,P,C,H=0,I=t&&t.__k||s$1,T=I.length,j=T,z=l.length;for(u.__k=[],p=0;p0?d$1(b.type,b.props,b.key,b.ref?b.ref:null,b.__v):b)?(b.__=u,b.__b=u.__b+1,-1===(P=A$2(b,I,x=p+H,j))?_=c$1:(_=I[P]||c$1,I[P]=void 0,j--),L$1(n,b,_,i,o,r,f,e,a,v),m=b.__e,(y=b.ref)&&_.ref!=y&&(_.ref&&O$1(_.ref,null,b),v.push(y,b.__c||m,b)),null!=m&&(null==w&&(w=m),(C=_===c$1||null===_.__v)?-1==P&&H--:P!==x&&(P===x+1?H++:P>x?j>z-x?H+=P-x:H--:H=P(null!=e?1:0))for(;r>=0||f=0){if((e=l[r])&&i==e.key&&o===e.type)return r;r--;}if(f2&&(e.children=arguments.length>3?n.call(arguments,2):t),d$1(l.type,e,i||l.key,o||l.ref,null)}function G$1(n,l){var u={__c:l="__cC"+e$1++,__:n,Consumer:function(n,l){return n.children(l)},Provider:function(n){var u,t;return this.getChildContext||(u=[],(t={})[l]=this,this.getChildContext=function(){return t},this.shouldComponentUpdate=function(n){this.props.value!==n.value&&u.some(function(n){n.__e=!0,w$2(n);});},this.sub=function(n){u.push(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u.splice(u.indexOf(n),1),l&&l.call(n);};}),n.children}};return u.Provider.__=u.Consumer.contextType=u}n=s$1.slice,l$1={__e:function(n,l,u,t){for(var i,o,r;l=l.__;)if((i=l.__c)&&!i.__)try{if((o=i.constructor)&&null!=o.getDerivedStateFromError&&(i.setState(o.getDerivedStateFromError(n)),r=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),r=i.__d),r)return i.__E=i}catch(l){n=l;}throw n}},u$1=0,b$1.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=v$1({},this.state),"function"==typeof n&&(n=n(v$1({},u),this.props)),n&&v$1(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),w$2(this));},b$1.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),w$2(this));},b$1.prototype.render=k$2,i$1=[],r$1="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,f$1=function(n,l){return n.__v.__b-l.__v.__b},x$2.__r=0,e$1=0; + +var t,r,u,i,o=0,f=[],c=[],e=l$1.__b,a=l$1.__r,v=l$1.diffed,l=l$1.__c,m=l$1.unmount;function d(t,u){l$1.__h&&l$1.__h(r,t,o||u),o=0;var i=r.__H||(r.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({__V:c}),i.__[t]}function h(n){return o=1,s(B$1,n)}function s(n,u,i){var o=d(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):B$1(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}));}],o.__c=r,!r.u)){var f=function(n,t,r){if(!o.__c.__H)return !0;var u=o.__c.__H.__.filter(function(n){return n.__c});if(u.every(function(n){return !n.__N}))return !c||c.call(this,n,t,r);var i=!1;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0);}}),!(!i&&o.__c.props===n)&&(!c||c.call(this,n,t,r))};r.u=!0;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u;}e&&e.call(this,n,t,r);},r.shouldComponentUpdate=f;}return o.__N||o.__}function p(u,i){var o=d(t++,3);!l$1.__s&&z$1(o.__H,i)&&(o.__=u,o.i=i,r.__H.__h.push(o));}function y(u,i){var o=d(t++,4);!l$1.__s&&z$1(o.__H,i)&&(o.__=u,o.i=i,r.__h.push(o));}function _(n){return o=5,F$1(function(){return {current:n}},[])}function A$1(n,t,r){o=6,y(function(){return "function"==typeof n?(n(t()),function(){return n(null)}):n?(n.current=t(),function(){return n.current=null}):void 0},null==r?r:r.concat(n));}function F$1(n,r){var u=d(t++,7);return z$1(u.__H,r)?(u.__V=n(),u.i=r,u.__h=n,u.__V):u.__}function T$1(n,t){return o=8,F$1(function(){return n},t)}function q$1(n){var u=r.context[n.__c],i=d(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function x$1(t,r){l$1.useDebugValue&&l$1.useDebugValue(r?r(t):t);}function V$1(){var n=d(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++;}return n.__}function b(){for(var t;t=f.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(k$1),t.__H.__h.forEach(w$1),t.__H.__h=[];}catch(r){t.__H.__h=[],l$1.__e(r,t.__v);}}l$1.__b=function(n){r=null,e&&e(n);},l$1.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.__V=c,n.__N=n.i=void 0;})):(i.__h.forEach(k$1),i.__h.forEach(w$1),i.__h=[],t=0)),u=r;},l$1.diffed=function(t){v&&v(t);var o=t.__c;o&&o.__H&&(o.__H.__h.length&&(1!==f.push(o)&&i===l$1.requestAnimationFrame||((i=l$1.requestAnimationFrame)||j$1)(b)),o.__H.__.forEach(function(n){n.i&&(n.__H=n.i),n.__V!==c&&(n.__=n.__V),n.i=void 0,n.__V=c;})),u=r=null;},l$1.__c=function(t,r){r.some(function(t){try{t.__h.forEach(k$1),t.__h=t.__h.filter(function(n){return !n.__||w$1(n)});}catch(u){r.some(function(n){n.__h&&(n.__h=[]);}),r=[],l$1.__e(u,t.__v);}}),l&&l(t,r);},l$1.unmount=function(t){m&&m(t);var r,u=t.__c;u&&u.__H&&(u.__H.__.forEach(function(n){try{k$1(n);}catch(n){r=n;}}),u.__H=void 0,r&&l$1.__e(r,u.__v));};var g$1="function"==typeof requestAnimationFrame;function j$1(n){var t,r=function(){clearTimeout(u),g$1&&cancelAnimationFrame(t),setTimeout(n);},u=setTimeout(r,100);g$1&&(t=requestAnimationFrame(r));}function k$1(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t;}function w$1(n){var t=r;n.__c=n.__(),r=t;}function z$1(n,t){return !n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function B$1(n,t){return "function"==typeof t?t(n):t} + +function g(n,t){for(var e in t)n[e]=t[e];return n}function C(n,t){for(var e in n)if("__source"!==e&&!(e in t))return !0;for(var r in t)if("__source"!==r&&n[r]!==t[r])return !0;return !1}function E(n,t){return n===t&&(0!==n||1/n==1/t)||n!=n&&t!=t}function w(n){this.props=n;}function x(n,e){function r(n){var t=this.props.ref,r=t==n.ref;return !r&&t&&(t.call?t(null):t.current=null),e?!e(this.props,n)||!r:C(this.props,n)}function u(e){return this.shouldComponentUpdate=r,y$1(n,e)}return u.displayName="Memo("+(n.displayName||n.name)+")",u.prototype.isReactComponent=!0,u.__f=!0,u}(w.prototype=new b$1).isPureReactComponent=!0,w.prototype.shouldComponentUpdate=function(n,t){return C(this.props,n)||C(this.state,t)};var R=l$1.__b;l$1.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),R&&R(n);};var N="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function k(n){function t(t){var e=g({},t);return delete e.ref,n(e,t.ref||null)}return t.$$typeof=N,t.render=t,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(n.displayName||n.name)+")",t}var A=function(n,t){return null==n?null:C$1(C$1(n).map(t))},O={map:A,forEach:A,count:function(n){return n?C$1(n).length:0},only:function(n){var t=C$1(n);if(1!==t.length)throw "Children.only";return t[0]},toArray:C$1},T=l$1.__e;l$1.__e=function(n,t,e,r){if(n.then)for(var u,o=t;o=o.__;)if((u=o.__c)&&u.__c)return null==t.__e&&(t.__e=e.__e,t.__k=e.__k),u.__c(n,t);T(n,t,e,r);};var F=l$1.unmount;function I(n,t,e){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(n){"function"==typeof n.__c&&n.__c();}),n.__c.__H=null),null!=(n=g({},n)).__c&&(n.__c.__P===e&&(n.__c.__P=t),n.__c=null),n.__k=n.__k&&n.__k.map(function(n){return I(n,t,e)})),n}function L(n,t,e){return n&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(n){return L(n,t,e)}),n.__c&&n.__c.__P===t&&(n.__e&&e.insertBefore(n.__e,n.__d),n.__c.__e=!0,n.__c.__P=e)),n}function U(){this.__u=0,this.t=null,this.__b=null;}function D(n){var t=n.__.__c;return t&&t.__a&&t.__a(n)}function M(n){var e,r,u;function o(o){if(e||(e=n()).then(function(n){r=n.default||n;},function(n){u=n;}),u)throw u;if(!r)throw e;return y$1(r,o)}return o.displayName="Lazy",o.__f=!0,o}function V(){this.u=null,this.o=null;}l$1.unmount=function(n){var t=n.__c;t&&t.__R&&t.__R(),t&&!0===n.__h&&(n.type=null),F&&F(n);},(U.prototype=new b$1).__c=function(n,t){var e=t.__c,r=this;null==r.t&&(r.t=[]),r.t.push(e);var u=D(r.__v),o=!1,i=function(){o||(o=!0,e.__R=null,u?u(l):l());};e.__R=i;var l=function(){if(!--r.__u){if(r.state.__a){var n=r.state.__a;r.__v.__k[0]=L(n,n.__c.__P,n.__c.__O);}var t;for(r.setState({__a:r.__b=null});t=r.t.pop();)t.forceUpdate();}},c=!0===t.__h;r.__u++||c||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(i,i);},U.prototype.componentWillUnmount=function(){this.t=[];},U.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=I(this.__b,r,o.__O=o.__P);}this.__b=null;}var i=e.__a&&y$1(k$2,null,n.fallback);return i&&(i.__h=null),[y$1(k$2,null,e.__a?null:n.children),i]};var W=function(n,t,e){if(++e[1]===e[0]&&n.o.delete(t),n.props.revealOrder&&("t"!==n.props.revealOrder[0]||!n.o.size))for(e=n.u;e;){for(;e.length>3;)e.pop()();if(e[1]>>1,1),e.i.removeChild(n);}}),D$1(y$1(P,{context:e.context},n.__v),e.l);}function z(n,e){var r=y$1(j,{__v:n,i:e});return r.containerInfo=e,r}(V.prototype=new b$1).__a=function(n){var t=this,e=D(t.__v),r=t.o.get(n);return r[0]++,function(u){var o=function(){t.props.revealOrder?(r.push(u),W(t,n,r)):u();};e?e(o):o();}},V.prototype.render=function(n){this.u=null,this.o=new Map;var t=C$1(n.children);n.revealOrder&&"b"===n.revealOrder[0]&&t.reverse();for(var e=t.length;e--;)this.o.set(t[e],this.u=[1,0,this.u]);return n.children},V.prototype.componentDidUpdate=V.prototype.componentDidMount=function(){var n=this;this.o.forEach(function(t,e){W(n,e,t);});};var B="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,H=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Z=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Y=/[A-Z0-9]/g,$="undefined"!=typeof document,q=function(n){return ("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(n)};function G(n,t,e){return null==t.__k&&(t.textContent=""),D$1(n,t),"function"==typeof e&&e(),n?n.__c:null}function J(n,t,e){return E$1(n,t),"function"==typeof e&&e(),n?n.__c:null}b$1.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(b$1.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n});}});});var K=l$1.event;function Q(){}function X(){return this.cancelBubble}function nn(){return this.defaultPrevented}l$1.event=function(n){return K&&(n=K(n)),n.persist=Q,n.isPropagationStopped=X,n.isDefaultPrevented=nn,n.nativeEvent=n};var tn,en={enumerable:!1,configurable:!0,get:function(){return this.class}},rn=l$1.vnode;l$1.vnode=function(n){"string"==typeof n.type&&function(n){var t=n.props,e=n.type,u={};for(var o in t){var i=t[o];if(!("value"===o&&"defaultValue"in t&&null==i||$&&"children"===o&&"noscript"===e||"class"===o||"className"===o)){var l=o.toLowerCase();"defaultValue"===o&&"value"in t&&null==t.value?o="value":"download"===o&&!0===i?i="":"ondoubleclick"===l?o="ondblclick":"onchange"!==l||"input"!==e&&"textarea"!==e||q(t.type)?"onfocus"===l?o="onfocusin":"onblur"===l?o="onfocusout":Z.test(o)?o=l:-1===e.indexOf("-")&&H.test(o)?o=o.replace(Y,"-$&").toLowerCase():null===i&&(i=void 0):l=o="oninput","oninput"===l&&u[o=l]&&(o="oninputCapture"),u[o]=i;}}"select"==e&&u.multiple&&Array.isArray(u.value)&&(u.value=C$1(t.children).forEach(function(n){n.props.selected=-1!=u.value.indexOf(n.props.value);})),"select"==e&&null!=u.defaultValue&&(u.value=C$1(t.children).forEach(function(n){n.props.selected=u.multiple?-1!=u.defaultValue.indexOf(n.props.value):u.defaultValue==n.props.value;})),t.class&&!t.className?(u.class=t.class,Object.defineProperty(u,"className",en)):(t.className&&!t.class||t.class&&t.className)&&(u.class=u.className=t.className),n.props=u;}(n),n.$$typeof=B,rn&&rn(n);};var un=l$1.__r;l$1.__r=function(n){un&&un(n),tn=n.__c;};var on=l$1.diffed;l$1.diffed=function(n){on&&on(n);var t=n.props,e=n.__e;null!=e&&"textarea"===n.type&&"value"in t&&t.value!==e.value&&(e.value=null==t.value?"":t.value),tn=null;};var ln={ReactCurrentDispatcher:{current:{readContext:function(n){return tn.__n[n.__c].props.value}}}};function fn(n){return y$1.bind(null,n)}function an(n){return !!n&&n.$$typeof===B}function sn(n){return an(n)&&n.type===k$2}function hn(n){return an(n)?F$2.apply(null,arguments):n}function vn(n){return !!n.__k&&(D$1(null,n),!0)}function dn(n){return n&&(n.base||1===n.nodeType&&n)||null}var pn=function(n,t){return n(t)},mn=function(n,t){return n(t)},yn=k$2;function _n(n){n();}function bn(n){return n}function Sn(){return [!1,_n]}var gn=y,Cn=an;function En(n,t){var e=t(),r=h({h:{__:e,v:t}}),u=r[0].h,o=r[1];return y(function(){u.__=e,u.v=t,E(u.__,t())||o({h:u});},[n,e,t]),p(function(){return E(u.__,u.v())||o({h:u}),n(function(){E(u.__,u.v())||o({h:u});})},[n]),e}var wn={useState:h,useId:V$1,useReducer:s,useEffect:p,useLayoutEffect:y,useInsertionEffect:gn,useTransition:Sn,useDeferredValue:bn,useSyncExternalStore:En,startTransition:_n,useRef:_,useImperativeHandle:A$1,useMemo:F$1,useCallback:T$1,useContext:q$1,useDebugValue:x$1,version:"17.0.2",Children:O,render:G,hydrate:J,unmountComponentAtNode:vn,createPortal:z,createElement:y$1,createContext:G$1,createFactory:fn,cloneElement:hn,createRef:_$1,Fragment:k$2,isValidElement:an,isElement:Cn,isFragment:sn,findDOMNode:dn,Component:b$1,PureComponent:w,memo:x,forwardRef:k,flushSync:mn,unstable_batchedUpdates:pn,StrictMode:yn,Suspense:U,SuspenseList:V,lazy:M,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ln}; + +const IMAGE_EXTENSIONS = Object.freeze(new Set([ + ".tif", + ".tiff", + ".gif", + ".png", + ".apng", + ".avif", + ".jpg", + ".jpeg", + ".jfif", + ".pjepg", + ".pjp", + ".svg", + ".webp", + ".bmp", + ".ico", + ".cur", +])); +/** Determines if the given link points to an embedded image. */ +function isImageEmbed(link) { + if (!link.path.contains(".")) + return false; + let extension = link.path.substring(link.path.lastIndexOf(".")); + return link.type == "file" && link.embed && IMAGE_EXTENSIONS.has(extension); +} +/** Extract text of the form 'WxH' or 'W' from the display of a link. */ +function extractImageDimensions(link) { + if (!link.display) + return undefined; + let match = /^(\d+)x(\d+)$/iu.exec(link.display); + if (match) + return [parseInt(match[1]), parseInt(match[2])]; + let match2 = /^(\d+)/.exec(link.display); + if (match2) + return [parseInt(match2[1])]; + // No match. + return undefined; +} + +/** Provides core preact / rendering utilities for all view types. */ +const DataviewContext = G$1(undefined); +/** Hacky preact component which wraps Obsidian's markdown renderer into a neat component. */ +function RawMarkdown({ content, sourcePath, inline = true, style, cls, onClick, }) { + const container = _(null); + const component = q$1(DataviewContext).component; + p(() => { + if (!container.current) + return; + container.current.innerHTML = ""; + obsidian.MarkdownRenderer.renderMarkdown(content, container.current, sourcePath, component).then(() => { + if (!container.current || !inline) + return; + // Unwrap any created paragraph elements if we are inline. + let paragraph = container.current.querySelector("p"); + while (paragraph) { + let children = paragraph.childNodes; + paragraph.replaceWith(...Array.from(children)); + paragraph = container.current.querySelector("p"); + } + }); + }, [content, sourcePath, container.current]); + return y$1("span", { ref: container, style: style, class: cls, onClick: onClick }); +} +/** Hacky preact component which wraps Obsidian's markdown renderer into a neat component. */ +const Markdown = wn.memo(RawMarkdown); +/** Embeds an HTML element in the react DOM. */ +function RawEmbedHtml({ element }) { + const container = _(null); + p(() => { + if (!container.current) + return; + container.current.innerHTML = ""; + container.current.appendChild(element); + }, [container.current, element]); + return y$1("span", { ref: container }); +} +/** Embeds an HTML element in the react DOM. */ +const EmbedHtml = wn.memo(RawEmbedHtml); +/** Intelligently render an arbitrary literal value. */ +function RawLit({ value, sourcePath, inline = false, depth = 0, }) { + const context = q$1(DataviewContext); + // Short-circuit if beyond the maximum render depth. + if (depth >= context.settings.maxRecursiveRenderDepth) + return y$1(k$2, null, "..."); + if (Values.isNull(value) || value === undefined) { + return y$1(Markdown, { content: context.settings.renderNullAs, sourcePath: sourcePath }); + } + else if (Values.isString(value)) { + return y$1(Markdown, { content: value, sourcePath: sourcePath }); + } + else if (Values.isNumber(value)) { + return y$1(k$2, null, "" + value); + } + else if (Values.isBoolean(value)) { + return y$1(k$2, null, "" + value); + } + else if (Values.isDate(value)) { + return y$1(k$2, null, renderMinimalDate(value, context.settings, currentLocale())); + } + else if (Values.isDuration(value)) { + return y$1(k$2, null, renderMinimalDuration(value)); + } + else if (Values.isLink(value)) { + // Special case handling of image/video/etc embeddings to bypass the Obsidian API not working. + if (isImageEmbed(value)) { + let realFile = context.app.metadataCache.getFirstLinkpathDest(value.path, sourcePath); + if (!realFile) + return y$1(Markdown, { content: value.markdown(), sourcePath: sourcePath }); + let dimensions = extractImageDimensions(value); + let resourcePath = context.app.vault.getResourcePath(realFile); + if (dimensions && dimensions.length == 2) + return y$1("img", { alt: value.path, src: resourcePath, width: dimensions[0], height: dimensions[1] }); + else if (dimensions && dimensions.length == 1) + return y$1("img", { alt: value.path, src: resourcePath, width: dimensions[0] }); + else + return y$1("img", { alt: value.path, src: resourcePath }); + } + return y$1(Markdown, { content: value.markdown(), sourcePath: sourcePath }); + } + else if (Values.isHtml(value)) { + return y$1(EmbedHtml, { element: value }); + } + else if (Values.isWidget(value)) { + if (Widgets.isListPair(value)) { + return (y$1(k$2, null, + y$1(Lit, { value: value.key, sourcePath: sourcePath }), + ":", + " ", + y$1(Lit, { value: value.value, sourcePath: sourcePath }))); + } + else if (Widgets.isExternalLink(value)) { + return (y$1("a", { href: value.url, rel: "noopener", target: "_blank", class: "external-link" }, value.display ?? value.url)); + } + else { + return y$1("b", null, + ""); + } + } + else if (Values.isFunction(value)) { + return y$1(k$2, null, ""); + } + else if (Values.isArray(value) || DataArray.isDataArray(value)) { + if (!inline) { + return (y$1("ul", { class: "dataview dataview-ul dataview-result-list-ul" }, value.map(subvalue => (y$1("li", { class: "dataview-result-list-li" }, + y$1(Lit, { value: subvalue, sourcePath: sourcePath, inline: inline, depth: depth + 1 })))))); + } + else { + if (value.length == 0) + return y$1(k$2, null, ""); + return (y$1("span", { class: "dataview dataview-result-list-span" }, value.map((subvalue, index) => (y$1(k$2, null, + index == 0 ? "" : ", ", + y$1(Lit, { value: subvalue, sourcePath: sourcePath, inline: inline, depth: depth + 1 })))))); + } + } + else if (Values.isObject(value)) { + // Don't render classes in case they have recursive references; spoopy. + if (value?.constructor?.name && value?.constructor?.name != "Object") { + return y$1(k$2, null, + "<", + value.constructor.name, + ">"); + } + if (!inline) { + return (y$1("ul", { class: "dataview dataview-ul dataview-result-object-ul" }, Object.entries(value).map(([key, value]) => (y$1("li", { class: "dataview dataview-li dataview-result-object-li" }, + key, + ": ", + y$1(Lit, { value: value, sourcePath: sourcePath, inline: inline, depth: depth + 1 })))))); + } + else { + if (Object.keys(value).length == 0) + return y$1(k$2, null, ""); + return (y$1("span", { class: "dataview dataview-result-object-span" }, Object.entries(value).map(([key, value], index) => (y$1(k$2, null, + index == 0 ? "" : ", ", + key, + ": ", + y$1(Lit, { value: value, sourcePath: sourcePath, inline: inline, depth: depth + 1 })))))); + } + } + return y$1(k$2, null, + ""); +} +/** Intelligently render an arbitrary literal value. */ +const Lit = wn.memo(RawLit); +/** Render a simple nice looking error box in a code style. */ +function ErrorPre(props, {}) { + return y$1("pre", { class: "dataview dataview-error" }, props.children); +} +/** Render a pretty centered error message in a box. */ +function ErrorMessage({ message }) { + return (y$1("div", { class: "dataview dataview-error-box" }, + y$1("p", { class: "dataview dataview-error-message" }, message))); +} +/** + * Complex convenience hook which calls `compute` every time the index updates, updating the current state. + */ +function useIndexBackedState(container, app, settings, index, initial, compute) { + let [initialized, setInitialized] = h(false); + let [state, updateState] = h(initial); + let [lastReload, setLastReload] = h(index.revision); + // Initial setup to queue fetching the correct state. + if (!initialized) { + setLastReload(index.revision); + setInitialized(true); + compute().then(updateState); + } + // Updated on every container re-create; automatically updates state. + p(() => { + const refreshOperation = () => { + if (lastReload != index.revision && container.isShown() && settings.refreshEnabled) { + compute().then(updateState); + setLastReload(index.revision); + } + }; + // Refresh after index changes stop. + let workEvent = app.workspace.on("dataview:refresh-views", refreshOperation); + // ...or when the DOM is shown (sidebar expands, tab selected, nodes scrolled into view). + let nodeEvent = container.onNodeInserted(refreshOperation); + return () => { + app.workspace.offref(workEvent); + nodeEvent(); + }; + }, [container, lastReload]); + return state; +} +/** A trivial wrapper which allows a react component to live for the duration of a `MarkdownRenderChild`. */ +class ReactRenderer extends obsidian.MarkdownRenderChild { + init; + element; + constructor(init, element) { + super(init.container); + this.init = init; + this.element = element; + } + onload() { + const context = Object.assign({}, { component: this }, this.init); + D$1(y$1(DataviewContext.Provider, { value: context }, this.element), this.containerEl); + } + onunload() { + vn(this.containerEl); + } +} + +/** Function used to test if a given event correspond to a pressed link */ +function wasLinkPressed(evt) { + return evt.target != null && evt.target != undefined && evt.target.tagName == "A"; +} +/** JSX component which renders a task element recursively. */ +function TaskItem({ item }) { + let context = q$1(DataviewContext); + // Navigate to the given task on click. + const onClicked = (evt) => { + if (wasLinkPressed(evt)) { + return; + } + evt.stopPropagation(); + const selectionState = { + eState: { + cursor: { + from: { line: item.line, ch: item.position.start.col }, + to: { line: item.line + item.lineCount - 1, ch: item.position.end.col }, + }, + line: item.line, + }, + }; + // MacOS interprets the Command key as Meta. + context.app.workspace.openLinkText(item.link.toFile().obsidianLink(), item.path, evt.ctrlKey || (evt.metaKey && obsidian.Platform.isMacOS), selectionState); + }; + // Check/uncheck the task in the original file. + const onChecked = (evt) => { + evt.stopPropagation(); + const completed = evt.currentTarget.checked; + const status = completed ? "x" : " "; + // Update data-task on the parent element (css style) + const parent = evt.currentTarget.parentElement; + parent?.setAttribute("data-task", status); + let flatted = [item]; + if (context.settings.recursiveSubTaskCompletion) { + function flatter(iitem) { + flatted.push(iitem); + iitem.children.forEach(flatter); + } + item.children.forEach(flatter); + flatted = flatted.flat(Infinity); + } + async function effectFn() { + for (let i = 0; i < flatted.length; i++) { + const _item = flatted[i]; + let updatedText = _item.text; + if (context.settings.taskCompletionTracking) { + updatedText = setTaskCompletion(_item.text, context.settings.taskCompletionUseEmojiShorthand, context.settings.taskCompletionText, context.settings.taskCompletionDateFormat, completed); + } + await rewriteTask(context.app.vault, _item, status, updatedText); + } + context.app.workspace.trigger("dataview:refresh-views"); + } + effectFn(); + }; + const checked = item.status !== " "; + return (y$1("li", { class: "dataview task-list-item" + (checked ? " is-checked" : ""), onClick: onClicked, "data-task": item.status }, + y$1("input", { class: "dataview task-list-item-checkbox", type: "checkbox", checked: checked, onClick: onChecked }), + y$1(Markdown, { inline: true, content: item.visual ?? item.text, sourcePath: item.path }), + item.children.length > 0 && y$1(TaskList, { items: item.children }))); +} +/** JSX component which renders a plain list item recursively. */ +function ListItem({ item }) { + let context = q$1(DataviewContext); + // Navigate to the given task on click. + const onClicked = (evt) => { + if (wasLinkPressed(evt)) { + return; + } + evt.stopPropagation(); + const selectionState = { + eState: { + cursor: { + from: { line: item.line, ch: item.position.start.col }, + to: { line: item.line + item.lineCount - 1, ch: item.position.end.col }, + }, + line: item.line, + }, + }; + // MacOS interprets the Command key as Meta. + context.app.workspace.openLinkText(item.link.toFile().obsidianLink(), item.path, evt.ctrlKey || (evt.metaKey && obsidian.Platform.isMacOS), selectionState); + }; + return (y$1("li", { class: "dataview task-list-basic-item", onClick: onClicked }, + y$1(Markdown, { inline: true, content: item.visual ?? item.text, sourcePath: item.path }), + item.children.length > 0 && y$1(TaskList, { items: item.children }))); +} +/** JSX component which renders a list of task items recursively. */ +function TaskList({ items }) { + const settings = q$1(DataviewContext).settings; + if (items.length == 0 && settings.warnOnEmptyResult) + return y$1(ErrorMessage, { message: "Dataview: No results to show for task query." }); + let [nest, _mask] = nestItems(items); + return (y$1("ul", { class: "contains-task-list" }, nest.map(item => item.task ? y$1(TaskItem, { key: listId(item), item: item }) : y$1(ListItem, { key: listId(item), item: item })))); +} +/** JSX component which returns the result count. */ +function ResultCount$1(props) { + const { settings } = q$1(DataviewContext); + return settings.showResultCount ? (y$1("span", { class: "dataview small-text" }, Groupings.count(props.item.rows))) : (y$1(k$2, null)); +} +/** JSX component which recursively renders grouped tasks. */ +function TaskGrouping({ items, sourcePath }) { + const isGrouping = items.length > 0 && Groupings.isGrouping(items); + return (y$1(k$2, null, + isGrouping && + items.map(item => (y$1(k$2, { key: item.key }, + y$1("h4", null, + y$1(Lit, { value: item.key, sourcePath: sourcePath }), + y$1(ResultCount$1, { item: item })), + y$1("div", { class: "dataview result-group" }, + y$1(TaskGrouping, { items: item.rows, sourcePath: sourcePath }))))), + !isGrouping && y$1(TaskList, { items: items }))); +} +/** + * Pure view over (potentially grouped) tasks and list items which allows for checking/unchecking tasks and manipulating + * the task view. + */ +function TaskView({ query, sourcePath }) { + let context = q$1(DataviewContext); + let items = useIndexBackedState(context.container, context.app, context.settings, context.index, { state: "loading" }, async () => { + let result = await asyncTryOrPropagate(() => executeTask(query, sourcePath, context.index, context.settings)); + if (!result.successful) + return { state: "error", error: result.error, sourcePath }; + else + return { state: "ready", items: result.value.tasks }; + }); + if (items.state == "loading") + return (y$1(k$2, null, + y$1(ErrorPre, null, "Loading"))); + else if (items.state == "error") + return (y$1(k$2, null, + y$1(ErrorPre, null, + "Dataview: ", + items.error))); + return (y$1("div", { class: "dataview dataview-container" }, + y$1(TaskGrouping, { items: items.items, sourcePath: sourcePath }))); +} +function createTaskView(init, query, sourcePath) { + return new ReactRenderer(init, y$1(TaskView, { query: query, sourcePath: sourcePath })); +} +function createFixedTaskView(init, items, sourcePath) { + return new ReactRenderer(init, y$1(TaskGrouping, { items: items, sourcePath: sourcePath })); +} +///////////////////////// +// Task De-Duplication // +///////////////////////// +function listId(item) { + return item.path + ":" + item.line; +} +function parentListId(item) { + return item.path + ":" + item.parent; +} +/** Compute a map of all task IDs -> tasks. */ +function enumerateChildren(item, output) { + if (!output.has(listId(item))) + output.set(listId(item), item); + for (let child of item.children) + enumerateChildren(child, output); + return output; +} +/** Replace basic tasks with tasks from a lookup map. Retains the original order of the list. */ +function replaceChildren(elements, lookup) { + return elements.map(element => { + element.children = replaceChildren(element.children, lookup); + const id = listId(element); + const map = lookup.get(id); + if (map) + return map; + else + return element; + }); +} +/** + * Removes tasks from a list if they are already present by being a child of another task. Fixes child pointers. + * Retains original order of input list. + */ +function nestItems(raw) { + let elements = new Map(); + let mask = new Set(); + for (let elem of raw) { + let id = listId(elem); + elements.set(id, elem); + mask.add(id); + } + // List all elements & their children in the lookup map. + for (let elem of raw) + enumerateChildren(elem, elements); + let roots = raw.filter(elem => elem.parent == undefined || elem.parent == null || !elements.has(parentListId(elem))); + return [replaceChildren(roots, elements), mask]; +} +/** + * Recursively removes tasks from each subgroup if they are already present by being a child of another task. + * Fixes child pointers. Retains original order of input list. + */ +function nestGroups(raw) { + if (Groupings.isGrouping(raw)) { + return raw.map(g => { + return { key: g.key, rows: nestGroups(g.rows) }; + }); + } + else { + return nestItems(raw)[0]; + } +} +/////////////////////// +// Task Manipulation // +/////////////////////// +/** Trim empty ending lines. */ +function trimEndingLines(text) { + let parts = text.split(/\r?\n/u); + let trim = parts.length - 1; + while (trim > 0 && parts[trim].trim() == "") + trim--; + return parts.join("\n"); +} +/** Set the task completion key on check. */ +function setTaskCompletion(originalText, useEmojiShorthand, completionKey, completionDateFormat, complete) { + const blockIdRegex = /\^[a-z0-9\-]+/i; + if (!complete && !useEmojiShorthand) + return trimEndingLines(setInlineField(originalText.trimEnd(), completionKey)).trimEnd(); + let parts = originalText.split(/\r?\n/u); + const matches = blockIdRegex.exec(parts[parts.length - 1]); + console.debug("matchreg", matches); + let processedPart = parts[parts.length - 1].split(blockIdRegex).join(""); // last part without block id + if (useEmojiShorthand) { + processedPart = setEmojiShorthandCompletionField(processedPart, complete ? DateTime.now().toFormat("yyyy-MM-dd") : ""); + } + else { + processedPart = setInlineField(processedPart, completionKey, DateTime.now().toFormat(completionDateFormat)); + } + processedPart = `${processedPart.trimEnd()}${matches?.length ? " " + matches[0].trim() : ""}`.trimEnd(); // add back block id + parts[parts.length - 1] = processedPart; + return parts.join("\n"); +} +/** Rewrite a task with the given completion status and new text. */ +async function rewriteTask(vault, task, desiredStatus, desiredText) { + if (desiredStatus == task.status && (desiredText == undefined || desiredText == task.text)) + return; + desiredStatus = desiredStatus == "" ? " " : desiredStatus; + let rawFiletext = await vault.adapter.read(task.path); + let hasRN = rawFiletext.contains("\r"); + let filetext = rawFiletext.split(/\r?\n/u); + if (filetext.length < task.line) + return; + let match = LIST_ITEM_REGEX.exec(filetext[task.line]); + if (!match || match[2].length == 0) + return; + let taskTextParts = task.text.split("\n"); + if (taskTextParts[0].trim() != match[3].trim()) + return; + // We have a positive match here at this point, so go ahead and do the rewrite of the status. + let initialSpacing = /^[\s>]*/u.exec(filetext[task.line])[0]; + if (desiredText) { + let desiredParts = desiredText.split("\n"); + let newTextLines = [`${initialSpacing}${task.symbol} [${desiredStatus}] ${desiredParts[0]}`].concat(desiredParts.slice(1).map(l => initialSpacing + "\t" + l)); + filetext.splice(task.line, task.lineCount, ...newTextLines); + } + else { + filetext[task.line] = `${initialSpacing}${task.symbol} [${desiredStatus}] ${taskTextParts[0].trim()}`; + } + let newText = filetext.join(hasRN ? "\r\n" : "\n"); + await vault.adapter.write(task.path, newText); +} + +function ListGrouping({ items, sourcePath }) { + return (y$1("ul", { class: "dataview list-view-ul" }, items.map(item => (y$1("li", null, + y$1(Lit, { value: item, sourcePath: sourcePath })))))); +} +/** Pure view over list elements. */ +function ListView({ query, sourcePath }) { + let context = q$1(DataviewContext); + let items = useIndexBackedState(context.container, context.app, context.settings, context.index, { state: "loading" }, async () => { + let result = await asyncTryOrPropagate(() => executeList(query, context.index, sourcePath, context.settings)); + if (!result.successful) + return { state: "error", error: result.error, sourcePath }; + return { state: "ready", items: result.value.data }; + }); + if (items.state == "loading") + return (y$1(k$2, null, + y$1(ErrorPre, null, "Loading..."))); + else if (items.state == "error") + return (y$1(k$2, null, + " ", + y$1(ErrorPre, null, + "Dataview: ", + items.error), + " ")); + if (items.items.length == 0 && context.settings.warnOnEmptyResult) + return y$1(ErrorMessage, { message: "Dataview: No results to show for list query." }); + return y$1(ListGrouping, { items: items.items, sourcePath: sourcePath }); +} +function createListView(init, query, sourcePath) { + return new ReactRenderer(init, y$1(ListView, { query: query, sourcePath: sourcePath })); +} +function createFixedListView(init, elements, sourcePath) { + return new ReactRenderer(init, y$1(ListGrouping, { items: elements, sourcePath: sourcePath })); +} + +/** JSX component which returns the result count. */ +function ResultCount(props) { + const { settings } = q$1(DataviewContext); + return settings.showResultCount ? y$1("span", { class: "dataview small-text" }, props.length) : y$1(k$2, null); +} +/** Simple table over headings and corresponding values. */ +function TableGrouping({ headings, values, sourcePath, }) { + let settings = q$1(DataviewContext).settings; + return (y$1(k$2, null, + y$1("table", { class: "dataview table-view-table" }, + y$1("thead", { class: "table-view-thead" }, + y$1("tr", { class: "table-view-tr-header" }, headings.map((heading, index) => (y$1("th", { class: "table-view-th" }, + y$1(Markdown, { sourcePath: sourcePath, content: heading }), + index == 0 && y$1(ResultCount, { length: values.length })))))), + y$1("tbody", { class: "table-view-tbody" }, values.map(row => (y$1("tr", null, row.map(element => (y$1("td", null, + y$1(Lit, { value: element, sourcePath: sourcePath }))))))))), + settings.warnOnEmptyResult && values.length == 0 && (y$1(ErrorMessage, { message: "Dataview: No results to show for table query." })))); +} +/** Pure view over list elements. */ +function TableView({ query, sourcePath }) { + let context = q$1(DataviewContext); + let items = useIndexBackedState(context.container, context.app, context.settings, context.index, { state: "loading" }, async () => { + let result = await asyncTryOrPropagate(() => executeTable(query, context.index, sourcePath, context.settings)); + if (!result.successful) + return { state: "error", error: result.error }; + return { state: "ready", headings: result.value.names, values: result.value.data }; + }); + if (items.state == "loading") + return (y$1(k$2, null, + y$1(ErrorPre, null, "Loading..."))); + else if (items.state == "error") + return (y$1(k$2, null, + " ", + y$1(ErrorPre, null, + "Dataview: ", + items.error), + " ")); + return y$1(TableGrouping, { headings: items.headings, values: items.values, sourcePath: sourcePath }); +} +function createTableView(init, query, sourcePath) { + return new ReactRenderer(init, y$1(TableView, { query: query, sourcePath: sourcePath })); +} +function createFixedTableView(init, headings, values, sourcePath) { + return new ReactRenderer(init, y$1(TableGrouping, { values: values, headings: headings, sourcePath: sourcePath })); +} + +/** Utility functions for quickly creating fields. */ +var QueryFields; +(function (QueryFields) { + function named(name, field) { + return { name, field }; + } + QueryFields.named = named; + function sortBy(field, dir) { + return { field, direction: dir }; + } + QueryFields.sortBy = sortBy; +})(QueryFields || (QueryFields = {})); + +/** Return a new parser which executes the underlying parser and returns it's raw string representation. */ +function captureRaw(base) { + return parsimmon_umd_minExports.custom((success, failure) => { + return (input, i) => { + let result = base._(input, i); + if (!result.status) + return result; + return Object.assign({}, result, { value: [result.value, input.substring(i, result.index)] }); + }; + }); +} +/** Strip newlines and excess whitespace out of text. */ +function stripNewlines(text) { + return text + .split(/[\r\n]+/) + .map(t => t.trim()) + .join(""); +} +/** Given `parser`, return the parser that returns `if_eof()` if EOF is found, + * otherwise `parser` preceded by (non-optional) whitespace */ +function precededByWhitespaceIfNotEof(if_eof, parser) { + return parsimmon_umd_minExports.eof.map(if_eof).or(parsimmon_umd_minExports.whitespace.then(parser)); +} +/** A parsimmon-powered parser-combinator implementation of the query language. */ +const QUERY_LANGUAGE = parsimmon_umd_minExports.createLanguage({ + // Simple atom parsing, like words, identifiers, numbers. + queryType: q => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/TABLE|LIST|TASK|CALENDAR/i)) + .map(str => str.toLowerCase()) + .desc("query type ('TABLE', 'LIST', 'TASK', or 'CALENDAR')"), + explicitNamedField: q => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.whitespace), parsimmon_umd_minExports.regexp(/AS/i).skip(parsimmon_umd_minExports.whitespace), EXPRESSION.identifier.or(EXPRESSION.string), (field, _as, ident) => QueryFields.named(ident, field)), + comment: () => parsimmon_umd_minExports.Parser((input, i) => { + // Parse a comment, which is a line starting with //. + let line = input.substring(i); + if (!line.startsWith("//")) + return parsimmon_umd_minExports.makeFailure(i, "Not a comment"); + // The comment ends at the end of the line. + line = line.split("\n")[0]; + let comment = line.substring(2).trim(); + return parsimmon_umd_minExports.makeSuccess(i + line.length, comment); + }), + namedField: q => parsimmon_umd_minExports.alt(q.explicitNamedField, captureRaw(EXPRESSION.field).map(([value, text]) => QueryFields.named(stripNewlines(text), value))), + sortField: q => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1), (field, dir) => { + let direction = dir.length == 0 ? "ascending" : dir[0].toLowerCase(); + if (direction == "desc") + direction = "descending"; + if (direction == "asc") + direction = "ascending"; + return { + field: field, + direction: direction, + }; + }), + headerClause: q => q.queryType + .chain(type => { + switch (type) { + case "table": { + return precededByWhitespaceIfNotEof(() => ({ type, fields: [], showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i) + .skip(parsimmon_umd_minExports.optWhitespace) + .atMost(1), parsimmon_umd_minExports.sepBy(q.namedField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (withoutId, fields) => { + return { type, fields, showId: withoutId.length == 0 }; + })); + } + case "list": + return precededByWhitespaceIfNotEof(() => ({ type, format: undefined, showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i) + .skip(parsimmon_umd_minExports.optWhitespace) + .atMost(1), EXPRESSION.field.atMost(1), (withoutId, format) => { + return { + type, + format: format.length == 1 ? format[0] : undefined, + showId: withoutId.length == 0, + }; + })); + case "task": + return parsimmon_umd_minExports.succeed({ type }); + case "calendar": + return parsimmon_umd_minExports.whitespace.then(parsimmon_umd_minExports.seqMap(q.namedField, field => { + return { + type, + showId: true, + field, + }; + })); + default: + return parsimmon_umd_minExports.fail(`Unrecognized query type '${type}'`); + } + }) + .desc("TABLE or LIST or TASK or CALENDAR"), + fromClause: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FROM/i), parsimmon_umd_minExports.whitespace, EXPRESSION.source, (_1, _2, source) => source), + whereClause: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WHERE/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (where, _, field) => { + return { type: "where", clause: field }; + }).desc("WHERE "), + sortByClause: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/SORT/i), parsimmon_umd_minExports.whitespace, q.sortField.sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (sort, _1, fields) => { + return { type: "sort", fields }; + }).desc("SORT field [ASC/DESC]"), + limitClause: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/LIMIT/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (limit, _1, field) => { + return { type: "limit", amount: field }; + }).desc("LIMIT "), + flattenClause: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FLATTEN/i).skip(parsimmon_umd_minExports.whitespace), q.namedField, (_, field) => { + return { type: "flatten", field }; + }).desc("FLATTEN [AS ]"), + groupByClause: q => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/GROUP BY/i).skip(parsimmon_umd_minExports.whitespace), q.namedField, (_, field) => { + return { type: "group", field }; + }).desc("GROUP BY [AS ]"), + // Full query parsing. + clause: q => parsimmon_umd_minExports.alt(q.fromClause, q.whereClause, q.sortByClause, q.limitClause, q.groupByClause, q.flattenClause), + query: q => parsimmon_umd_minExports.seqMap(q.headerClause.trim(optionalWhitespaceOrComment), q.fromClause.trim(optionalWhitespaceOrComment).atMost(1), q.clause.trim(optionalWhitespaceOrComment).many(), (header, from, clauses) => { + return { + header, + source: from.length == 0 ? Sources.folder("") : from[0], + operations: clauses, + settings: DEFAULT_QUERY_SETTINGS, + }; + }), +}); +/** + * A parser for optional whitespace or comments. This is used to exclude whitespace and comments from other parsers. + */ +const optionalWhitespaceOrComment = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.whitespace, QUERY_LANGUAGE.comment) + .many() // Use many() since there may be zero whitespaces or comments. + // Transform the many to a single result. + .map(arr => arr.join("")); +/** + * Attempt to parse a query from the given query text, returning a string error + * if the parse failed. + */ +function parseQuery(text) { + try { + let query = QUERY_LANGUAGE.query.tryParse(text); + return Result.success(query); + } + catch (error) { + return Result.failure("" + error); + } +} + +function noop() { } +function assign(tar, src) { + // @ts-ignore + for (const k in src) + tar[k] = src[k]; + return tar; +} +function is_promise(value) { + return value && typeof value === 'object' && typeof value.then === 'function'; +} +function run(fn) { + return fn(); +} +function blank_object() { + return Object.create(null); +} +function run_all(fns) { + fns.forEach(run); +} +function is_function(thing) { + return typeof thing === 'function'; +} +function safe_not_equal(a, b) { + return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); +} +function not_equal(a, b) { + return a != a ? b == b : a !== b; +} +function is_empty(obj) { + return Object.keys(obj).length === 0; +} +function create_slot(definition, ctx, $$scope, fn) { + if (definition) { + const slot_ctx = get_slot_context(definition, ctx, $$scope, fn); + return definition[0](slot_ctx); + } +} +function get_slot_context(definition, ctx, $$scope, fn) { + return definition[1] && fn + ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) + : $$scope.ctx; +} +function 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 update_slot(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) { + const slot_changes = get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn); + if (slot_changes) { + const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn); + slot.p(slot_context, slot_changes); + } +} +function null_to_empty(value) { + return value == null ? '' : value; +} + +function append(target, node) { + target.appendChild(node); +} +function insert(target, node, anchor) { + target.insertBefore(node, anchor || null); +} +function detach(node) { + node.parentNode.removeChild(node); +} +function destroy_each(iterations, detaching) { + for (let i = 0; i < iterations.length; i += 1) { + if (iterations[i]) + iterations[i].d(detaching); + } +} +function element(name) { + return document.createElement(name); +} +function svg_element(name) { + return document.createElementNS('http://www.w3.org/2000/svg', name); +} +function text(data) { + return document.createTextNode(data); +} +function space() { + return text(' '); +} +function empty() { + return text(''); +} +function listen(node, event, handler, options) { + node.addEventListener(event, handler, options); + return () => node.removeEventListener(event, handler, options); +} +function attr(node, attribute, value) { + if (value == null) + node.removeAttribute(attribute); + else if (node.getAttribute(attribute) !== value) + node.setAttribute(attribute, value); +} +function 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) { + node[key] = attributes[key]; + } + else { + attr(node, key, attributes[key]); + } + } +} +function children(element) { + return Array.from(element.childNodes); +} +function set_data(text, data) { + data = '' + data; + if (text.wholeText !== data) + text.data = data; +} +function toggle_class(element, name, toggle) { + element.classList[toggle ? 'add' : 'remove'](name); +} + +let current_component; +function set_current_component(component) { + current_component = component; +} +function get_current_component() { + if (!current_component) + throw new Error('Function called outside component initialization'); + return current_component; +} + +const dirty_components = []; +const binding_callbacks = []; +const render_callbacks = []; +const flush_callbacks = []; +const resolved_promise = Promise.resolve(); +let update_scheduled = false; +function schedule_update() { + if (!update_scheduled) { + update_scheduled = true; + resolved_promise.then(flush); + } +} +function add_render_callback(fn) { + render_callbacks.push(fn); +} +let flushing = false; +const seen_callbacks = new Set(); +function flush() { + if (flushing) + return; + flushing = true; + do { + // first, call beforeUpdate functions + // and update components + for (let i = 0; i < dirty_components.length; i += 1) { + const component = dirty_components[i]; + set_current_component(component); + update(component.$$); + } + set_current_component(null); + dirty_components.length = 0; + while (binding_callbacks.length) + binding_callbacks.pop()(); + // then, once components are updated, call + // afterUpdate functions. This may cause + // subsequent updates... + for (let i = 0; i < render_callbacks.length; i += 1) { + const callback = render_callbacks[i]; + if (!seen_callbacks.has(callback)) { + // ...so guard against infinite loops + seen_callbacks.add(callback); + callback(); + } + } + render_callbacks.length = 0; + } while (dirty_components.length); + while (flush_callbacks.length) { + flush_callbacks.pop()(); + } + update_scheduled = false; + flushing = false; + seen_callbacks.clear(); +} +function update($$) { + if ($$.fragment !== null) { + $$.update(); + run_all($$.before_update); + const dirty = $$.dirty; + $$.dirty = [-1]; + $$.fragment && $$.fragment.p($$.ctx, dirty); + $$.after_update.forEach(add_render_callback); + } +} +const outroing = new Set(); +let outros; +function group_outros() { + outros = { + r: 0, + c: [], + p: outros // parent group + }; +} +function check_outros() { + if (!outros.r) { + run_all(outros.c); + } + outros = outros.p; +} +function transition_in(block, local) { + if (block && block.i) { + outroing.delete(block); + block.i(local); + } +} +function transition_out(block, local, detach, callback) { + if (block && block.o) { + if (outroing.has(block)) + return; + outroing.add(block); + outros.c.push(() => { + outroing.delete(block); + if (callback) { + if (detach) + block.d(1); + callback(); + } + }); + block.o(local); + } +} + +function 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) { + group_outros(); + transition_out(block, 1, 1, () => { + if (info.blocks[i] === block) { + info.blocks[i] = null; + } + }); + check_outros(); + } + }); + } + else { + info.block.d(1); + } + block.c(); + 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) { + flush(); + } + } + if (is_promise(promise)) { + const current_component = get_current_component(); + promise.then(value => { + set_current_component(current_component); + update(info.then, 1, info.value, value); + set_current_component(null); + }, error => { + set_current_component(current_component); + update(info.catch, 2, info.error, error); + 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 outro_and_destroy_block(block, lookup) { + transition_out(block, 1, 1, () => { + lookup.delete(block.key); + }); +} +function 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(); + 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) { + 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) { + 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]); + return new_blocks; +} + +function 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 get_spread_object(spread_props) { + return typeof spread_props === 'object' && spread_props !== null ? spread_props : {}; +} +function create_component(block) { + block && block.c(); +} +function mount_component(component, target, anchor, customElement) { + const { fragment, on_mount, on_destroy, after_update } = component.$$; + fragment && fragment.m(target, anchor); + if (!customElement) { + // onMount happens before the initial afterUpdate + add_render_callback(() => { + const new_on_destroy = on_mount.map(run).filter(is_function); + if (on_destroy) { + on_destroy.push(...new_on_destroy); + } + else { + // Edge case - component was destroyed immediately, + // most likely as a result of a binding initialising + run_all(new_on_destroy); + } + component.$$.on_mount = []; + }); + } + after_update.forEach(add_render_callback); +} +function destroy_component(component, detaching) { + const $$ = component.$$; + if ($$.fragment !== null) { + 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 make_dirty(component, i) { + if (component.$$.dirty[0] === -1) { + dirty_components.push(component); + schedule_update(); + component.$$.dirty.fill(0); + } + component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31)); +} +function init(component, options, instance, create_fragment, not_equal, props, dirty = [-1]) { + const parent_component = current_component; + set_current_component(component); + const $$ = component.$$ = { + fragment: null, + ctx: null, + // state + props, + update: noop, + not_equal, + bound: blank_object(), + // lifecycle + on_mount: [], + on_destroy: [], + on_disconnect: [], + before_update: [], + after_update: [], + context: new Map(parent_component ? parent_component.$$.context : []), + // everything else + callbacks: blank_object(), + dirty, + skip_bound: false + }; + 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) + make_dirty(component, i); + } + return ret; + }) + : []; + $$.update(); + ready = true; + 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) { + const nodes = children(options.target); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.l(nodes); + nodes.forEach(detach); + } + else { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.c(); + } + if (options.intro) + transition_in(component.$$.fragment); + mount_component(component, options.target, options.anchor, options.customElement); + flush(); + } + set_current_component(parent_component); +} +/** + * Base class for Svelte components. Used when dev=false. + */ +class SvelteComponent { + $destroy() { + destroy_component(this, 1); + this.$destroy = noop; + } + $on(type, callback) { + 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 && !is_empty($$props)) { + this.$$.skip_bound = true; + this.$$set($$props); + this.$$.skip_bound = false; + } + } +} + +/** + * dateUID is a way of weekly identifying daily/weekly/monthly notes. + * They are prefixed with the granularity to avoid ambiguity. + */ +function getDateUID(date, granularity = "day") { + const ts = date.clone().startOf(granularity).format(); + return `${granularity}-${ts}`; +} +var getDateUID_1 = getDateUID; + +/* src/components/Dot.svelte generated by Svelte v3.35.0 */ + +function add_css$5() { + var style = element("style"); + style.id = "svelte-1widvzq-style"; + style.textContent = ".dot.svelte-1widvzq,.hollow.svelte-1widvzq{display:inline-block;height:6px;width:6px;margin:0 1px}.filled.svelte-1widvzq{fill:var(--color-dot)}.active.filled.svelte-1widvzq{fill:var(--text-on-accent)}.hollow.svelte-1widvzq{fill:none;stroke:var(--color-dot)}.active.hollow.svelte-1widvzq{fill:none;stroke:var(--text-on-accent)}"; + append(document.head, style); +} + +// (14:0) {:else} +function create_else_block$1(ctx) { + let svg; + let circle; + let svg_class_value; + + return { + c() { + svg = svg_element("svg"); + circle = svg_element("circle"); + attr(circle, "cx", "3"); + attr(circle, "cy", "3"); + attr(circle, "r", "2"); + attr(svg, "class", svg_class_value = "" + (null_to_empty(`hollow ${/*className*/ ctx[0]}`) + " svelte-1widvzq")); + attr(svg, "viewBox", "0 0 6 6"); + attr(svg, "xmlns", "http://www.w3.org/2000/svg"); + toggle_class(svg, "active", /*isActive*/ ctx[2]); + }, + m(target, anchor) { + insert(target, svg, anchor); + append(svg, circle); + }, + p(ctx, dirty) { + if (dirty & /*className*/ 1 && svg_class_value !== (svg_class_value = "" + (null_to_empty(`hollow ${/*className*/ ctx[0]}`) + " svelte-1widvzq"))) { + attr(svg, "class", svg_class_value); + } + + if (dirty & /*className, isActive*/ 5) { + toggle_class(svg, "active", /*isActive*/ ctx[2]); + } + }, + d(detaching) { + if (detaching) detach(svg); + } + }; +} + +// (6:0) {#if isFilled} +function create_if_block$2(ctx) { + let svg; + let circle; + let svg_class_value; + + return { + c() { + svg = svg_element("svg"); + circle = svg_element("circle"); + attr(circle, "cx", "3"); + attr(circle, "cy", "3"); + attr(circle, "r", "2"); + attr(svg, "class", svg_class_value = "" + (null_to_empty(`dot filled ${/*className*/ ctx[0]}`) + " svelte-1widvzq")); + attr(svg, "viewBox", "0 0 6 6"); + attr(svg, "xmlns", "http://www.w3.org/2000/svg"); + toggle_class(svg, "active", /*isActive*/ ctx[2]); + }, + m(target, anchor) { + insert(target, svg, anchor); + append(svg, circle); + }, + p(ctx, dirty) { + if (dirty & /*className*/ 1 && svg_class_value !== (svg_class_value = "" + (null_to_empty(`dot filled ${/*className*/ ctx[0]}`) + " svelte-1widvzq"))) { + attr(svg, "class", svg_class_value); + } + + if (dirty & /*className, isActive*/ 5) { + toggle_class(svg, "active", /*isActive*/ ctx[2]); + } + }, + d(detaching) { + if (detaching) detach(svg); + } + }; +} + +function create_fragment$6(ctx) { + let if_block_anchor; + + function select_block_type(ctx, dirty) { + if (/*isFilled*/ ctx[1]) return create_if_block$2; + return create_else_block$1; + } + + let current_block_type = select_block_type(ctx); + let if_block = current_block_type(ctx); + + return { + c() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + }, + p(ctx, [dirty]) { + if (current_block_type === (current_block_type = select_block_type(ctx)) && 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(if_block_anchor.parentNode, if_block_anchor); + } + } + }, + i: noop, + o: noop, + d(detaching) { + if_block.d(detaching); + if (detaching) detach(if_block_anchor); + } + }; +} + +function instance$6($$self, $$props, $$invalidate) { + let { className = "" } = $$props; + let { isFilled } = $$props; + let { isActive } = $$props; + + $$self.$$set = $$props => { + if ("className" in $$props) $$invalidate(0, className = $$props.className); + if ("isFilled" in $$props) $$invalidate(1, isFilled = $$props.isFilled); + if ("isActive" in $$props) $$invalidate(2, isActive = $$props.isActive); + }; + + return [className, isFilled, isActive]; +} + +class Dot extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-1widvzq-style")) add_css$5(); + init(this, options, instance$6, create_fragment$6, safe_not_equal, { className: 0, isFilled: 1, isActive: 2 }); + } +} + +/* src/components/MetadataResolver.svelte generated by Svelte v3.35.0 */ + +const get_default_slot_changes_1 = dirty => ({}); +const get_default_slot_context_1 = ctx => ({ metadata: null }); +const get_default_slot_changes = dirty => ({ metadata: dirty & /*metadata*/ 1 }); +const get_default_slot_context = ctx => ({ metadata: /*resolvedMeta*/ ctx[3] }); + +// (11:0) {:else} +function create_else_block(ctx) { + let current; + const default_slot_template = /*#slots*/ ctx[2].default; + const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[1], get_default_slot_context_1); + + return { + c() { + if (default_slot) default_slot.c(); + }, + m(target, anchor) { + if (default_slot) { + default_slot.m(target, anchor); + } + + current = true; + }, + p(ctx, dirty) { + if (default_slot) { + if (default_slot.p && dirty & /*$$scope*/ 2) { + update_slot(default_slot, default_slot_template, ctx, /*$$scope*/ ctx[1], dirty, get_default_slot_changes_1, get_default_slot_context_1); + } + } + }, + i(local) { + if (current) return; + transition_in(default_slot, local); + current = true; + }, + o(local) { + transition_out(default_slot, local); + current = false; + }, + d(detaching) { + if (default_slot) default_slot.d(detaching); + } + }; +} + +// (7:0) {#if metadata} +function create_if_block$1(ctx) { + let await_block_anchor; + let promise; + let current; + + let info = { + ctx, + current: null, + token: null, + hasCatch: false, + pending: create_pending_block, + then: create_then_block, + catch: create_catch_block, + value: 3, + blocks: [,,,] + }; + + handle_promise(promise = /*metadata*/ ctx[0], info); + + return { + c() { + await_block_anchor = empty(); + info.block.c(); + }, + m(target, anchor) { + insert(target, await_block_anchor, anchor); + info.block.m(target, info.anchor = anchor); + info.mount = () => await_block_anchor.parentNode; + info.anchor = await_block_anchor; + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + info.ctx = ctx; + + if (dirty & /*metadata*/ 1 && promise !== (promise = /*metadata*/ ctx[0]) && handle_promise(promise, info)) ; else { + const child_ctx = ctx.slice(); + child_ctx[3] = info.resolved; + info.block.p(child_ctx, dirty); + } + }, + i(local) { + if (current) return; + transition_in(info.block); + current = true; + }, + o(local) { + for (let i = 0; i < 3; i += 1) { + const block = info.blocks[i]; + transition_out(block); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(await_block_anchor); + info.block.d(detaching); + info.token = null; + info = null; + } + }; +} + +// (1:0) {#if metadata} +function create_catch_block(ctx) { + return { + c: noop, + m: noop, + p: noop, + i: noop, + o: noop, + d: noop + }; +} + +// (8:37) ; export let metadata; {#if metadata} +function create_pending_block(ctx) { + return { + c: noop, + m: noop, + p: noop, + i: noop, + o: noop, + d: noop + }; +} + +function create_fragment$5(ctx) { + let current_block_type_index; + let if_block; + let if_block_anchor; + let current; + const if_block_creators = [create_if_block$1, create_else_block]; + const if_blocks = []; + + function select_block_type(ctx, dirty) { + if (/*metadata*/ ctx[0]) return 0; + return 1; + } + + current_block_type_index = select_block_type(ctx); + if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); + + return { + c() { + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if_blocks[current_block_type_index].m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx, [dirty]) { + let previous_block_index = current_block_type_index; + current_block_type_index = select_block_type(ctx); + + if (current_block_type_index === previous_block_index) { + if_blocks[current_block_type_index].p(ctx, dirty); + } else { + group_outros(); + + transition_out(if_blocks[previous_block_index], 1, 1, () => { + if_blocks[previous_block_index] = null; + }); + + 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); + } + + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + }, + i(local) { + if (current) return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if_blocks[current_block_type_index].d(detaching); + if (detaching) detach(if_block_anchor); + } + }; +} + +function instance$5($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + + let { metadata } = $$props; + + $$self.$$set = $$props => { + if ("metadata" in $$props) $$invalidate(0, metadata = $$props.metadata); + if ("$$scope" in $$props) $$invalidate(1, $$scope = $$props.$$scope); + }; + + return [metadata, $$scope, slots]; +} + +class MetadataResolver extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance$5, create_fragment$5, not_equal, { metadata: 0 }); + } +} + +function isMacOS() { + return navigator.appVersion.indexOf("Mac") !== -1; +} +function isMetaPressed(e) { + return isMacOS() ? e.metaKey : e.ctrlKey; +} +function getDaysOfWeek(..._args) { + return window.moment.weekdaysShort(true); +} +function isWeekend(date) { + return date.isoWeekday() === 6 || date.isoWeekday() === 7; +} +function getStartOfWeek(days) { + return days[0].weekday(0); +} +/** + * Generate a 2D array of daily information to power + * the calendar view. + */ +function getMonth(displayedMonth, ..._args) { + const locale = window.moment().locale(); + const month = []; + let week; + const startOfMonth = displayedMonth.clone().locale(locale).date(1); + const startOffset = startOfMonth.weekday(); + let date = startOfMonth.clone().subtract(startOffset, "days"); + for (let _day = 0; _day < 42; _day++) { + if (_day % 7 === 0) { + week = { + days: [], + weekNum: date.week(), + }; + month.push(week); + } + week.days.push(date); + date = date.clone().add(1, "days"); + } + return month; +} + +/* src/components/Day.svelte generated by Svelte v3.35.0 */ + +function add_css$4() { + var style = element("style"); + style.id = "svelte-q3wqg9-style"; + style.textContent = ".day.svelte-q3wqg9{background-color:var(--color-background-day);border-radius:4px;color:var(--color-text-day);cursor:pointer;font-size:0.8em;height:100%;padding:4px;position:relative;text-align:center;transition:background-color 0.1s ease-in, color 0.1s ease-in;vertical-align:baseline}.day.svelte-q3wqg9:hover{background-color:var(--interactive-hover)}.day.active.svelte-q3wqg9:hover{background-color:var(--interactive-accent-hover)}.adjacent-month.svelte-q3wqg9{opacity:0.25}.today.svelte-q3wqg9{color:var(--color-text-today)}.day.svelte-q3wqg9:active,.active.svelte-q3wqg9,.active.today.svelte-q3wqg9{color:var(--text-on-accent);background-color:var(--interactive-accent)}.dot-container.svelte-q3wqg9{display:flex;flex-wrap:wrap;justify-content:center;line-height:6px;min-height:6px}"; + append(document.head, style); +} + +function get_each_context$2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[11] = list[i]; + return child_ctx; +} + +// (36:8) {#each metadata.dots as dot} +function create_each_block$2(ctx) { + let dot; + let current; + const dot_spread_levels = [/*dot*/ ctx[11]]; + let dot_props = {}; + + for (let i = 0; i < dot_spread_levels.length; i += 1) { + dot_props = assign(dot_props, dot_spread_levels[i]); + } + + dot = new Dot({ props: dot_props }); + + return { + c() { + create_component(dot.$$.fragment); + }, + m(target, anchor) { + mount_component(dot, target, anchor); + current = true; + }, + p(ctx, dirty) { + const dot_changes = (dirty & /*metadata*/ 128) + ? get_spread_update(dot_spread_levels, [get_spread_object(/*dot*/ ctx[11])]) + : {}; + + dot.$set(dot_changes); + }, + i(local) { + if (current) return; + transition_in(dot.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(dot.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(dot, detaching); + } + }; +} + +// (22:2) +function create_default_slot$1(ctx) { + let div1; + let t0_value = /*date*/ ctx[0].format("D") + ""; + let t0; + let t1; + let div0; + let div1_class_value; + let current; + let mounted; + let dispose; + let each_value = /*metadata*/ ctx[7].dots; + let each_blocks = []; + + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i)); + } + + const out = i => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + + let div1_levels = [ + { + class: div1_class_value = `day ${/*metadata*/ ctx[7].classes.join(" ")}` + }, + /*metadata*/ ctx[7].dataAttributes || {} + ]; + + let div1_data = {}; + + for (let i = 0; i < div1_levels.length; i += 1) { + div1_data = assign(div1_data, div1_levels[i]); + } + + return { + c() { + div1 = element("div"); + t0 = text(t0_value); + t1 = space(); + div0 = element("div"); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + attr(div0, "class", "dot-container svelte-q3wqg9"); + set_attributes(div1, div1_data); + toggle_class(div1, "active", /*selectedId*/ ctx[6] === getDateUID_1(/*date*/ ctx[0], "day")); + toggle_class(div1, "adjacent-month", !/*date*/ ctx[0].isSame(/*displayedMonth*/ ctx[5], "month")); + toggle_class(div1, "today", /*date*/ ctx[0].isSame(/*today*/ ctx[4], "day")); + toggle_class(div1, "svelte-q3wqg9", true); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, t0); + append(div1, t1); + append(div1, div0); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div0, null); + } + + current = true; + + if (!mounted) { + dispose = [ + listen(div1, "click", function () { + if (is_function(/*onClick*/ ctx[2] && /*click_handler*/ ctx[8])) (/*onClick*/ ctx[2] && /*click_handler*/ ctx[8]).apply(this, arguments); + }), + listen(div1, "contextmenu", function () { + if (is_function(/*onContextMenu*/ ctx[3] && /*contextmenu_handler*/ ctx[9])) (/*onContextMenu*/ ctx[3] && /*contextmenu_handler*/ ctx[9]).apply(this, arguments); + }), + listen(div1, "pointerover", function () { + if (is_function(/*onHover*/ ctx[1] && /*pointerover_handler*/ ctx[10])) (/*onHover*/ ctx[1] && /*pointerover_handler*/ ctx[10]).apply(this, arguments); + }) + ]; + + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if ((!current || dirty & /*date*/ 1) && t0_value !== (t0_value = /*date*/ ctx[0].format("D") + "")) set_data(t0, t0_value); + + if (dirty & /*metadata*/ 128) { + each_value = /*metadata*/ ctx[7].dots; + let i; + + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context$2(ctx, each_value, i); + + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block$2(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div0, null); + } + } + + group_outros(); + + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + + check_outros(); + } + + set_attributes(div1, div1_data = get_spread_update(div1_levels, [ + (!current || dirty & /*metadata*/ 128 && div1_class_value !== (div1_class_value = `day ${/*metadata*/ ctx[7].classes.join(" ")}`)) && { class: div1_class_value }, + dirty & /*metadata*/ 128 && (/*metadata*/ ctx[7].dataAttributes || {}) + ])); + + toggle_class(div1, "active", /*selectedId*/ ctx[6] === getDateUID_1(/*date*/ ctx[0], "day")); + toggle_class(div1, "adjacent-month", !/*date*/ ctx[0].isSame(/*displayedMonth*/ ctx[5], "month")); + toggle_class(div1, "today", /*date*/ ctx[0].isSame(/*today*/ ctx[4], "day")); + toggle_class(div1, "svelte-q3wqg9", true); + }, + i(local) { + if (current) return; + + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(div1); + destroy_each(each_blocks, detaching); + mounted = false; + run_all(dispose); + } + }; +} + +function create_fragment$4(ctx) { + let td; + let metadataresolver; + let current; + + metadataresolver = new MetadataResolver({ + props: { + metadata: /*metadata*/ ctx[7], + $$slots: { + default: [ + create_default_slot$1, + ({ metadata }) => ({ 7: metadata }), + ({ metadata }) => metadata ? 128 : 0 + ] + }, + $$scope: { ctx } + } + }); + + return { + c() { + td = element("td"); + create_component(metadataresolver.$$.fragment); + }, + m(target, anchor) { + insert(target, td, anchor); + mount_component(metadataresolver, td, null); + current = true; + }, + p(ctx, [dirty]) { + const metadataresolver_changes = {}; + if (dirty & /*metadata*/ 128) metadataresolver_changes.metadata = /*metadata*/ ctx[7]; + + if (dirty & /*$$scope, metadata, selectedId, date, displayedMonth, today, onClick, onContextMenu, onHover*/ 16639) { + metadataresolver_changes.$$scope = { dirty, ctx }; + } + + metadataresolver.$set(metadataresolver_changes); + }, + i(local) { + if (current) return; + transition_in(metadataresolver.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(metadataresolver.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(td); + destroy_component(metadataresolver); + } + }; +} + +function instance$4($$self, $$props, $$invalidate) { + + + let { date } = $$props; + let { metadata } = $$props; + let { onHover } = $$props; + let { onClick } = $$props; + let { onContextMenu } = $$props; + let { today } = $$props; + let { displayedMonth = null } = $$props; + let { selectedId = null } = $$props; + const click_handler = e => onClick(date, isMetaPressed(e)); + const contextmenu_handler = e => onContextMenu(date, e); + const pointerover_handler = e => onHover(date, e.target, isMetaPressed(e)); + + $$self.$$set = $$props => { + if ("date" in $$props) $$invalidate(0, date = $$props.date); + if ("metadata" in $$props) $$invalidate(7, metadata = $$props.metadata); + if ("onHover" in $$props) $$invalidate(1, onHover = $$props.onHover); + if ("onClick" in $$props) $$invalidate(2, onClick = $$props.onClick); + if ("onContextMenu" in $$props) $$invalidate(3, onContextMenu = $$props.onContextMenu); + if ("today" in $$props) $$invalidate(4, today = $$props.today); + if ("displayedMonth" in $$props) $$invalidate(5, displayedMonth = $$props.displayedMonth); + if ("selectedId" in $$props) $$invalidate(6, selectedId = $$props.selectedId); + }; + + return [ + date, + onHover, + onClick, + onContextMenu, + today, + displayedMonth, + selectedId, + metadata, + click_handler, + contextmenu_handler, + pointerover_handler + ]; +} + +class Day extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-q3wqg9-style")) add_css$4(); + + init(this, options, instance$4, create_fragment$4, not_equal, { + date: 0, + metadata: 7, + onHover: 1, + onClick: 2, + onContextMenu: 3, + today: 4, + displayedMonth: 5, + selectedId: 6 + }); + } +} + +/* src/components/Arrow.svelte generated by Svelte v3.35.0 */ + +function add_css$3() { + var style = element("style"); + style.id = "svelte-156w7na-style"; + style.textContent = ".arrow.svelte-156w7na.svelte-156w7na{align-items:center;cursor:pointer;display:flex;justify-content:center;width:24px}.arrow.is-mobile.svelte-156w7na.svelte-156w7na{width:32px}.right.svelte-156w7na.svelte-156w7na{transform:rotate(180deg)}.arrow.svelte-156w7na svg.svelte-156w7na{color:var(--color-arrow);height:16px;width:16px}"; + append(document.head, style); +} + +function create_fragment$3(ctx) { + let div; + let svg; + let path; + let mounted; + let dispose; + + return { + c() { + div = element("div"); + svg = svg_element("svg"); + path = svg_element("path"); + attr(path, "fill", "currentColor"); + attr(path, "d", "M34.52 239.03L228.87 44.69c9.37-9.37 24.57-9.37 33.94 0l22.67 22.67c9.36 9.36 9.37 24.52.04 33.9L131.49 256l154.02 154.75c9.34 9.38 9.32 24.54-.04 33.9l-22.67 22.67c-9.37 9.37-24.57 9.37-33.94 0L34.52 272.97c-9.37-9.37-9.37-24.57 0-33.94z"); + attr(svg, "focusable", "false"); + attr(svg, "role", "img"); + attr(svg, "xmlns", "http://www.w3.org/2000/svg"); + attr(svg, "viewBox", "0 0 320 512"); + attr(svg, "class", "svelte-156w7na"); + attr(div, "class", "arrow svelte-156w7na"); + attr(div, "aria-label", /*tooltip*/ ctx[1]); + toggle_class(div, "is-mobile", /*isMobile*/ ctx[3]); + toggle_class(div, "right", /*direction*/ ctx[2] === "right"); + }, + m(target, anchor) { + insert(target, div, anchor); + append(div, svg); + append(svg, path); + + if (!mounted) { + dispose = listen(div, "click", function () { + if (is_function(/*onClick*/ ctx[0])) /*onClick*/ ctx[0].apply(this, arguments); + }); + + mounted = true; + } + }, + p(new_ctx, [dirty]) { + ctx = new_ctx; + + if (dirty & /*tooltip*/ 2) { + attr(div, "aria-label", /*tooltip*/ ctx[1]); + } + + if (dirty & /*direction*/ 4) { + toggle_class(div, "right", /*direction*/ ctx[2] === "right"); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) detach(div); + mounted = false; + dispose(); + } + }; +} + +function instance$3($$self, $$props, $$invalidate) { + let { onClick } = $$props; + let { tooltip } = $$props; + let { direction } = $$props; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let isMobile = window.app.isMobile; + + $$self.$$set = $$props => { + if ("onClick" in $$props) $$invalidate(0, onClick = $$props.onClick); + if ("tooltip" in $$props) $$invalidate(1, tooltip = $$props.tooltip); + if ("direction" in $$props) $$invalidate(2, direction = $$props.direction); + }; + + return [onClick, tooltip, direction, isMobile]; +} + +class Arrow extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-156w7na-style")) add_css$3(); + init(this, options, instance$3, create_fragment$3, safe_not_equal, { onClick: 0, tooltip: 1, direction: 2 }); + } +} + +/* src/components/Nav.svelte generated by Svelte v3.35.0 */ + +function add_css$2() { + var style = element("style"); + style.id = "svelte-1vwr9dd-style"; + style.textContent = ".nav.svelte-1vwr9dd.svelte-1vwr9dd{align-items:center;display:flex;margin:0.6em 0 1em;padding:0 8px;width:100%}.nav.is-mobile.svelte-1vwr9dd.svelte-1vwr9dd{padding:0}.title.svelte-1vwr9dd.svelte-1vwr9dd{color:var(--color-text-title);font-size:1.5em;margin:0}.is-mobile.svelte-1vwr9dd .title.svelte-1vwr9dd{font-size:1.3em}.month.svelte-1vwr9dd.svelte-1vwr9dd{font-weight:500;text-transform:capitalize}.year.svelte-1vwr9dd.svelte-1vwr9dd{color:var(--interactive-accent)}.right-nav.svelte-1vwr9dd.svelte-1vwr9dd{display:flex;justify-content:center;margin-left:auto}.reset-button.svelte-1vwr9dd.svelte-1vwr9dd{cursor:pointer;border-radius:4px;color:var(--text-muted);font-size:0.7em;font-weight:600;letter-spacing:1px;margin:0 4px;padding:0px 4px;text-transform:uppercase}.is-mobile.svelte-1vwr9dd .reset-button.svelte-1vwr9dd{display:none}"; + append(document.head, style); +} + +function create_fragment$2(ctx) { + let div2; + let h3; + let span0; + let t0_value = /*displayedMonth*/ ctx[0].format("MMM") + ""; + let t0; + let t1; + let span1; + let t2_value = /*displayedMonth*/ ctx[0].format("YYYY") + ""; + let t2; + let t3; + let div1; + let arrow0; + let t4; + let div0; + let t6; + let arrow1; + let current; + let mounted; + let dispose; + + arrow0 = new Arrow({ + props: { + direction: "left", + onClick: /*decrementDisplayedMonth*/ ctx[3], + tooltip: "Previous Month" + } + }); + + arrow1 = new Arrow({ + props: { + direction: "right", + onClick: /*incrementDisplayedMonth*/ ctx[2], + tooltip: "Next Month" + } + }); + + return { + c() { + div2 = element("div"); + h3 = element("h3"); + span0 = element("span"); + t0 = text(t0_value); + t1 = space(); + span1 = element("span"); + t2 = text(t2_value); + t3 = space(); + div1 = element("div"); + create_component(arrow0.$$.fragment); + t4 = space(); + div0 = element("div"); + div0.textContent = `${/*todayDisplayStr*/ ctx[4]}`; + t6 = space(); + create_component(arrow1.$$.fragment); + attr(span0, "class", "month svelte-1vwr9dd"); + attr(span1, "class", "year svelte-1vwr9dd"); + attr(h3, "class", "title svelte-1vwr9dd"); + attr(div0, "class", "reset-button svelte-1vwr9dd"); + attr(div1, "class", "right-nav svelte-1vwr9dd"); + attr(div2, "class", "nav svelte-1vwr9dd"); + toggle_class(div2, "is-mobile", /*isMobile*/ ctx[5]); + }, + m(target, anchor) { + insert(target, div2, anchor); + append(div2, h3); + append(h3, span0); + append(span0, t0); + append(h3, t1); + append(h3, span1); + append(span1, t2); + append(div2, t3); + append(div2, div1); + mount_component(arrow0, div1, null); + append(div1, t4); + append(div1, div0); + append(div1, t6); + mount_component(arrow1, div1, null); + current = true; + + if (!mounted) { + dispose = [ + listen(h3, "click", function () { + if (is_function(/*resetDisplayedMonth*/ ctx[1])) /*resetDisplayedMonth*/ ctx[1].apply(this, arguments); + }), + listen(div0, "click", function () { + if (is_function(/*resetDisplayedMonth*/ ctx[1])) /*resetDisplayedMonth*/ ctx[1].apply(this, arguments); + }) + ]; + + mounted = true; + } + }, + p(new_ctx, [dirty]) { + ctx = new_ctx; + if ((!current || dirty & /*displayedMonth*/ 1) && t0_value !== (t0_value = /*displayedMonth*/ ctx[0].format("MMM") + "")) set_data(t0, t0_value); + if ((!current || dirty & /*displayedMonth*/ 1) && t2_value !== (t2_value = /*displayedMonth*/ ctx[0].format("YYYY") + "")) set_data(t2, t2_value); + const arrow0_changes = {}; + if (dirty & /*decrementDisplayedMonth*/ 8) arrow0_changes.onClick = /*decrementDisplayedMonth*/ ctx[3]; + arrow0.$set(arrow0_changes); + const arrow1_changes = {}; + if (dirty & /*incrementDisplayedMonth*/ 4) arrow1_changes.onClick = /*incrementDisplayedMonth*/ ctx[2]; + arrow1.$set(arrow1_changes); + }, + i(local) { + if (current) return; + transition_in(arrow0.$$.fragment, local); + transition_in(arrow1.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(arrow0.$$.fragment, local); + transition_out(arrow1.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(div2); + destroy_component(arrow0); + destroy_component(arrow1); + mounted = false; + run_all(dispose); + } + }; +} + +function instance$2($$self, $$props, $$invalidate) { + + let { displayedMonth } = $$props; + let { today } = $$props; + let { resetDisplayedMonth } = $$props; + let { incrementDisplayedMonth } = $$props; + let { decrementDisplayedMonth } = $$props; + + // Get the word 'Today' but localized to the current language + const todayDisplayStr = today.calendar().split(/\d|\s/)[0]; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let isMobile = window.app.isMobile; + + $$self.$$set = $$props => { + if ("displayedMonth" in $$props) $$invalidate(0, displayedMonth = $$props.displayedMonth); + if ("today" in $$props) $$invalidate(6, today = $$props.today); + if ("resetDisplayedMonth" in $$props) $$invalidate(1, resetDisplayedMonth = $$props.resetDisplayedMonth); + if ("incrementDisplayedMonth" in $$props) $$invalidate(2, incrementDisplayedMonth = $$props.incrementDisplayedMonth); + if ("decrementDisplayedMonth" in $$props) $$invalidate(3, decrementDisplayedMonth = $$props.decrementDisplayedMonth); + }; + + return [ + displayedMonth, + resetDisplayedMonth, + incrementDisplayedMonth, + decrementDisplayedMonth, + todayDisplayStr, + isMobile, + today + ]; +} + +class Nav extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-1vwr9dd-style")) add_css$2(); + + init(this, options, instance$2, create_fragment$2, safe_not_equal, { + displayedMonth: 0, + today: 6, + resetDisplayedMonth: 1, + incrementDisplayedMonth: 2, + decrementDisplayedMonth: 3 + }); + } +} + +/* src/components/WeekNum.svelte generated by Svelte v3.35.0 */ + +function add_css$1() { + var style = element("style"); + style.id = "svelte-egt0yd-style"; + style.textContent = "td.svelte-egt0yd{border-right:1px solid var(--background-modifier-border)}.week-num.svelte-egt0yd{background-color:var(--color-background-weeknum);border-radius:4px;color:var(--color-text-weeknum);cursor:pointer;font-size:0.65em;height:100%;padding:4px;text-align:center;transition:background-color 0.1s ease-in, color 0.1s ease-in;vertical-align:baseline}.week-num.svelte-egt0yd:hover{background-color:var(--interactive-hover)}.week-num.active.svelte-egt0yd:hover{background-color:var(--interactive-accent-hover)}.active.svelte-egt0yd{color:var(--text-on-accent);background-color:var(--interactive-accent)}.dot-container.svelte-egt0yd{display:flex;flex-wrap:wrap;justify-content:center;line-height:6px;min-height:6px}"; + append(document.head, style); +} + +function get_each_context$1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[11] = list[i]; + return child_ctx; +} + +// (35:8) {#each metadata.dots as dot} +function create_each_block$1(ctx) { + let dot; + let current; + const dot_spread_levels = [/*dot*/ ctx[11]]; + let dot_props = {}; + + for (let i = 0; i < dot_spread_levels.length; i += 1) { + dot_props = assign(dot_props, dot_spread_levels[i]); + } + + dot = new Dot({ props: dot_props }); + + return { + c() { + create_component(dot.$$.fragment); + }, + m(target, anchor) { + mount_component(dot, target, anchor); + current = true; + }, + p(ctx, dirty) { + const dot_changes = (dirty & /*metadata*/ 64) + ? get_spread_update(dot_spread_levels, [get_spread_object(/*dot*/ ctx[11])]) + : {}; + + dot.$set(dot_changes); + }, + i(local) { + if (current) return; + transition_in(dot.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(dot.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(dot, detaching); + } + }; +} + +// (24:2) +function create_default_slot(ctx) { + let div1; + let t0; + let t1; + let div0; + let div1_class_value; + let current; + let mounted; + let dispose; + let each_value = /*metadata*/ ctx[6].dots; + let each_blocks = []; + + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i)); + } + + const out = i => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + + return { + c() { + div1 = element("div"); + t0 = text(/*weekNum*/ ctx[0]); + t1 = space(); + div0 = element("div"); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + attr(div0, "class", "dot-container svelte-egt0yd"); + attr(div1, "class", div1_class_value = "" + (null_to_empty(`week-num ${/*metadata*/ ctx[6].classes.join(" ")}`) + " svelte-egt0yd")); + toggle_class(div1, "active", /*selectedId*/ ctx[5] === getDateUID_1(/*days*/ ctx[1][0], "week")); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, t0); + append(div1, t1); + append(div1, div0); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div0, null); + } + + current = true; + + if (!mounted) { + dispose = [ + listen(div1, "click", function () { + if (is_function(/*onClick*/ ctx[3] && /*click_handler*/ ctx[8])) (/*onClick*/ ctx[3] && /*click_handler*/ ctx[8]).apply(this, arguments); + }), + listen(div1, "contextmenu", function () { + if (is_function(/*onContextMenu*/ ctx[4] && /*contextmenu_handler*/ ctx[9])) (/*onContextMenu*/ ctx[4] && /*contextmenu_handler*/ ctx[9]).apply(this, arguments); + }), + listen(div1, "pointerover", function () { + if (is_function(/*onHover*/ ctx[2] && /*pointerover_handler*/ ctx[10])) (/*onHover*/ ctx[2] && /*pointerover_handler*/ ctx[10]).apply(this, arguments); + }) + ]; + + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (!current || dirty & /*weekNum*/ 1) set_data(t0, /*weekNum*/ ctx[0]); + + if (dirty & /*metadata*/ 64) { + each_value = /*metadata*/ ctx[6].dots; + let i; + + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context$1(ctx, each_value, i); + + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block$1(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div0, null); + } + } + + group_outros(); + + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + + check_outros(); + } + + if (!current || dirty & /*metadata*/ 64 && div1_class_value !== (div1_class_value = "" + (null_to_empty(`week-num ${/*metadata*/ ctx[6].classes.join(" ")}`) + " svelte-egt0yd"))) { + attr(div1, "class", div1_class_value); + } + + if (dirty & /*metadata, selectedId, getDateUID, days*/ 98) { + toggle_class(div1, "active", /*selectedId*/ ctx[5] === getDateUID_1(/*days*/ ctx[1][0], "week")); + } + }, + i(local) { + if (current) return; + + for (let i = 0; i < each_value.length; i += 1) { + 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) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(div1); + destroy_each(each_blocks, detaching); + mounted = false; + run_all(dispose); + } + }; +} + +function create_fragment$1(ctx) { + let td; + let metadataresolver; + let current; + + metadataresolver = new MetadataResolver({ + props: { + metadata: /*metadata*/ ctx[6], + $$slots: { + default: [ + create_default_slot, + ({ metadata }) => ({ 6: metadata }), + ({ metadata }) => metadata ? 64 : 0 + ] + }, + $$scope: { ctx } + } + }); + + return { + c() { + td = element("td"); + create_component(metadataresolver.$$.fragment); + attr(td, "class", "svelte-egt0yd"); + }, + m(target, anchor) { + insert(target, td, anchor); + mount_component(metadataresolver, td, null); + current = true; + }, + p(ctx, [dirty]) { + const metadataresolver_changes = {}; + if (dirty & /*metadata*/ 64) metadataresolver_changes.metadata = /*metadata*/ ctx[6]; + + if (dirty & /*$$scope, metadata, selectedId, days, onClick, startOfWeek, onContextMenu, onHover, weekNum*/ 16639) { + metadataresolver_changes.$$scope = { dirty, ctx }; + } + + metadataresolver.$set(metadataresolver_changes); + }, + i(local) { + if (current) return; + transition_in(metadataresolver.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(metadataresolver.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(td); + destroy_component(metadataresolver); + } + }; +} + +function instance$1($$self, $$props, $$invalidate) { + + + let { weekNum } = $$props; + let { days } = $$props; + let { metadata } = $$props; + let { onHover } = $$props; + let { onClick } = $$props; + let { onContextMenu } = $$props; + let { selectedId = null } = $$props; + let startOfWeek; + const click_handler = e => onClick(startOfWeek, isMetaPressed(e)); + const contextmenu_handler = e => onContextMenu(days[0], e); + const pointerover_handler = e => onHover(startOfWeek, e.target, isMetaPressed(e)); + + $$self.$$set = $$props => { + if ("weekNum" in $$props) $$invalidate(0, weekNum = $$props.weekNum); + if ("days" in $$props) $$invalidate(1, days = $$props.days); + if ("metadata" in $$props) $$invalidate(6, metadata = $$props.metadata); + if ("onHover" in $$props) $$invalidate(2, onHover = $$props.onHover); + if ("onClick" in $$props) $$invalidate(3, onClick = $$props.onClick); + if ("onContextMenu" in $$props) $$invalidate(4, onContextMenu = $$props.onContextMenu); + if ("selectedId" in $$props) $$invalidate(5, selectedId = $$props.selectedId); + }; + + $$self.$$.update = () => { + if ($$self.$$.dirty & /*days*/ 2) { + $$invalidate(7, startOfWeek = getStartOfWeek(days)); + } + }; + + return [ + weekNum, + days, + onHover, + onClick, + onContextMenu, + selectedId, + metadata, + startOfWeek, + click_handler, + contextmenu_handler, + pointerover_handler + ]; +} + +class WeekNum extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-egt0yd-style")) add_css$1(); + + init(this, options, instance$1, create_fragment$1, not_equal, { + weekNum: 0, + days: 1, + metadata: 6, + onHover: 2, + onClick: 3, + onContextMenu: 4, + selectedId: 5 + }); + } +} + +async function metadataReducer(promisedMetadata) { + const meta = { + dots: [], + classes: [], + dataAttributes: {}, + }; + const metas = await Promise.all(promisedMetadata); + return metas.reduce((acc, meta) => ({ + classes: [...acc.classes, ...(meta.classes || [])], + dataAttributes: Object.assign(acc.dataAttributes, meta.dataAttributes), + dots: [...acc.dots, ...(meta.dots || [])], + }), meta); +} +function getDailyMetadata(sources, date, ..._args) { + return metadataReducer(sources.map((source) => source.getDailyMetadata(date))); +} +function getWeeklyMetadata(sources, date, ..._args) { + return metadataReducer(sources.map((source) => source.getWeeklyMetadata(date))); +} + +/* src/components/Calendar.svelte generated by Svelte v3.35.0 */ + +function add_css() { + var style = element("style"); + style.id = "svelte-pcimu8-style"; + style.textContent = ".container.svelte-pcimu8{--color-background-heading:transparent;--color-background-day:transparent;--color-background-weeknum:transparent;--color-background-weekend:transparent;--color-dot:var(--text-muted);--color-arrow:var(--text-muted);--color-button:var(--text-muted);--color-text-title:var(--text-normal);--color-text-heading:var(--text-muted);--color-text-day:var(--text-normal);--color-text-today:var(--interactive-accent);--color-text-weeknum:var(--text-muted)}.container.svelte-pcimu8{padding:0 8px}.container.is-mobile.svelte-pcimu8{padding:0}th.svelte-pcimu8{text-align:center}.weekend.svelte-pcimu8{background-color:var(--color-background-weekend)}.calendar.svelte-pcimu8{border-collapse:collapse;width:100%}th.svelte-pcimu8{background-color:var(--color-background-heading);color:var(--color-text-heading);font-size:0.6em;letter-spacing:1px;padding:4px;text-transform:uppercase}"; + append(document.head, style); +} + +function get_each_context(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[18] = list[i]; + return child_ctx; +} + +function get_each_context_1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[21] = list[i]; + return child_ctx; +} + +function get_each_context_2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[24] = list[i]; + return child_ctx; +} + +function get_each_context_3(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[27] = list[i]; + return child_ctx; +} + +// (55:6) {#if showWeekNums} +function create_if_block_2(ctx) { + let col; + + return { + c() { + col = element("col"); + }, + m(target, anchor) { + insert(target, col, anchor); + }, + d(detaching) { + if (detaching) detach(col); + } + }; +} + +// (58:6) {#each month[1].days as date} +function create_each_block_3(ctx) { + let col; + + return { + c() { + col = element("col"); + attr(col, "class", "svelte-pcimu8"); + toggle_class(col, "weekend", isWeekend(/*date*/ ctx[27])); + }, + m(target, anchor) { + insert(target, col, anchor); + }, + p(ctx, dirty) { + if (dirty & /*isWeekend, month*/ 16384) { + toggle_class(col, "weekend", isWeekend(/*date*/ ctx[27])); + } + }, + d(detaching) { + if (detaching) detach(col); + } + }; +} + +// (64:8) {#if showWeekNums} +function create_if_block_1(ctx) { + let th; + + return { + c() { + th = element("th"); + th.textContent = "W"; + attr(th, "class", "svelte-pcimu8"); + }, + m(target, anchor) { + insert(target, th, anchor); + }, + d(detaching) { + if (detaching) detach(th); + } + }; +} + +// (67:8) {#each daysOfWeek as dayOfWeek} +function create_each_block_2(ctx) { + let th; + let t_value = /*dayOfWeek*/ ctx[24] + ""; + let t; + + return { + c() { + th = element("th"); + t = text(t_value); + attr(th, "class", "svelte-pcimu8"); + }, + m(target, anchor) { + insert(target, th, anchor); + append(th, t); + }, + p(ctx, dirty) { + if (dirty & /*daysOfWeek*/ 32768 && t_value !== (t_value = /*dayOfWeek*/ ctx[24] + "")) set_data(t, t_value); + }, + d(detaching) { + if (detaching) detach(th); + } + }; +} + +// (75:10) {#if showWeekNums} +function create_if_block(ctx) { + let weeknum; + let current; + + const weeknum_spread_levels = [ + /*week*/ ctx[18], + { + metadata: getWeeklyMetadata(/*sources*/ ctx[8], /*week*/ ctx[18].days[0], /*today*/ ctx[10]) + }, + { onClick: /*onClickWeek*/ ctx[7] }, + { + onContextMenu: /*onContextMenuWeek*/ ctx[5] + }, + { onHover: /*onHoverWeek*/ ctx[3] }, + { selectedId: /*selectedId*/ ctx[9] } + ]; + + let weeknum_props = {}; + + for (let i = 0; i < weeknum_spread_levels.length; i += 1) { + weeknum_props = assign(weeknum_props, weeknum_spread_levels[i]); + } + + weeknum = new WeekNum({ props: weeknum_props }); + + return { + c() { + create_component(weeknum.$$.fragment); + }, + m(target, anchor) { + mount_component(weeknum, target, anchor); + current = true; + }, + p(ctx, dirty) { + const weeknum_changes = (dirty & /*month, getWeeklyMetadata, sources, today, onClickWeek, onContextMenuWeek, onHoverWeek, selectedId*/ 18344) + ? get_spread_update(weeknum_spread_levels, [ + dirty & /*month*/ 16384 && get_spread_object(/*week*/ ctx[18]), + dirty & /*getWeeklyMetadata, sources, month, today*/ 17664 && { + metadata: getWeeklyMetadata(/*sources*/ ctx[8], /*week*/ ctx[18].days[0], /*today*/ ctx[10]) + }, + dirty & /*onClickWeek*/ 128 && { onClick: /*onClickWeek*/ ctx[7] }, + dirty & /*onContextMenuWeek*/ 32 && { + onContextMenu: /*onContextMenuWeek*/ ctx[5] + }, + dirty & /*onHoverWeek*/ 8 && { onHover: /*onHoverWeek*/ ctx[3] }, + dirty & /*selectedId*/ 512 && { selectedId: /*selectedId*/ ctx[9] } + ]) + : {}; + + weeknum.$set(weeknum_changes); + }, + i(local) { + if (current) return; + transition_in(weeknum.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(weeknum.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(weeknum, detaching); + } + }; +} + +// (85:10) {#each week.days as day (day.format())} +function create_each_block_1(key_1, ctx) { + let first; + let day; + let current; + + day = new Day({ + props: { + date: /*day*/ ctx[21], + today: /*today*/ ctx[10], + displayedMonth: /*displayedMonth*/ ctx[0], + onClick: /*onClickDay*/ ctx[6], + onContextMenu: /*onContextMenuDay*/ ctx[4], + onHover: /*onHoverDay*/ ctx[2], + metadata: getDailyMetadata(/*sources*/ ctx[8], /*day*/ ctx[21], /*today*/ ctx[10]), + selectedId: /*selectedId*/ ctx[9] + } + }); + + return { + key: key_1, + first: null, + c() { + first = empty(); + create_component(day.$$.fragment); + this.first = first; + }, + m(target, anchor) { + insert(target, first, anchor); + mount_component(day, target, anchor); + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + const day_changes = {}; + if (dirty & /*month*/ 16384) day_changes.date = /*day*/ ctx[21]; + if (dirty & /*today*/ 1024) day_changes.today = /*today*/ ctx[10]; + if (dirty & /*displayedMonth*/ 1) day_changes.displayedMonth = /*displayedMonth*/ ctx[0]; + if (dirty & /*onClickDay*/ 64) day_changes.onClick = /*onClickDay*/ ctx[6]; + if (dirty & /*onContextMenuDay*/ 16) day_changes.onContextMenu = /*onContextMenuDay*/ ctx[4]; + if (dirty & /*onHoverDay*/ 4) day_changes.onHover = /*onHoverDay*/ ctx[2]; + if (dirty & /*sources, month, today*/ 17664) day_changes.metadata = getDailyMetadata(/*sources*/ ctx[8], /*day*/ ctx[21], /*today*/ ctx[10]); + if (dirty & /*selectedId*/ 512) day_changes.selectedId = /*selectedId*/ ctx[9]; + day.$set(day_changes); + }, + i(local) { + if (current) return; + transition_in(day.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(day.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) detach(first); + destroy_component(day, detaching); + } + }; +} + +// (73:6) {#each month as week (week.weekNum)} +function create_each_block(key_1, ctx) { + let tr; + let t0; + let each_blocks = []; + let each_1_lookup = new Map(); + let t1; + let current; + let if_block = /*showWeekNums*/ ctx[1] && create_if_block(ctx); + let each_value_1 = /*week*/ ctx[18].days; + const get_key = ctx => /*day*/ ctx[21].format(); + + for (let i = 0; i < each_value_1.length; i += 1) { + let child_ctx = get_each_context_1(ctx, each_value_1, i); + let key = get_key(child_ctx); + each_1_lookup.set(key, each_blocks[i] = create_each_block_1(key, child_ctx)); + } + + return { + key: key_1, + first: null, + c() { + tr = element("tr"); + if (if_block) if_block.c(); + t0 = space(); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + t1 = space(); + this.first = tr; + }, + m(target, anchor) { + insert(target, tr, anchor); + if (if_block) if_block.m(tr, null); + append(tr, t0); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(tr, null); + } + + append(tr, t1); + current = true; + }, + p(new_ctx, dirty) { + ctx = new_ctx; + + if (/*showWeekNums*/ ctx[1]) { + if (if_block) { + if_block.p(ctx, dirty); + + if (dirty & /*showWeekNums*/ 2) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block(ctx); + if_block.c(); + transition_in(if_block, 1); + if_block.m(tr, t0); + } + } else if (if_block) { + group_outros(); + + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + + check_outros(); + } + + if (dirty & /*month, today, displayedMonth, onClickDay, onContextMenuDay, onHoverDay, getDailyMetadata, sources, selectedId*/ 18261) { + each_value_1 = /*week*/ ctx[18].days; + group_outros(); + each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value_1, each_1_lookup, tr, outro_and_destroy_block, create_each_block_1, t1, get_each_context_1); + check_outros(); + } + }, + i(local) { + if (current) return; + transition_in(if_block); + + for (let i = 0; i < each_value_1.length; i += 1) { + transition_in(each_blocks[i]); + } + + current = true; + }, + o(local) { + transition_out(if_block); + + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(tr); + if (if_block) if_block.d(); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].d(); + } + } + }; +} + +function create_fragment(ctx) { + let div; + let nav; + let t0; + let table; + let colgroup; + let t1; + let t2; + let thead; + let tr; + let t3; + let t4; + let tbody; + let each_blocks = []; + let each2_lookup = new Map(); + let current; + + nav = new Nav({ + props: { + today: /*today*/ ctx[10], + displayedMonth: /*displayedMonth*/ ctx[0], + incrementDisplayedMonth: /*incrementDisplayedMonth*/ ctx[11], + decrementDisplayedMonth: /*decrementDisplayedMonth*/ ctx[12], + resetDisplayedMonth: /*resetDisplayedMonth*/ ctx[13] + } + }); + + let if_block0 = /*showWeekNums*/ ctx[1] && create_if_block_2(); + let each_value_3 = /*month*/ ctx[14][1].days; + let each_blocks_2 = []; + + for (let i = 0; i < each_value_3.length; i += 1) { + each_blocks_2[i] = create_each_block_3(get_each_context_3(ctx, each_value_3, i)); + } + + let if_block1 = /*showWeekNums*/ ctx[1] && create_if_block_1(); + let each_value_2 = /*daysOfWeek*/ ctx[15]; + let each_blocks_1 = []; + + for (let i = 0; i < each_value_2.length; i += 1) { + each_blocks_1[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i)); + } + + let each_value = /*month*/ ctx[14]; + const get_key = ctx => /*week*/ ctx[18].weekNum; + + for (let i = 0; i < each_value.length; i += 1) { + let child_ctx = get_each_context(ctx, each_value, i); + let key = get_key(child_ctx); + each2_lookup.set(key, each_blocks[i] = create_each_block(key, child_ctx)); + } + + return { + c() { + div = element("div"); + create_component(nav.$$.fragment); + t0 = space(); + table = element("table"); + colgroup = element("colgroup"); + if (if_block0) if_block0.c(); + t1 = space(); + + for (let i = 0; i < each_blocks_2.length; i += 1) { + each_blocks_2[i].c(); + } + + t2 = space(); + thead = element("thead"); + tr = element("tr"); + if (if_block1) if_block1.c(); + t3 = space(); + + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].c(); + } + + t4 = space(); + tbody = element("tbody"); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + + attr(table, "class", "calendar svelte-pcimu8"); + attr(div, "id", "calendar-container"); + attr(div, "class", "container svelte-pcimu8"); + toggle_class(div, "is-mobile", /*isMobile*/ ctx[16]); + }, + m(target, anchor) { + insert(target, div, anchor); + mount_component(nav, div, null); + append(div, t0); + append(div, table); + append(table, colgroup); + if (if_block0) if_block0.m(colgroup, null); + append(colgroup, t1); + + for (let i = 0; i < each_blocks_2.length; i += 1) { + each_blocks_2[i].m(colgroup, null); + } + + append(table, t2); + append(table, thead); + append(thead, tr); + if (if_block1) if_block1.m(tr, null); + append(tr, t3); + + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].m(tr, null); + } + + append(table, t4); + append(table, tbody); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(tbody, null); + } + + current = true; + }, + p(ctx, [dirty]) { + const nav_changes = {}; + if (dirty & /*today*/ 1024) nav_changes.today = /*today*/ ctx[10]; + if (dirty & /*displayedMonth*/ 1) nav_changes.displayedMonth = /*displayedMonth*/ ctx[0]; + nav.$set(nav_changes); + + if (/*showWeekNums*/ ctx[1]) { + if (if_block0) ; else { + if_block0 = create_if_block_2(); + if_block0.c(); + if_block0.m(colgroup, t1); + } + } else if (if_block0) { + if_block0.d(1); + if_block0 = null; + } + + if (dirty & /*isWeekend, month*/ 16384) { + each_value_3 = /*month*/ ctx[14][1].days; + let i; + + for (i = 0; i < each_value_3.length; i += 1) { + const child_ctx = get_each_context_3(ctx, each_value_3, i); + + if (each_blocks_2[i]) { + each_blocks_2[i].p(child_ctx, dirty); + } else { + each_blocks_2[i] = create_each_block_3(child_ctx); + each_blocks_2[i].c(); + each_blocks_2[i].m(colgroup, null); + } + } + + for (; i < each_blocks_2.length; i += 1) { + each_blocks_2[i].d(1); + } + + each_blocks_2.length = each_value_3.length; + } + + if (/*showWeekNums*/ ctx[1]) { + if (if_block1) ; else { + if_block1 = create_if_block_1(); + if_block1.c(); + if_block1.m(tr, t3); + } + } else if (if_block1) { + if_block1.d(1); + if_block1 = null; + } + + if (dirty & /*daysOfWeek*/ 32768) { + each_value_2 = /*daysOfWeek*/ ctx[15]; + let i; + + for (i = 0; i < each_value_2.length; i += 1) { + const child_ctx = get_each_context_2(ctx, each_value_2, i); + + if (each_blocks_1[i]) { + each_blocks_1[i].p(child_ctx, dirty); + } else { + each_blocks_1[i] = create_each_block_2(child_ctx); + each_blocks_1[i].c(); + each_blocks_1[i].m(tr, null); + } + } + + for (; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].d(1); + } + + each_blocks_1.length = each_value_2.length; + } + + if (dirty & /*month, today, displayedMonth, onClickDay, onContextMenuDay, onHoverDay, getDailyMetadata, sources, selectedId, getWeeklyMetadata, onClickWeek, onContextMenuWeek, onHoverWeek, showWeekNums*/ 18431) { + each_value = /*month*/ ctx[14]; + group_outros(); + each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx, each_value, each2_lookup, tbody, outro_and_destroy_block, create_each_block, null, get_each_context); + check_outros(); + } + }, + i(local) { + if (current) return; + transition_in(nav.$$.fragment, local); + + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + + current = true; + }, + o(local) { + transition_out(nav.$$.fragment, local); + + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + + current = false; + }, + d(detaching) { + if (detaching) detach(div); + destroy_component(nav); + if (if_block0) if_block0.d(); + destroy_each(each_blocks_2, detaching); + if (if_block1) if_block1.d(); + destroy_each(each_blocks_1, detaching); + + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].d(); + } + } + }; +} + +function instance($$self, $$props, $$invalidate) { + + + let { localeData } = $$props; + let { showWeekNums = false } = $$props; + let { onHoverDay } = $$props; + let { onHoverWeek } = $$props; + let { onContextMenuDay } = $$props; + let { onContextMenuWeek } = $$props; + let { onClickDay } = $$props; + let { onClickWeek } = $$props; + let { sources = [] } = $$props; + let { selectedId } = $$props; + let { today = window.moment() } = $$props; + let { displayedMonth = today } = $$props; + let month; + let daysOfWeek; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let isMobile = window.app.isMobile; + + function incrementDisplayedMonth() { + $$invalidate(0, displayedMonth = displayedMonth.clone().add(1, "month")); + } + + function decrementDisplayedMonth() { + $$invalidate(0, displayedMonth = displayedMonth.clone().subtract(1, "month")); + } + + function resetDisplayedMonth() { + $$invalidate(0, displayedMonth = today.clone()); + } + + $$self.$$set = $$props => { + if ("localeData" in $$props) $$invalidate(17, localeData = $$props.localeData); + if ("showWeekNums" in $$props) $$invalidate(1, showWeekNums = $$props.showWeekNums); + if ("onHoverDay" in $$props) $$invalidate(2, onHoverDay = $$props.onHoverDay); + if ("onHoverWeek" in $$props) $$invalidate(3, onHoverWeek = $$props.onHoverWeek); + if ("onContextMenuDay" in $$props) $$invalidate(4, onContextMenuDay = $$props.onContextMenuDay); + if ("onContextMenuWeek" in $$props) $$invalidate(5, onContextMenuWeek = $$props.onContextMenuWeek); + if ("onClickDay" in $$props) $$invalidate(6, onClickDay = $$props.onClickDay); + if ("onClickWeek" in $$props) $$invalidate(7, onClickWeek = $$props.onClickWeek); + if ("sources" in $$props) $$invalidate(8, sources = $$props.sources); + if ("selectedId" in $$props) $$invalidate(9, selectedId = $$props.selectedId); + if ("today" in $$props) $$invalidate(10, today = $$props.today); + if ("displayedMonth" in $$props) $$invalidate(0, displayedMonth = $$props.displayedMonth); + }; + + $$self.$$.update = () => { + if ($$self.$$.dirty & /*displayedMonth, localeData*/ 131073) { + $$invalidate(14, month = getMonth(displayedMonth, localeData)); + } + + if ($$self.$$.dirty & /*today, localeData*/ 132096) { + $$invalidate(15, daysOfWeek = getDaysOfWeek(today, localeData)); + } + }; + + return [ + displayedMonth, + showWeekNums, + onHoverDay, + onHoverWeek, + onContextMenuDay, + onContextMenuWeek, + onClickDay, + onClickWeek, + sources, + selectedId, + today, + incrementDisplayedMonth, + decrementDisplayedMonth, + resetDisplayedMonth, + month, + daysOfWeek, + isMobile, + localeData + ]; +} + +class Calendar extends SvelteComponent { + constructor(options) { + super(); + if (!document.getElementById("svelte-pcimu8-style")) add_css(); + + init(this, options, instance, create_fragment, not_equal, { + localeData: 17, + showWeekNums: 1, + onHoverDay: 2, + onHoverWeek: 3, + onContextMenuDay: 4, + onContextMenuWeek: 5, + onClickDay: 6, + onClickWeek: 7, + sources: 8, + selectedId: 9, + today: 10, + displayedMonth: 0, + incrementDisplayedMonth: 11, + decrementDisplayedMonth: 12, + resetDisplayedMonth: 13 + }); + } + + get incrementDisplayedMonth() { + return this.$$.ctx[11]; + } + + get decrementDisplayedMonth() { + return this.$$.ctx[12]; + } + + get resetDisplayedMonth() { + return this.$$.ctx[13]; + } +} + +/** Generic code for embedded Dataviews. */ +class DataviewRefreshableRenderer extends obsidian.MarkdownRenderChild { + container; + index; + app; + settings; + lastReload; + constructor(container, index, app, settings) { + super(container); + this.container = container; + this.index = index; + this.app = app; + this.settings = settings; + this.lastReload = 0; + } + onload() { + this.render(); + this.lastReload = this.index.revision; + // Refresh after index changes stop. + this.registerEvent(this.app.workspace.on("dataview:refresh-views", this.maybeRefresh)); + // ...or when the DOM is shown (sidebar expands, tab selected, nodes scrolled into view). + this.register(this.container.onNodeInserted(this.maybeRefresh)); + } + maybeRefresh = () => { + // If the index revision has changed recently, then queue a reload. + // But only if we're mounted in the DOM and auto-refreshing is active. + if (this.lastReload != this.index.revision && this.container.isShown() && this.settings.refreshEnabled) { + this.lastReload = this.index.revision; + this.render(); + } + }; +} + +class DataviewCalendarRenderer extends DataviewRefreshableRenderer { + query; + container; + index; + origin; + settings; + app; + calendar; + constructor(query, container, index, origin, settings, app) { + super(container, index, app, settings); + this.query = query; + this.container = container; + this.index = index; + this.origin = origin; + this.settings = settings; + this.app = app; + } + async render() { + this.container.innerHTML = ""; + let maybeResult = await asyncTryOrPropagate(() => executeCalendar(this.query, this.index, this.origin, this.settings)); + if (!maybeResult.successful) { + renderErrorPre(this.container, "Dataview: " + maybeResult.error); + return; + } + else if (maybeResult.value.data.length == 0 && this.settings.warnOnEmptyResult) { + renderErrorPre(this.container, "Dataview: Query returned 0 results."); + return; + } + let dateMap = new Map(); + for (let data of maybeResult.value.data) { + const dot = { + color: "default", + className: "note", + isFilled: true, + link: data.link, + }; + const d = data.date.toFormat("yyyyLLdd"); + if (!dateMap.has(d)) { + dateMap.set(d, [dot]); + } + else { + dateMap.get(d)?.push(dot); + } + } + const querySource = { + getDailyMetadata: async (date) => { + return { + dots: dateMap.get(date.format("YYYYMMDD")) || [], + }; + }, + }; + const sources = [querySource]; + const renderer = this; + this.calendar = new Calendar({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + target: this.container, + props: { + onHoverDay(date, targetEl) { + const vals = dateMap.get(date.format("YYYYMMDD")); + if (!vals || vals.length == 0) { + return; + } + if (vals?.length == 0) { + return; + } + renderer.app.workspace.trigger("link-hover", {}, targetEl, vals[0].link.path, vals[0].link.path); + }, + onClickDay: async (date) => { + const vals = dateMap.get(date.format("YYYYMMDD")); + if (!vals || vals.length == 0) { + return; + } + if (vals?.length == 0) { + return; + } + const file = renderer.app.metadataCache.getFirstLinkpathDest(vals[0].link.path, ""); + if (file == null) { + return; + } + const leaf = renderer.app.workspace.getUnpinnedLeaf(); + await leaf.openFile(file, { active: true }); + }, + showWeekNums: false, + sources, + }, + }); + } + onClose() { + if (this.calendar) { + this.calendar.$destroy(); + } + return Promise.resolve(); + } +} + +/** Fancy wrappers for the JavaScript API, used both by external plugins AND by the dataview javascript view. */ +/** Asynchronous API calls related to file / system IO. */ +class DataviewInlineIOApi { + api; + currentFile; + constructor(api, currentFile) { + this.api = api; + this.currentFile = currentFile; + } + /** Load the contents of a CSV asynchronously, returning a data array of rows (or undefined if it does not exist). */ + async csv(path, originFile) { + return this.api.csv(path, originFile || this.currentFile); + } + /** Asynchronously load the contents of any link or path in an Obsidian vault. */ + async load(path, originFile) { + return this.api.load(path, originFile || this.currentFile); + } + /** Normalize a link or path relative to an optional origin file. Returns a textual fully-qualified-path. */ + normalize(path, originFile) { + return this.api.normalize(path, originFile || this.currentFile); + } +} +class DataviewInlineApi { + /** + * The raw dataview indices, which track file <-> metadata relations. Use these if the intuitive API does not support + * your use case. + */ + index; + /** The component that handles the lifetime of this view. Use it if you are adding custom event handlers/components. */ + component; + /** The path to the current file this script is running in. */ + currentFilePath; + /** + * The container which holds the output of this view. You can directly append fields to this, if you wish, though + * the rendering API is likely to be easier for straight-forward purposes. + */ + container; + /** Directly access the Obsidian app object, such as for reaching out to other plugins. */ + app; + /** The general plugin API which much of this inline API delegates to. */ + api; + /** Settings which determine defaults, incl. many rendering options. */ + settings; + /** Evaluation context which expressions can be evaluated in. */ + evaluationContext; + /** Value utilities which allow for type-checking and comparisons. */ + value = Values; + /** Widget utility functions for creating built-in widgets. */ + widget = Widgets; + /** IO utilities which are largely asynchronous. */ + io; + /** Re-exporting of luxon for people who can't easily require it. Sorry! */ + luxon = Luxon; + /** Dataview functions which can be called from DataviewJS. */ + func; + constructor(api, component, container, currentFilePath) { + this.index = api.index; + this.app = api.app; + this.settings = api.settings; + this.component = component; + this.container = container; + this.currentFilePath = currentFilePath; + this.api = api; + this.io = new DataviewInlineIOApi(this.api.io, this.currentFilePath); + // Set up the evaluation context with variables from the current file. + let fileMeta = this.index.pages.get(this.currentFilePath)?.serialize(this.index) ?? {}; + this.evaluationContext = new Context(defaultLinkHandler(this.index, this.currentFilePath), this.settings, { + this: fileMeta, + }); + this.func = Functions.bindAll(DEFAULT_FUNCTIONS, this.evaluationContext); + } + ///////////////////////////// + // Index + Data Collection // + ///////////////////////////// + /** Return an array of paths (as strings) corresponding to pages which match the query. */ + pagePaths(query) { + return this.api.pagePaths(query, this.currentFilePath); + } + /** Map a page path to the actual data contained within that page. */ + page(path) { + return this.api.page(path, this.currentFilePath); + } + /** Return an array of page objects corresponding to pages which match the query. */ + pages(query) { + return this.api.pages(query, this.currentFilePath); + } + /** Return the information about the current page. */ + current() { + return this.page(this.currentFilePath); + } + /////////////////////////////// + // Dataview Query Evaluation // + /////////////////////////////// + /** Execute a Dataview query, returning the results in programmatic form. */ + async query(source, originFile, settings) { + return this.api.query(source, originFile ?? this.currentFilePath, settings); + } + /** Error-throwing version of {@link query}. */ + async tryQuery(source, originFile, settings) { + return this.api.tryQuery(source, originFile ?? this.currentFilePath, settings); + } + /** Execute a Dataview query, returning the results in Markdown. */ + async queryMarkdown(source, originFile, settings) { + return this.api.queryMarkdown(source, originFile ?? this.currentFilePath, settings); + } + /** Error-throwing version of {@link queryMarkdown}. */ + async tryQueryMarkdown(source, originFile, settings) { + return this.api.tryQueryMarkdown(source, originFile ?? this.currentFilePath, settings); + } + /** + * Evaluate a dataview expression (like '2 + 2' or 'link("hello")'), returning the evaluated result. + * This takes an optional second argument which provides definitions for variables, such as: + * + * ``` + * dv.evaluate("x + 6", { x: 2 }) = 8 + * dv.evaluate('link(target)', { target: "Okay" }) = [[Okay]] + * ``` + * + * Note that `this` is implicitly available and refers to the current file. + * + * This method returns a Result type instead of throwing an error; you can check the result of the + * execution via `result.successful` and obtain `result.value` or `result.error` accordingly. If + * you'd rather this method throw on an error, use `dv.tryEvaluate`. + */ + evaluate(expression, context) { + let field = EXPRESSION.field.parse(expression); + if (!field.status) + return Result.failure(`Failed to parse expression "${expression}"`); + return this.evaluationContext.evaluate(field.value, context); + } + /** Error-throwing version of `dv.evaluate`. */ + tryEvaluate(expression, context) { + return this.evaluate(expression, context).orElseThrow(); + } + /** Execute a Dataview query and embed it into the current view. */ + async execute(source) { + this.api.execute(source, this.container, this.component, this.currentFilePath); + } + /** Execute a DataviewJS query and embed it into the current view. */ + async executeJs(code) { + this.api.executeJs(code, this.container, this.component, this.currentFilePath); + } + ///////////// + // Utility // + ///////////// + /** + * Convert an input element or array into a Dataview data-array. If the input is already a data array, + * it is returned unchanged. + */ + array(raw) { + return this.api.array(raw); + } + /** Return true if the given value is a javascript array OR a dataview data array. */ + isArray(raw) { + return this.api.isArray(raw); + } + /** Return true if the given value is a dataview data array; this returns FALSE for plain JS arrays. */ + isDataArray(raw) { + return DataArray.isDataArray(raw); + } + /** Create a dataview file link to the given path. */ + fileLink(path, embed = false, display) { + return Link.file(path, embed, display); + } + /** Create a dataview section link to the given path. */ + sectionLink(path, section, embed = false, display) { + return Link.header(path, section, embed, display); + } + /** Create a dataview block link to the given path. */ + blockLink(path, blockId, embed = false, display) { + return Link.block(path, blockId, embed, display); + } + /** Attempt to extract a date from a string, link or date. */ + date(pathlike) { + return this.api.date(pathlike); + } + /** Attempt to extract a duration from a string or duration. */ + duration(dur) { + return this.api.duration(dur); + } + /** Parse a raw textual value into a complex Dataview type, if possible. */ + parse(value) { + return this.api.parse(value); + } + /** Convert a basic JS type into a Dataview type by parsing dates, links, durations, and so on. */ + literal(value) { + return this.api.literal(value); + } + /** Deep clone the given literal, returning a new literal which is independent of the original. */ + clone(value) { + return Values.deepCopy(value); + } + /** + * Compare two arbitrary JavaScript values using Dataview's default comparison rules. Returns a negative value if + * a < b, 0 if a = b, and a positive value if a > b. + */ + compare(a, b) { + return Values.compareValue(a, b); + } + /** Return true if the two given JavaScript values are equal using Dataview's default comparison rules. */ + equal(a, b) { + return this.compare(a, b) == 0; + } + ///////////////////////// + // Rendering Functions // + ///////////////////////// + /** Render an HTML element, containing arbitrary text. */ + el(el, text, { container = this.container, ...options } = {}) { + let wrapped = Values.wrapValue(text); + if (wrapped === null || wrapped === undefined) { + return container.createEl(el, Object.assign({ text }, options)); + } + let _el = container.createEl(el, options); + renderValue(this.app, wrapped.value, _el, this.currentFilePath, this.component, this.settings, true); + return _el; + } + /** Render an HTML header; the level can be anything from 1 - 6. */ + header(level, text, options) { + let header = { 1: "h1", 2: "h2", 3: "h3", 4: "h4", 5: "h5", 6: "h6" }[level]; + if (!header) + throw Error(`Unrecognized level '${level}' (expected 1, 2, 3, 4, 5, or 6)`); + return this.el(header, text, options); + } + /** Render an HTML paragraph, containing arbitrary text. */ + paragraph(text, options) { + return this.el("p", text, options); + } + /** Render an inline span, containing arbitrary text. */ + span(text, options) { + return this.el("span", text, options); + } + /** + * Render HTML from the output of a template "view" saved as a file in the vault. + * Takes a filename and arbitrary input data. + */ + async view(viewName, input) { + // Look for `${viewName}.js` first, then for `${viewName}/view.js`. + const simpleViewPath = `${viewName}.js`; + const complexViewPath = `${viewName}/view.js`; + let checkForCss = false; + let cssElement = undefined; + let viewFile = this.app.metadataCache.getFirstLinkpathDest(simpleViewPath, this.currentFilePath); + if (!viewFile) { + viewFile = this.app.metadataCache.getFirstLinkpathDest(complexViewPath, this.currentFilePath); + checkForCss = true; + } + if (!viewFile) { + renderErrorPre(this.container, `Dataview: custom view not found for '${simpleViewPath}' or '${complexViewPath}'.`); + return; + } + if (checkForCss) { + // Check for optional CSS. + let cssFile = this.app.metadataCache.getFirstLinkpathDest(`${viewName}/view.css`, this.currentFilePath); + if (cssFile) { + let cssContents = await this.app.vault.read(cssFile); + cssContents += `\n/*# sourceURL=${location.origin}/${cssFile.path} */`; + cssElement = this.container.createEl("style", { text: cssContents, attr: { scope: " " } }); + } + } + let contents = await this.app.vault.read(viewFile); + if (contents.contains("await")) + contents = "(async () => { " + contents + " })()"; + contents += `\n//# sourceURL=${viewFile.path}`; + let func = new Function("dv", "input", contents); + try { + // This may directly render, in which case it will likely return undefined or null. + let result = await Promise.resolve(func(this, input)); + if (result) + await renderValue(this.app, result, this.container, this.currentFilePath, this.component, this.settings, true); + } + catch (ex) { + if (cssElement) + this.container.removeChild(cssElement); + renderErrorPre(this.container, `Dataview: Failed to execute view '${viewFile.path}'.\n\n${ex}`); + } + } + /** Render a dataview list of the given values. */ + list(values) { + return this.api.list(values, this.container, this.component, this.currentFilePath); + } + /** Render a dataview table with the given headers, and the 2D array of values. */ + table(headers, values) { + return this.api.table(headers, values, this.container, this.component, this.currentFilePath); + } + /** Render a dataview task view with the given tasks. */ + taskList(tasks, groupByFile = true) { + return this.api.taskList(tasks, groupByFile, this.container, this.component, this.currentFilePath); + } + //////////////////////// + // Markdown Rendering // + //////////////////////// + /** Render a table directly to markdown, returning the markdown. */ + markdownTable(headers, values, settings) { + return this.api.markdownTable(headers, values, settings); + } + /** Render a list directly to markdown, returning the markdown. */ + markdownList(values, settings) { + return this.api.markdownList(values, settings); + } + /** Render at ask list directly to markdown, returning the markdown. */ + markdownTaskList(values, settings) { + return this.api.markdownTaskList(values, settings); + } +} +/** + * Evaluate a script where 'this' for the script is set to the given context. Allows you to define global variables. + */ +function evalInContext(script, context) { + return function () { + return eval(script); + }.call(context); +} +/** + * Evaluate a script possibly asynchronously, if the script contains `async/await` blocks. + */ +async function asyncEvalInContext(script, context) { + if (script.includes("await")) { + return evalInContext("(async () => { " + script + " })()", context); + } + else { + return Promise.resolve(evalInContext(script, context)); + } +} + +class DataviewJSRenderer extends DataviewRefreshableRenderer { + api; + script; + container; + origin; + static PREAMBLE = "const dataview = this;const dv = this;"; + constructor(api, script, container, origin) { + super(container, api.index, api.app, api.settings); + this.api = api; + this.script = script; + this.container = container; + this.origin = origin; + } + async render() { + this.container.innerHTML = ""; + if (!this.settings.enableDataviewJs) { + this.containerEl.innerHTML = ""; + renderErrorPre(this.container, "Dataview JS queries are disabled. You can enable them in the Dataview settings."); + return; + } + // Assume that the code is javascript, and try to eval it. + try { + await asyncEvalInContext(DataviewJSRenderer.PREAMBLE + this.script, new DataviewInlineApi(this.api, this, this.container, this.origin)); + } + catch (e) { + this.containerEl.innerHTML = ""; + renderErrorPre(this.container, "Evaluation Error: " + e.stack); + } + } +} +/** Inline JS renderer accessible using '=$' by default. */ +class DataviewInlineJSRenderer extends DataviewRefreshableRenderer { + api; + script; + container; + target; + origin; + static PREAMBLE = "const dataview = this;const dv=this;"; + // The box that the error is rendered in, if relevant. + errorbox; + constructor(api, script, container, target, origin) { + super(container, api.index, api.app, api.settings); + this.api = api; + this.script = script; + this.container = container; + this.target = target; + this.origin = origin; + } + async render() { + this.errorbox?.remove(); + if (!this.settings.enableDataviewJs || !this.settings.enableInlineDataviewJs) { + let temp = document.createElement("span"); + temp.innerText = "(disabled; enable in settings)"; + this.target.replaceWith(temp); + this.target = temp; + return; + } + // Assume that the code is javascript, and try to eval it. + try { + let temp = document.createElement("span"); + let result = await asyncEvalInContext(DataviewInlineJSRenderer.PREAMBLE + this.script, new DataviewInlineApi(this.api, this, temp, this.origin)); + this.target.replaceWith(temp); + this.target = temp; + if (result === undefined) + return; + renderValue(this.api.app, result, temp, this.origin, this, this.settings, false); + } + catch (e) { + this.errorbox = this.container.createEl("div"); + renderErrorPre(this.errorbox, "Dataview (for inline JS query '" + this.script + "'): " + e); + } + } +} + +//////////// +// Tables // +//////////// +/** Render a table of literals to Markdown. */ +function markdownTable(headers, values, settings) { + if (values.length > 0 && headers.length != values[0].length) + throw new Error(`The number of headers (${headers.length}) must match the number of columns (${values[0].length})`); + settings = settings ?? DEFAULT_SETTINGS; + const mvalues = []; + const maxLengths = Array.from(headers, v => escapeTable(v).length); + // Pre-construct the table in memory so we can size columns. + for (let row = 0; row < values.length; row++) { + const current = []; + for (let col = 0; col < values[row].length; col++) { + const text = tableLiteral(values[row][col], settings.allowHtml, settings); + current.push(text); + maxLengths[col] = Math.max(maxLengths[col], text.length); + } + mvalues.push(current); + } + // Then construct the actual table... + // Append the header fields first. + let table = `| ${headers.map((v, i) => padright(escapeTable(v), " ", maxLengths[i])).join(" | ")} |\n`; + // Then the separating column. + table += `| ${maxLengths.map(i => padright("", "-", i)).join(" | ")} |\n`; + // Then the data columns. + for (let row = 0; row < values.length; row++) { + table += `| ${mvalues[row].map((v, i) => padright(v, " ", maxLengths[i])).join(" | ")} |\n`; + } + return table; +} +/** Convert a value to a Markdown-friendly string. */ +function tableLiteral(value, allowHtml = true, settings) { + return escapeTable(rawTableLiteral(value, allowHtml, settings)); +} +/** Convert a value to a Markdown-friendly string; does not do escaping. */ +function rawTableLiteral(value, allowHtml = true, settings) { + if (!allowHtml) + return Values.toString(value, settings); + if (Values.isArray(value)) { + return `
    ${value.map(v => "
  • " + tableLiteral(v, allowHtml, settings) + "
  • ").join("")}
`; + } + else if (Values.isObject(value)) { + const inner = Object.entries(value) + .map(([k, v]) => { + return `
  • ${tableLiteral(k, allowHtml, settings)}: ${tableLiteral(v, allowHtml, settings)}
  • `; + }) + .join(""); + return `
      ${inner}
    `; + } + else { + return Values.toString(value, settings); + } +} +/** Don't need to import a library for this one... */ +function padright(text, padding, length) { + if (text.length >= length) + return text; + return text + padding.repeat(length - text.length); +} +/** Escape bars inside table content to prevent it from messing up table rows. */ +function escapeTable(text) { + return text.split(/(?!\\)\|/i).join("\\|"); +} +/////////// +// Lists // +/////////// +/** Render a list of literal elements to a markdown list. */ +function markdownList(values, settings) { + return markdownListRec(values, settings, 0); +} +/** Internal recursive function which renders markdown lists. */ +function markdownListRec(input, settings, depth = 0) { + if (Values.isArray(input)) { + let result = depth == 0 ? "" : "\n"; + for (let value of input) { + result += " ".repeat(depth) + "- "; + result += markdownListRec(value, settings, depth); + result += "\n"; + } + return result; + } + else if (Values.isObject(input)) { + let result = depth == 0 ? "" : "\n"; + for (let [key, value] of Object.entries(input)) { + result += " ".repeat(depth) + "- "; + result += Values.toString(key) + ": "; + result += markdownListRec(value, settings, depth); + result += "\n"; + } + return result; + } + else if (Values.isWidget(input) && Widgets.isListPair(input)) { + return `${Values.toString(input.key)}: ${markdownListRec(input.value, settings, depth + 1)}`; + } + return Values.toString(input); +} +/////////// +// Tasks // +/////////// +/** Render the result of a task query to markdown. */ +function markdownTaskList(tasks, settings, depth = 0) { + if (Groupings.isGrouping(tasks)) { + let result = ""; + for (let element of tasks) { + result += "#".repeat(depth + 1) + " " + Values.toString(element.key) + "\n\n"; + result += markdownTaskList(element.rows, settings, depth + 1); + } + return result; + } + else { + // Remove task line duplicates if present to match `taskList()` behavior. + const [dedupTasks, _] = nestItems(tasks); + let result = ""; + for (let element of dedupTasks) { + result += " ".repeat(depth) + "- "; + if (element.task) { + result += `[${element.status}] ${(element.visual ?? element.text).split("\n").join(" ")}\n`; + } + else { + result += `${(element.visual ?? element.text).split("\n").join(" ")}\n`; + } + result += markdownTaskList(element.children, settings, depth + 1); + } + return result; + } +} + +/** The general, externally accessible plugin API (available at `app.plugins.plugins.dataview.api` or as global `DataviewAPI`). */ +/** Asynchronous API calls related to file / system IO. */ +class DataviewIOApi { + api; + constructor(api) { + this.api = api; + } + /** Load the contents of a CSV asynchronously, returning a data array of rows (or undefined if it does not exist). */ + async csv(path, originFile) { + if (!Values.isLink(path) && !Values.isString(path)) { + throw Error(`dv.io.csv only handles string or link paths; was provided type '${typeof path}'.`); + } + let data = await this.api.index.csv.get(this.normalize(path, originFile)); + if (data.successful) + return DataArray.from(data.value, this.api.settings); + else + throw Error(`Could not find CSV for path '${path}' (relative to origin '${originFile ?? "/"}')`); + } + /** Asynchronously load the contents of any link or path in an Obsidian vault. */ + async load(path, originFile) { + if (!Values.isLink(path) && !Values.isString(path)) { + throw Error(`dv.io.load only handles string or link paths; was provided type '${typeof path}'.`); + } + let existingFile = this.api.index.vault.getAbstractFileByPath(this.normalize(path, originFile)); + if (!existingFile || !(existingFile instanceof obsidian.TFile)) + return undefined; + return this.api.index.vault.cachedRead(existingFile); + } + /** Normalize a link or path relative to an optional origin file. Returns a textual fully-qualified-path. */ + normalize(path, originFile) { + let realPath; + if (Values.isLink(path)) + realPath = path.path; + else + realPath = path; + return this.api.index.prefix.resolveRelative(realPath, originFile); + } +} +/** Global API for accessing the Dataview API, executing dataview queries, and */ +class DataviewApi { + app; + index; + settings; + verNum; + /** Evaluation context which expressions can be evaluated in. */ + evaluationContext; + /** IO API which supports asynchronous loading of data directly. */ + io; + /** Dataview functions which can be called from DataviewJS. */ + func; + /** Value utility functions for comparisons and type-checking. */ + value = Values; + /** Widget utility functions for creating built-in widgets. */ + widget = Widgets; + /** Re-exporting of luxon for people who can't easily require it. Sorry! */ + luxon = Luxon; + constructor(app, index, settings, verNum) { + this.app = app; + this.index = index; + this.settings = settings; + this.verNum = verNum; + this.evaluationContext = new Context(defaultLinkHandler(index, ""), settings); + this.func = Functions.bindAll(DEFAULT_FUNCTIONS, this.evaluationContext); + this.io = new DataviewIOApi(this); + } + /** Utilities to check the current Dataview version and compare it to SemVer version ranges. */ + version = (() => { + const self = this; + return { + get current() { + return self.verNum; + }, + compare: (op, ver) => compare(this.verNum, ver, op), + satisfies: (range) => satisfies(this.verNum, range), + }; + })(); + ///////////////////////////// + // Index + Data Collection // + ///////////////////////////// + /** Return an array of paths (as strings) corresponding to pages which match the query. */ + pagePaths(query, originFile) { + let source; + try { + if (!query || query.trim() === "") + source = Sources.folder(""); + else + source = EXPRESSION.source.tryParse(query); + } + catch (ex) { + throw new Error(`Failed to parse query in 'pagePaths': ${ex}`); + } + return matchingSourcePaths(source, this.index, originFile) + .map(s => DataArray.from(s, this.settings)) + .orElseThrow(); + } + /** Map a page path to the actual data contained within that page. */ + page(path, originFile) { + if (!(typeof path === "string") && !Values.isLink(path)) { + throw Error("dv.page only handles string and link paths; was provided type '" + typeof path + "'"); + } + let rawPath = path instanceof Link ? path.path : path; + let normPath = this.app.metadataCache.getFirstLinkpathDest(rawPath, originFile ?? ""); + if (!normPath) + return undefined; + let pageObject = this.index.pages.get(normPath.path); + if (!pageObject) + return undefined; + return this._addDataArrays(pageObject.serialize(this.index)); + } + /** Return an array of page objects corresponding to pages which match the source query. */ + pages(query, originFile) { + return this.pagePaths(query, originFile).flatMap(p => { + let res = this.page(p, originFile); + return res ? [res] : []; + }); + } + /** Remaps important metadata to add data arrays. */ + _addDataArrays(pageObject) { + // Remap the "file" metadata entries to be data arrays. + for (let [key, value] of Object.entries(pageObject.file)) { + if (Array.isArray(value)) + pageObject.file[key] = DataArray.wrap(value, this.settings); + } + return pageObject; + } + ///////////// + // Utility // + ///////////// + /** + * Convert an input element or array into a Dataview data-array. If the input is already a data array, + * it is returned unchanged. + */ + array(raw) { + if (DataArray.isDataArray(raw)) + return raw; + if (Array.isArray(raw)) + return DataArray.wrap(raw, this.settings); + return DataArray.wrap([raw], this.settings); + } + /** Return true if the given value is a javascript array OR a dataview data array. */ + isArray(raw) { + return DataArray.isDataArray(raw) || Array.isArray(raw); + } + /** Return true if the given value is a dataview data array; this returns FALSE for plain JS arrays. */ + isDataArray(raw) { + return DataArray.isDataArray(raw); + } + /** Create a dataview file link to the given path. */ + fileLink(path, embed = false, display) { + return Link.file(path, embed, display); + } + /** Create a dataview section link to the given path. */ + sectionLink(path, section, embed = false, display) { + return Link.header(path, section, embed, display); + } + /** Create a dataview block link to the given path. */ + blockLink(path, blockId, embed = false, display) { + return Link.block(path, blockId, embed, display); + } + /** Attempt to extract a date from a string, link or date. */ + date(pathlike) { + return this.func.date(pathlike); + } + /** Attempt to extract a duration from a string or duration. */ + duration(str) { + return this.func.dur(str); + } + /** Parse a raw textual value into a complex Dataview type, if possible. */ + parse(value) { + let raw = EXPRESSION.inlineField.parse(value); + if (raw.status) + return raw.value; + else + return value; + } + /** Convert a basic JS type into a Dataview type by parsing dates, links, durations, and so on. */ + literal(value) { + return parseFrontmatter(value); + } + /** Deep clone the given literal, returning a new literal which is independent of the original. */ + clone(value) { + return Values.deepCopy(value); + } + /** + * Compare two arbitrary JavaScript values using Dataview's default comparison rules. Returns a negative value if + * a < b, 0 if a = b, and a positive value if a > b. + */ + compare(a, b) { + return Values.compareValue(a, b, this.evaluationContext.linkHandler.normalize); + } + /** Return true if the two given JavaScript values are equal using Dataview's default comparison rules. */ + equal(a, b) { + return this.compare(a, b) == 0; + } + /////////////////////////////// + // Dataview Query Evaluation // + /////////////////////////////// + /** + * Execute an arbitrary Dataview query, returning a query result which: + * + * 1. Indicates the type of query, + * 2. Includes the raw AST of the parsed query. + * 3. Includes the output in the form relevant to that query type. + * + * List queries will return a list of objects ({ id, value }); table queries return a header array + * and a 2D array of values; and task arrays return a Grouping type which allows for recursive + * task nesting. + */ + async query(source, originFile, settings) { + const query = typeof source === "string" ? parseQuery(source) : Result.success(source); + if (!query.successful) + return query.cast(); + const header = query.value.header; + switch (header.type) { + case "calendar": + const cres = await executeCalendar(query.value, this.index, originFile ?? "", this.settings); + if (!cres.successful) + return cres.cast(); + return Result.success({ type: "calendar", values: cres.value.data }); + case "task": + const tasks = await executeTask(query.value, originFile ?? "", this.index, this.settings); + if (!tasks.successful) + return tasks.cast(); + return Result.success({ type: "task", values: tasks.value.tasks }); + case "list": + if (settings?.forceId !== undefined) + header.showId = settings.forceId; + const lres = await executeList(query.value, this.index, originFile ?? "", this.settings); + if (!lres.successful) + return lres.cast(); + // TODO: WITHOUT ID probably shouldn't exist, or should be moved to the engine itself. + // For now, until I fix it up in an upcoming refactor, we re-implement the behavior here. + return Result.success({ + type: "list", + values: lres.value.data, + primaryMeaning: lres.value.primaryMeaning, + }); + case "table": + if (settings?.forceId !== undefined) + header.showId = settings.forceId; + const tres = await executeTable(query.value, this.index, originFile ?? "", this.settings); + if (!tres.successful) + return tres.cast(); + return Result.success({ + type: "table", + values: tres.value.data, + headers: tres.value.names, + idMeaning: tres.value.idMeaning, + }); + } + } + /** Error-throwing version of {@link query}. */ + async tryQuery(source, originFile, settings) { + return (await this.query(source, originFile, settings)).orElseThrow(); + } + /** Execute an arbitrary dataview query, returning the results in well-formatted markdown. */ + async queryMarkdown(source, originFile, settings) { + const result = await this.query(source, originFile, settings); + if (!result.successful) + return result.cast(); + switch (result.value.type) { + case "list": + return Result.success(this.markdownList(result.value.values, settings)); + case "table": + return Result.success(this.markdownTable(result.value.headers, result.value.values, settings)); + case "task": + return Result.success(this.markdownTaskList(result.value.values, settings)); + case "calendar": + return Result.failure("Cannot render calendar queries to markdown."); + } + } + /** Error-throwing version of {@link queryMarkdown}. */ + async tryQueryMarkdown(source, originFile, settings) { + return (await this.queryMarkdown(source, originFile, settings)).orElseThrow(); + } + /** + * Evaluate a dataview expression (like '2 + 2' or 'link("hello")'), returning the evaluated result. + * This takes an optional second argument which provides definitions for variables, such as: + * + * ``` + * dv.evaluate("x + 6", { x: 2 }) = 8 + * dv.evaluate('link(target)', { target: "Okay" }) = [[Okay]] + * ``` + * + * This method returns a Result type instead of throwing an error; you can check the result of the + * execution via `result.successful` and obtain `result.value` or `result.error` accordingly. If + * you'd rather this method throw on an error, use `dv.tryEvaluate`. + */ + evaluate(expression, context, originFile) { + let field = EXPRESSION.field.parse(expression); + if (!field.status) + return Result.failure(`Failed to parse expression "${expression}"`); + let evaluationContext = originFile + ? new Context(defaultLinkHandler(this.index, originFile), this.settings) + : this.evaluationContext; + return evaluationContext.evaluate(field.value, context); + } + /** Error-throwing version of `dv.evaluate`. */ + tryEvaluate(expression, context, originFile) { + return this.evaluate(expression, context, originFile).orElseThrow(); + } + /** Evaluate an expression in the context of the given file. */ + evaluateInline(expression, origin) { + let field = EXPRESSION.field.parse(expression); + if (!field.status) + return Result.failure(`Failed to parse expression "${expression}"`); + return executeInline(field.value, origin, this.index, this.settings); + } + /////////////// + // Rendering // + /////////////// + /** + * Execute the given query, rendering results into the given container using the components lifecycle. + * Your component should be a *real* component which calls onload() on it's child components at some point, + * or a MarkdownPostProcessorContext! + * + * Note that views made in this way are live updating and will automatically clean themselves up when + * the component is unloaded or the container is removed. + */ + async execute(source, container, component, filePath) { + if (isDataviewDisabled(filePath)) { + renderCodeBlock(container, source); + return; + } + let maybeQuery = tryOrPropagate(() => parseQuery(source)); + // In case of parse error, just render the error. + if (!maybeQuery.successful) { + renderErrorPre(container, "Dataview: " + maybeQuery.error); + return; + } + let query = maybeQuery.value; + let init = { app: this.app, settings: this.settings, index: this.index, container }; + let childComponent; + switch (query.header.type) { + case "task": + childComponent = createTaskView(init, query, filePath); + component.addChild(childComponent); + break; + case "list": + childComponent = createListView(init, query, filePath); + component.addChild(childComponent); + break; + case "table": + childComponent = createTableView(init, query, filePath); + component.addChild(childComponent); + break; + case "calendar": + childComponent = new DataviewCalendarRenderer(query, container, this.index, filePath, this.settings, this.app); + component.addChild(childComponent); + break; + } + childComponent.load(); + } + /** + * Execute the given DataviewJS query, rendering results into the given container using the components lifecycle. + * See {@link execute} for general rendering semantics. + */ + async executeJs(code, container, component, filePath) { + if (isDataviewDisabled(filePath)) { + renderCodeBlock(container, code, "javascript"); + return; + } + const renderer = new DataviewJSRenderer(this, code, container, filePath); + renderer.load(); + component.addChild(renderer); + } + /** Render a dataview list of the given values. */ + async list(values, container, component, filePath) { + if (!values) + return; + if (values !== undefined && values !== null && !Array.isArray(values) && !DataArray.isDataArray(values)) + values = Array.from(values); + // Append a child div, since React will keep re-rendering otherwise. + let subcontainer = container.createEl("div"); + component.addChild(createFixedListView({ app: this.app, settings: this.settings, index: this.index, container: subcontainer }, values, filePath)); + } + /** Render a dataview table with the given headers, and the 2D array of values. */ + async table(headers, values, container, component, filePath) { + if (!headers) + headers = []; + if (!values) + values = []; + if (!Array.isArray(headers) && !DataArray.isDataArray(headers)) + headers = Array.from(headers); + // Append a child div, since React will keep re-rendering otherwise. + let subcontainer = container.createEl("div"); + component.addChild(createFixedTableView({ app: this.app, settings: this.settings, index: this.index, container: subcontainer }, headers, values, filePath)); + } + /** Render a dataview task view with the given tasks. */ + async taskList(tasks, groupByFile = true, container, component, filePath = "") { + let groupedTasks = !Groupings.isGrouping(tasks) && groupByFile ? this.array(tasks).groupBy(t => Link.file(t.path)) : tasks; + // Append a child div, since React will override several task lists otherwise. + let taskContainer = container.createEl("div"); + component.addChild(createFixedTaskView({ app: this.app, settings: this.settings, index: this.index, container: taskContainer }, groupedTasks, filePath)); + } + /** Render an arbitrary value into a container. */ + async renderValue(value, container, component, filePath, inline = false) { + return renderValue(this.app, value, container, filePath, component, this.settings, inline); + } + ///////////////// + // Data Export // + ///////////////// + /** Render data to a markdown table. */ + markdownTable(headers, values, settings) { + if (!headers) + headers = []; + if (!values) + values = []; + const combined = Object.assign({}, this.settings, settings); + return markdownTable(headers, values, combined); + } + /** Render data to a markdown list. */ + markdownList(values, settings) { + if (!values) + values = []; + const combined = Object.assign({}, this.settings, settings); + return markdownList(values, combined); + } + /** Render tasks or list items to a markdown task list. */ + markdownTaskList(values, settings) { + if (!values) + values = []; + const sparse = nestGroups(values); + const combined = Object.assign({}, this.settings, settings); + return markdownTaskList(sparse, combined); + } +} +/** Determines if source-path has a `?no-dataview` annotation that disables dataview. */ +function isDataviewDisabled(sourcePath) { + if (!sourcePath) + return false; + let questionLocation = sourcePath.lastIndexOf("?"); + if (questionLocation == -1) + return false; + return sourcePath.substring(questionLocation).contains("no-dataview"); +} + +/** Refreshable renderer which renders inline instead of in a div. */ +class DataviewInlineRenderer extends DataviewRefreshableRenderer { + field; + fieldText; + container; + target; + index; + origin; + settings; + app; + // The box that the error is rendered in, if relevant. + errorbox; + constructor(field, fieldText, container, target, index, origin, settings, app) { + super(container, index, app, settings); + this.field = field; + this.fieldText = fieldText; + this.container = container; + this.target = target; + this.index = index; + this.origin = origin; + this.settings = settings; + this.app = app; + } + async render() { + this.errorbox?.remove(); + let result = tryOrPropagate(() => executeInline(this.field, this.origin, this.index, this.settings)); + if (!result.successful) { + this.errorbox = this.container.createEl("div"); + renderErrorPre(this.errorbox, "Dataview (for inline query '" + this.fieldText + "'): " + result.error); + } + else { + let temp = document.createElement("span"); + temp.addClasses(["dataview", "dataview-inline-query"]); + await renderValue(this.app, result.value, temp, this.origin, this, this.settings, false); + this.target.replaceWith(temp); + } + } +} + +/** Replaces raw textual inline fields in text containers with pretty HTML equivalents. */ +async function replaceInlineFields(ctx, init) { + const inlineFields = extractInlineFields(init.container.innerHTML); + if (inlineFields.length == 0) + return; + const component = new obsidian.MarkdownRenderChild(init.container); + ctx.addChild(component); + // Iterate through the raw HTML and replace inline field matches with corresponding rendered values. + let result = init.container.innerHTML; + for (let x = inlineFields.length - 1; x >= 0; x--) { + let field = inlineFields[x]; + let renderContainer = document.createElement("span"); + renderContainer.addClasses(["dataview", "inline-field"]); + // Block inline fields render the key, parenthesis ones do not. + if (field.wrapping == "[") { + const key = renderContainer.createSpan({ + cls: ["dataview", "inline-field-key"], + attr: { + "data-dv-key": field.key, + "data-dv-norm-key": canonicalizeVarName(field.key), + }, + }); + // Explicitly set the inner HTML to respect any key formatting that we should carry over. + key.innerHTML = field.key; + renderContainer.createSpan({ + cls: ["dataview", "inline-field-value"], + attr: { id: "dataview-inline-field-" + x }, + }); + } + else { + renderContainer.createSpan({ + cls: ["dataview", "inline-field-standalone-value"], + attr: { + id: "dataview-inline-field-" + x, + "data-dv-key": field.key, + "data-dv-norm-key": canonicalizeVarName(field.key), + }, + }); + } + result = result.slice(0, field.start) + renderContainer.outerHTML + result.slice(field.end); + } + // Use a