UNPKG

@tko/build.knockout

Version:

Knockout makes it easier to create rich, responsive UIs with JavaScript

1,426 lines (1,405 loc) 321 kB
// @tko/build.knockout 🥊 4.0.1 IIFE "use strict"; var ko = (() => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name); var __typeError = (msg) => { throw TypeError(msg); }; var __pow = Math.pow; var __defNormalProp = (obj, key, value2) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value2 }) : obj[key] = value2; 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 __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); var __publicField = (obj, key, value2) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value2); var __accessCheck = (obj, member2, msg) => member2.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member2, getter) => (__accessCheck(obj, member2, "read from private field"), getter ? getter.call(obj) : member2.get(obj)); var __privateAdd = (obj, member2, value2) => member2.has(obj) ? __typeError("Cannot add the same private member more than once") : member2 instanceof WeakSet ? member2.add(obj) : member2.set(obj, value2); var __privateSet = (obj, member2, value2, setter) => (__accessCheck(obj, member2, "write to private field"), setter ? setter.call(obj, value2) : member2.set(obj, value2), value2); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value2) => { try { step(generator.next(value2)); } catch (e) { reject(e); } }; var rejected = (value2) => { try { step(generator.throw(value2)); } 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()); }); }; var __await = function(promise, isYieldStar) { this[0] = promise; this[1] = isYieldStar; }; var __yieldStar = (value2) => { var obj = value2[__knownSymbol("asyncIterator")], isAwait = false, method, it = {}; if (obj == null) { obj = value2[__knownSymbol("iterator")](); method = (k) => it[k] = (x) => obj[k](x); } else { obj = obj.call(value2); method = (k) => it[k] = (v) => { if (isAwait) { isAwait = false; if (k === "throw") throw v; return v; } isAwait = true; return { done: false, value: new __await(new Promise((resolve) => { var x = obj[k](v); if (!(x instanceof Object)) __typeError("Object expected"); resolve(x); }), 1) }; }; } return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => { throw x; }, "return" in obj && method("return"), it; }; // src/index.ts var index_exports = {}; __export(index_exports, { default: () => index_default }); // ../../packages/utils/src/array.ts var { isArray } = Array; function arrayForEach(array, action, actionOwner) { if (arguments.length > 2) { action = action.bind(actionOwner); } for (let i = 0, j = array.length; i < j; ++i) { action(array[i], i, array); } } function arrayIndexOf(array, item) { return (isArray(array) ? array : [...array]).indexOf(item); } function arrayFirst(array, predicate, predicateOwner) { return (isArray(array) ? array : [...array]).find(predicate, predicateOwner); } function arrayMap(array, mapping, thisArg) { if (arguments.length > 2) { mapping = mapping.bind(thisArg); } return array === null ? [] : Array.from(array, mapping); } function arrayRemoveItem(array, itemToRemove) { const index = arrayIndexOf(array, itemToRemove); if (index > 0) { array.splice(index, 1); } else if (index === 0) { array.shift(); } } function arrayGetDistinctValues(array) { const seen = /* @__PURE__ */ new Set(); if (array === null) { return []; } return (isArray(array) ? array : [...array]).filter((item) => seen.has(item) ? false : seen.add(item)); } function arrayFilter(array, predicate, predicateOwner) { if (arguments.length > 2) { predicate = predicate.bind(predicateOwner); } return array === null ? [] : (isArray(array) ? array : [...array]).filter(predicate); } function arrayPushAll(array, valuesToPush) { if (isArray(valuesToPush)) { array.push.apply(array, valuesToPush); } else { for (let i = 0, j = valuesToPush.length; i < j; i++) { array.push(valuesToPush[i]); } } return array; } function addOrRemoveItem(array, value2, included) { const existingEntryIndex = arrayIndexOf(typeof array.peek === "function" ? array.peek() : array, value2); if (existingEntryIndex < 0) { if (included) { array.push(value2); } } else { if (!included) { array.splice(existingEntryIndex, 1); } } } function makeArray(arrayLikeObject) { return Array.from(arrayLikeObject); } function range(min, max) { const minimum = typeof min === "function" ? min() : min; const maximum = typeof max === "function" ? max() : max; const result = []; for (let i = minimum; i <= maximum; i++) { result.push(i); } return result; } function findMovesInArrayComparison(left, right, limitFailedCompares) { if (left.length && right.length) { let failedCompares, l, r, leftItem, rightItem; for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) { for (r = 0; rightItem = right[r]; ++r) { if (leftItem.value === rightItem.value) { leftItem.moved = rightItem.index; rightItem.moved = leftItem.index; right.splice(r, 1); failedCompares = r = 0; break; } } failedCompares += r; } } } var statusNotInOld = "added"; var statusNotInNew = "deleted"; function compareArrays(oldArray, newArray, options3) { options3 = typeof options3 === "boolean" ? { dontLimitMoves: options3 } : options3 || {}; oldArray = oldArray || []; newArray = newArray || []; if (oldArray.length < newArray.length) { return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options3); } else { return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options3); } } function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options3) { let myMin = Math.min, myMax = Math.max, editDistanceMatrix = new Array(), smlIndex, smlIndexMax = smlArray.length, bigIndex, bigIndexMax = bigArray.length, compareRange = bigIndexMax - smlIndexMax || 1, maxDistance = smlIndexMax + bigIndexMax + 1, thisRow, lastRow, bigIndexMaxForRow, bigIndexMinForRow; for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) { lastRow = thisRow; editDistanceMatrix.push(thisRow = new Array()); bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange); bigIndexMinForRow = myMax(0, smlIndex - 1); for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) { if (!bigIndex) { thisRow[bigIndex] = smlIndex + 1; } else if (!smlIndex) { thisRow[bigIndex] = bigIndex + 1; } else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1]) { thisRow[bigIndex] = lastRow[bigIndex - 1]; } else { const northDistance = lastRow[bigIndex] || maxDistance; const westDistance = thisRow[bigIndex - 1] || maxDistance; thisRow[bigIndex] = myMin(northDistance, westDistance) + 1; } } } let editScript = new Array(), meMinusOne, notInSml = new Array(), notInBig = new Array(); for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex; ) { meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1; if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex - 1]) { notInSml.push( editScript[editScript.length] = { // added status: statusNotInSml, value: bigArray[--bigIndex], index: bigIndex } ); } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) { notInBig.push( editScript[editScript.length] = { // deleted status: statusNotInBig, value: smlArray[--smlIndex], index: smlIndex } ); } else { --bigIndex; --smlIndex; if (!(options3 == null ? void 0 : options3.sparse)) { editScript.push({ status: "retained", value: bigArray[bigIndex] }); } } } findMovesInArrayComparison(notInBig, notInSml, !options3.dontLimitMoves && smlIndexMax * 10); return editScript.reverse(); } // ../../packages/utils/src/options.ts var Options = class { constructor() { // The following options can be set on ko.options to make a function rewriting or something similar. __publicField(this, "bindingStringPreparsers", []); // Reference to the own knockout instance __publicField(this, "knockoutInstance", null); __publicField(this, "deferUpdates", false); // Don't set this false, with jquery 3.7+ __publicField(this, "useOnlyNativeEvents", true); // Use HTML5 <template> tags if is supported __publicField(this, "useTemplateTag", true); __publicField(this, "protoProperty", "__ko_proto__"); // Modify the default attribute from `data-bind`. __publicField(this, "defaultBindingAttribute", "data-bind"); // Enable/disable <!-- ko binding: ... -> style bindings __publicField(this, "allowVirtualElements", true); // Global variables that can be accessed from bindings. __publicField(this, "bindingGlobals", /* @__PURE__ */ Object.create(null)); // An instance of the binding provider. __publicField(this, "bindingProviderInstance"); // Whether the `with` binding creates a child context when used with `as`. __publicField(this, "createChildContextWithAs", false); // jQuery will be automatically set to globalThis.jQuery in applyBindings // if it is (strictly equal to) undefined. Set it to true to // disable automatically setting jQuery. __publicField(this, "disableJQueryUsage", false); __publicField(this, "_jQuery"); __publicField(this, "Promise", globalThis.Promise); __publicField(this, "taskScheduler", null); __publicField(this, "debug", false); /** * The maximum size of template to parse. * Set to 0 to disable the limit. */ __publicField(this, "templateSizeLimit", 4096); /** * Whether or not to allow script tags in templates. * If false, an error will be thrown if a script tag is detected in the template. * It is not recommended to set this to true. */ __publicField(this, "allowScriptTagsInTemplates", false); __publicField(this, "_sanitizeWarningLogged", false); __publicField(this, "global", globalThis); __publicField(this, "document", globalThis.document); // Filters for bindings // data-bind="expression | filter_1 | filter_2" __publicField(this, "filters", {}); // Used by the template binding. __publicField(this, "includeDestroyed", false); __publicField(this, "foreachHidesDestroyed", false); } get jQuery() { var _a; if (this.disableJQueryUsage) return void 0; return (_a = this._jQuery) != null ? _a : globalThis.jQuery; } /** * Set jQuery manuall to be used by TKO. * @param jQuery If jQuery set to undefined, TKO will not use jQuery and this.disableJQueryUsage to true. */ set jQuery(jQuery2) { if (!jQuery2) { this.disableJQueryUsage = true; this._jQuery = void 0; } else { this._jQuery = jQuery2; this.disableJQueryUsage = false; } } /** * Sanitize HTML templates before parsing them. Default is a no-op. * Please configure something like DOMPurify or validator.js for your environment. * @param html HTML string to be sanitized * @returns Sanitized HTML string */ sanitizeHtmlTemplate(html2) { if (!this._sanitizeWarningLogged) { console.warn( "WARNING -- You don't have a HTML sanitizer configured. Please configure options.sanitizeHtmlTemplate to avoid XSS vulnerabilities." ); this._sanitizeWarningLogged = true; } return html2; } onError(e, throws = true) { if (throws) throw e; return e; } set(name, value2) { this[name] = value2; } // Overload getBindingHandler to have a custom lookup function. getBindingHandler(key) { return null; } cleanExternalData(node, callback) { } }; var options = new Options(); function defineOption(name, config) { var _a; let _value = config.default; Object.defineProperty(options, name, { get() { return _value; }, set(value2) { var _a2; _value = value2; (_a2 = config.set) == null ? void 0 : _a2.call(config, value2); }, enumerable: true, configurable: true }); (_a = config.set) == null ? void 0 : _a.call(config, _value); } var options_default = options; // ../../packages/utils/src/error.ts function catchFunctionErrors(delegate) { if (!options_default.onError) { return delegate; } return (...args) => { try { return delegate(...args); } catch (err) { options_default.onError(err); } }; } function deferError(error) { safeSetTimeout(function() { throw error; }, 0); } function safeSetTimeout(handler, timeout) { return setTimeout(catchFunctionErrors(handler), timeout); } // ../../packages/utils/src/async.ts function throttle(callback, timeout) { let timeoutInstance; return function(...args) { if (!timeoutInstance) { timeoutInstance = safeSetTimeout(function() { timeoutInstance = void 0; callback(...args); }, timeout); } }; } function debounce(callback, timeout) { let timeoutInstance; return function(...args) { clearTimeout(timeoutInstance); timeoutInstance = safeSetTimeout(() => callback(...args), timeout); }; } // ../../packages/utils/src/object.ts function hasOwnProperty(obj, propName) { return Object.prototype.hasOwnProperty.call(obj, propName); } function isObjectLike(obj) { if (obj === null) { return false; } return typeof obj === "object" || typeof obj === "function"; } function extend(target, source) { if (source) { for (const prop of Object.keys(source)) { if (hasOwnProperty(source, prop)) { ; target[prop] = source[prop]; } } } return target; } function objectForEach(obj, action) { for (const prop in obj) { if (hasOwnProperty(obj, prop)) { action(prop, obj[prop]); } } } function objectMap(source, mapping, thisArg) { if (!source) { return source; } if (arguments.length > 2) { mapping = mapping.bind(thisArg); } const target = {}; for (const prop in source) { if (hasOwnProperty(source, prop)) { target[prop] = mapping(source[prop], prop, source); } } return target; } function getObjectOwnProperty(obj, propName) { return hasOwnProperty(obj, propName) ? obj[propName] : void 0; } function clonePlainObjectDeep(obj, seen) { if (!seen) { seen = new Array(); } if (!obj || typeof obj !== "object" || obj.constructor !== Object || seen.indexOf(obj) !== -1) { return obj; } seen.push(obj); const result = {}; for (const prop in obj) { if (hasOwnProperty(obj, prop)) { result[prop] = clonePlainObjectDeep(obj[prop], seen); } } return result; } function safeStringify(value2) { const seen = /* @__PURE__ */ new Set(); return JSON.stringify(value2, (k, v) => { if (seen.has(v)) { return "..."; } if (typeof v === "object") { seen.add(v); } return v; }); } function isThenable(object) { return isObjectLike(object) && typeof object.then === "function"; } // ../../packages/utils/src/function.ts function testOverwrite() { try { Object.defineProperty(function x() { }, "length", {}); return true; } catch (e) { return false; } } var functionSupportsLengthOverwrite = testOverwrite(); function overwriteLengthPropertyIfSupported(fn, descriptor) { if (functionSupportsLengthOverwrite) { Object.defineProperty(fn, "length", descriptor); } } // ../../packages/utils/src/string.ts function stringTrim(string) { return string === null || string === void 0 ? "" : string.trim ? string.trim() : string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, ""); } function stringStartsWith(string, startsWith) { string = string || ""; if (startsWith.length > string.length) { return false; } return string.substring(0, startsWith.length) === startsWith; } function parseJson(jsonString) { if (typeof jsonString === "string") { jsonString = stringTrim(jsonString); if (jsonString) { return JSON.parse(jsonString); } } return null; } // ../../packages/utils/src/symbol.ts var useSymbols = typeof Symbol === "function"; function createSymbolOrString(identifier) { return useSymbols ? Symbol(identifier) : identifier; } // ../../packages/utils/src/css.ts var cssClassNameRegex = /\S+/g; function toggleDomNodeCssClass(node, classNames, shouldHaveClass) { let addOrRemoveFn; if (!classNames) { return; } if (typeof node.classList === "object") { addOrRemoveFn = node.classList[shouldHaveClass ? "add" : "remove"]; arrayForEach(classNames.match(cssClassNameRegex), function(className) { addOrRemoveFn.call(node.classList, className); }); } else if (typeof node.className["baseVal"] === "string") { toggleObjectClassPropertyString(node.className, "baseVal", classNames, shouldHaveClass); } else { toggleObjectClassPropertyString(node, "className", classNames, shouldHaveClass); } } function toggleObjectClassPropertyString(obj, prop, classNames, shouldHaveClass) { const currentClassNames = obj[prop].match(cssClassNameRegex) || []; arrayForEach(classNames.match(cssClassNameRegex), function(className) { addOrRemoveItem(currentClassNames, className, shouldHaveClass); }); obj[prop] = currentClassNames.join(" "); } // ../../packages/utils/src/dom/info.ts function domNodeIsContainedBy(node, containedByNode) { if (node === containedByNode) { return true; } if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { return false; } if (containedByNode.contains) { return containedByNode.contains(node.nodeType !== Node.ELEMENT_NODE ? node.parentNode : node); } if (containedByNode.compareDocumentPosition) { return (containedByNode.compareDocumentPosition(node) & 16) == 16; } let parentNode = node; while (parentNode && parentNode != containedByNode) { parentNode = parentNode.parentNode; } return !!parentNode; } function domNodeIsAttachedToDocument(node) { return domNodeIsContainedBy(node, node.ownerDocument.documentElement); } function anyDomNodeIsAttachedToDocument(nodes) { return !!arrayFirst(nodes, domNodeIsAttachedToDocument); } function tagNameLower(element) { return element && element.tagName && element.tagName.toLowerCase(); } function isDomElement(obj) { if (window.HTMLElement) { return obj instanceof HTMLElement; } else { return obj && obj.tagName && obj.nodeType === Node.ELEMENT_NODE; } } function isDocumentFragment(obj) { if (window.DocumentFragment) { return obj instanceof DocumentFragment; } else { return obj && obj.nodeType === Node.DOCUMENT_FRAGMENT_NODE; } } // ../../packages/utils/src/dom/event.ts var knownEvents = {}; var knownEventTypesByEventName = {}; knownEvents["UIEvents"] = ["keyup", "keydown", "keypress"]; knownEvents["MouseEvents"] = [ "click", "dblclick", "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "mouseenter", "mouseleave" ]; objectForEach(knownEvents, function(eventType, knownEventsForType) { if (knownEventsForType.length) { for (let i = 0, j = knownEventsForType.length; i < j; i++) { knownEventTypesByEventName[knownEventsForType[i]] = eventType; } } }); function isClickOnCheckableElement(element, eventType) { if (tagNameLower(element) !== "input" || !element.type) return false; if (eventType.toLowerCase() != "click") return false; const inputType = element.type; return inputType == "checkbox" || inputType == "radio"; } function registerEventHandler(element, eventType, handler, eventOptions = false) { const wrappedHandler = catchFunctionErrors(handler); const mustUseNative = Boolean(eventOptions); const jQuery2 = options_default.jQuery; if (!options_default.useOnlyNativeEvents && !mustUseNative && jQuery2) { jQuery2(element).on(eventType, wrappedHandler); } else if (typeof element.addEventListener === "function") { element.addEventListener(eventType, wrappedHandler, eventOptions); } else { throw new Error("Browser doesn't support addEventListener"); } } function hasClick(element) { return typeof element.click === "function"; } function triggerEvent(element, eventType) { if (!(element && element.nodeType)) { throw new Error("element must be a DOM node when calling triggerEvent"); } const useClickWorkaround = isClickOnCheckableElement(element, eventType); if (!options_default.useOnlyNativeEvents && options_default.jQuery && !useClickWorkaround) { options_default.jQuery(element).trigger(eventType); } else if (typeof document.createEvent === "function") { if (typeof element.dispatchEvent === "function") { const eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents"; const event = document.createEvent(eventCategory); event.initEvent( eventType, true, true, options_default.global, 0, 0, 0, 0, 0, false, false, false, false, 0, element ); element.dispatchEvent(event); } else { throw new Error("The supplied element doesn't support dispatchEvent"); } } else if (useClickWorkaround && hasClick(element)) { element.click(); } else { throw new Error("Browser doesn't support triggering events"); } } // ../../packages/utils/src/dom/data.ts var data_exports = {}; __export(data_exports, { clear: () => clear, get: () => get, getOrSet: () => getOrSet, nextKey: () => nextKey, set: () => set }); var datastoreTime = (/* @__PURE__ */ new Date()).getTime(); var dataStoreKeyExpandoPropertyName = `__ko__${datastoreTime}`; var dataStoreSymbol = /* @__PURE__ */ Symbol("Knockout data"); var uniqueId = 0; function isSafeKey(key) { return key !== "__proto__" && key !== "constructor" && key !== "prototype"; } function getDataForNode(node, createIfNotFound) { let dataForNode = node[dataStoreSymbol]; if (!dataForNode && createIfNotFound) { dataForNode = node[dataStoreSymbol] = {}; } return dataForNode; } function clear(node) { if (node[dataStoreSymbol]) { delete node[dataStoreSymbol]; return true; } return false; } function nextKey() { return uniqueId++ + dataStoreKeyExpandoPropertyName; } function get(node, key) { if (!isSafeKey(key)) throw new Error("Unsafe key for DOM data: " + key); const dataForNode = getDataForNode(node, false); return dataForNode && dataForNode[key]; } function set(node, key, value2) { if (!isSafeKey(key)) throw new Error("Unsafe key for DOM data: " + key); const dataForNode = getDataForNode( node, value2 !== void 0 /* createIfNotFound */ ); if (dataForNode) { dataForNode[key] = value2; } } function getOrSet(node, key, value2) { if (!isSafeKey(key)) throw new Error("Unsafe key for DOM data: " + key); const dataForNode = getDataForNode( node, true /* createIfNotFound */ ); return dataForNode[key] || (dataForNode[key] = value2); } // ../../packages/utils/src/dom/disposal.ts var domDataKey = nextKey(); var cleanableNodeTypes = { 1: true, 8: true, 9: true }; var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; function getDisposeCallbacksCollection(node, createIfNotFound) { let allDisposeCallbacks = get(node, domDataKey); if (allDisposeCallbacks === void 0 && createIfNotFound) { allDisposeCallbacks = new Array(); set(node, domDataKey, allDisposeCallbacks); } return allDisposeCallbacks; } function destroyCallbacksCollection(node) { set(node, domDataKey, void 0); } function cleanSingleNode(node) { let callbacks = getDisposeCallbacksCollection(node, false); if (callbacks) { callbacks = callbacks.slice(0); for (let i = 0; i < callbacks.length; i++) { callbacks[i](node); } } clear(node); for (let i = 0, j = otherNodeCleanerFunctions.length; i < j; ++i) { otherNodeCleanerFunctions[i](node); } if (options_default.cleanExternalData) { options_default.cleanExternalData(node); } if (cleanableNodeTypesWithDescendants[node.nodeType]) { cleanNodesInList( node.childNodes, true /* onlyComments */ ); } } function cleanNodesInList(nodeList, onlyComments) { const cleanedNodes = new Array(); let lastCleanedNode; for (let i = 0; i < nodeList.length; i++) { if (!onlyComments || nodeList[i].nodeType === Node.COMMENT_NODE) { cleanSingleNode(cleanedNodes[cleanedNodes.length] = lastCleanedNode = nodeList[i]); if (nodeList[i] !== lastCleanedNode) { while (i-- && arrayIndexOf(cleanedNodes, nodeList[i]) === -1) { } } } } } function addDisposeCallback(node, callback) { if (typeof callback !== "function") { throw new Error("Callback must be a function"); } getDisposeCallbacksCollection(node, true).push(callback); } function removeDisposeCallback(node, callback) { const callbacksCollection = getDisposeCallbacksCollection(node, false); if (callbacksCollection) { arrayRemoveItem(callbacksCollection, callback); if (callbacksCollection.length === 0) { destroyCallbacksCollection(node); } } } function cleanNode(node) { if (cleanableNodeTypes[node.nodeType]) { cleanSingleNode(node); if (cleanableNodeTypesWithDescendants[node.nodeType] && node instanceof Element) { cleanNodesInList(node.getElementsByTagName("*")); } } return node; } function removeNode(node) { if (!node) { return; } cleanNode(node); if (node.parentNode) { node.parentNode.removeChild(node); } } var otherNodeCleanerFunctions = new Array(); function addCleaner(fn) { otherNodeCleanerFunctions.push(fn); } function removeCleaner(fn) { const fnIndex = otherNodeCleanerFunctions.indexOf(fn); if (fnIndex >= 0) { otherNodeCleanerFunctions.splice(fnIndex, 1); } } function cleanjQueryData(node) { const jQueryCleanNodeFn = options_default.jQuery ? options_default.jQuery.cleanData : null; if (jQueryCleanNodeFn) { jQueryCleanNodeFn([node]); } } otherNodeCleanerFunctions.push(cleanjQueryData); // ../../packages/utils/src/dom/manipulation.ts function moveCleanedNodesToContainerElement(nodes) { const nodesArray = makeArray(nodes); const templateDocument = nodesArray[0] && nodesArray[0].ownerDocument || document; const container = templateDocument.createElement("div"); for (let i = 0, j = nodesArray.length; i < j; i++) { container.appendChild(cleanNode(nodesArray[i])); } return container; } function cloneNodes(nodesArray, shouldCleanNodes) { const newNodesArray = new Array(); for (let i = 0; i < nodesArray.length; i++) { const clonedNode = nodesArray[i].cloneNode(true); newNodesArray.push(shouldCleanNodes ? cleanNode(clonedNode) : clonedNode); } return newNodesArray; } function setDomNodeChildren(domNode, childNodes2) { emptyDomNode(domNode); if (childNodes2) { for (let i = 0; i < childNodes2.length; i++) { domNode.appendChild(childNodes2[i]); } } } function replaceDomNodes(nodeToReplaceOrNodeArray, newNodesArray) { const nodesToReplaceArray = Array.isArray(nodeToReplaceOrNodeArray) ? nodeToReplaceOrNodeArray : [nodeToReplaceOrNodeArray]; if (nodesToReplaceArray.length > 0) { const insertionPoint = nodesToReplaceArray[0]; const parent = insertionPoint.parentNode; for (let i = 0; i < newNodesArray.length; i++) { parent == null ? void 0 : parent.insertBefore(newNodesArray[i], insertionPoint); } for (let i = 0; i < nodesToReplaceArray.length; i++) { removeNode(nodesToReplaceArray[i]); } } } function emptyDomNode(domNode) { while (domNode.firstChild) { removeNode(domNode.firstChild); } } // ../../packages/utils/src/dom/fixes.ts function fixUpContinuousNodeArray(continuousNodeArray, parentNode) { if (continuousNodeArray.length) { parentNode = parentNode.nodeType === Node.COMMENT_NODE && parentNode.parentNode || parentNode; while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode) { continuousNodeArray.splice(0, 1); } while (continuousNodeArray.length > 1 && continuousNodeArray[continuousNodeArray.length - 1].parentNode !== parentNode) { continuousNodeArray.length--; } if (continuousNodeArray.length > 1) { let current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1]; continuousNodeArray.length = 0; while (current !== last) { continuousNodeArray.push(current); current = current.nextSibling; } continuousNodeArray.push(last); } } return continuousNodeArray; } function setOptionNodeSelectionState(optionNode, isSelected) { optionNode.selected = isSelected; } // ../../packages/utils/src/dom/virtualElements.ts var virtualElements_exports = {}; __export(virtualElements_exports, { allowedBindings: () => allowedBindings, childNodes: () => childNodes, emptyNode: () => emptyNode, endCommentRegex: () => endCommentRegex, firstChild: () => firstChild, getVirtualChildren: () => getVirtualChildren, hasBindingValue: () => hasBindingValue, insertAfter: () => insertAfter, isEndComment: () => isEndComment, isStartComment: () => isStartComment, lastChild: () => lastChild, nextSibling: () => nextSibling, normaliseVirtualElementDomStructure: () => normaliseVirtualElementDomStructure, prepend: () => prepend, previousSibling: () => previousSibling, setDomNodeChildren: () => setDomNodeChildren2, startCommentRegex: () => startCommentRegex, virtualNodeBindingValue: () => virtualNodeBindingValue }); var startCommentRegex = /^\s*ko(?:\s+([\s\S]+))?\s*$/; var endCommentRegex = /^\s*\/ko\s*$/; var htmlTagsWithOptionallyClosingChildren = { ul: true, ol: true }; function isStartComment(node) { return node.nodeType === Node.COMMENT_NODE && startCommentRegex.test(node.nodeValue); } function isEndComment(node) { return node.nodeType === Node.COMMENT_NODE && endCommentRegex.test(node.nodeValue); } function isUnmatchedEndComment(node) { return isEndComment(node) && !get(node, matchedEndCommentDataKey); } var matchedEndCommentDataKey = "__ko_matchedEndComment__"; function getVirtualChildren(startComment, allowUnbalanced) { let currentNode = startComment; let depth = 1; const children = new Array(); while (currentNode = currentNode.nextSibling) { if (isEndComment(currentNode)) { set(currentNode, matchedEndCommentDataKey, true); depth--; if (depth === 0) { return children; } } children.push(currentNode); if (isStartComment(currentNode)) { depth++; } } if (!allowUnbalanced) { throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue); } return null; } function getMatchingEndComment(startComment, allowUnbalanced) { const allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced); if (allVirtualChildren) { if (allVirtualChildren.length > 0) { return allVirtualChildren[allVirtualChildren.length - 1].nextSibling; } return startComment.nextSibling; } else { return null; } } function getUnbalancedChildTags(node) { let childNode = node.firstChild, captureRemaining = null; if (childNode) { do { if (captureRemaining) { captureRemaining.push(childNode); } else if (isStartComment(childNode)) { const matchingEndComment = getMatchingEndComment( childNode, /* allowUnbalanced: */ true ); if (matchingEndComment) { childNode = matchingEndComment; } else { captureRemaining = [childNode]; } } else if (isEndComment(childNode)) { captureRemaining = [childNode]; } } while (childNode = childNode.nextSibling); } return captureRemaining; } var allowedBindings = /* @__PURE__ */ Object.create(null); var hasBindingValue = isStartComment; function childNodes(node) { return isStartComment(node) ? getVirtualChildren(node) : node.childNodes; } function emptyNode(node) { if (!isStartComment(node)) { emptyDomNode(node); } else { const virtualChildren = childNodes(node); for (let i = 0, j = virtualChildren.length; i < j; i++) { removeNode(virtualChildren[i]); } } } function setDomNodeChildren2(node, childNodes2) { if (!isStartComment(node)) { setDomNodeChildren(node, childNodes2); } else { emptyNode(node); const endCommentNode = node.nextSibling; if (endCommentNode && endCommentNode.parentNode) { const parentNode = endCommentNode.parentNode; for (let i = 0, j = childNodes2.length; i < j; ++i) { parentNode.insertBefore(childNodes2[i], endCommentNode); } } } } function prepend(containerNode, nodeToPrepend) { var _a; if (!isStartComment(containerNode)) { if (containerNode.firstChild) { containerNode.insertBefore(nodeToPrepend, containerNode.firstChild); } else { containerNode.appendChild(nodeToPrepend); } } else { (_a = containerNode.parentNode) == null ? void 0 : _a.insertBefore(nodeToPrepend, containerNode.nextSibling); } } function insertAfter(containerNode, nodeToInsert, insertAfterNode) { var _a; if (!insertAfterNode) { prepend(containerNode, nodeToInsert); } else if (!isStartComment(containerNode)) { if (insertAfterNode.nextSibling) { containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling); } else { containerNode.appendChild(nodeToInsert); } } else { (_a = containerNode.parentNode) == null ? void 0 : _a.insertBefore(nodeToInsert, insertAfterNode.nextSibling); } } function firstChild(node) { if (!isStartComment(node)) { if (node.firstChild && isEndComment(node.firstChild)) { throw new Error("Found invalid end comment, as the first child of " + node.outerHTML); } return node.firstChild; } if (!node.nextSibling || isEndComment(node.nextSibling)) { return null; } return node.nextSibling; } function lastChild(node) { let nextChild = firstChild(node); if (!nextChild) return null; let lastChildNode; do { lastChildNode = nextChild; } while (nextChild = nextSibling(nextChild)); return lastChildNode; } function nextSibling(node) { if (isStartComment(node)) { node = getMatchingEndComment(node); } if (node.nextSibling && isEndComment(node.nextSibling)) { if (isUnmatchedEndComment(node.nextSibling)) { throw Error( "Found end comment without a matching opening comment, as next sibling of " + node.outerHTML ); } return null; } else { return node.nextSibling; } } function previousSibling(node) { let depth = 0; do { if (node.nodeType === Node.COMMENT_NODE) { if (isStartComment(node)) { if (--depth === 0) { return node; } } else if (isEndComment(node)) { depth++; } } else { if (depth === 0) { return node; } } } while (node = node.previousSibling); } function virtualNodeBindingValue(node) { const regexMatch = node.nodeValue.match(startCommentRegex); return regexMatch ? regexMatch[1] : null; } function normaliseVirtualElementDomStructure(elementVerified) { if (!htmlTagsWithOptionallyClosingChildren[tagNameLower(elementVerified)]) { return; } let childNode = elementVerified.firstChild; if (childNode) { do { if (childNode.nodeType === Node.ELEMENT_NODE) { const unbalancedTags = getUnbalancedChildTags(childNode); if (unbalancedTags) { const nodeToInsertBefore = childNode.nextSibling; for (let i = 0; i < unbalancedTags.length; i++) { if (nodeToInsertBefore) { elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore); } else { elementVerified.appendChild(unbalancedTags[i]); } } } } } while (childNode = childNode.nextSibling); } } // ../../packages/utils/src/dom/html.ts var supportsTemplateTag = options_default.useTemplateTag && options_default.document && "content" in options_default.document.createElement("template"); function simpleHtmlParse(html2, documentContext) { if (!documentContext) { documentContext = document; } const div2 = documentContext.createElement("div"); div2.innerHTML = html2; return makeArray(div2.childNodes); } function templateHtmlParse(html2, documentContext) { if (!documentContext) { documentContext = document; } const template = documentContext.createElement("template"); template.innerHTML = html2; return makeArray(template.content.childNodes); } function jQueryHtmlParse(html2, documentContext) { const jQuery2 = options_default.jQuery; if (jQuery2) { return jQuery2.parseHTML(html2, documentContext) || []; } return []; } function parseHtmlFragment(html2, documentContext) { const saferHtml = validateHTMLInput(html2); if (supportsTemplateTag) return templateHtmlParse(saferHtml, documentContext); if (options_default.jQuery) { return jQueryHtmlParse(saferHtml, documentContext); } return simpleHtmlParse(saferHtml, documentContext); } var scriptTagPattern = /<script\b[^>]*>([\s\S]*?)<\/script[^>]*>/i; function validateHTMLInput(html2) { if (!html2) return ""; if (options_default.templateSizeLimit > 0 && html2.length > options_default.templateSizeLimit) { throw new Error("Template is too long. Please configure the 'templateSizeLimit'"); } if (!options_default.allowScriptTagsInTemplates && scriptTagPattern.test(html2)) { throw new Error("Script-tag in template detected."); } return options_default.sanitizeHtmlTemplate(html2); } function parseHtmlForTemplateNodes(html2, documentContext) { const nodes = parseHtmlFragment(html2, documentContext); return nodes.length && nodes[0].parentElement || moveCleanedNodesToContainerElement(nodes); } function setHtml(node, html2) { emptyDomNode(node); if (typeof html2 === "function") { html2 = html2(); } if (html2 !== null && html2 !== void 0) { if (typeof html2 !== "string") { html2 = html2.toString(); } const jQuery2 = options_default.jQuery; if (jQuery2 && !supportsTemplateTag) { const saferHtml = validateHTMLInput(html2); jQuery2(node).html(saferHtml); } else { let parsedNodes; if (node.ownerDocument) { parsedNodes = parseHtmlFragment(html2, node.ownerDocument); } else { parsedNodes = parseHtmlFragment(html2); } if (node.nodeType === Node.COMMENT_NODE) { if (html2 === null) { emptyNode(node); } else { setDomNodeChildren2(node, parsedNodes); } } else { for (let i = 0; i < parsedNodes.length; i++) { node.appendChild(parsedNodes[i]); } } } } } function setTextContent(element, textContent) { let value2 = typeof textContent === "function" ? textContent() : textContent; if (value2 === null || value2 === void 0) { value2 = ""; } const innerTextNode = firstChild(element); if (!innerTextNode || innerTextNode.nodeType !== Node.TEXT_NODE || nextSibling(innerTextNode)) { setDomNodeChildren2(element, [element.ownerDocument.createTextNode(value2)]); } else { ; innerTextNode.data = value2; } } // ../../packages/utils/src/dom/selectExtensions.ts var hasDomDataExpandoProperty = /* @__PURE__ */ Symbol("Knockout selectExtensions hasDomDataProperty"); var selectExtensions = { optionValueDomDataKey: nextKey(), readValue: function(element) { switch (tagNameLower(element)) { case "option": { if (element[hasDomDataExpandoProperty] === true) { return get(element, selectExtensions.optionValueDomDataKey); } return element.value; } case "select": { const selectElement = element; return selectElement.selectedIndex >= 0 ? selectExtensions.readValue(selectElement.options[selectElement.selectedIndex]) : void 0; } default: return element.value; } }, writeValue: function(element, value2, allowUnset) { switch (tagNameLower(element)) { case "option": if (typeof value2 === "string") { set(element, selectExtensions.optionValueDomDataKey, void 0); if (hasDomDataExpandoProperty in element) { delete element[hasDomDataExpandoProperty]; } ; element.value = value2; } else { const el = element; set(element, selectExtensions.optionValueDomDataKey, value2); el[hasDomDataExpandoProperty] = true; el.value = typeof value2 === "number" ? value2 : ""; } break; case "select": { if (value2 === "" || value2 === null) { value2 = void 0; } let selection = -1; const selectElement = element; for (let i = 0, n = selectElement.options.length, optionValue; i < n; ++i) { optionValue = selectExtensions.readValue(selectElement.options[i]); const strictEqual2 = optionValue === value2; const blankEqual = optionValue === "" && value2 === void 0; const numericEqual = typeof value2 === "number" && Number(optionValue) === value2; if (strictEqual2 || blankEqual || numericEqual) { selection = i; break; } } if (allowUnset || selection >= 0 || value2 === void 0 && selectElement.size > 1) { selectElement.selectedIndex = selection; } } break; default: if (value2 === null || value2 === void 0) { value2 = ""; } ; element.value = value2; break; } } }; // ../../packages/utils/src/memoization.ts var memoization_exports = {}; __export(memoization_exports, { memoize: () => memoize, parseMemoText: () => parseMemoText, unmemoize: () => unmemoize, unmemoizeDomNodeAndDescendants: () => unmemoizeDomNodeAndDescendants }); var memos = {}; function randomMax8HexChars() { return ((1 + Math.random()) * 4294967296 | 0).toString(16).substring(1); } function generateRandomId() { return randomMax8HexChars() + randomMax8HexChars(); } function findMemoNodes(rootNode, appendToArray) { if (!rootNode) { return; } if (rootNode.nodeType === Node.COMMENT_NODE) { const comment = rootNode; const memoId = parseMemoText(comment.nodeValue); if (memoId != null) { appendToArray.push({ domNode: rootNode, memoId }); } } else if (rootNode.nodeType === Node.ELEMENT_NODE) { for (let i = 0, childNodes2 = rootNode.childNodes, j = childNodes2.length; i < j; i++) { findMemoNodes(childNodes2[i], appendToArray); } } } function memoize(callback) { if (typeof callback !== "function") { throw new Error("You can only pass a function to memoization.memoize()"); } const memoId = generateRandomId(); memos[memoId] = callback; return "<!--[ko_memo:" + memoId + "]-->"; } function unmemoize(memoId, callbackParams) { const callback = memos[memoId]; if (callback === void 0) { throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized."); } try { callback.apply(null, callbackParams || []); return true; } finally { delete memos[memoId]; } } function unmemoizeDomNodeAndDescendants(domNode, extraCallbackParamsArray) { const memos2 = new Array(); findMemoNodes(domNode, memos2); for (let i = 0, j = memos2.length; i < j; i++) { const node = memos2[i].domNode; const combinedParams = [node]; if (extraCallbackParamsArray) { arrayPushAll(combinedParams, extraCallbackParamsArray); } unmemoize(memos2[i].memoId, combinedParams); node.nodeValue = ""; if (node.parentNode) { node.parentNode.removeChild(node); } } } function parseMemoText(memoText) { if (!memoText) { return null; } const match = memoText.match(/^\[ko_memo\:(.*?)\]$/); return match ? match[1] : null; } // ../../packages/utils/src/tasks.ts var tasks_exports = {}; __export(tasks_exports, { cancel: () => cancel, resetForTesting: () => resetForTesting, runEarly: () => processTasks, schedule: () => schedule }); var taskQueue = new Array(); var taskQueueLength = 0; var nextHandle = 1; var nextIndexToProcess = 0; var schedulerGlobal = options_default.global; if (schedulerGlobal && typeof schedulerGlobal.queueMicrotask === "function") { options_default.taskScheduler = (callback) => schedulerGlobal.queueMicrotask(callback); } else if (schedulerGlobal && schedulerGlobal.MutationObserver && schedulerGlobal.document && !(schedulerGlobal.navigator && schedulerGlobal.navigator.standalone)) { options_default.taskScheduler = (function() { let scheduledCallback = null; let toggle = false; const div2 = schedulerGlobal.document.createElement("div"); new schedulerGlobal.MutationObserver(function() { const callback = scheduledCallback; scheduledCallback = null; callback == null ? void 0 : callback(); }).observe(div2, { attributes: true }); return function(callback) { scheduledCallback = callback; toggle = !toggle; div2.setAttribute("data-task-scheduler", toggle ? "1" : "0"); }; })(); } else { options_default.taskScheduler = (callback) => setTimeout(callback, 0); } function processTasks() { if (taskQueueLength) { let mark = taskQueueLength, countMarks = 0; for (let task; nextIndexToProcess < taskQueueLength; ) { if (task = taskQueue[nextIndexToProcess++])