@lipsjs/lips 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +185 -85
- package/dist/lips.js +6274 -0
- package/dist/lips.js.map +53 -0
- package/dist/lips.min.js +13 -2
- package/dist/lips.min.js.map +47 -43
- package/dist/mf2.min.js +4 -0
- package/dist/mf2.min.js.map +38 -0
- package/dist/precompile.min.js +23 -0
- package/dist/precompile.min.js.map +14 -0
- package/dist/runtime.min.js +5 -0
- package/dist/runtime.min.js.map +20 -0
- package/dist/stylis.min.js +3 -0
- package/dist/stylis.min.js.map +16 -0
- package/dist/types/events.d.ts +1 -1
- package/dist/types/i18n/engine.d.ts +14 -0
- package/dist/types/i18n/index.d.ts +122 -5
- package/dist/types/i18n/intl.d.ts +1 -0
- package/dist/types/i18n/lookup.d.ts +22 -0
- package/dist/types/ir/compiler.d.ts +226 -0
- package/dist/types/ir/expression.d.ts +149 -0
- package/dist/types/ir/facade.d.ts +138 -0
- package/dist/types/ir/host.d.ts +75 -0
- package/dist/types/ir/index.d.ts +18 -0
- package/dist/types/ir/parser.d.ts +124 -0
- package/dist/types/ir/policy.d.ts +95 -0
- package/dist/types/ir/router.d.ts +47 -0
- package/dist/types/ir/runtime.d.ts +130 -0
- package/dist/types/ir/signal.d.ts +28 -0
- package/dist/types/ir/style.d.ts +119 -0
- package/dist/types/ir/swap.d.ts +28 -0
- package/dist/types/ir/tree.d.ts +51 -0
- package/dist/types/lips.d.ts +33 -37
- package/dist/types/lynx/a11y.d.ts +61 -0
- package/dist/types/lynx/background.d.ts +71 -0
- package/dist/types/lynx/main.d.ts +46 -0
- package/dist/types/lynx/protocol.d.ts +52 -0
- package/dist/types/lynx/style.d.ts +49 -0
- package/dist/types/lynx/template.d.ts +37 -0
- package/dist/types/mf2.d.ts +14 -0
- package/dist/types/precompile.d.ts +85 -0
- package/dist/types/runtime.d.ts +16 -0
- package/dist/types/stylesheet.d.ts +21 -41
- package/dist/types/stylis.d.ts +2 -0
- package/dist/types/types.d.ts +176 -185
- package/dist/types/untrusted.d.ts +17 -0
- package/dist/untrusted.min.js +5 -0
- package/dist/untrusted.min.js.map +13 -0
- package/package.json +46 -10
- package/dist/test.component.min.js +0 -3
- package/dist/test.component.min.js.map +0 -50
- package/dist/test.stress.min.js +0 -476
- package/dist/test.stress.min.js.map +0 -50
- package/dist/types/component.d.ts +0 -107
- package/dist/types/constants.d.ts +0 -23
- package/dist/types/dws.d.ts +0 -14
- package/dist/types/iuc/index.d.ts +0 -25
- package/dist/types/iuc/tick.d.ts +0 -38
- package/dist/types/iuc.d.ts +0 -25
- package/dist/types/metrics.d.ts +0 -50
- package/dist/types/preprocess.d.ts +0 -2
- package/dist/types/signal.d.ts +0 -30
- package/dist/types/syntax/async.d.ts +0 -16
- package/dist/types/syntax/for.d.ts +0 -25
- package/dist/types/syntax/if.d.ts +0 -14
- package/dist/types/syntax/router.d.ts +0 -40
- package/dist/types/syntax/switch.d.ts +0 -16
- package/dist/types/tick.d.ts +0 -38
- package/dist/types/tps.d.ts +0 -11
- package/dist/types/uqs.d.ts +0 -37
- package/dist/types/utils.d.ts +0 -25
package/dist/lips.min.js.map
CHANGED
|
@@ -1,49 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../
|
|
3
|
+
"sources": ["../src/ir/expression.ts", "../src/ir/signal.ts", "../src/ir/host.ts", "../src/i18n/lookup.ts", "../src/ir/swap.ts", "../src/ir/runtime.ts", "../src/events.ts", "../src/stylesheet.ts", "../src/i18n/index.ts", "../src/ir/facade.ts", "../src/i18n/intl.ts", "../node_modules/messageformat/lib/cst/names.js", "../node_modules/messageformat/lib/data-model/from-cst.js", "../node_modules/messageformat/lib/errors.js", "../node_modules/messageformat/lib/data-model/parse.js", "../node_modules/messageformat/lib/data-model/visit.js", "../node_modules/messageformat/lib/data-model/validate.js", "../node_modules/messageformat/lib/dir-utils.js", "../node_modules/messageformat/lib/functions/utils.js", "../node_modules/messageformat/lib/functions/number.js", "../node_modules/messageformat/lib/functions/currency.js", "../node_modules/messageformat/lib/functions/datetime.js", "../node_modules/messageformat/lib/functions/offset.js", "../node_modules/messageformat/lib/functions/percent.js", "../node_modules/messageformat/lib/functions/string.js", "../node_modules/messageformat/lib/functions/unit.js", "../node_modules/messageformat/lib/functions/index.js", "../node_modules/messageformat/lib/message-value.js", "../node_modules/messageformat/lib/functions/fallback.js", "../node_modules/messageformat/lib/functions/unknown.js", "../node_modules/messageformat/lib/resolve/function-context.js", "../node_modules/messageformat/lib/resolve/resolve-function-ref.js", "../node_modules/messageformat/lib/resolve/resolve-expression.js", "../node_modules/messageformat/lib/resolve/resolve-variable.js", "../node_modules/messageformat/lib/resolve/resolve-value.js", "../node_modules/messageformat/lib/resolve/format-markup.js", "../node_modules/messageformat/lib/select-pattern.js", "../node_modules/messageformat/lib/messageformat.js", "../src/i18n/engine.ts", "../src/ir/style.ts", "../src/ir/parser.ts", "../src/ir/compiler.ts", "../src/ir/router.ts", "../src/lips.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"(function(){\n\"use strict\";\nvar doc = document;\nvar win = window;\nvar docEle = doc.documentElement;\nvar createElement = doc.createElement.bind(doc);\nvar div = createElement('div');\nvar table = createElement('table');\nvar tbody = createElement('tbody');\nvar tr = createElement('tr');\nvar isArray = Array.isArray, ArrayPrototype = Array.prototype;\nvar concat = ArrayPrototype.concat, filter = ArrayPrototype.filter, indexOf = ArrayPrototype.indexOf, map = ArrayPrototype.map, push = ArrayPrototype.push, slice = ArrayPrototype.slice, some = ArrayPrototype.some, splice = ArrayPrototype.splice;\nvar idRe = /^#(?:[\\w-]|\\\\.|[^\\x00-\\xa0])*$/;\nvar classRe = /^\\.(?:[\\w-]|\\\\.|[^\\x00-\\xa0])*$/;\nvar htmlRe = /<.+>/;\nvar tagRe = /^\\w+$/;\n// @require ./variables.ts\nfunction find(selector, context) {\n var isFragment = isDocumentFragment(context);\n return !selector || (!isFragment && !isDocument(context) && !isElement(context))\n ? []\n : !isFragment && classRe.test(selector)\n ? context.getElementsByClassName(selector.slice(1).replace(/\\\\/g, ''))\n : !isFragment && tagRe.test(selector)\n ? context.getElementsByTagName(selector)\n : context.querySelectorAll(selector);\n}\n// @require ./find.ts\n// @require ./variables.ts\nvar Cash = /** @class */ (function () {\n function Cash(selector, context) {\n if (!selector)\n return;\n if (isCash(selector))\n return selector;\n var eles = selector;\n if (isString(selector)) {\n var ctx = context || doc;\n eles = idRe.test(selector) && isDocument(ctx)\n ? ctx.getElementById(selector.slice(1).replace(/\\\\/g, ''))\n : htmlRe.test(selector)\n ? parseHTML(selector)\n : isCash(ctx)\n ? ctx.find(selector)\n : isString(ctx)\n ? cash(ctx).find(selector)\n : find(selector, ctx);\n if (!eles)\n return;\n }\n else if (isFunction(selector)) {\n return this.ready(selector); //FIXME: `fn.ready` is not included in `core`, but it's actually a core functionality\n }\n if (eles.nodeType || eles === win)\n eles = [eles];\n this.length = eles.length;\n for (var i = 0, l = this.length; i < l; i++) {\n this[i] = eles[i];\n }\n }\n Cash.prototype.init = function (selector, context) {\n return new Cash(selector, context);\n };\n return Cash;\n}());\nvar fn = Cash.prototype;\nvar cash = fn.init;\ncash.fn = cash.prototype = fn; // Ensuring that `cash () instanceof cash`\nfn.length = 0;\nfn.splice = splice; // Ensuring a cash collection gets printed as array-like in Chrome's devtools\nif (typeof Symbol === 'function') { // Ensuring a cash collection is iterable\n fn[Symbol['iterator']] = ArrayPrototype[Symbol['iterator']];\n}\nfunction isCash(value) {\n return value instanceof Cash;\n}\nfunction isWindow(value) {\n return !!value && value === value.window;\n}\nfunction isDocument(value) {\n return !!value && value.nodeType === 9;\n}\nfunction isDocumentFragment(value) {\n return !!value && value.nodeType === 11;\n}\nfunction isElement(value) {\n return !!value && value.nodeType === 1;\n}\nfunction isText(value) {\n return !!value && value.nodeType === 3;\n}\nfunction isBoolean(value) {\n return typeof value === 'boolean';\n}\nfunction isFunction(value) {\n return typeof value === 'function';\n}\nfunction isString(value) {\n return typeof value === 'string';\n}\nfunction isUndefined(value) {\n return value === undefined;\n}\nfunction isNull(value) {\n return value === null;\n}\nfunction isNumeric(value) {\n return !isNaN(parseFloat(value)) && isFinite(value);\n}\nfunction isPlainObject(value) {\n if (typeof value !== 'object' || value === null)\n return false;\n var proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\ncash.isWindow = isWindow;\ncash.isFunction = isFunction;\ncash.isArray = isArray;\ncash.isNumeric = isNumeric;\ncash.isPlainObject = isPlainObject;\nfunction each(arr, callback, _reverse) {\n if (_reverse) {\n var i = arr.length;\n while (i--) {\n if (callback.call(arr[i], i, arr[i]) === false)\n return arr;\n }\n }\n else if (isPlainObject(arr)) {\n var keys = Object.keys(arr);\n for (var i = 0, l = keys.length; i < l; i++) {\n var key = keys[i];\n if (callback.call(arr[key], key, arr[key]) === false)\n return arr;\n }\n }\n else {\n for (var i = 0, l = arr.length; i < l; i++) {\n if (callback.call(arr[i], i, arr[i]) === false)\n return arr;\n }\n }\n return arr;\n}\ncash.each = each;\nfn.each = function (callback) {\n return each(this, callback);\n};\nfn.empty = function () {\n return this.each(function (i, ele) {\n while (ele.firstChild) {\n ele.removeChild(ele.firstChild);\n }\n });\n};\nfunction extend() {\n var sources = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n sources[_i] = arguments[_i];\n }\n var deep = isBoolean(sources[0]) ? sources.shift() : false;\n var target = sources.shift();\n var length = sources.length;\n if (!target)\n return {};\n if (!length)\n return extend(deep, cash, target);\n for (var i = 0; i < length; i++) {\n var source = sources[i];\n for (var key in source) {\n if (deep && (isArray(source[key]) || isPlainObject(source[key]))) {\n if (!target[key] || target[key].constructor !== source[key].constructor)\n target[key] = new source[key].constructor();\n extend(deep, target[key], source[key]);\n }\n else {\n target[key] = source[key];\n }\n }\n }\n return target;\n}\ncash.extend = extend;\nfn.extend = function (plugins) {\n return extend(fn, plugins);\n};\n// @require ./type_checking.ts\nvar splitValuesRe = /\\S+/g;\nfunction getSplitValues(str) {\n return isString(str) ? str.match(splitValuesRe) || [] : [];\n}\nfn.toggleClass = function (cls, force) {\n var classes = getSplitValues(cls);\n var isForce = !isUndefined(force);\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n each(classes, function (i, c) {\n if (isForce) {\n force ? ele.classList.add(c) : ele.classList.remove(c);\n }\n else {\n ele.classList.toggle(c);\n }\n });\n });\n};\nfn.addClass = function (cls) {\n return this.toggleClass(cls, true);\n};\nfn.removeAttr = function (attr) {\n var attrs = getSplitValues(attr);\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n each(attrs, function (i, a) {\n ele.removeAttribute(a);\n });\n });\n};\nfunction attr(attr, value) {\n if (!attr)\n return;\n if (isString(attr)) {\n if (arguments.length < 2) {\n if (!this[0] || !isElement(this[0]))\n return;\n var value_1 = this[0].getAttribute(attr);\n return isNull(value_1) ? undefined : value_1;\n }\n if (isUndefined(value))\n return this;\n if (isNull(value))\n return this.removeAttr(attr);\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n ele.setAttribute(attr, value);\n });\n }\n for (var key in attr) {\n this.attr(key, attr[key]);\n }\n return this;\n}\nfn.attr = attr;\nfn.removeClass = function (cls) {\n if (arguments.length)\n return this.toggleClass(cls, false);\n return this.attr('class', '');\n};\nfn.hasClass = function (cls) {\n return !!cls && some.call(this, function (ele) { return isElement(ele) && ele.classList.contains(cls); });\n};\nfn.get = function (index) {\n if (isUndefined(index))\n return slice.call(this);\n index = Number(index);\n return this[index < 0 ? index + this.length : index];\n};\nfn.eq = function (index) {\n return cash(this.get(index));\n};\nfn.first = function () {\n return this.eq(0);\n};\nfn.last = function () {\n return this.eq(-1);\n};\nfunction text(text) {\n if (isUndefined(text)) {\n return this.get().map(function (ele) { return isElement(ele) || isText(ele) ? ele.textContent : ''; }).join('');\n }\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n ele.textContent = text;\n });\n}\nfn.text = text;\n// @require core/type_checking.ts\n// @require core/variables.ts\nfunction computeStyle(ele, prop, isVariable) {\n if (!isElement(ele))\n return;\n var style = win.getComputedStyle(ele, null);\n return isVariable ? style.getPropertyValue(prop) || undefined : style[prop] || ele.style[prop];\n}\n// @require ./compute_style.ts\nfunction computeStyleInt(ele, prop) {\n return parseInt(computeStyle(ele, prop), 10) || 0;\n}\n// @require css/helpers/compute_style_int.ts\nfunction getExtraSpace(ele, xAxis) {\n return computeStyleInt(ele, \"border\".concat(xAxis ? 'Left' : 'Top', \"Width\")) + computeStyleInt(ele, \"padding\".concat(xAxis ? 'Left' : 'Top')) + computeStyleInt(ele, \"padding\".concat(xAxis ? 'Right' : 'Bottom')) + computeStyleInt(ele, \"border\".concat(xAxis ? 'Right' : 'Bottom', \"Width\"));\n}\n// @require css/helpers/compute_style.ts\nvar defaultDisplay = {};\nfunction getDefaultDisplay(tagName) {\n if (defaultDisplay[tagName])\n return defaultDisplay[tagName];\n var ele = createElement(tagName);\n doc.body.insertBefore(ele, null);\n var display = computeStyle(ele, 'display');\n doc.body.removeChild(ele);\n return defaultDisplay[tagName] = display !== 'none' ? display : 'block';\n}\n// @require css/helpers/compute_style.ts\nfunction isHidden(ele) {\n return computeStyle(ele, 'display') === 'none';\n}\n// @require ./cash.ts\nfunction matches(ele, selector) {\n var matches = ele && (ele['matches'] || ele['webkitMatchesSelector'] || ele['msMatchesSelector']);\n return !!matches && !!selector && matches.call(ele, selector);\n}\n// @require ./matches.ts\n// @require ./type_checking.ts\nfunction getCompareFunction(comparator) {\n return isString(comparator)\n ? function (i, ele) { return matches(ele, comparator); }\n : isFunction(comparator)\n ? comparator\n : isCash(comparator)\n ? function (i, ele) { return comparator.is(ele); }\n : !comparator\n ? function () { return false; }\n : function (i, ele) { return ele === comparator; };\n}\nfn.filter = function (comparator) {\n var compare = getCompareFunction(comparator);\n return cash(filter.call(this, function (ele, i) { return compare.call(ele, i, ele); }));\n};\n// @require collection/filter.ts\nfunction filtered(collection, comparator) {\n return !comparator ? collection : collection.filter(comparator);\n}\nfn.detach = function (comparator) {\n filtered(this, comparator).each(function (i, ele) {\n if (ele.parentNode) {\n ele.parentNode.removeChild(ele);\n }\n });\n return this;\n};\nvar fragmentRe = /^\\s*<(\\w+)[^>]*>/;\nvar singleTagRe = /^<(\\w+)\\s*\\/?>(?:<\\/\\1>)?$/;\nvar containers = {\n '*': div,\n tr: tbody,\n td: tr,\n th: tr,\n thead: table,\n tbody: table,\n tfoot: table\n};\n//TODO: Create elements inside a document fragment, in order to prevent inline event handlers from firing\n//TODO: Ensure the created elements have the fragment as their parent instead of null, this also ensures we can deal with detatched nodes more reliably\nfunction parseHTML(html) {\n if (!isString(html))\n return [];\n if (singleTagRe.test(html))\n return [createElement(RegExp.$1)];\n var fragment = fragmentRe.test(html) && RegExp.$1;\n var container = containers[fragment] || containers['*'];\n container.innerHTML = html;\n return cash(container.childNodes).detach().get();\n}\ncash.parseHTML = parseHTML;\nfn.has = function (selector) {\n var comparator = isString(selector)\n ? function (i, ele) { return find(selector, ele).length; }\n : function (i, ele) { return ele.contains(selector); };\n return this.filter(comparator);\n};\nfn.not = function (comparator) {\n var compare = getCompareFunction(comparator);\n return this.filter(function (i, ele) { return (!isString(comparator) || isElement(ele)) && !compare.call(ele, i, ele); });\n};\nfunction pluck(arr, prop, deep, until) {\n var plucked = [];\n var isCallback = isFunction(prop);\n var compare = until && getCompareFunction(until);\n for (var i = 0, l = arr.length; i < l; i++) {\n if (isCallback) {\n var val_1 = prop(arr[i]);\n if (val_1.length)\n push.apply(plucked, val_1);\n }\n else {\n var val_2 = arr[i][prop];\n while (val_2 != null) {\n if (until && compare(-1, val_2))\n break;\n plucked.push(val_2);\n val_2 = deep ? val_2[prop] : null;\n }\n }\n }\n return plucked;\n}\n// @require core/pluck.ts\n// @require core/variables.ts\nfunction getValue(ele) {\n if (ele.multiple && ele.options)\n return pluck(filter.call(ele.options, function (option) { return option.selected && !option.disabled && !option.parentNode.disabled; }), 'value');\n return ele.value || '';\n}\nfunction val(value) {\n if (!arguments.length)\n return this[0] && getValue(this[0]);\n return this.each(function (i, ele) {\n var isSelect = ele.multiple && ele.options;\n if (isSelect || checkableRe.test(ele.type)) {\n var eleValue_1 = isArray(value) ? map.call(value, String) : (isNull(value) ? [] : [String(value)]);\n if (isSelect) {\n each(ele.options, function (i, option) {\n option.selected = eleValue_1.indexOf(option.value) >= 0;\n }, true);\n }\n else {\n ele.checked = eleValue_1.indexOf(ele.value) >= 0;\n }\n }\n else {\n ele.value = isUndefined(value) || isNull(value) ? '' : value;\n }\n });\n}\nfn.val = val;\nfn.is = function (comparator) {\n var compare = getCompareFunction(comparator);\n return some.call(this, function (ele, i) { return compare.call(ele, i, ele); });\n};\ncash.guid = 1;\nfunction unique(arr) {\n return arr.length > 1 ? filter.call(arr, function (item, index, self) { return indexOf.call(self, item) === index; }) : arr;\n}\ncash.unique = unique;\nfn.add = function (selector, context) {\n return cash(unique(this.get().concat(cash(selector, context).get())));\n};\nfn.children = function (comparator) {\n return filtered(cash(unique(pluck(this, function (ele) { return ele.children; }))), comparator);\n};\nfn.parent = function (comparator) {\n return filtered(cash(unique(pluck(this, 'parentNode'))), comparator);\n};\nfn.index = function (selector) {\n var child = selector ? cash(selector)[0] : this[0];\n var collection = selector ? this : cash(child).parent().children();\n return indexOf.call(collection, child);\n};\nfn.closest = function (comparator) {\n var filtered = this.filter(comparator);\n if (filtered.length)\n return filtered;\n var $parent = this.parent();\n if (!$parent.length)\n return filtered;\n return $parent.closest(comparator);\n};\nfn.siblings = function (comparator) {\n return filtered(cash(unique(pluck(this, function (ele) { return cash(ele).parent().children().not(ele); }))), comparator);\n};\nfn.find = function (selector) {\n return cash(unique(pluck(this, function (ele) { return find(selector, ele); })));\n};\n// @require core/variables.ts\n// @require collection/filter.ts\n// @require traversal/find.ts\nvar HTMLCDATARe = /^\\s*<!(?:\\[CDATA\\[|--)|(?:\\]\\]|--)>\\s*$/g;\nvar scriptTypeRe = /^$|^module$|\\/(java|ecma)script/i;\nvar scriptAttributes = ['type', 'src', 'nonce', 'noModule'];\nfunction evalScripts(node, doc) {\n var collection = cash(node);\n collection.filter('script').add(collection.find('script')).each(function (i, ele) {\n if (scriptTypeRe.test(ele.type) && docEle.contains(ele)) { // The script type is supported // The element is attached to the DOM // Using `documentElement` for broader browser support\n var script_1 = createElement('script');\n script_1.text = ele.textContent.replace(HTMLCDATARe, '');\n each(scriptAttributes, function (i, attr) {\n if (ele[attr])\n script_1[attr] = ele[attr];\n });\n doc.head.insertBefore(script_1, null);\n doc.head.removeChild(script_1);\n }\n });\n}\n// @require ./eval_scripts.ts\nfunction insertElement(anchor, target, left, inside, evaluate) {\n if (inside) { // prepend/append\n anchor.insertBefore(target, left ? anchor.firstChild : null);\n }\n else { // before/after\n if (anchor.nodeName === 'HTML') {\n anchor.parentNode.replaceChild(target, anchor);\n }\n else {\n anchor.parentNode.insertBefore(target, left ? anchor : anchor.nextSibling);\n }\n }\n if (evaluate) {\n evalScripts(target, anchor.ownerDocument);\n }\n}\n// @require ./insert_element.ts\nfunction insertSelectors(selectors, anchors, inverse, left, inside, reverseLoop1, reverseLoop2, reverseLoop3) {\n each(selectors, function (si, selector) {\n each(cash(selector), function (ti, target) {\n each(cash(anchors), function (ai, anchor) {\n var anchorFinal = inverse ? target : anchor;\n var targetFinal = inverse ? anchor : target;\n var indexFinal = inverse ? ti : ai;\n insertElement(anchorFinal, !indexFinal ? targetFinal : targetFinal.cloneNode(true), left, inside, !indexFinal);\n }, reverseLoop3);\n }, reverseLoop2);\n }, reverseLoop1);\n return anchors;\n}\nfn.after = function () {\n return insertSelectors(arguments, this, false, false, false, true, true);\n};\nfn.append = function () {\n return insertSelectors(arguments, this, false, false, true);\n};\nfunction html(html) {\n if (!arguments.length)\n return this[0] && this[0].innerHTML;\n if (isUndefined(html))\n return this;\n var hasScript = /<script[\\s>]/.test(html);\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n if (hasScript) {\n cash(ele).empty().append(html);\n }\n else {\n ele.innerHTML = html;\n }\n });\n}\nfn.html = html;\nfn.appendTo = function (selector) {\n return insertSelectors(arguments, this, true, false, true);\n};\nfn.wrapInner = function (selector) {\n return this.each(function (i, ele) {\n var $ele = cash(ele);\n var contents = $ele.contents();\n contents.length ? contents.wrapAll(selector) : $ele.append(selector);\n });\n};\nfn.before = function () {\n return insertSelectors(arguments, this, false, true);\n};\nfn.wrapAll = function (selector) {\n var structure = cash(selector);\n var wrapper = structure[0];\n while (wrapper.children.length)\n wrapper = wrapper.firstElementChild;\n this.first().before(structure);\n return this.appendTo(wrapper);\n};\nfn.wrap = function (selector) {\n return this.each(function (i, ele) {\n var wrapper = cash(selector)[0];\n cash(ele).wrapAll(!i ? wrapper : wrapper.cloneNode(true));\n });\n};\nfn.insertAfter = function (selector) {\n return insertSelectors(arguments, this, true, false, false, false, false, true);\n};\nfn.insertBefore = function (selector) {\n return insertSelectors(arguments, this, true, true);\n};\nfn.prepend = function () {\n return insertSelectors(arguments, this, false, true, true, true, true);\n};\nfn.prependTo = function (selector) {\n return insertSelectors(arguments, this, true, true, true, false, false, true);\n};\nfn.contents = function () {\n return cash(unique(pluck(this, function (ele) { return ele.tagName === 'IFRAME' ? [ele.contentDocument] : (ele.tagName === 'TEMPLATE' ? ele.content.childNodes : ele.childNodes); })));\n};\nfn.next = function (comparator, _all, _until) {\n return filtered(cash(unique(pluck(this, 'nextElementSibling', _all, _until))), comparator);\n};\nfn.nextAll = function (comparator) {\n return this.next(comparator, true);\n};\nfn.nextUntil = function (until, comparator) {\n return this.next(comparator, true, until);\n};\nfn.parents = function (comparator, _until) {\n return filtered(cash(unique(pluck(this, 'parentElement', true, _until))), comparator);\n};\nfn.parentsUntil = function (until, comparator) {\n return this.parents(comparator, until);\n};\nfn.prev = function (comparator, _all, _until) {\n return filtered(cash(unique(pluck(this, 'previousElementSibling', _all, _until))), comparator);\n};\nfn.prevAll = function (comparator) {\n return this.prev(comparator, true);\n};\nfn.prevUntil = function (until, comparator) {\n return this.prev(comparator, true, until);\n};\nfn.map = function (callback) {\n return cash(concat.apply([], map.call(this, function (ele, i) { return callback.call(ele, i, ele); })));\n};\nfn.clone = function () {\n return this.map(function (i, ele) { return ele.cloneNode(true); });\n};\nfn.offsetParent = function () {\n return this.map(function (i, ele) {\n var offsetParent = ele.offsetParent;\n while (offsetParent && computeStyle(offsetParent, 'position') === 'static') {\n offsetParent = offsetParent.offsetParent;\n }\n return offsetParent || docEle;\n });\n};\nfn.slice = function (start, end) {\n return cash(slice.call(this, start, end));\n};\n// @require ./cash.ts\nvar dashAlphaRe = /-([a-z])/g;\nfunction camelCase(str) {\n return str.replace(dashAlphaRe, function (match, letter) { return letter.toUpperCase(); });\n}\nfn.ready = function (callback) {\n var cb = function () { return setTimeout(callback, 0, cash); };\n if (doc.readyState !== 'loading') {\n cb();\n }\n else {\n doc.addEventListener('DOMContentLoaded', cb);\n }\n return this;\n};\nfn.unwrap = function () {\n this.parent().each(function (i, ele) {\n if (ele.tagName === 'BODY')\n return;\n var $ele = cash(ele);\n $ele.replaceWith($ele.children());\n });\n return this;\n};\nfn.offset = function () {\n var ele = this[0];\n if (!ele)\n return;\n var rect = ele.getBoundingClientRect();\n return {\n top: rect.top + win.pageYOffset,\n left: rect.left + win.pageXOffset\n };\n};\nfn.position = function () {\n var ele = this[0];\n if (!ele)\n return;\n var isFixed = (computeStyle(ele, 'position') === 'fixed');\n var offset = isFixed ? ele.getBoundingClientRect() : this.offset();\n if (!isFixed) {\n var doc_1 = ele.ownerDocument;\n var offsetParent = ele.offsetParent || doc_1.documentElement;\n while ((offsetParent === doc_1.body || offsetParent === doc_1.documentElement) && computeStyle(offsetParent, 'position') === 'static') {\n offsetParent = offsetParent.parentNode;\n }\n if (offsetParent !== ele && isElement(offsetParent)) {\n var parentOffset = cash(offsetParent).offset();\n offset.top -= parentOffset.top + computeStyleInt(offsetParent, 'borderTopWidth');\n offset.left -= parentOffset.left + computeStyleInt(offsetParent, 'borderLeftWidth');\n }\n }\n return {\n top: offset.top - computeStyleInt(ele, 'marginTop'),\n left: offset.left - computeStyleInt(ele, 'marginLeft')\n };\n};\nvar propMap = {\n /* GENERAL */\n class: 'className',\n contenteditable: 'contentEditable',\n /* LABEL */\n for: 'htmlFor',\n /* INPUT */\n readonly: 'readOnly',\n maxlength: 'maxLength',\n tabindex: 'tabIndex',\n /* TABLE */\n colspan: 'colSpan',\n rowspan: 'rowSpan',\n /* IMAGE */\n usemap: 'useMap'\n};\nfn.prop = function (prop, value) {\n if (!prop)\n return;\n if (isString(prop)) {\n prop = propMap[prop] || prop;\n if (arguments.length < 2)\n return this[0] && this[0][prop];\n return this.each(function (i, ele) { ele[prop] = value; });\n }\n for (var key in prop) {\n this.prop(key, prop[key]);\n }\n return this;\n};\nfn.removeProp = function (prop) {\n return this.each(function (i, ele) { delete ele[propMap[prop] || prop]; });\n};\nvar cssVariableRe = /^--/;\n// @require ./variables.ts\nfunction isCSSVariable(prop) {\n return cssVariableRe.test(prop);\n}\n// @require core/camel_case.ts\n// @require core/cash.ts\n// @require core/each.ts\n// @require core/variables.ts\n// @require ./is_css_variable.ts\nvar prefixedProps = {};\nvar style = div.style;\nvar vendorsPrefixes = ['webkit', 'moz', 'ms'];\nfunction getPrefixedProp(prop, isVariable) {\n if (isVariable === void 0) { isVariable = isCSSVariable(prop); }\n if (isVariable)\n return prop;\n if (!prefixedProps[prop]) {\n var propCC = camelCase(prop);\n var propUC = \"\".concat(propCC[0].toUpperCase()).concat(propCC.slice(1));\n var props = (\"\".concat(propCC, \" \").concat(vendorsPrefixes.join(\"\".concat(propUC, \" \"))).concat(propUC)).split(' ');\n each(props, function (i, p) {\n if (p in style) {\n prefixedProps[prop] = p;\n return false;\n }\n });\n }\n return prefixedProps[prop];\n}\n// @require core/type_checking.ts\n// @require ./is_css_variable.ts\nvar numericProps = {\n animationIterationCount: true,\n columnCount: true,\n flexGrow: true,\n flexShrink: true,\n fontWeight: true,\n gridArea: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnStart: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowStart: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n widows: true,\n zIndex: true\n};\nfunction getSuffixedValue(prop, value, isVariable) {\n if (isVariable === void 0) { isVariable = isCSSVariable(prop); }\n return !isVariable && !numericProps[prop] && isNumeric(value) ? \"\".concat(value, \"px\") : value;\n}\nfunction css(prop, value) {\n if (isString(prop)) {\n var isVariable_1 = isCSSVariable(prop);\n prop = getPrefixedProp(prop, isVariable_1);\n if (arguments.length < 2)\n return this[0] && computeStyle(this[0], prop, isVariable_1);\n if (!prop)\n return this;\n value = getSuffixedValue(prop, value, isVariable_1);\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n if (isVariable_1) {\n ele.style.setProperty(prop, value);\n }\n else {\n ele.style[prop] = value;\n }\n });\n }\n for (var key in prop) {\n this.css(key, prop[key]);\n }\n return this;\n}\n;\nfn.css = css;\nfunction attempt(fn, arg) {\n try {\n return fn(arg);\n }\n catch (_a) {\n return arg;\n }\n}\n// @require core/attempt.ts\n// @require core/camel_case.ts\nvar JSONStringRe = /^\\s+|\\s+$/;\nfunction getData(ele, key) {\n var value = ele.dataset[key] || ele.dataset[camelCase(key)];\n if (JSONStringRe.test(value))\n return value;\n return attempt(JSON.parse, value);\n}\n// @require core/attempt.ts\n// @require core/camel_case.ts\nfunction setData(ele, key, value) {\n value = attempt(JSON.stringify, value);\n ele.dataset[camelCase(key)] = value;\n}\nfunction data(name, value) {\n if (!name) {\n if (!this[0])\n return;\n var datas = {};\n for (var key in this[0].dataset) {\n datas[key] = getData(this[0], key);\n }\n return datas;\n }\n if (isString(name)) {\n if (arguments.length < 2)\n return this[0] && getData(this[0], name);\n if (isUndefined(value))\n return this;\n return this.each(function (i, ele) { setData(ele, name, value); });\n }\n for (var key in name) {\n this.data(key, name[key]);\n }\n return this;\n}\nfn.data = data;\nfunction getDocumentDimension(doc, dimension) {\n var docEle = doc.documentElement;\n return Math.max(doc.body[\"scroll\".concat(dimension)], docEle[\"scroll\".concat(dimension)], doc.body[\"offset\".concat(dimension)], docEle[\"offset\".concat(dimension)], docEle[\"client\".concat(dimension)]);\n}\neach([true, false], function (i, outer) {\n each(['Width', 'Height'], function (i, prop) {\n var name = \"\".concat(outer ? 'outer' : 'inner').concat(prop);\n fn[name] = function (includeMargins) {\n if (!this[0])\n return;\n if (isWindow(this[0]))\n return outer ? this[0][\"inner\".concat(prop)] : this[0].document.documentElement[\"client\".concat(prop)];\n if (isDocument(this[0]))\n return getDocumentDimension(this[0], prop);\n return this[0][\"\".concat(outer ? 'offset' : 'client').concat(prop)] + (includeMargins && outer ? computeStyleInt(this[0], \"margin\".concat(i ? 'Top' : 'Left')) + computeStyleInt(this[0], \"margin\".concat(i ? 'Bottom' : 'Right')) : 0);\n };\n });\n});\neach(['Width', 'Height'], function (index, prop) {\n var propLC = prop.toLowerCase();\n fn[propLC] = function (value) {\n if (!this[0])\n return isUndefined(value) ? undefined : this;\n if (!arguments.length) {\n if (isWindow(this[0]))\n return this[0].document.documentElement[\"client\".concat(prop)];\n if (isDocument(this[0]))\n return getDocumentDimension(this[0], prop);\n return this[0].getBoundingClientRect()[propLC] - getExtraSpace(this[0], !index);\n }\n var valueNumber = parseInt(value, 10);\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n var boxSizing = computeStyle(ele, 'boxSizing');\n ele.style[propLC] = getSuffixedValue(propLC, valueNumber + (boxSizing === 'border-box' ? getExtraSpace(ele, !index) : 0));\n });\n };\n});\nvar displayProperty = '___cd';\nfn.toggle = function (force) {\n return this.each(function (i, ele) {\n if (!isElement(ele))\n return;\n var hidden = isHidden(ele);\n var show = isUndefined(force) ? hidden : force;\n if (show) {\n ele.style.display = ele[displayProperty] || '';\n if (isHidden(ele)) {\n ele.style.display = getDefaultDisplay(ele.tagName);\n }\n }\n else if (!hidden) {\n ele[displayProperty] = computeStyle(ele, 'display');\n ele.style.display = 'none';\n }\n });\n};\nfn.hide = function () {\n return this.toggle(false);\n};\nfn.show = function () {\n return this.toggle(true);\n};\nvar eventsNamespace = '___ce';\nvar eventsNamespacesSeparator = '.';\nvar eventsFocus = { focus: 'focusin', blur: 'focusout' };\nvar eventsHover = { mouseenter: 'mouseover', mouseleave: 'mouseout' };\nvar eventsMouseRe = /^(mouse|pointer|contextmenu|drag|drop|click|dblclick)/i;\n// @require ./variables.ts\nfunction getEventNameBubbling(name) {\n return eventsHover[name] || eventsFocus[name] || name;\n}\n// @require ./variables.ts\nfunction parseEventName(eventName) {\n var parts = eventName.split(eventsNamespacesSeparator);\n return [parts[0], parts.slice(1).sort()]; // [name, namespace[]]\n}\nfn.trigger = function (event, data) {\n if (isString(event)) {\n var _a = parseEventName(event), nameOriginal = _a[0], namespaces = _a[1];\n var name_1 = getEventNameBubbling(nameOriginal);\n if (!name_1)\n return this;\n var type = eventsMouseRe.test(name_1) ? 'MouseEvents' : 'HTMLEvents';\n event = doc.createEvent(type);\n event.initEvent(name_1, true, true);\n event.namespace = namespaces.join(eventsNamespacesSeparator);\n event.___ot = nameOriginal;\n }\n event.___td = data;\n var isEventFocus = (event.___ot in eventsFocus);\n return this.each(function (i, ele) {\n if (isEventFocus && isFunction(ele[event.___ot])) {\n ele[\"___i\".concat(event.type)] = true; // Ensuring the native event is ignored\n ele[event.___ot]();\n ele[\"___i\".concat(event.type)] = false; // Ensuring the custom event is not ignored\n }\n ele.dispatchEvent(event);\n });\n};\n// @require ./variables.ts\nfunction getEventsCache(ele) {\n return ele[eventsNamespace] = (ele[eventsNamespace] || {});\n}\n// @require core/guid.ts\n// @require events/helpers/get_events_cache.ts\nfunction addEvent(ele, name, namespaces, selector, callback) {\n var eventCache = getEventsCache(ele);\n eventCache[name] = (eventCache[name] || []);\n eventCache[name].push([namespaces, selector, callback]);\n ele.addEventListener(name, callback);\n}\nfunction hasNamespaces(ns1, ns2) {\n return !ns2 || !some.call(ns2, function (ns) { return ns1.indexOf(ns) < 0; });\n}\n// @require ./get_events_cache.ts\n// @require ./has_namespaces.ts\n// @require ./parse_event_name.ts\nfunction removeEvent(ele, name, namespaces, selector, callback) {\n var cache = getEventsCache(ele);\n if (!name) {\n for (name in cache) {\n removeEvent(ele, name, namespaces, selector, callback);\n }\n }\n else if (cache[name]) {\n cache[name] = cache[name].filter(function (_a) {\n var ns = _a[0], sel = _a[1], cb = _a[2];\n if ((callback && cb.guid !== callback.guid) || !hasNamespaces(ns, namespaces) || (selector && selector !== sel))\n return true;\n ele.removeEventListener(name, cb);\n });\n }\n}\nfn.off = function (eventFullName, selector, callback) {\n var _this = this;\n if (isUndefined(eventFullName)) {\n this.each(function (i, ele) {\n if (!isElement(ele) && !isDocument(ele) && !isWindow(ele))\n return;\n removeEvent(ele);\n });\n }\n else if (!isString(eventFullName)) {\n for (var key in eventFullName) {\n this.off(key, eventFullName[key]);\n }\n }\n else {\n if (isFunction(selector)) {\n callback = selector;\n selector = '';\n }\n each(getSplitValues(eventFullName), function (i, eventFullName) {\n var _a = parseEventName(eventFullName), nameOriginal = _a[0], namespaces = _a[1];\n var name = getEventNameBubbling(nameOriginal);\n _this.each(function (i, ele) {\n if (!isElement(ele) && !isDocument(ele) && !isWindow(ele))\n return;\n removeEvent(ele, name, namespaces, selector, callback);\n });\n });\n }\n return this;\n};\nfn.remove = function (comparator) {\n filtered(this, comparator).detach().off();\n return this;\n};\nfn.replaceWith = function (selector) {\n return this.before(selector).remove();\n};\nfn.replaceAll = function (selector) {\n cash(selector).replaceWith(this);\n return this;\n};\nfunction on(eventFullName, selector, data, callback, _one) {\n var _this = this;\n if (!isString(eventFullName)) {\n for (var key in eventFullName) {\n this.on(key, selector, data, eventFullName[key], _one);\n }\n return this;\n }\n if (!isString(selector)) {\n if (isUndefined(selector) || isNull(selector)) {\n selector = '';\n }\n else if (isUndefined(data)) {\n data = selector;\n selector = '';\n }\n else {\n callback = data;\n data = selector;\n selector = '';\n }\n }\n if (!isFunction(callback)) {\n callback = data;\n data = undefined;\n }\n if (!callback)\n return this;\n each(getSplitValues(eventFullName), function (i, eventFullName) {\n var _a = parseEventName(eventFullName), nameOriginal = _a[0], namespaces = _a[1];\n var name = getEventNameBubbling(nameOriginal);\n var isEventHover = (nameOriginal in eventsHover);\n var isEventFocus = (nameOriginal in eventsFocus);\n if (!name)\n return;\n _this.each(function (i, ele) {\n if (!isElement(ele) && !isDocument(ele) && !isWindow(ele))\n return;\n var finalCallback = function (event) {\n if (event.target[\"___i\".concat(event.type)])\n return event.stopImmediatePropagation(); // Ignoring native event in favor of the upcoming custom one\n if (event.namespace && !hasNamespaces(namespaces, event.namespace.split(eventsNamespacesSeparator)))\n return;\n if (!selector && ((isEventFocus && (event.target !== ele || event.___ot === name)) || (isEventHover && event.relatedTarget && ele.contains(event.relatedTarget))))\n return;\n var thisArg = ele;\n if (selector) {\n var target = event.target;\n while (!matches(target, selector)) {\n if (target === ele)\n return;\n target = target.parentNode;\n if (!target)\n return;\n }\n thisArg = target;\n }\n Object.defineProperty(event, 'currentTarget', {\n configurable: true,\n get: function () {\n return thisArg;\n }\n });\n Object.defineProperty(event, 'delegateTarget', {\n configurable: true,\n get: function () {\n return ele;\n }\n });\n Object.defineProperty(event, 'data', {\n configurable: true,\n get: function () {\n return data;\n }\n });\n var returnValue = callback.call(thisArg, event, event.___td);\n if (_one) {\n removeEvent(ele, name, namespaces, selector, finalCallback);\n }\n if (returnValue === false) {\n event.preventDefault();\n event.stopPropagation();\n }\n };\n finalCallback.guid = callback.guid = (callback.guid || cash.guid++);\n addEvent(ele, name, namespaces, selector, finalCallback);\n });\n });\n return this;\n}\nfn.on = on;\nfunction one(eventFullName, selector, data, callback) {\n return this.on(eventFullName, selector, data, callback, true);\n}\n;\nfn.one = one;\nvar queryEncodeCRLFRe = /\\r?\\n/g;\nfunction queryEncode(prop, value) {\n return \"&\".concat(encodeURIComponent(prop), \"=\").concat(encodeURIComponent(value.replace(queryEncodeCRLFRe, '\\r\\n')));\n}\nvar skippableRe = /file|reset|submit|button|image/i;\nvar checkableRe = /radio|checkbox/i;\nfn.serialize = function () {\n var query = '';\n this.each(function (i, ele) {\n each(ele.elements || [ele], function (i, ele) {\n if (ele.disabled || !ele.name || ele.tagName === 'FIELDSET' || skippableRe.test(ele.type) || (checkableRe.test(ele.type) && !ele.checked))\n return;\n var value = getValue(ele);\n if (!isUndefined(value)) {\n var values = isArray(value) ? value : [value];\n each(values, function (i, value) {\n query += queryEncode(ele.name, value);\n });\n }\n });\n });\n return query.slice(1);\n};\n// @require core/types.ts\n// @require core/cash.ts\n// @require core/type_checking.ts\n// @require core/variables.ts\n// @require core/each.ts\n// @require core/extend.ts\n// @require core/find.ts\n// @require core/get_compare_function.ts\n// @require core/get_split_values.ts\n// @require core/guid.ts\n// @require core/parse_html.ts\n// @require core/unique.ts\n// @require attributes/add_class.ts\n// @require attributes/attr.ts\n// @require attributes/has_class.ts\n// @require attributes/prop.ts\n// @require attributes/remove_attr.ts\n// @require attributes/remove_class.ts\n// @require attributes/remove_prop.ts\n// @require attributes/toggle_class.ts\n// @require collection/add.ts\n// @require collection/each.ts\n// @require collection/eq.ts\n// @require collection/filter.ts\n// @require collection/first.ts\n// @require collection/get.ts\n// @require collection/index.ts\n// @require collection/last.ts\n// @require collection/map.ts\n// @require collection/slice.ts\n// @require css/css.ts\n// @require data/data.ts\n// @require dimensions/inner_outer.ts\n// @require dimensions/normal.ts\n// @require effects/hide.ts\n// @require effects/show.ts\n// @require effects/toggle.ts\n// @require events/off.ts\n// @require events/on.ts\n// @require events/one.ts\n// @require events/ready.ts\n// @require events/trigger.ts\n// @require forms/serialize.ts\n// @require forms/val.ts\n// @require manipulation/after.ts\n// @require manipulation/append.ts\n// @require manipulation/append_to.ts\n// @require manipulation/before.ts\n// @require manipulation/clone.ts\n// @require manipulation/detach.ts\n// @require manipulation/empty.ts\n// @require manipulation/html.ts\n// @require manipulation/insert_after.ts\n// @require manipulation/insert_before.ts\n// @require manipulation/prepend.ts\n// @require manipulation/prepend_to.ts\n// @require manipulation/remove.ts\n// @require manipulation/replace_all.ts\n// @require manipulation/replace_with.ts\n// @require manipulation/text.ts\n// @require manipulation/unwrap.ts\n// @require manipulation/wrap.ts\n// @require manipulation/wrap_all.ts\n// @require manipulation/wrap_inner.ts\n// @require offset/offset.ts\n// @require offset/offset_parent.ts\n// @require offset/position.ts\n// @require traversal/children.ts\n// @require traversal/closest.ts\n// @require traversal/contents.ts\n// @require traversal/find.ts\n// @require traversal/has.ts\n// @require traversal/is.ts\n// @require traversal/next.ts\n// @require traversal/next_all.ts\n// @require traversal/next_until.ts\n// @require traversal/not.ts\n// @require traversal/parent.ts\n// @require traversal/parents.ts\n// @require traversal/parents_until.ts\n// @require traversal/prev.ts\n// @require traversal/prev_all.ts\n// @require traversal/prev_until.ts\n// @require traversal/siblings.ts\n// @no-require extras/get_script.ts\n// @no-require extras/shorthands.ts\n// @require methods.ts\nif (typeof exports !== 'undefined') { // Node.js\n module.exports = cash;\n}\nelse { // Browser\n win['cash'] = win['$'] = cash;\n}\n})();",
|
|
6
|
-
"\nexport const ROOT_PATH = '#0'\nexport const I18N_ATTR_FLAG = 'i18n'\nexport const SYNCTAX_VAR_FLAG = 'syn:'\nexport const FUNCTION_ATTR_FLAG = 'fn:'\nexport const EVENT_LISTENER_FLAG = 'on-'\nexport const SPREAD_VAR_PATTERN = /^\\.\\.\\./\nexport const ARGUMENT_VAR_PATTERN = /^\\[(.*?)\\]$/\nexport const INTERPOLATE_PATTERN = /{\\s*([^{}]+)\\s*}/g\nexport const META_ATTRIBUTES = ['@html', '@text', '@format']\nexport const NATIVE_SYNTAX_TAGS = ['if', 'for', 'switch', 'async', 'router']\nexport const LAYOUT_AFFECTING_ATTRS = [ 'display', 'visibility', 'position', 'width', 'height' ]\n\nexport const NODE_PREFIX = ':n'\nexport const PARTIAL_ROOT_PREFIX = ':pr'\nexport const MACRO_PREFIX = 'm'\nexport const COMPONENT_PREFIX = 'c'\nexport const SYNTAX_COMPONENT_PREFIX = 'x'\nexport const DEFAULT_PARTIAL_PATH_SLOT = '*'\nexport const GENERIC_TAGNAME_ATTR = ':xtag'\nexport const DYNAMIC_TAGNAME_ATTR = ':dtag'\n\n/**\n * Constant for max update type priorities\n */\nexport const MAX_PRIORITY_TYPES = 100\n",
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"import { Metavars } from './types'\nimport type Component from './component'\n\ntype WatchData = {\n timeout: NodeJS.Timeout\n type: 'attach' | 'detach'\n}\n\n/**\n * DOM Watch Service\n */\nexport default class DWS<MT extends Metavars> {\n private domObserver: MutationObserver\n private observedComponents = new Map<Component<MT>, WatchData>()\n private readonly TIMEOUT = 10000 // 10 seconds\n\n constructor(){\n this.domObserver = new MutationObserver( () => {\n this.observedComponents.forEach( ( watchData, component ) => {\n try {\n const $node = component.node\n if( !$node ){\n this.unwatch( component )\n return\n }\n \n if( watchData.type === 'attach' && document.contains( $node[0] as Element ) ){\n this.unwatch( component )\n component.emit('component:attached')\n \n typeof component.onAttach == 'function'\n && component.onAttach.bind( component )()\n }\n else if( watchData.type === 'detach' && !document.contains( $node[0] as Element ) ){\n this.unwatch( component )\n component.emit('component:detached')\n\n typeof component.onDetach == 'function'\n && component.onDetach.bind( component )()\n }\n }\n catch( error ){ console.log('DWS error --', error ) }\n })\n\n // Stop observing if no components left to watch\n !this.observedComponents.size && this.domObserver.disconnect()\n })\n }\n\n watch( component: Component<MT>, type: 'attach' | 'detach' = 'attach' ){\n const $node = component.node\n if( !$node ) return\n\n // For attachment, check if already in DOM\n if( type === 'attach' && document.contains( $node[0] as Element ) ){\n component.emit('component:attached')\n\n typeof component.onAttach == 'function'\n && component.onAttach.bind( component )()\n \n return\n }\n\n // For detachment, check if already out of DOM\n if( type === 'detach' && !document.contains( $node[0] as Element ) ){\n component.emit('component:detached')\n\n typeof component.onDetach == 'function'\n && component.onDetach.bind( component )()\n\n return\n }\n\n // Clean up any existing watch\n this.unwatch( component )\n\n // Start new watch\n const timeout = setTimeout( () => {\n this.unwatch( component )\n component.emit(`component:${type}ment-timeout`)\n }, this.TIMEOUT )\n\n this.observedComponents.set( component, { timeout, type })\n\n // Start observing if first component\n this.observedComponents.size === 1\n && this.domObserver.observe( document.body, { childList: true, subtree: true })\n\n // Set up detachment watching once attached\n type === 'attach'\n && component.once('component:attached', () => this.watch( component, 'detach' ))\n }\n\n unwatch( component: Component<MT> ){\n const watchData = this.observedComponents.get( component )\n if( watchData ){\n clearTimeout( watchData.timeout )\n this.observedComponents.delete( component )\n }\n\n // Stop observing if no components left\n !this.observedComponents.size && this.domObserver.disconnect()\n }\n\n dispose(){\n this.domObserver.disconnect()\n this.observedComponents.forEach( watchData => clearTimeout( watchData.timeout ) )\n\n this.observedComponents.clear()\n }\n}",
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
"import $, { type Cash } from 'cash-dom'\nimport { compile, serialize, stringify, middleware } from 'stylis'\n\ntype StyleSettings = {\n sheet?: string\n meta?: boolean\n custom?: {\n enabled: boolean\n allowedRules: string[]\n allowedProperties: string[]\n }\n}\n\nexport default class Stylesheet {\n private nsp: string\n private settings: StyleSettings\n private $head: Cash\n\n constructor( nsp: string, settings?: StyleSettings ){\n if( typeof nsp !== 'string' ) \n throw new Error('Undefined or invalid styles attachement element(s) namespace')\n \n /**\n * Unique namespace identifier of targeted \n * views/elements\n */\n this.nsp = nsp\n\n /**\n * Head element of the DOM in where stylesheet\n * will be injected.\n */\n this.$head = $('head')\n\n /**\n * Styles settings\n * \n * - sheet\n * - custom\n */\n this.settings = settings || {}\n\n // Auto-load defined sheet rules\n this.settings && this.load( this.settings )\n }\n\n /**\n * Process sheet string using Stylis\n */\n compile( str: string ): string {\n try { return serialize( compile( str ), middleware([ stringify ]) ) } \n catch( error: any ){\n throw new Error(`Style compilation failed: ${error.message}`)\n }\n }\n\n /**\n * Wait for styles to be applied\n */\n private waitForStyles( selector: string ): Promise<void>{\n return new Promise( resolve => {\n const observer = new MutationObserver( () => {\n const element = document.querySelector( selector )\n if( element && getComputedStyle( element ).cssText ){\n observer.disconnect()\n resolve()\n }\n } )\n\n observer.observe( document.documentElement, {\n attributes: true,\n childList: true,\n subtree: true\n } )\n } )\n }\n\n /**\n * Compile and inject a style chunk in the DOM\n * using `<style mv-style=\"*\">...</style>` tag\n */\n private async inject( str: string ): Promise<HTMLStyleElement>{\n if( !str )\n throw new Error('Invalid injection arguments')\n\n const selector = `rel=\"${this.settings.meta ? '@' : ''}${this.nsp}\"`\n\n /**\n * Defined meta sheet properties or sheet by view \n * elements by wrapping in a closure using the \n * namespaces selector.\n */\n str = this.settings.meta ? str : `[rel=\"${this.nsp}\"] { ${str} }`\n\n try {\n const sheet = this.compile( str )\n if( !sheet )\n throw new Error(`<component:${this.nsp}> sheet compilation failed`)\n\n // Create new style element\n const styleSheet = document.createElement('style')\n styleSheet.setAttribute('rel', `${this.settings.meta ? '@' : ''}${this.nsp}` )\n styleSheet.textContent = sheet\n\n /**\n * `dindex` is a deletion index to keep track of\n * the share dependency of this style element by\n * all components bind to it.\n * \n * Every component `on-destroy` automatically\n * cleanup it's stylesheet but on if it's rendered\n * only once. In case of multiple renderings, the\n * index indicate the number of current rendering instances\n * of the component.\n * \n * - on instance created, `dindex` value increases\n * - on instance destroyed, `dindex` value decreases\n * - on instance destroyed, when `dindex` value == 0, \n * the style element is removed\n */\n let dindex = 0\n\n /**\n * Check for Existing Shared Style\n */\n const $ESS = this.$head.find(`style[${selector}]`)\n if( $ESS.length ){\n dindex = parseInt( $ESS.attr('dindex') as string ) + 1\n $ESS.remove()\n }\n\n /**\n * Assign deletion index\n */\n styleSheet.setAttribute('dindex', String( dindex ) )\n\n // Insert new style element\n this.settings.meta\n ? document.head.prepend( styleSheet )\n : document.head.appendChild( styleSheet )\n\n return styleSheet\n }\n catch( error: any ){\n throw new Error(`Style injection failed: ${error.message}`)\n }\n }\n\n /**\n * Load/inject predefined sheet to the document\n */\n async load( settings: StyleSettings ){\n this.settings = settings\n if( typeof this.settings !== 'object' )\n throw new Error('Undefined styles settings')\n \n if( this.settings.sheet ){\n const styleElement = await this.inject( this.settings.sheet )\n await this.waitForStyles(`style[rel=\"${this.settings.meta ? '@' : ''}${this.nsp}\"]`)\n }\n }\n\n /**\n * Retreive this view's main node styles including natively \n * defined ones.\n */\n get(){\n \n }\n\n /**\n * Remove all injected styles from the DOM\n */\n async clear(){\n const $ESS = this.$head.find(`style[rel=\"${this.settings.meta ? '@' : ''}${this.nsp}\"]`)\n if( !$ESS.length ) return\n \n /**\n * Procedure to clear an Existing Shared Style\n * \n * @note refere to the comment in `inject()` to\n * know more.\n */\n const dindex = parseInt( $ESS.attr('dindex') as string )\n dindex === 0 ?\n // Last instance dependency: Remove the style from DOM\n $ESS.remove()\n // Keep the style for active instance dependencies\n : $ESS.attr('dindex', String( dindex - 1 ) )\n }\n\n /**\n * Return css custom properties\n */\n async custom(): Promise<Record<string, string>>{\n return {}\n }\n\n /**\n * Overridable function to return an element \n * style attribute value as JSON object.\n */\n async style(): Promise<Record<string, string>>{\n return {}\n }\n}",
|
|
14
|
-
"export var MS = '-ms-'\nexport var MOZ = '-moz-'\nexport var WEBKIT = '-webkit-'\n\nexport var COMMENT = 'comm'\nexport var RULESET = 'rule'\nexport var DECLARATION = 'decl'\n\nexport var PAGE = '@page'\nexport var MEDIA = '@media'\nexport var IMPORT = '@import'\nexport var CHARSET = '@charset'\nexport var VIEWPORT = '@viewport'\nexport var SUPPORTS = '@supports'\nexport var DOCUMENT = '@document'\nexport var NAMESPACE = '@namespace'\nexport var KEYFRAMES = '@keyframes'\nexport var FONT_FACE = '@font-face'\nexport var COUNTER_STYLE = '@counter-style'\nexport var FONT_FEATURE_VALUES = '@font-feature-values'\nexport var LAYER = '@layer'\nexport var SCOPE = '@scope'\n",
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
"/**\n * @param {number}\n * @return {number}\n */\nexport var abs = Math.abs\n\n/**\n * @param {number}\n * @return {string}\n */\nexport var from = String.fromCharCode\n\n/**\n * @param {object}\n * @return {object}\n */\nexport var assign = Object.assign\n\n/**\n * @param {string} value\n * @param {number} length\n * @return {number}\n */\nexport function hash (value, length) {\n\treturn charat(value, 0) ^ 45 ? (((((((length << 2) ^ charat(value, 0)) << 2) ^ charat(value, 1)) << 2) ^ charat(value, 2)) << 2) ^ charat(value, 3) : 0\n}\n\n/**\n * @param {string} value\n * @return {string}\n */\nexport function trim (value) {\n\treturn value.trim()\n}\n\n/**\n * @param {string} value\n * @param {RegExp} pattern\n * @return {string?}\n */\nexport function match (value, pattern) {\n\treturn (value = pattern.exec(value)) ? value[0] : value\n}\n\n/**\n * @param {string} value\n * @param {(string|RegExp)} pattern\n * @param {string} replacement\n * @return {string}\n */\nexport function replace (value, pattern, replacement) {\n\treturn value.replace(pattern, replacement)\n}\n\n/**\n * @param {string} value\n * @param {string} search\n * @param {number} position\n * @return {number}\n */\nexport function indexof (value, search, position) {\n\treturn value.indexOf(search, position)\n}\n\n/**\n * @param {string} value\n * @param {number} index\n * @return {number}\n */\nexport function charat (value, index) {\n\treturn value.charCodeAt(index) | 0\n}\n\n/**\n * @param {string} value\n * @param {number} begin\n * @param {number} end\n * @return {string}\n */\nexport function substr (value, begin, end) {\n\treturn value.slice(begin, end)\n}\n\n/**\n * @param {string} value\n * @return {number}\n */\nexport function strlen (value) {\n\treturn value.length\n}\n\n/**\n * @param {any[]} value\n * @return {number}\n */\nexport function sizeof (value) {\n\treturn value.length\n}\n\n/**\n * @param {any} value\n * @param {any[]} array\n * @return {any}\n */\nexport function append (value, array) {\n\treturn array.push(value), value\n}\n\n/**\n * @param {string[]} array\n * @param {function} callback\n * @return {string}\n */\nexport function combine (array, callback) {\n\treturn array.map(callback).join('')\n}\n\n/**\n * @param {string[]} array\n * @param {RegExp} pattern\n * @return {string[]}\n */\nexport function filter (array, pattern) {\n\treturn array.filter(function (value) { return !match(value, pattern) })\n}\n",
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
"import $ from 'cash-dom'\n\n$.fn.extend({\n attrs: function(){\n const \n obj: any = {},\n elem = this[0]\n\n elem\n && elem.nodeType !== Node.TEXT_NODE\n && $.each( elem.attributes, function( this: any ){ obj[ this.name ] = this.value })\n\n return obj\n }\n})\n\n/**\n * Deep difference checker with support for Map, Set,\n * and various JS built-in types\n */\nexport function isDiff( a: any, b: any ){\n // Early reference equality check\n if( a === b ) return false\n \n if( typeof a !== 'object'\n || typeof b !== 'object' ) return false\n \n // Early null check\n if( a === null || b === null ) return true\n\n // Handle Set objects with optimized comparison\n if( a instanceof Set ){\n if( !( b instanceof Set ) ) return true\n if( a.size !== b.size ) return true\n \n // Fast path for primitive-only Sets\n if( isPrimitiveSet( a ) && isPrimitiveSet( b ) ){\n for( const value of a ){\n if( !b.has( value ) ) return true\n }\n return false\n }\n \n // For Sets with objects, use a WeakMap to cache results\n const compared = new WeakMap()\n \n for( const aValue of a ){\n let found = false\n \n if( typeof aValue !== 'object' ){\n if( b.has( aValue ) ){\n found = true\n }\n } else {\n for( const bValue of b ){\n // Skip if value types don't match\n if( typeof bValue !== 'object' ) continue\n \n // Check cache first using WeakMap\n if( !compared.has( aValue ) ){\n compared.set( aValue, new WeakMap() )\n }\n const valueMap = compared.get( aValue )\n \n if( valueMap.has( bValue ) ){\n found = valueMap.get( bValue )\n if( found ) break\n continue\n }\n \n // Compare objects\n const result = !isDiff( aValue, bValue )\n valueMap.set( bValue, result )\n \n if( result ){\n found = true\n break\n }\n }\n }\n \n if( !found ) return true\n }\n \n return false\n }\n\n // Handle Map objects with optimized comparison\n if( a instanceof Map ){\n if( !( b instanceof Map ) ) return true\n if( a.size !== b.size ) return true\n\n // Fast path for primitive-only Maps\n if( isPrimitiveMap( a ) && isPrimitiveMap( b ) ){\n for( const [key, aValue] of a ){\n // Get is O(1) and already checks existence\n const bValue = b.get( key )\n if( bValue !== aValue ) return true\n }\n return false\n }\n\n // For Maps with object keys/values\n const compared = new WeakMap()\n\n for( const [aKey, aValue] of a ){\n // Handle primitive keys using direct lookup\n if( typeof aKey !== 'object' ){\n if( !b.has( aKey ) ) return true\n \n const bValue = b.get( aKey )\n \n // Quick check for primitive values\n if( typeof aValue !== 'object' ){\n if( aValue !== bValue ) return true\n continue\n }\n\n // Deep compare object values\n if( typeof bValue !== 'object' || isDiff( aValue, bValue ) ) return true\n continue\n }\n\n // Handle object keys\n let keyFound = false\n let valueMatched = false\n\n // Compare each key deeply since keys are objects\n for( const [bKey, bValue] of b ){\n if( typeof bKey !== 'object' ) continue\n\n // Use WeakMap for caching comparisons\n if( !compared.has( aKey ) ){\n compared.set( aKey, new WeakMap() )\n }\n const keyMap = compared.get( aKey )\n \n if( keyMap.has( bKey ) ){\n const [keyMatch, valueMatch] = keyMap.get( bKey )\n if( keyMatch ){\n keyFound = true\n valueMatched = valueMatch\n break\n }\n continue\n }\n\n // Compare keys\n if( !isDiff( aKey, bKey ) ){\n keyFound = true\n \n // Compare values only if keys match\n valueMatched = typeof aValue === 'object' && typeof bValue === 'object' ?\n !isDiff( aValue, bValue ) :\n aValue === bValue\n\n // Cache both key and value comparison results\n keyMap.set( bKey, [true, valueMatched] )\n \n if( valueMatched ) break\n } else {\n keyMap.set( bKey, [false, false] )\n }\n }\n\n if( !keyFound || !valueMatched ) return true\n }\n\n return false\n }\n\n // Fast path for arrays\n if( Array.isArray( a ) ){\n if( !Array.isArray( b ) ) return true\n if( a.length !== b.length ) return true\n for( let i = 0; i < a.length; i++ ){\n const aVal = a[i], bVal = b[i]\n // Early exit on primitive comparison\n if( aVal !== bVal && ( typeof aVal !== 'object' || isDiff( aVal, bVal ) ) ) return true\n }\n return false\n }\n\n // Cache keys to avoid multiple calls\n const aKeys = Object.keys( a )\n const bKeys = Object.keys( b )\n\n // Quick length comparison before sorting\n if( aKeys.length !== bKeys.length ) return true\n\n // Sort keys only if necessary (when lengths are equal)\n aKeys.sort()\n bKeys.sort()\n\n // Use cached length\n const length = aKeys.length\n\n // Compare sorted keys first\n for( let i = 0; i < length; i++ ){\n if( aKeys[i] !== bKeys[i] ) return true\n }\n\n // Now we know keys match, compare values\n for( let i = 0; i < length; i++ ){\n const key = aKeys[i]\n const aVal = a[key]\n const bVal = b[key]\n\n // Early exit for primitive equality\n if( aVal === bVal ) continue\n\n // Type checks\n if( aVal instanceof Date ){\n if( !( bVal instanceof Date ) || String( aVal ) !== String( bVal ) ) return true\n continue\n }\n\n if( aVal instanceof RegExp ){\n if( !( bVal instanceof RegExp ) \n || aVal.source !== bVal.source \n || aVal.flags !== bVal.flags ) return true\n continue\n }\n\n if( aVal instanceof Map ){\n if( !( bVal instanceof Map ) || isDiff( aVal, bVal ) ) return true\n continue\n }\n\n if( aVal instanceof Set ){\n if( !( bVal instanceof Set ) || isDiff( aVal, bVal ) ) return true\n continue\n }\n\n if( aVal instanceof Function ){\n if( !( bVal instanceof Function ) ) return true\n continue\n }\n\n if( typeof aVal === 'object' ){\n if( typeof bVal !== 'object' ) return true\n\n // Self reference check\n if( aVal === a ){\n if( bVal !== b ) return true\n }\n // WARNING: Doesn't deal with circular refs other than ^^\n else if( isDiff( aVal, bVal ) ) return true\n }\n // Primitive values that weren't caught by === check must be different\n else return true\n }\n\n return false\n}\n\nexport function isEqual( a: any, b: any ): boolean {\n // Handle identical references and primitive equality\n if( a === b) return true\n \n // Handle null/undefined cases\n if (a == null || b == null) return a === b\n \n // Get the type of both values\n const typeA = typeof a\n const typeB = typeof b\n \n // If types don't match, they're not equal\n if (typeA !== typeB) return false\n \n // Handle primitives that weren't caught by ===\n if (typeA !== 'object') {\n // Special case for NaN\n if (typeA === 'number' && isNaN(a) && isNaN(b)) return true\n return false // Other primitives would have been caught by ===\n }\n \n // Handle special object types\n if (a instanceof Date) {\n return b instanceof Date && a.getTime() === b.getTime()\n }\n \n if (a instanceof RegExp) {\n return b instanceof RegExp && a.source === b.source && a.flags === b.flags\n }\n \n if (a instanceof Error) {\n return b instanceof Error && \n a.name === b.name && \n a.message === b.message &&\n (a.stack === b.stack || (!a.stack && !b.stack))\n }\n \n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(a)) {\n // Handle TypedArrays and DataView\n if (!ArrayBuffer.isView(b)) return false\n if (a.byteLength !== b.byteLength) return false\n // Convert to Uint8Array for byte-by-byte comparison\n const viewA = new Uint8Array(a.buffer, a.byteOffset, a.byteLength)\n const viewB = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n for (let i = 0; i < viewA.length; i++) {\n if (viewA[i] !== viewB[i]) return false\n }\n return true\n }\n \n if (a instanceof Promise || a instanceof WeakMap || a instanceof WeakSet) {\n // These types can't be meaningfully compared\n return a === b\n }\n \n // For functions, compare their string representation\n if (typeof a === 'function') {\n if (typeof b !== 'function') return false\n return a.toString() === b.toString() && a.name === b.name\n }\n \n // Use isDiff for objects, arrays, Maps, and Sets, but invert its result\n // We also ensure both values are the same type of object\n if (a.constructor !== b.constructor) return false\n \n if (a instanceof Map || a instanceof Set || Array.isArray(a) || \n Object.getPrototypeOf(a) === Object.prototype) {\n return !isDiff(a, b)\n }\n \n // For other object types (custom classes), compare properties\n const prototypeA = Object.getPrototypeOf(a)\n if (prototypeA !== Object.getPrototypeOf(b)) return false\n \n // Get all properties including non-enumerable ones\n const propsA = Object.getOwnPropertyNames(a)\n const propsB = Object.getOwnPropertyNames(b)\n \n if (propsA.length !== propsB.length) return false\n \n for (const prop of propsA) {\n if (!Object.prototype.hasOwnProperty.call(b, prop)) return false\n if (!isEqual(a[prop], b[prop])) return false\n }\n \n // If the prototype is not Object.prototype or null, compare up the chain\n if (prototypeA !== null && prototypeA !== Object.prototype) {\n const protoPropsA = Object.getOwnPropertyNames(prototypeA)\n const protoPropsB = Object.getOwnPropertyNames(Object.getPrototypeOf(b))\n \n if (protoPropsA.length !== protoPropsB.length) return false\n \n for (const prop of protoPropsA) {\n // Skip constructor\n if (prop === 'constructor') continue\n if (!isEqual(prototypeA[prop], Object.getPrototypeOf(b)[prop])) return false\n }\n }\n \n return true\n}\n\n/**\n * Helper to check if Set contains only \n * primitives\n */\nexport function isPrimitiveSet( set: Set<any> ): boolean {\n for( const item of set )\n if( typeof item === 'object' && item !== null ) \n return false\n \n return true\n}\n\n/**\n * Helper to check if Map contains only \n * primitives for both keys and values\n */\nexport function isPrimitiveMap( map: Map<any, any> ): boolean {\n for( const [key, value] of map )\n if( (typeof key === 'object' && key !== null) \n || (typeof value === 'object' && value !== null) ) \n return false\n\n return true\n}\n\nexport function deepClone( obj: any, seen = new WeakMap() ){\n // Handle primitives, promises and functions\n if( obj === null || typeof obj !== 'object' || obj instanceof Promise ) return obj\n\n // Handle circular references\n if( seen.has( obj ) ) return seen.get( obj )\n\n // Handle Date objects\n if( obj instanceof Date ) return new Date( obj.getTime() )\n\n // Handle RegExp objects\n if( obj instanceof RegExp ) return new RegExp( obj.source, obj.flags )\n\n // Handle Map objects\n if( obj instanceof Map ){\n const mapClone = new Map()\n\n seen.set( obj, mapClone )\n obj.forEach( ( value, key ) => mapClone.set( deepClone( key, seen ), deepClone( value, seen ) ) )\n \n return mapClone\n }\n\n // Handle Set objects\n if( obj instanceof Set ){\n const setClone = new Set()\n\n seen.set( obj, setClone )\n obj.forEach( value => setClone.add( deepClone( value, seen ) ) )\n\n return setClone\n }\n\n // Handle Arrays\n if( Array.isArray( obj ) ){\n const arrClone: any[] = []\n seen.set( obj, arrClone )\n\n for( let i = 0; i < obj.length; i++ )\n arrClone[i] = deepClone( obj[i], seen )\n \n return arrClone\n }\n\n // Handle TypedArrays\n if( ArrayBuffer.isView( obj ) )\n return new (obj.constructor as any)( obj )\n\n // Handle plain objects\n const clone = Object.create( Object.getPrototypeOf( obj ) )\n seen.set( obj, clone )\n\n // Copy symbol properties\n const symbols = Object.getOwnPropertySymbols( obj )\n for( const symbol of symbols )\n clone[symbol] = deepClone( obj[symbol], seen )\n\n // Copy enumerable properties\n for( const key in obj )\n if( Object.prototype.hasOwnProperty.call( obj, key ) )\n clone[key] = deepClone( obj[key], seen )\n\n return clone\n}\n\n/**\n * Deep assign values to an object using dot notation paths\n * @param original The source object to modify\n * @param toSet Object containing path-value pairs to set\n * @returns A new object with the assigned values\n */\nexport function deepAssign<T>( original: T, toSet: Record<string, any> ): T {\n if( !original || typeof original !== 'object' )\n throw new TypeError('Original argument must be an object')\n\n if( !toSet || typeof toSet !== 'object' )\n throw new TypeError('ToSet argument must be an object')\n \n if( !Object.keys( toSet ).length )\n return { ...original }\n\n function setValueAtPath( obj: Record<string, any>, path: string, value: any ){\n const parts = path.split(/\\.|\\[|\\]/).filter( Boolean )\n let current = obj\n\n for( let i = 0; i < parts.length; i++ ){\n const \n key = parts[i],\n isArrayIndex = !isNaN( Number( key ) ),\n isLastPart = i === parts.length - 1,\n nextIsArrayIndex = !isNaN( Number( parts[ i + 1 ] ) )\n\n if( isLastPart ){\n current[ key ] = value\n continue\n }\n\n if( !( key in current ) )\n current[ key ] = nextIsArrayIndex ? [] : {}\n \n else if( nextIsArrayIndex && !Array.isArray( current[ key ] ) )\n current[ key ] = []\n \n else if( !nextIsArrayIndex && Array.isArray( current[ key ] ) )\n current[ key ] = {}\n\n current = current[ key ]\n }\n }\n\n const modified = deepClone( original )\n try {\n for( const [ path, value ] of Object.entries( toSet ) ){\n if( typeof path !== 'string' )\n throw new TypeError(`Invalid path: ${path}`)\n\n if( !/^[a-zA-Z0-9_\\-\\[\\].]+$/.test( path ) )\n throw new Error(`Invalid path format: ${path}`)\n\n setValueAtPath( modified, path, value )\n }\n }\n catch( error: any ){\n throw new Error(`Failed to assign value: ${error.message}`)\n }\n\n return modified\n}\n\nexport function sterilize( obj: Record<string, any> ){\n return JSON.parse( JSON.stringify( obj ) )\n}",
|
|
32
|
-
|
|
33
|
-
"import type Lips from './lips'\nimport type {\n Handler,\n Metavars,\n ComponentScope,\n ComponentOptions,\n InteractiveMetavars,\n Macro,\n Variable,\n VariableSet,\n MeshRenderer,\n MeshTemplate,\n RenderedNode,\n FGUDependencies,\n FGUDependency,\n Declaration,\n FragmentBoundaries,\n VirtualEvent,\n MeshWireSetup,\n SyntaxAttributes,\n DynamicTemplate,\n I18nDependency,\n VariableArguments,\n FGUDMemory,\n SpreadOpeartor\n} from './types'\n\nimport UQS from './uqs'\nimport Events from './events'\nimport Metrics from './metrics'\nimport $, { Cash } from 'cash-dom'\nimport Stylesheet from './stylesheet'\nimport { effect, EffectControl, memo, signal } from './signal'\nimport { \n isDiff,\n isEqual,\n sterilize,\n deepClone,\n deepAssign\n} from './utils'\n\nimport {\n SPREAD_VAR_PATTERN,\n ARGUMENT_VAR_PATTERN,\n INTERPOLATE_PATTERN,\n GENERIC_TAGNAME_ATTR,\n I18N_ATTR_FLAG,\n SYNCTAX_VAR_FLAG,\n FUNCTION_ATTR_FLAG,\n EVENT_LISTENER_FLAG,\n LAYOUT_AFFECTING_ATTRS,\n MAX_PRIORITY_TYPES,\n NODE_PREFIX,\n COMPONENT_PREFIX,\n PARTIAL_ROOT_PREFIX,\n SYNTAX_COMPONENT_PREFIX,\n MACRO_PREFIX,\n DEFAULT_PARTIAL_PATH_SLOT,\n NATIVE_SYNTAX_TAGS,\n DYNAMIC_TAGNAME_ATTR\n} from './constants'\n\nexport default class Component<MT extends Metavars> extends Events {\n private declaration: Declaration\n private $?: Cash | null = null\n\n public input: MT['Input']\n public state: MT['State'] & {\n toJSON(): MT['State']\n reset(): void\n }\n public static: MT['Static']\n public context: MT['Context']\n\n public __name__: string\n public __path__: string\n private __lang__: string\n private __template__: string\n private __previous: InteractiveMetavars<MT>\n private __macros: Map<string, Macro> = new Map() // Cached macros templates\n private __i18nDeps: Map<string, I18nDependency> = new Map()\n\n // Initial FGU dependencies\n public FGUD: FGUDependencies = new Map()\n public FGUDMemory: FGUDMemory = new Map()\n // Preserved Child Components\n private PCC: Map<string, Component<MT>> = new Map()\n // Virtual Events Registry\n private VER: Array<VirtualEvent<MT>> = []\n\n private prepath = '0'\n private debug = false\n private isRendered = false\n\n private __setInput: ( input: MT['Input'] ) => void\n private __setState: ( state: MT['State'] ) => void\n private __getState: () => MT['State'] | undefined\n\n // Update Queue System for high-frequency DOM updates\n private UQS: UQS<MT>\n // Internal Component Effect\n private ICE: EffectControl\n\n public lips: Lips\n public metrics: Metrics\n public stylesheet?: Stylesheet\n\n private __inpath__ = ''\n private __inpathCounter__ = 0\n private __renderDepth__ = 0\n private __boundaries__\n\n /**\n * Allow methods of `handler` to be dynamically\n * added to `this` component object.\n */\n ;[key: string]: any\n\n constructor( name: string, template: string, { input, state, context, _static, handler, stylesheet, macros, declaration }: ComponentScope<MT>, options: ComponentOptions<any> ){\n super()\n this.lips = options.lips\n \n if( options?.debug ) this.debug = options.debug || this.lips.debug\n if( options?.prepath ) this.prepath = options.prepath\n\n this.__name__ = name\n this.__lang__ = this.lips.i18n.lang\n this.__path__ = \n this.__inpath__ = `${this.prepath}:${this.__name__}`\n this.__boundaries__ = options.boundaries\n \n this.declaration = declaration || { name }\n\n this.input = input || {}\n this.static = _static || {}\n this.context = {}\n // Detect all state mutations, including deep mutations\n this.state = this.lips.IUC.proxyState<MT['State']>( this.__path__, state || {} )\n\n macros && this.setMacros( macros )\n handler && this.setHandler( handler )\n stylesheet && this.setStylesheet( stylesheet )\n\n /**\n * IMPORTANT:\n * \n * Parse component's template only after\n * parsing macros templates for alternative macro\n * reference check during preprocessing.\n */\n this.__template__ = this.lips.preprocessor.parse( template, this.__macros )\n\n /**\n * Track rendering cycle metrics to evaluate\n * performance.\n * \n */\n this.metrics = new Metrics( this.debug )\n // Track component creation\n this.metrics.inc('componentCount')\n \n /**\n * Batch Dependencies Update handler\n */\n this.UQS = new UQS( this )\n\n /**\n * Triggered during component creation\n * \n * NOTE: Any state value set during this process\n * is considered initial state.\n */\n typeof this.onCreate == 'function'\n && this.onCreate.bind(this)()\n this.emit('component:create')\n\n /**\n * Triggered an initial input is provided\n */\n if( this.input\n && Object.keys( this.input ).length\n && typeof this.onInput == 'function' ){\n this.onInput.bind(this)()\n this.emit('component:input')\n }\n\n /**\n * Initialize previous interative metavars to initial metavars\n * \n * IMPORTANT: this prevent any update effect during\n * component creating for initial input, state and\n * context\n */\n this.__previous = {\n state: deepClone( this.state ),\n input: deepClone( this.input ),\n context: deepClone( this.context )\n }\n\n const\n [ getInput, setInput ] = signal<MT['Input']>( this.input ),\n [ getState, setState ] = signal<MT['State']>( this.state ),\n [ getContext, setContext ] = signal<MT['Context']>( this.context )\n\n this.__setInput = setInput\n this.__setState = setState\n this.__getState = getState\n\n /**\n * Register to queue & apply update only when \n * a new change occured on the state.\n * \n * Merge with initial/active state.\n */\n this.lips.IUC.register( this.__path__, () => {\n isDiff( this.__previous?.state as Record<string, any>, this.state as Record<string, any> )\n && this.__setState({ ...this.__getState(), ...this.state })\n })\n \n /**\n * Set context update effect listener\n * to merge with initial/active context\n * after any occurances.\n */\n Array.isArray( context )\n && context.length\n && this.lips.useContext<MT['Context']>( context, ctx => {\n if( !isDiff( this.context as Record<string, any>, ctx ) ) return\n\n setContext( ctx )\n /**\n * IMPORTANT: Make `ctx` data available for the\n * onContext lifecycle event before component get\n * rendered of update.\n */\n this.context = ctx\n \n /**\n * Triggered anytime component context changed\n */\n typeof this.onContext == 'function'\n && this.onContext.bind(this)()\n this.emit('component:context')\n })\n\n /**\n * Subscribe to i18n changes\n * \n * - `*` support all languages\n * - [...] TODO: Explicitly defined list of supported languages\n */\n this.lips.useTranslator( '*', lang => {\n /**\n * Run translation update only when the \n * language truly changed\n */\n if( lang === this.__lang__ ) return\n\n this.__updateI18nDepNodes__()\n this.__lang__ = lang\n })\n \n this.ICE = effect( () => {\n const\n state = getState(),\n input = this.input = getInput(),\n /**\n * `this.context` is initialized empty so it's\n * important to set it before component render \n * or update.\n */\n context = this.context = getContext()\n \n /**\n * Initial render - parse template and establish \n * dependencies\n */\n if( !this.isRendered ){\n // Reset metrics before render\n this.metrics.reset()\n \n /**\n * For non-template component or syntax component \n * that requires to self-outsource and process the \n * initial rendering.\n * \n * NOTE: `onSelfRender()` lifecycle method must \n * define and can return the initially rendered \n * component log. An empty fragment is used otherwise.\n */\n if( !this.__template__.length \n || declaration?.syntax && typeof this.onSelfRender == 'function' ){\n const $log = this.onSelfRender.bind(this)( this.input )\n\n if( !this.__boundaries__?.start || !this.__boundaries__?.end )\n throw new Error(`Undefined <${this.__name__} syntax component boundaries`)\n\n this.$ = $log || $()\n }\n /**\n * Normal component rendering\n */\n else {\n const { $log } = this.render( '', undefined, undefined, this.FGUD )\n this.$ = $log\n }\n \n /**\n * Assign CSS relationship attribute\n * for only non-syntax components.\n */\n !declaration?.syntax\n && this.$?.each( ( i, el ) => {\n typeof el.setAttribute == 'function'\n && el.setAttribute('rel', this.__name__ )\n } )\n\n this.isRendered = true\n \n /**\n * Triggered after component get mounted for\n * the first time.\n */\n typeof this.onMount == 'function'\n && this.onMount.bind(this)()\n this.emit('component:mount')\n\n /**\n * Watch when component's element get \n * attached to the DOM\n */\n this.lips.watcher.watch( this as any )\n }\n else {\n /**\n * Update only dependent nodes\n */\n this.__updateDepNodes__()\n \n /**\n * Triggered anytime component gets updated\n */\n typeof this.onUpdate == 'function' && this.onUpdate.bind(this)()\n this.emit('component:update')\n \n /**\n * Save as previous meta variables for next cycle.\n * \n * IMPORTANT: Required to check changes on the state\n * during IUC processes.\n */\n this.__previous = {\n input: deepClone( input ),\n state: deepClone( state ),\n context: deepClone( context )\n }\n }\n\n // this.metrics.log()\n\n /**\n * Triggered anytime component gets rendered\n */\n typeof this.onRender == 'function' && this.onRender.bind(this)()\n this.emit('component:render')\n })\n }\n\n setContext( arg: Partial<Record<string, any>> | string, value?: any ){\n /**\n * Set global context value from any component\n * \n * Note: `arg` if object isn't restricted to \n * this component's required context fields scope.\n */\n this.lips.setContext( arg, value )\n }\n setInput( input: MT['Input'], memo?: VariableSet ){\n /**\n * Apply update only when new input is different \n * from the incoming input\n */\n if( !isDiff( this.input as Record<string, any>, input as Record<string, any> ) )\n return\n \n // Set new input.\n this.__setInput( input )\n \n /**\n * Triggered anytime component recieve new input\n * \n * Only passed `memo` in special cases like\n * self-rendered syntax comopnent.\n */\n typeof this.onInput == 'function'\n && this.onInput.bind(this)( this.declaration.syntax ? memo : undefined )\n }\n /**\n * Inject grain/partial input to current component \n * instead of sending a whole updated input\n */\n subInput( data: Record<string, any>, memo?: VariableSet ){\n if( typeof data !== 'object' )\n throw new Error('Invalid sub input data argument')\n \n /**\n * Only passed `memo` in special cases like\n * self-rendered syntax comopnent.\n */\n this.setInput( deepAssign<MT['Input']>( this.input, data ), this.declaration.syntax ? memo : undefined )\n return this\n }\n setMacros( template: string ){\n const\n prepo = this.lips.preprocessor.parse( template ),\n $nodes = $(prepo)\n if( !$nodes.length ) return\n\n const self = this\n $nodes.each( function(){\n const\n $node = $(this),\n { argv, attrs } = self.__getAttributes__( $node )\n\n if( !Object.keys( attrs ) )\n throw new Error('Invalid macro component definition')\n\n if( !attrs.literals.name )\n throw new Error('Undefined macro `name` attribute.')\n\n if( self.__macros.get( attrs.literals.name ) )\n console.warn(`Duplicate macro <${attrs.literals.name}> will be override`)\n\n if( !$node.contents()?.length )\n throw new Error('Invalid macro component definition. Template content expected.')\n\n self.__macros.set( attrs.literals.name, { argv, $node } )\n } )\n }\n setHandler( list: Handler<MT> ){\n Object\n .entries( list )\n .map( ([ method, fn ]) => this[ method ] = fn?.bind(this) )\n }\n setStylesheet( sheet?: string ){\n const cssOptions = {\n sheet,\n /**\n * Inject root component styles into global meta\n * style tag.\n */\n meta: this.__name__ === '__ROOT__'\n }\n\n this.stylesheet = new Stylesheet( this.__name__, cssOptions )\n }\n\n get node(){\n if( !this.isRendered )\n throw new Error('node() is expected to be call after component get rendered')\n\n return this.$\n }\n get boundaries(){\n return this.__boundaries__\n }\n \n render( inpath: string, $nodes?: Cash, scope: VariableSet = {}, sharedDeps?: FGUDependencies, xmlns?: boolean ): RenderedNode<MT> {\n if( $nodes && !$nodes.length ){\n console.warn('Undefined node element to render')\n return { $log: $nodes, dependencies: sharedDeps || new Map() }\n }\n\n const\n self = this,\n dependencies: FGUDependencies = sharedDeps || new Map(),\n attachableEvents: Array<VirtualEvent<MT>> = []\n\n // Start metrics measuring\n this.metrics.startRender()\n\n /**\n * Initialize an empty cash object to \n * act like a DocumentFragment\n */\n let _$ = $()\n\n function useScope(){\n return deepClone( scope )\n }\n function generatePath( type: string, isSyntax = false ): string {\n const key = generateComponentName( type, isSyntax )\n self.__inpathCounter__++\n\n return self.__inpath__ ? `${self.__inpath__}/${key}` : `${inpath ? inpath +'/' : ''}${key}`\n }\n function generateComponentName( type: string, isSyntax = false ){\n let prefix = ''\n switch( type ){\n case 'component': prefix = isSyntax ? SYNTAX_COMPONENT_PREFIX : COMPONENT_PREFIX; break\n case 'macro': prefix = MACRO_PREFIX; break\n }\n\n return prefix + self.__inpathCounter__\n }\n function isMesh( arg: any ){\n return arg === null // Null renderer\n || (typeof arg === 'object' // Valid Renderer\n && typeof arg.mesh === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.update === 'function'\n && typeof arg.cleanup === 'function')\n }\n function isTemplate( arg: any ){\n /**\n * DO NOT SUPPORT self-rendered components\n * because the don't provide `default`.\n */\n return arg !== null\n && typeof arg === 'object'\n && typeof arg.default\n && typeof arg.default === 'string'\n }\n\n function execLog( $node: Cash ){\n const\n args = $node.attr(':args'),\n logPath = generatePath('log')\n if( !args ) return\n \n // Log context scope\n const contextScope = useScope()\n\n self.__evaluate__(`console.log(${args})`, contextScope )\n \n if( self.__isReactive__( args as string, contextScope ) ){\n const deps = self.__extractExpressionDeps__( args as string, contextScope )\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'log',\n nodepath: logPath,\n target: 'argument',\n $fragment: null,\n update: memo => self.__evaluate__(`console.log(${args})`, memo ),\n syntax: true\n }) )\n }\n }\n function execLet( $node: Cash ){\n const\n varPath = generatePath('var'),\n { attrs } = self.__getAttributes__( $node )\n if( !attrs ) return\n\n Object\n .entries( attrs.literals )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`Cannot override <const ${key}=[value]/> variable`)\n \n scope[ key ] = { value: assign, type: 'let' }\n })\n\n Object\n .entries( attrs.expressions )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`Cannot override <const ${key}=[value]/> variable`)\n\n scope[ key ] = {\n value: self.__evaluate__( assign as string, scope ),\n type: 'let'\n }\n\n if( self.__isReactive__( assign, scope ) ){\n const \n deps = self.__extractExpressionDeps__( assign, scope ),\n updateVar = ( memo: VariableSet, by?: string ) => {\n if( memo[ key ] && memo[ key ].type === 'const' )\n throw new Error(`Cannot override <const ${key}=[value]/> variable`)\n\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n\n const value = self.__evaluate__( assign as string, memo )\n if( isEqual( memo[ key ].value, value ) ) return\n\n memo[ key ] = { value, type: 'let' }\n \n /**\n * Apply update to related dependencies\n */\n self.__updateVarDepNodes__( key, varPath, memo )\n\n return sterilize({ memo })\n }\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, useScope(), {\n nodetype: 'let',\n nodepath: varPath,\n deppath: `${varPath}.${key}`,\n target: 'attr',\n $fragment: null,\n update: updateVar,\n syntax: true\n }) )\n }\n })\n \n /**\n * METRICS: Tracking total elements rendered\n */\n self.metrics.inc('elementCount')\n }\n function execConst( $node: Cash ){\n const\n { attrs } = self.__getAttributes__( $node )\n if( !attrs ) return\n \n Object\n .entries( attrs.literals )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`<const ${key}=[value]/> variable already defined`)\n \n if( !assign ) return\n\n scope[ key ] = { value: assign, type: 'const' }\n } )\n\n Object\n .entries( attrs.expressions )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`<const ${key}=[value]/> variable already defined`)\n\n if( !assign ) return\n \n scope[ key ] = {\n value: self.__evaluate__( assign as string, scope ),\n type: 'const'\n }\n } )\n \n /**\n * METRICS: Tracking total elements rendered\n */\n self.metrics.inc('elementCount')\n }\n function execDynamicElement( $node: Cash, dtag: string, verb: MeshRenderer | string | null ): Cash {\n const\n { attrs } = self.__getAttributes__( $node ),\n elementPath = generatePath('element'),\n boundaries = self.__getBoundaries__( elementPath ),\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n SPREAD_KEYSTORES: Record<string, string[]> = {}\n\n let\n contextScope = useScope(),\n $fragment = $(boundaries.start),\n renderer: MeshRenderer | null\n\n const handleMeshRendererAttributes = ( scope: VariableSet ) => {\n const \n // Keep track of the latest mesh scope\n argvalues: VariableSet = {},\n __arguments__: VariableArguments = {}\n\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => {\n __arguments__[ key ] = value\n argvalues[ key ] = { type: 'arg', value }\n } )\n\n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( !renderer ) return\n \n if( SPREAD_VAR_PATTERN.test( key ) )\n self.__evaluateSpreadAttr__( key, {\n memo: scope,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n __arguments__[ _key ] = _value\n\n // Only consume declared arguments' value\n if( !renderer?.argv.includes( _key ) ) return\n\n argvalues[ _key ] = {\n type: 'arg',\n value: _value\n }\n }\n })\n \n else {\n const evalue = value ? self.__evaluate__( value, scope ) : true\n __arguments__[ key ] = evalue\n\n // Only consume declared arguments' value\n if( !renderer.argv.includes( key ) ) return\n\n argvalues[ key ] = {\n type: 'arg',\n value: evalue\n }\n }\n })\n\n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( !renderer ) return\n \n if( SPREAD_VAR_PATTERN.test( key ) && self.__isReactive__( key, scope ) ){\n const\n deps = self.__extractExpressionDeps__( key, scope ),\n spreadPartialUpdate = ( memo: VariableSet, by?: string ) => {\n if( !renderer ) return\n\n const extracted: VariableSet = {}\n let changedDeps: string[] = []\n\n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n */\n if( attrs.map.afterSpreadAttrs.includes( _key ) ) return\n // Only update declared arguments' value\n if( !renderer?.argv.includes( _key ) ) return\n // Ignore unchanged values\n if( isEqual( _value, memo[ _key ]?.value ) ) return\n\n argvalues[ _key ] =\n extracted[ _key ] = {\n value: _value,\n type: 'arg'\n }\n\n // Update __arguments__ variable as well\n __arguments__[ _key ] = _value\n // Schedule only what changed values for updated.\n changedDeps.push( _key )\n },\n nullify: pattrs => {\n pattrs.forEach( _key => {\n extracted[ _key ] = {\n value: undefined,\n type: 'arg'\n }\n delete __arguments__[ _key ]\n } )\n\n changedDeps = pattrs\n }\n })\n \n if( changedDeps.length ){\n // Update arguments dep nodes\n renderer.argv.length\n && self.__updateArgumentsDepNodes__( elementPath, __arguments__ )\n\n // Update partial deps\n renderer.update( changedDeps, extracted, memo, boundaries )\n }\n }\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, scope, {\n nodetype: 'dynamic',\n nodepath: elementPath,\n deppath: `${elementPath}.${key}`,\n target: 'spread-attr',\n $fragment: null,\n boundaries,\n update: spreadPartialUpdate\n }) )\n }\n else if( ( renderer.argv.includes( key ) )\n && self.__isReactive__( value, scope ) ){\n const\n deps = self.__extractExpressionDeps__( value, scope ),\n partialUpdate = ( memo: VariableSet, by?: string ) => {\n if( !renderer ) return\n\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n\n const \n _value: Variable = value ? self.__evaluate__( value, memo ) : true,\n newvalue: Variable = { type: 'arg', value: _value }\n argvalues[ key ] = newvalue\n \n /**\n * Update arguments dep nodes\n */\n if( renderer.argv.length ){\n __arguments__[ key ] = _value\n self.__updateArgumentsDepNodes__( elementPath, __arguments__ )\n }\n \n renderer.update( [ key ], { [ key ]: newvalue }, memo, boundaries )\n }\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, scope, {\n nodetype: 'dynamic',\n nodepath: elementPath,\n deppath: `${elementPath}.${key}`,\n target: 'attr',\n $fragment: null,\n boundaries,\n update: partialUpdate\n }) )\n }\n } )\n\n return { argvalues, __arguments__ }\n }\n\n /**\n * Dynamic mesh rendering\n */\n if( isMesh( verb ) ){\n renderer = verb as MeshRenderer\n\n // Process argvalues and dependencies track\n const { argvalues, __arguments__ } = handleMeshRendererAttributes( contextScope )\n\n /**\n * Return all possible arguments passed to the\n * dynamic element in a single object variable \n * form that can be accessible in macro template \n * as `arguments`.\n */\n contextScope.__arguments__ = __arguments__\n\n const $log = renderer.mesh( argvalues )\n if( $log && $log.length )\n $fragment = $fragment.add( $log )\n }\n /**\n * Dynamic component, macro or element\n * rendering.\n */\n else if( typeof verb === 'string' ){\n /**\n * Process dynamic macro set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n if( self.__macros.has( verb ) )\n $fragment = $fragment.add( execMacro( $node, verb ) )\n\n /**\n * Process dynamic component tag set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n else if( self.lips.has( verb ) )\n $fragment = $fragment.add( execComponent( $node, { name: verb } ) )\n\n // Render standard HTML element\n else $fragment = $fragment.add( execElement( $node, verb ) )\n }\n\n // Track FGU dependency update on the dynamic tag\n if( self.__isReactive__( dtag as string, contextScope ) ){\n const\n updateDynamicElement = ( memo: VariableSet, by?: string ) => {\n /**\n * Re-evaluate dynamic tag expression before \n * re-rendering the element\n */\n const verb = self.__evaluate__( dtag, memo )\n let $newContent\n\n /**\n * IMPORTANT: Clean up previously rendered\n * content and its dependencies and nullify\n * the active mesh renderer if exist.\n */\n if( renderer ){\n renderer.cleanup( boundaries )\n renderer = null\n }\n else self.__emptyBoundaries__( boundaries, elementPath )\n \n /**\n * The mesh renderer changed\n */\n if( isMesh( verb ) ){\n renderer = verb as MeshRenderer\n\n // Reset attribute trackers\n const { argvalues, __arguments__ } = handleMeshRendererAttributes( memo )\n\n // Update arguments dep nodes\n renderer.argv.length\n && self.__updateArgumentsDepNodes__( elementPath, __arguments__ )\n \n // Rerender mesh content.\n $newContent = renderer.mesh( argvalues, memo )\n\n $newContent?.length\n && renderer.fill( $newContent, boundaries )\n }\n\n /**\n * Render dynamic template only when first \n * time renderer is `null` and the element's\n * dynamic update provide a component `template`\n * instead of a mesh `renderer`.\n */\n else if( isTemplate( verb ) ){\n $newContent = execComponent( $node, { template: verb }, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n \n /**\n * Process dynamic macro set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n else if( typeof verb === 'string' && self.__macros.has( verb ) ){\n $newContent = execMacro( $node, verb, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n\n /**\n * Process dynamic tag set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n else if( typeof verb === 'string' && self.lips.has( verb ) ){\n $newContent = execComponent( $node, { name: verb }, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n\n // Render standard HTML element\n else if( typeof verb === 'string' ){\n $newContent = execElement( $node, verb, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n },\n deps = self.__extractExpressionDeps__( dtag, contextScope )\n\n // Share general scope alongside the argvalues\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'dynamic',\n nodepath: elementPath,\n deppath: `${elementPath}.dtag`,\n target: 'dtag',\n $fragment: null,\n boundaries,\n update: updateDynamicElement\n }) )\n }\n\n $fragment = $fragment.add( boundaries.end )\n\n return $fragment\n }\n function execComponent( $node: Cash, dynamic?: DynamicTemplate<any>, scope?: VariableSet ): Cash {\n let\n template,\n name\n\n // Dynamic component template\n if( dynamic?.template ){\n template = dynamic.template\n name = generateComponentName('component', template.declaration?.syntax )\n }\n // Lookup component by its name\n else {\n name = dynamic?.name\n || $node.attr( GENERIC_TAGNAME_ATTR ) as string\n || $node.prop('tagName')?.toLowerCase() as string\n\n if( !name ) throw new Error('Invalid component')\n if( name === self.__name__ ) throw new Error('Render component within itself is forbidden')\n\n // Import template from lips registry\n template = self.lips.import<any>( name )\n }\n \n if( !template || !name )\n throw new Error(`<${name}> template not found`)\n\n const\n componentPath = generatePath('component', template.declaration?.syntax ),\n componentCacheId = `${componentPath}#${name}`,\n boundaries = self.__getBoundaries__( componentPath ),\n { argv, functions, attrs, events } = self.__getAttributes__( $node ),\n TRACKABLE_ATTRS: Record<string, string> = {},\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n SPREAD_KEYSTORES: Record<string, string[]> = {}\n\n /**\n * Parse assigned attributes to be injected into\n * the component as input.\n */\n let\n input: any = {},\n $fragment = $(boundaries.start),\n // Get cached component with same path if exists\n component = self.PCC.get( componentCacheId ),\n contextScope = scope || useScope()\n\n /**\n * Cast attributes to compnent inputs\n */\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => {\n if( key == 'key' ) return\n input[ key ] = value\n })\n \n functions && Object\n .entries( functions )\n .forEach( ([ key, expr ]) => {\n input[ key ] = self.__evaluateFunction__( expr, [], contextScope )\n \n template.declaration?.syntax\n ? TRACKABLE_ATTRS[ SYNCTAX_VAR_FLAG + FUNCTION_ATTR_FLAG + key ] = expr\n : TRACKABLE_ATTRS[ FUNCTION_ATTR_FLAG + key ] = expr\n })\n \n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( key == 'key' ) return\n \n if( SPREAD_VAR_PATTERN.test( key ) )\n self.__evaluateSpreadAttr__( key, {\n memo: contextScope,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => input[ _key ] = _value\n })\n\n else input[ key ] = value\n ? self.__evaluate__( value as string, contextScope )\n /**\n * IMPORTANT: An attribute without a value is\n * considered neutral but `true` of a value by\n * default.\n * \n * Eg. <counter initial=3 throttle/>\n * \n * the `throttle` attribute is hereby an input with a\n * value `true`.\n */\n : true\n\n template.declaration?.syntax\n ? TRACKABLE_ATTRS[ SYNCTAX_VAR_FLAG + key ] = value\n : TRACKABLE_ATTRS[ key ] = value\n })\n\n /**\n * Also inject component slotted body into inputs\n */\n const $nodeContents = $node.contents()\n if( $nodeContents.length ){\n // Pass in the regular body contents\n input = {\n ...input,\n ...self.__meshwire__({\n $node,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n meshPath: null,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration,\n }, TRACKABLE_ATTRS )\n }\n\n /**\n * Parse a syntactic declaration body contents\n */\n if( template.declaration ){\n /**\n * Extract node syntax component declaration tag nodes\n */\n if( template.declaration.tags ){\n let $lastNext: Cash\n\n Object\n .entries( template.declaration?.tags )\n .forEach( ([ tagname, { type, many, alts }]) => {\n switch( type ){\n case 'nexted': {\n let $next = $node.next( tagname ) // Default\n // Fish nexted only by defined `alts` (alternatives)\n if( !$next.length\n && Array.isArray( alts ) \n && $lastNext?.length\n && $lastNext.is( alts.join(',') ) )\n $next = $lastNext.next( tagname )\n \n // Nothing to do\n if( !$next.length ) return\n\n if( many ){\n input[ tagname ] = []\n\n let\n index = 0,\n reachedEndOfChain = false\n \n // Continue until we reach the end of the chain\n while( !reachedEndOfChain ){\n input[ tagname ].push( self.__meshwire__({\n $node: $next,\n meshPath: `${tagname}[${index}]`,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS ) )\n\n // Check if there's a next sibling\n if( !$next.next( tagname ).length ){\n reachedEndOfChain = true\n break\n }\n \n // Move to the next siblings\n $next = \n $lastNext = $next.next( tagname )\n index++\n }\n }\n else input[ tagname ] = self.__meshwire__({\n $node: $next,\n meshPath: tagname,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS )\n } break\n\n case 'child': {\n const $children = $node.children( tagname )\n if( many ){\n input[ tagname ] = []\n $children.each(function( index ){\n const \n $this = $(this),\n // Only allowed for child tags\n { argv } = self.__getAttributes__( $this )\n \n input[ tagname ].push( self.__meshwire__({ \n $node: $this,\n meshPath: `${tagname}[${index}]`,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS ) )\n })\n }\n else if( $node.children( tagname ).first().length ){\n const\n $this = $node.children( tagname ).first(),\n // Only allowed for child tags\n { argv } = self.__getAttributes__( $this )\n \n input[ tagname ] = self.__meshwire__({\n $node: $this,\n meshPath: tagname,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS )\n }\n } break\n }\n } )\n }\n\n /**\n * Pass raw content nodes to component\n */\n else if( template.declaration.contents )\n input.__contents__ = $nodeContents\n }\n }\n \n /**\n * Use preserved child component is available.\n * \n * NOTE: Only employ for non-syntax components.\n */\n if( component ){\n component.setInput( deepClone( input ) )\n $fragment = $fragment.add( component.node )\n }\n // Render child component\n else {\n const { declaration, state, _static, handler, context, default: _default, stylesheet } = template\n \n component = new Component( name, _default || '', {\n state: deepClone( state ),\n input: deepClone( input ),\n context,\n _static: deepClone( _static ),\n handler,\n stylesheet,\n declaration\n }, {\n debug: self.debug,\n lips: self.lips,\n prepath: componentPath,\n /**\n * IMPORTANT: Store boundaries on component\n * object for edge case like: \n * \n * - When event-handler dependency update checks\n * whether the component is still in the DOM. \n * - \n */\n boundaries\n })\n\n $fragment = $fragment.add( component.node )\n\n /**\n * Only cache non-syntax components \n * for post-rendering reusability purpose.\n */\n !template.declaration?.syntax\n && self.PCC.set( componentCacheId, component )\n }\n\n // Close boundaries to the initial fragment when it's added to DOM\n $fragment = $fragment.add( boundaries.end )\n\n // Listen to this nexted component's events\n Object\n .entries( events )\n .forEach( ([ _event, instruction ]) => {\n self.__attachEvent__({\n nodepath: componentPath,\n element: component,\n _event,\n instruction,\n scope: contextScope,\n get __dependencies__(){ return dependencies }\n })\n })\n\n /**\n * Setup input dependency track\n */\n TRACKABLE_ATTRS && Object\n .entries( TRACKABLE_ATTRS )\n .forEach( ([ key, value ]) => {\n let \n isSyntax = false,\n isFunction = false\n\n if( key.startsWith( SYNCTAX_VAR_FLAG ) ){\n isSyntax = true\n key = key.replace( SYNCTAX_VAR_FLAG, '')\n }\n if( key.startsWith( FUNCTION_ATTR_FLAG ) ){\n isFunction = true\n key = key.replace( FUNCTION_ATTR_FLAG, '')\n }\n\n if( SPREAD_VAR_PATTERN.test( key ) ){\n if( self.__isReactive__( key, contextScope ) ){\n const\n spreadvalues = ( memo: VariableSet ) => {\n const extracted: Record<string, any> = {}\n\n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n */\n if( attrs.map.afterSpreadAttrs.includes( _key ) ) return\n \n extracted[ _key ] = _value\n },\n nullify: pattrs => pattrs.forEach( _key => extracted[ _key ] = undefined )\n })\n \n component?.subInput( extracted, memo )\n },\n deps = self.__extractExpressionDeps__( key, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'component',\n nodepath: componentPath,\n deppath: `${componentPath}.${key}`,\n target: 'spread-attr',\n $fragment: null,\n boundaries,\n update: spreadvalues,\n syntax: isSyntax\n }) )\n }\n }\n else if( self.__isReactive__( value, contextScope ) ){\n const\n evalue = ( memo: VariableSet ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n\n const _value = isFunction\n ? self.__evaluateFunction__( value, [], memo )\n : value ? self.__evaluate__( value, memo ) : true\n \n component?.subInput({ [ key ]: _value }, memo )\n },\n deps = self.__extractExpressionDeps__( value, contextScope )\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'component',\n nodepath: componentPath,\n deppath: `${componentPath}.${key}`,\n target: 'attr',\n $fragment: null,\n boundaries,\n update: evalue,\n syntax: isSyntax\n }) )\n }\n })\n\n // Track component creation\n self.metrics.inc('componentCount')\n\n return $fragment\n }\n function execMacro( $node: Cash, name?: string, scope?: VariableSet ): Cash {\n name = name || $node.attr( GENERIC_TAGNAME_ATTR ) as string\n if( !name )\n throw new Error('Invalid macro rendering call')\n \n const macro = self.__macros.get( name )\n if( !macro )\n throw new Error('Macro component not found')\n \n const\n macroPath = generatePath('macro'),\n boundaries = self.__getBoundaries__( macroPath ),\n { attrs } = self.__getAttributes__( $node ),\n TRACKABLE_ATTRS: Record<string, string> = {},\n contextScope = scope || useScope()\n \n /**\n * Parse assigned attributes to be injected into\n * the component as input.\n */\n const\n __arguments__: VariableArguments = {},\n argvalues: VariableSet = {}\n \n /**\n * Cast attributes to compnent inputs\n */\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => {\n __arguments__[ key ] = value\n argvalues[ key ] = { value, type: 'arg' }\n })\n\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n const SPREAD_KEYSTORES: Record<string, string[]> = {}\n\n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( SPREAD_VAR_PATTERN.test( key ) ){\n self.__evaluateSpreadAttr__( key, {\n memo: contextScope,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n __arguments__[ _key ] = _value\n\n if( macro.argv.includes( _key ) )\n argvalues[ _key ] = {\n value: _value,\n type: 'arg'\n }\n }\n })\n \n /**\n * Always track spread operators for their \n * content might be reactive\n */\n TRACKABLE_ATTRS[ key ] = value\n }\n\n else {\n const val = value ? self.__evaluate__( value as string, contextScope ) : true\n __arguments__[ key ] = val\n\n if( macro.argv.includes( key ) ){\n argvalues[ key ] = {\n value: val,\n type: 'arg'\n }\n \n TRACKABLE_ATTRS[ key ] = value\n }\n }\n \n /**\n * VERY IMPORTANT: Cancel out invalid argv variables \n * by `false`. It help assigning `undefined` values\n * to element's attribute that are considered `true`\n * as set.\n * \n * Eg. <div active=undefined></div> is same as <div active></div>\n * which is considered as <div active=true></div>\n * \n * REVIEW well before or during maintenance\n */\n macro.argv.forEach( each => {\n if( argvalues[ each ] !== undefined ) return\n\n argvalues[ each ] = {\n value: false, // REVIEW the `false` value assignment later.\n type: 'arg'\n }\n })\n })\n\n /**\n * Return all possible arguments passed to the macro\n * in a single object variable form that can be \n * accessible in macro template as `argvalues`.\n */\n argvalues.__arguments__ = __arguments__\n\n /**\n * - $fragment\n * - macroPath\n * - template.declaration?\n */\n let $fragment = $(boundaries.start)\n const\n setup: MeshWireSetup = {\n $node: macro.$node,\n meshPath: null,\n fragmentPath: macroPath,\n fragmentBoundaries: boundaries,\n argv: macro.argv,\n scope: contextScope,\n xmlns,\n useAttributes: true\n },\n macrowire = self.__meshwire__( setup, TRACKABLE_ATTRS ),\n $log = macrowire.renderer.mesh( argvalues, contextScope )\n\n $fragment = $fragment.add( $log )\n \n /**\n * Setup input dependency track\n */\n TRACKABLE_ATTRS && Object\n .entries( TRACKABLE_ATTRS )\n .forEach( ([ key, value ]) => {\n let isSyntax = false\n if( new RegExp(`^${SYNCTAX_VAR_FLAG}`).test( key ) ){\n isSyntax = true\n key = key.replace( SYNCTAX_VAR_FLAG, '' )\n }\n\n if( SPREAD_VAR_PATTERN.test( key ) ){\n if( !self.__isReactive__( key, contextScope ) ) return\n\n const\n deps = self.__extractExpressionDeps__( key, contextScope ),\n spreadvalues = ( memo: VariableSet ) => {\n const extracted: VariableSet = {}\n let changedDeps: string[] = []\n\n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n */\n if( attrs.map.afterSpreadAttrs.includes( _key ) ) return\n // Ignore unchanged values\n if( isEqual( _value, memo[ _key ]?.value ) ) return\n\n extracted[ _key ] = {\n value: _value,\n type: 'arg'\n }\n\n // Update __arguments__ variable as well\n __arguments__[ _key ] = _value\n // Schedule only what changed values for updated.\n changedDeps.push( _key )\n },\n nullify: pattrs => {\n pattrs.forEach( _key => {\n extracted[ _key ] = {\n value: undefined,\n type: 'arg'\n }\n delete __arguments__[ _key ]\n } )\n\n changedDeps = pattrs\n }\n })\n \n if( changedDeps.length ){\n // Update arguments dep nodes\n self.__updateArgumentsDepNodes__( macroPath, __arguments__ )\n // Update partial deps\n macrowire.renderer.update( changedDeps, extracted, memo )\n }\n\n return sterilize({ memo: { ...memo, ...extracted } })\n }\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, { ...contextScope, ...argvalues }, {\n nodetype: 'macro',\n nodepath: macroPath,\n deppath: `${macroPath}.${key}`,\n target: 'spread-attr',\n $fragment: null,\n boundaries,\n update: spreadvalues,\n syntax: isSyntax\n }) )\n }\n else if( self.__isReactive__( value, contextScope ) ){\n const\n deps = self.__extractExpressionDeps__( value, contextScope ),\n evalue = ( memo: VariableSet ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n \n const newvalue = value ? self.__evaluate__( value as string, memo ) : true\n \n /**\n * Update arguments dep nodes\n */\n __arguments__[ key ] = newvalue\n self.__updateArgumentsDepNodes__( macroPath, __arguments__ )\n\n // Update the whole partial\n macrowire.renderer.update( [ key ], { [ key ]: { value: newvalue, type: 'arg' } }, memo )\n\n return sterilize({ memo })\n }\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, { ...contextScope, ...argvalues }, {\n nodetype: 'macro',\n nodepath: macroPath,\n deppath: `${macroPath}.${key}`,\n target: 'attr',\n $fragment: null,\n boundaries,\n update: evalue,\n syntax: isSyntax\n }) )\n }\n })\n\n $fragment = $fragment.add( boundaries.end )\n\n /**\n * METRICS: Tracking total elements rendered\n */\n self.metrics.inc('elementCount')\n \n return $fragment\n }\n function execElement( $node: Cash, tagname?: string, scope?: VariableSet ): Cash {\n if( !$node.length || !$node.prop('tagName') && !tagname )\n return $node\n\n tagname = tagname || $node.prop('tagName').toLowerCase() as string\n\n /**\n * Special treatement for SVG xml tags\n * because of their delicate namespace\n * definition.\n * \n * Note: `xmlns` to indicate to and xmlns \n * parent tag's nexted contents, like\n * \n * - rect\n * - path\n * - circle\n * - etc\n */\n const\n isXMLNS = $node.is('svg') || xmlns,\n $fragment = isXMLNS\n ? $(document.createElementNS('http://www.w3.org/2000/svg', tagname ))\n // Standard HTML element\n : $(`<${tagname}/>`),\n $contents = $node.contents(),\n elementPath = generatePath('element'),\n contextScope = scope || useScope()\n \n // Process contents recursively if they exist\n $contents.length\n && $fragment.append( self.__withPath__( elementPath, () => self.render( elementPath + NODE_PREFIX, $contents, contextScope, dependencies, isXMLNS ).$log ) )\n\n const { attrs, events } = self.__getAttributes__( $node )\n\n /**\n * Literal value attributes\n */\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ attr, value ]) => {\n if( attr === I18N_ATTR_FLAG ) return\n\n /**\n * Translate standard visual attributes like:\n * \n * - placeholder text\n * - title\n */\n const canTranslate = $node.is(`[${I18N_ATTR_FLAG}]`) && ['title', 'placeholder'].includes( attr )\n \n $fragment.attr( attr, canTranslate ? self.lips.i18n.translate( value ).text : value )\n\n const updateAttr = ( memo: VariableSet ) => {\n $fragment.attr( attr, canTranslate ? self.lips.i18n.translate( value ).text : value )\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttr\n })\n }\n \n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttr\n })\n })\n\n const assignAttrs = ( list: SyntaxAttributes['expressions'], track: boolean = false ) => {\n list && Object\n .entries( list )\n .forEach( ([ attr, value ]) => {\n switch( attr ){\n // Inject inner html into the element\n case '@html': {\n const updateHTML = ( memo: VariableSet ) => {\n $fragment.html( self.__evaluate__( value as string, memo ) )\n }\n\n updateHTML( contextScope )\n\n if( track && self.__isReactive__( value, contextScope ) ){\n const deps = self.__extractExpressionDeps__( value, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateHTML\n }) )\n }\n } break\n\n // Inject text into the element\n case '@text': {\n const \n canTranslate = $node.is(`[${I18N_ATTR_FLAG}]`),\n updateText = ( memo: VariableSet ) => {\n $fragment.text( self.__evaluate__( value as string, memo, { translate: canTranslate } ) )\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateText\n })\n }\n\n updateText( contextScope )\n \n if( track && self.__isReactive__( value, contextScope ) ){\n const deps = self.__extractExpressionDeps__( value, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateText\n }) )\n }\n\n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateText\n })\n } break\n\n // Inject formated text into the element\n case '@format': {\n const [ reference, params ] = value.split(',').map( ( part: string )=> part.trim() )\n if( !reference )\n throw new Error('Invalid @format reference')\n\n if( !params )\n throw new Error('Invalid @format parameters')\n\n const applyFormat = ( memo: VariableSet ) => {\n /**\n * IMPORTANT: Parse parameters if provided\n * with `!` flag to signal interpolation\n * exception during expression evaluation.\n */\n const _params = self.__evaluate__(`!${params.trim()}`, memo )\n if( typeof _params !== 'object' )\n throw new Error('Invalid @format parameters')\n\n // Get the translation\n const text = self.lips.i18n.format( reference, _params )\n text !== undefined && $fragment.text( text )\n \n // Track for i18n translation updates\n self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: applyFormat\n })\n }\n\n applyFormat( contextScope )\n \n // Track reactive dependencies in parameters\n self\n .__extractExpressionDeps__( params, contextScope )\n .forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: applyFormat\n }))\n } break\n\n // Convert object style attribute to string\n case 'style': {\n if( track && self.__isReactive__( value, contextScope ) ){\n const updateStyle = ( memo: VariableSet ) => {\n const style = self.__evaluate__( value as string, memo )\n \n // Defined in object format\n if( typeof style === 'object' ){\n let str = ''\n\n Object\n .entries( style )\n .forEach( ([ k, v ]) => str += `${k}:${v};` )\n \n str.length && $fragment.attr('style', str )\n }\n // Defined in string format\n else $fragment.attr('style', style )\n }\n\n updateStyle( contextScope )\n \n const deps = self.__extractExpressionDeps__( value, contextScope )\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateStyle\n }) )\n }\n else $fragment.attr('style', value )\n } break\n\n // Inject the evaluation result of any other attributes\n default: {\n /**\n * Translate standard visual attributes like:\n * \n * - placeholder text\n * - title\n */\n const \n canTranslate = $node.is(`[${I18N_ATTR_FLAG}]`) && ['title', 'placeholder'].includes( attr ),\n updateAttrs = ( memo: VariableSet ) => {\n const res = value && self.__isReactive__( value, contextScope )\n ? self.__evaluate__( value as string, memo, { translate: canTranslate } )\n /**\n * IMPORTANT: An attribute without a value is\n * considered neutral but `true` of a value by\n * default.\n * \n * Eg. <counter initial=3 throttle/>\n * \n * the `throttle` attribute is hereby an input with a\n * value `true`.\n */\n : value !== undefined ? value : true\n\n /**\n * (?) evaluation return signal to unset the attribute.\n * \n * Very useful case where the attribute don't necessarily\n * have values by default.\n */\n if( res === undefined || res === false )\n $fragment.removeAttr( attr )\n \n else {\n $fragment.attr( attr, res )\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttrs\n })\n }\n }\n\n updateAttrs( contextScope )\n \n if( track && self.__isReactive__( value, contextScope ) ){\n const deps = self.__extractExpressionDeps__( value, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttrs\n }) )\n }\n \n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttrs\n })\n }\n }\n })\n }\n\n // Check, process & track expression attributes\n attrs.expressions && Object\n .keys( attrs.expressions )\n .forEach( key => {\n if( !SPREAD_VAR_PATTERN.test( key ) ) return\n\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n let SPREAD_KEYSTORE: string[] = []\n const updateSpreadAttrs = ( memo: VariableSet, by?: string, initialize = false ) => {\n const extracted: Record<string, any> = {}\n \n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORE },\n set keystore( __ ){ SPREAD_KEYSTORE = __ },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n * \n * NOTE: Checks only occured during update\n */\n if( !initialize && attrs.map.afterSpreadAttrs.includes( _key ) ) return\n\n extracted[ _key ] = _value\n },\n nullify: pattrs => pattrs.forEach( attr => $fragment.removeAttr( attr ) )\n })\n\n Object.keys( extracted ).length && assignAttrs( extracted )\n }\n\n delete attrs.expressions[ key ]\n updateSpreadAttrs( contextScope, '', true )\n\n if( key && self.__isReactive__( key, contextScope ) ){\n const deps = self.__extractExpressionDeps__( key, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${key}`,\n target: 'spread-attr',\n $fragment,\n update: updateSpreadAttrs\n }) )\n }\n })\n\n assignAttrs( attrs.expressions, true )\n \n // Record attachable events to the element\n events && Object\n .entries( events )\n .forEach( ([ _event, value ]) => {\n attachableEvents.push({\n nodepath: elementPath,\n element: $fragment,\n _event,\n instruction: value as string,\n scope: contextScope,\n get __dependencies__(){ return dependencies }\n })\n })\n\n // Track DOM insertion\n self.metrics.inc('elementCount')\n self.metrics.inc('domInsertsCount')\n\n return $fragment\n }\n function execText( $node: Cash ): Cash {\n const\n content = $node.text(),\n contextScope = useScope(),\n textPath = generatePath('element'),\n canTranslate = $node.parent().is(`[${I18N_ATTR_FLAG}]`),\n // Initial rendering\n $fragment = $(document.createTextNode( self.__interpolate__( content, contextScope, canTranslate ) ))\n\n // Update rendering handler\n const updateTextContent = ( memo: VariableSet ) => {\n const text = self.__interpolate__( content, memo, canTranslate )\n if( !$fragment[0] ) return\n $fragment[0].textContent = text\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'text',\n nodepath: textPath,\n target: 'value',\n $fragment,\n update: updateTextContent\n })\n }\n\n // Track for dependency update\n if( content && self.__isReactive__( content, contextScope ) ){\n const deps = self.__extractTextDeps__( content, contextScope )\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'text',\n nodepath: textPath,\n deppath: `${textPath}.${dep}`,\n target: 'value',\n $fragment,\n update: updateTextContent\n }) )\n }\n\n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'text',\n nodepath: textPath,\n target: 'value',\n $fragment,\n update: updateTextContent\n })\n\n // Track DOM insertion\n self.metrics.inc('elementCount')\n self.metrics.inc('domInsertsCount')\n\n return $fragment\n }\n\n function dynamicRoute( $node: Cash ){\n if( !$node.attr( DYNAMIC_TAGNAME_ATTR ) || $node.prop('tagName') !== 'LIPS' )\n throw new Error('Invalid dynamic tag name')\n \n const\n dtag = $node.attr( DYNAMIC_TAGNAME_ATTR ) as string,\n result = self.__evaluate__( dtag, scope )\n\n /**\n * Process dynamic component rendering tag set by:\n * \n * Syntax `<{[template-object]}/>`\n * processed to `<lips :dtag=\"[template-object]\"></lips>`\n */\n if( isTemplate( result ) )\n return execComponent( $node, { template: result } )\n\n /**\n * Process dynamic content rendering tag set by:\n * \n * Syntax `<{input.render}/>`\n * processed to `<lips :dtag=input.render></lips>`\n * \n * or\n * \n * Syntax `<{standard-tagname}/>`\n * processed to `<lips :dtag=\"[standard-tagname]\"></lips>`\n */\n else return execDynamicElement( $node, dtag, result )\n }\n function parse( $node: Cash ){\n if( $node.get(0)?.nodeType === Node.COMMENT_NODE )\n return $node\n\n if( $node.get(0)?.nodeType === Node.TEXT_NODE )\n return execText( $node )\n\n // Lips in-build scope variables syntax components\n if( $node.is('let') ) return execLet( $node )\n else if( $node.is('const') ) return execConst( $node )\n\n /**\n * Lips's dynamic tags like:\n * \n * - component\n * - dynamic-tag\n */\n else if( $node.is('lips') && $node.attr( DYNAMIC_TAGNAME_ATTR ) )\n return dynamicRoute( $node )\n \n /**\n * Convenient `console.log` wired into \n * template rendering\n */\n else if( $node.is('log') ) return execLog( $node )\n \n /**\n * Identify and render macro components\n * \n * Note: Always check `tagname` in registered \n * macros list before in the registered components\n * list.\n */\n else if( self.__macros.has( $node.attr( GENERIC_TAGNAME_ATTR ) as string ) )\n return execMacro( $node )\n \n /**\n * Lips in-build syntax component\n * or identify and render custom components\n */\n else if( $node.is( NATIVE_SYNTAX_TAGS.join(',') ) || self.lips.has( $node.attr( GENERIC_TAGNAME_ATTR ) as string ) )\n return execComponent( $node )\n \n /**\n * Ignore <else-if> and <else> tags as node\n * for their should be already process by <if>\n */\n else if( $node.is('else-if, else') ) return\n \n // Any other note type\n return execElement( $node )\n }\n\n try {\n this.__renderDepth__++\n\n /**\n * Create raw DOM root\n * \n * IMPORTANT:\n * Create a proper DOM tree with sibling \n * relationships when template contains\n * multiple root elements.\n */\n $nodes = !$nodes && $(this.__template__).length > 1\n ? $('<template>').html( this.__template__ ).contents()\n : $nodes || $(this.__template__)\n \n $nodes.each( function(){\n const $node = parse( $(this) )\n if( $node ) _$ = _$.add( $node )\n })\n\n /**\n * Attach extracted events listeners after\n * component get rendered.\n * \n * This to avoid loosing binding to attached\n * DOM element's events\n */\n attachableEvents.forEach( this.__attachEvent__.bind(this) )\n\n /**\n * METRICS: Tracking total occurence of recursive rendering\n */\n self.metrics.inc('renderCount')\n }\n catch( error ){\n console.error('Rendering Failed --', error ) \n self.metrics.trackError( error as Error )\n }\n finally {\n this.__renderDepth__--\n \n // End metrics measuring\n this.metrics.endRender()\n this.metrics.trackMemory()\n \n // Clear path when main render completes\n if( this.__renderDepth__ === 0 ){\n this.__inpath__ = ''\n this.__inpathCounter__ = 0\n }\n }\n \n return {\n $log: _$,\n dependencies,\n events: attachableEvents\n }\n }\n destroy(){\n /**\n * Dispose signal effect dependency of this\n * component.\n */\n this.ICE.dispose()\n /**\n * Clean up stylesheets\n */\n this.stylesheet?.clear()\n /**\n * Clean up metrics resources\n */\n this.metrics.dispose()\n /**\n * Unregister this component from IUC\n */\n this.lips.IUC.unregister( this.__path__ )\n /**\n * Stop watcher when component's element get \n * detached from the DOM\n */\n this.lips.watcher.unwatch( this as any )\n\n /**\n * Detached all events\n */\n this.VER.forEach( this.__detachEvent__.bind(this) )\n this.VER = []\n\n /**\n * Destroy nexted components as well\n */\n for( const each in this.PCC ){\n const component = this.PCC.get( each )\n\n component?.destroy()\n component?.delete( each )\n }\n\n /**\n * Cleanup\n */\n this.$?.remove()\n this.PCC?.clear()\n this.FGUD?.clear()\n this.FGUDMemory?.clear()\n // this.state.reset()\n this.__macros.clear()\n this.__i18nDeps.clear()\n\n // @ts-ignore\n this.__previous = null\n // @ts-ignore\n this.state = null\n // @ts-ignore\n this.input = null\n // @ts-ignore\n this.context = null\n\n // Clear DOM references\n if( this.$ ){\n this.$.each( ( _, el ) => {\n $(el).off() // Clear event handlers\n // $(el).removeData() // Remove custom data\n })\n \n // Clear the reference\n this.$ = null\n }\n\n // Trigger on-destroy lifecycle events\n typeof this.onDestroy === 'function'\n && this.onDestroy.bind(this)()\n this.emit('component:destroy')\n }\n \n private __meshwire__( setup: MeshWireSetup, TRACKABLE_ATTRS: Record<string, string> ){\n const\n self = this,\n {\n $node,\n meshPath,\n fragmentPath,\n fragmentBoundaries,\n argv,\n xmlns,\n declaration,\n useAttributes\n } = setup\n\n let PARTIAL_CONTENT: Cash | undefined\n const\n PARTIAL_PATHS: Map<string, Set<string>> = new Map(),\n MESH_COMPOSITE_PATH = fragmentPath + PARTIAL_ROOT_PREFIX,\n mesh = ( argvalues?: VariableSet, freshscope?: VariableSet, suffix?: string ) => {\n PARTIAL_CONTENT = $node.contents()\n if( !PARTIAL_CONTENT?.length ) return null\n\n freshscope = freshscope || setup.scope\n \n // Render the partial\n const\n partialPath = MESH_COMPOSITE_PATH + (suffix || ''),\n { $log, dependencies, events } = self.__withPath__( partialPath, () => {\n return self.render( partialPath, PARTIAL_CONTENT, { ...freshscope, ...argvalues }, undefined, xmlns )\n })\n \n /**\n * Index the path by slot for fast lookups\n * \n * NOTE: (*) is default slot for standard\n * mesh partial.\n */\n const pathSlot = suffix || DEFAULT_PARTIAL_PATH_SLOT\n // Create new slot\n !PARTIAL_PATHS.has( pathSlot ) && PARTIAL_PATHS.set( pathSlot, new Set() )\n PARTIAL_PATHS.get( pathSlot )?.add( partialPath )\n \n /**\n * Share partial FGU dependenies with main component thread\n * for parallel updates (main & partial) on the meshed node.\n * \n * 1. From main FGU dependency track\n * 2. From mesh rendering track\n */\n dependencies?.forEach( ( dependents, dep ) => {\n !self.FGUD?.has( dep ) && self.FGUD.set( dep, new Map() )\n // Add partial dependency\n dependents.forEach( ( dependent, path ) => {\n if( dependent.garbage ) return\n\n dependent.partial?.length\n ? dependent.partial.push( partialPath )\n : dependent.partial = [ partialPath ]\n \n self.FGUD.get( dep )?.set( path, dependent )\n } )\n } )\n \n self.metrics.inc('partialCount')\n return $log\n },\n update = ( deps: string[], argvalues: VariableSet, freshscope: VariableSet, boundaries: FragmentBoundaries, suffix?: string ) => {\n if( !PARTIAL_PATHS.get( suffix || DEFAULT_PARTIAL_PATH_SLOT )?.size ) return\n \n freshscope = freshscope || setup.scope\n boundaries = boundaries || fragmentBoundaries\n \n // Start measuring\n self.metrics.startRender()\n \n /**\n * IMPORTANT: Target item paths slot by \n * context to avoid unecessary dependency\n * checks or updates.\n */\n const targetedPaths = Array.from( PARTIAL_PATHS.get( suffix || DEFAULT_PARTIAL_PATH_SLOT ) || [] )\n // Execute partial mesh update\n deps.forEach( dep => {\n const dependents = self.FGUD.get( dep )\n if( !dependents ) return\n \n dependents.forEach( dependent => {\n // Process only dependents of this partial and its subpartials\n const partialPath = targetedPaths.find( p => {\n return dependent.partial?.find( pp => p == pp || self.__hasSamePathParent__( pp, p ) )\n })\n if( !dependent.partial || !partialPath ) return\n \n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n \n if( dependent.garbage || boundaries?.start && !document.contains( boundaries.start ) ){\n // console.warn(`${partialPath} -- partial boundaries missing in the DOM`)\n dependents.delete( deppath )\n self.__unbindMemo__( dependent )\n return\n }\n\n if( !memoslot ){\n console.warn(`unexpected occurence: <${deppath}> has no memo`)\n return\n }\n \n if( memoslot.memo?.[ dep ]\n && argvalues?.[ dep ]\n && !isEqual( memoslot.memo[ dep ], argvalues[ dep ] ) )\n memoslot.memo = { ...freshscope, ...memoslot.memo, ...argvalues }\n\n self.UQS.queue({ dep, deppath, priority: dependent.priority })\n self.metrics.inc('dependencyUpdateCount')\n } )\n\n /**\n * Clean up if no more dependents\n */\n !dependents.size && self.FGUD.delete( dep )\n })\n \n // Track update\n self.metrics.inc('partialUpdateCount')\n // Finish measuring\n self.metrics.endRender()\n },\n cleanup = ( boundaries?: FragmentBoundaries, suffix?: string | boolean ) => {\n /**\n * Clear all path attached to this suffix \n * or default slot.\n */\n PARTIAL_PATHS.delete( typeof suffix === 'string' && suffix || DEFAULT_PARTIAL_PATH_SLOT )\n\n /**\n * Clean rendered mesh content\n */\n boundaries = boundaries || fragmentBoundaries\n self.__emptyBoundaries__( boundaries, MESH_COMPOSITE_PATH +(suffix || '') )\n\n /**\n * Partial Mesh self-removal: Clear mesh \n * boundaries as well.\n */\n if( suffix ){\n boundaries.start.remove()\n boundaries.end.remove()\n }\n },\n wire: MeshTemplate = {\n renderer: {\n path: meshPath,\n argv,\n mesh,\n update,\n cleanup,\n\n fill( $newcontent, boundaries ){\n self.__fillBoundaries__( $newcontent, boundaries || fragmentBoundaries )\n },\n demarcate( $newcontent, suffix ){\n const boundaries = self.__getBoundaries__( MESH_COMPOSITE_PATH + (suffix || '') )\n\n // Attach boundaries\n let $partial = $(boundaries.start)\n $partial = $partial.add( $newcontent )\n $partial = $partial.add( boundaries.end )\n \n return { $partial, boundaries }\n }\n }\n }\n\n /**\n * Allow attributes consumption as input/props.\n */\n if( useAttributes && meshPath ){\n const { attrs } = self.__getAttributes__( $node )\n \n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => wire[ key ] = value )\n \n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( SPREAD_VAR_PATTERN.test( key ) ){\n\n let SPREAD_KEYSTORE: string[] = []\n self.__evaluateSpreadAttr__( key, {\n memo: setup.scope,\n get keystore(){ return SPREAD_KEYSTORE },\n set keystore( __ ){ SPREAD_KEYSTORE = __ },\n each: ( _key, _value ) => wire[ _key ] = _value\n })\n\n TRACKABLE_ATTRS[`${declaration?.syntax ? SYNCTAX_VAR_FLAG : ''}${meshPath}.${key}`] = value\n }\n else {\n wire[ key ] = value ? self.__evaluate__( value as string, setup.scope ) : true\n // Record attribute to be tracked as FGU dependency\n TRACKABLE_ATTRS[`${declaration?.syntax ? SYNCTAX_VAR_FLAG : ''}${meshPath}.${key}`] = value\n }\n })\n }\n\n return wire\n }\n private __getBoundaries__( path: string ): FragmentBoundaries {\n // Track DOM operations for boundary creation\n this.metrics.inc('domOperations')\n this.metrics.inc('domInsertsCount')\n\n return {\n start: document.createComment(`s:${path}`),\n end: document.createComment(`e:${path}`)\n }\n }\n private __emptyBoundaries__( boundaries: FragmentBoundaries, parentPath: string ){\n /**\n * Clean tracking mesh content dependencies\n */\n this.FGUD.forEach( ( dependents, dep ) => {\n /**\n * Find and remove dependents that match \n * the branch pattern.\n */\n dependents.forEach( ( dependent, path ) => {\n // console.debug( path, MESH_COMPOSITE_PATH +(suffix || ''), self.__hasSamePathParent__( path, MESH_COMPOSITE_PATH ) )\n if( !this.__hasSamePathParent__( path, parentPath ) ) return\n \n // Unbind memo for this dependent\n this.__unbindMemo__( dependent )\n // Clear garbage dependent from the dependencies map\n dependent.garbage = true\n })\n\n // Cleanup empty dependency maps\n !dependents.size && this.FGUD.delete( dep )\n })\n \n const\n nodesToRemove = [] // Nodes between boundaries\n let currentNode = boundaries.start.nextSibling\n \n while( currentNode && currentNode !== boundaries.end ){\n nodesToRemove.push( currentNode )\n currentNode = currentNode.nextSibling\n }\n \n // Remove old content and insert new\n $(nodesToRemove).remove()\n }\n private __fillBoundaries__( $content: Cash, boundaries: FragmentBoundaries ){\n // Check if boundaries are in DOM\n if( !document.contains( boundaries.start ) || !document.contains( boundaries.end ) ){\n console.warn('Dynamic element boundaries not found')\n return\n }\n\n // this.__emptyBoundaries__( boundaries )\n // Render new content\n $content.length && $(boundaries.start).after( $content )\n }\n private __getAttributes__( $node: Cash ){\n const \n extracted = ($node as any).attrs(),\n events: Record<string, any> = {},\n functions: Record<string, any> = {},\n attrs: SyntaxAttributes = {\n literals: {},\n expressions: {},\n map: {\n explicitAttrs: [],\n spreadAttrs: [],\n beforeSpreadAttrs: [],\n afterSpreadAttrs: [],\n metaAttrs: []\n }\n },\n /**\n * Check extracted spread attribute\n * to initiate attribute positioning\n * mapping.\n */\n containSpreads = Object.keys( extracted ).find( key => SPREAD_VAR_PATTERN.test( key ) )\n\n let\n argv: string[] = [],\n spreadAttrPoint = false\n \n // Process attributes including spread operator\n extracted && Object\n .entries( extracted )\n .forEach( ([ key, value ]) => {\n if( [ GENERIC_TAGNAME_ATTR, DYNAMIC_TAGNAME_ATTR ].includes( key ) ) return\n \n if( key.startsWith(':')\n || key.startsWith( FUNCTION_ATTR_FLAG )\n || key.startsWith( EVENT_LISTENER_FLAG )\n || SPREAD_VAR_PATTERN.test( key )\n || ARGUMENT_VAR_PATTERN.test( key ) ){\n if( ARGUMENT_VAR_PATTERN.test( key ) ){\n const [ _, vars ] = key.match( ARGUMENT_VAR_PATTERN ) || []\n argv = vars.split(',')\n }\n else if( key.startsWith( EVENT_LISTENER_FLAG ) )\n events[ key.replace( EVENT_LISTENER_FLAG, '') ] = value\n\n else if( key.startsWith( FUNCTION_ATTR_FLAG ) )\n functions[ key.replace( FUNCTION_ATTR_FLAG, '') ] = value\n \n else {\n if( key.startsWith(':') )\n key = key.slice( 1, key.length )\n \n /**\n * Record attributes map the\n * extracted attribute contain\n * a spread attr.\n */\n if( containSpreads ){\n if( SPREAD_VAR_PATTERN.test( key ) ){\n attrs.map.spreadAttrs.push( key )\n spreadAttrPoint = true\n }\n else {\n attrs.map.explicitAttrs.push( key )\n !spreadAttrPoint\n ? attrs.map.beforeSpreadAttrs.push( key )\n : attrs.map.afterSpreadAttrs.push( key )\n }\n }\n\n attrs.expressions[ key ] = value || ''\n }\n }\n // Literal value attribute\n else {\n attrs.literals[ key ] = value\n\n /**\n * Record attributes map the\n * extracted attribute contain\n * a spread attr.\n */\n if( containSpreads ){\n attrs.map.explicitAttrs.push( key )\n !spreadAttrPoint\n ? attrs.map.beforeSpreadAttrs.push( key )\n : attrs.map.afterSpreadAttrs.push( key )\n }\n }\n })\n\n return { argv, events, functions, attrs }\n }\n private __withPath__<T>( path: string, fn: () => T ): T {\n const prevPath = this.__inpath__\n this.__inpath__ = path\n\n const result = fn()\n this.__inpath__ = prevPath\n\n return result\n }\n private __getPathParent__( path: string ){\n const __ = path.split('/')\n if( __.length > 1 ) __.pop()\n\n return __.join('/')\n }\n private __hasSamePathParent__( path: string, parentPath: string ){\n return (path.startsWith( parentPath ) && !path.replace( parentPath, '' ).startsWith('.'))\n /**\n * When parent is a mesh partial root element\n */\n || path.startsWith(`${parentPath + PARTIAL_ROOT_PREFIX}`)\n }\n\n private __evaluate__( expr: string, scope?: VariableSet, options?: { translate?: boolean, mute?: boolean }){\n expr = typeof expr === 'string' ? expr.trim() : expr\n try {\n const exec = ( each: string ) => {\n /**\n * Only use none-proxy state for eval\n * to avoid state mutation expression\n * during template rendering.\n */\n const\n _state = this.state.toJSON(),\n /**\n * Safe wrapper function to returns \n * undefined on errors\n */\n safeEval = ( fn: Function, ...args: any[] ) => {\n try { return fn( ...args ) }\n catch( error ){\n !options?.mute && console.error('Eval error --', error )\n return undefined\n }\n }\n\n let expression = `return ${each};`\n \n if( scope ){\n let\n __scope__: Record<string, any> = {},\n __arguments__: Record<string, any> | undefined\n\n for( const key in scope ){\n if( key === '__arguments__' ) continue\n __scope__[ key ] = scope[ key ].value\n }\n\n /**\n * IMPORTANT: `__arguments__` is use to inject\n * all an element's context variables as `arguments`.\n */\n if( typeof scope.__arguments__ === 'object' )\n __arguments__ = scope.__arguments__\n \n /**\n * Wrap expression to inject scope\n * variable.\n */\n expression = `with( scope ){ ${expression} }`\n\n const fn = new Function('self', 'input', 'state', 'static', 'context', 'scope', 'arguments', expression )\n return safeEval( fn, this, this.input, _state, this.static, this.context, __scope__ || {}, __arguments__ )\n }\n else {\n const fn = new Function('self', 'input', 'state', 'static', 'context', expression )\n return safeEval( fn, this, this.input, _state, this.static, this.context )\n }\n }\n\n // Check for interpolation or object expression\n if( /{\\s*([^{}]+)\\s*}/.test( expr ) ){\n /**\n * IMPORTANT: Object exception flag.\n * \n * Case where closures supposedly to define\n * interpolation are instead flagged with `!` \n * sign to be processed as a javascript object.\n */\n if( expr.startsWith('!{') && expr.endsWith('}') )\n return exec( expr.slice(1) )\n\n // Interpolation\n return expr.replace( INTERPOLATE_PATTERN, ( _, expr ) => exec( expr ) )\n }\n\n return exec( expr )\n }\n catch( error ){\n !options?.mute && console.error('Expression evaluation error --', error )\n return undefined\n }\n }\n private __evaluateFunction__( expr: string, params: any[], scope?: VariableSet ){\n /**\n * Execute function expression directly attach \n * as attribute.\n * \n * Eg. \n * `attr=\"() => console.log('Hello world')\"`\n * `attr=\"e => self.onChange(e)\"`\n */\n if( /(\\s*\\w+|\\s*\\([^)]*\\)|\\s*)\\s*=>\\s*(\\s*\\{[^}]*\\}|\\s*[^\\n;\"]+)/g.test( expr ) )\n return this.__evaluate__( expr, scope )( ...params )\n\n /**\n * Execute reference handler function\n * \n * Eg. \n * `attr=\"handleInputValue\"`\n * `attr=\"handleClick, this.input.count++\"`\n * \n * Note: `handleInputValue` and `handleClick` handlers\n * must be defined as `handler` at the component\n * level before any assignment or the execution\n * will throw error.\n */\n else {\n let \n [ fn, ...args ] = expr.split(/\\s*,\\s*/),\n _fn\n \n /**\n * Evaluate whether `fn` is a function itself or\n * a name of an expression resulting in a function.\n */\n const evalfn = this.__evaluate__( fn, scope, { mute: true } )\n\n if( typeof evalfn === 'function' ) _fn = evalfn\n else {\n if( typeof this[ fn ] !== 'function' )\n throw new Error(`Undefined <${fn}> handler method`)\n\n _fn = this[ fn ].bind(this)\n }\n \n if( typeof _fn !== 'function' )\n throw new Error(`Expected <${fn}> to be a function or handler method`)\n\n let _args = args.map( each => (this.__evaluate__( each, scope )) )\n\n if( params.length )\n _args = [ ..._args, ...params ]\n \n return _fn( ..._args )\n }\n }\n private __evaluateSpreadAttr__( expr: string, operator: SpreadOpeartor ){\n const spreads = this.__evaluate__( expr.replace( SPREAD_VAR_PATTERN, '' ) as string, operator.memo )\n if( !spreads ){\n if( !operator.keystore.length )\n throw new Error(`Undefined spread operator ${expr}`)\n \n /**\n * Considered previous spread got nullified\n */\n typeof operator.nullify === 'function' && operator.nullify( operator.keystore )\n return\n }\n \n if( typeof spreads !== 'object' || Array.isArray( spreads ) )\n throw new Error(`Invalid spread operator ${expr}`)\n \n operator.keystore = Object.keys( spreads ) || []\n\n if( typeof operator.each === 'function' )\n for( const key in spreads ) \n operator.each( key, spreads[ key ] )\n }\n private __interpolate__( str: string, scope?: VariableSet, translate?: boolean ){\n str = str.replace( INTERPOLATE_PATTERN, ( _, expr ) => this.__evaluate__( expr, scope ) )\n // Apply translation\n if( translate )\n str = this.lips.i18n.translate( str ).text\n\n return str\n }\n private __attachEvent__( metadata: VirtualEvent<MT> ){\n const { element, nodepath, _event, instruction, scope, __dependencies__ } = metadata \n let eventScope = scope\n\n /**\n * Execute function script directly attach \n * as the listener.\n * \n * Eg. \n * `on-click=\"() => console.log('Hello world')\"`\n * `on-change=\"e => self.onChange(e)\"`\n * \n * Or\n * \n * Execute reference handler function\n * \n * Eg. \n * `on-input=\"handleInputValue\"`\n * `on-click=\"handleClick, this.input.count++\"`\n * \n * Note: `handleInputValue` and `handleClick` handlers\n * must be defined as `handler` at the component\n * level before any assignment.\n */\n element.on( _event, ( ...params: any[] ) => this.__evaluateFunction__( instruction, params, eventScope ) )\n\n this.VER.push( metadata )\n \n // Track DOM operation\n this.metrics.inc('domUpdatesCount')\n this.metrics.inc('domRemovalsCount')\n \n // Track the event handler as a dependency\n if( this.__isReactive__( instruction, scope ) ){\n const deps = this.__extractExpressionDeps__( instruction, scope )\n deps.forEach( dep => this.__trackDep__( __dependencies__, dep, scope || {}, {\n nodetype: 'event',\n nodepath,\n deppath: `${nodepath}.${_event}`,\n target: 'event-handler',\n $fragment: !(element instanceof Component) ? element : null,\n boundaries: element instanceof Component ? element.__boundaries__ : undefined,\n /**\n * Update event's scope with fresh memo\n */\n update: memo => { eventScope = memo }\n }))\n }\n }\n private __detachEvent__({ element, nodepath, _event, instruction, scope, __dependencies__ }: VirtualEvent<MT> ){\n element.off( _event )\n\n // Clean up tracking event handler dependencies\n if( this.__isReactive__( instruction, scope ) ){\n const \n deps = this.__extractExpressionDeps__( instruction, scope ),\n eventPath = `${nodepath}.${_event}`\n \n deps.forEach( dep => {\n // From partial dependencies if there is\n __dependencies__.get( dep )?.delete( eventPath )\n // From main dependencies\n this.FGUD.get( dep )?.delete( eventPath )\n })\n }\n \n // Track DOM operation\n this.metrics.inc('domOperations')\n this.metrics.inc('domRemovalsCount')\n }\n\n private __extractTextDeps__( expr: string, scope?: VariableSet ): string[] {\n const deps = new Set<string>()\n \n // Handle interpolation expressions\n const matches = expr.match(/{\\s*([^{}]+)\\s*}/g) || []\n matches.forEach( match => {\n const\n innerExpr = match.replace(/[{}]/g, '').trim(),\n exprDeps = this.__extractExpressionDeps__( innerExpr, scope )\n\n exprDeps.forEach( dep => deps.add( dep ) )\n })\n\n return Array.from( deps )\n }\n private __extractExpressionDeps__( expr: string, scope?: VariableSet ): string[] {\n const\n /**\n * Metavars pattern\n * \n * - state.items\n * - input.name\n * - context.action\n */\n MVP = /\\b(state|input|context|arguments)(?:\\.[a-zA-Z_]\\w*)+(?=\\[|\\.|$|\\s|;|,|\\))/g,\n /**\n * Metacall pattern\n * \n * - self.getStyle()\n * - self.rule\n */\n MCP = /\\b(self)(?:\\.[a-zA-Z_]\\w*)+(?=\\()/g,\n /**\n * Scope argument pattern\n * \n * - arguments\n * - argument.<key>\n * - argument.<key>[,subkey]\n */\n SAP = /\\b(arguments)((?:\\.[a-zA-Z_]\\w*)+)?(?=\\[|\\.|$|\\s|;|,|\\))/g\n\n let matches = [\n ...Array.from( expr.matchAll( MVP ) ),\n ...Array.from( expr.matchAll( MCP ) ),\n ...Array.from( expr.matchAll( SAP ) )\n ]\n\n /**\n * Extract scope interpolation expressions\n */\n if( scope && Object.keys( scope ).length ){\n const\n scopeRegex = new RegExp(`\\\\b(?<!\\\\.)(${Object.keys( scope ).join('|')})`, 'g'),\n spreadScopeRegex = new RegExp(`(?:(?<=\\\\.\\\\.\\\\.))(${Object.keys(scope).join('|')})\\\\b`, 'g')\n \n matches = [\n ...matches,\n ...Array.from( expr.matchAll( scopeRegex ) ),\n ...Array.from( expr.matchAll( spreadScopeRegex ) )\n ]\n }\n \n // Filter out duplicate deps\n return [ ...new Set( matches.map( m => m[0] ) ) ]\n }\n private __isReactive__( expr: string, scope?: VariableSet ): boolean {\n // Reactive component variables\n if( /(self|state|input|context|arguments)(\\.[\\w.]+)?/.test( expr ) ) return true\n // Reactive internal scope\n if( scope\n && Object.keys( scope ).length\n && new RegExp( Object.keys( scope ).join('|') ).test( expr ) ) return true\n\n return false\n }\n /**\n * Store dependencies memory separately:\n * \n * IMPORTANT: Every node's tracked deps share\n * the same memo reference by the path\n * of that node.\n * \n * Example 1: `<div id=state.item.id style=\"padding: {input.size/2}\">...</div>`\n * The dependencies tracking `id` and `style` attributes\n * will respectively share the memo that is referenced by\n * the `div` element's path\n * Example 2. `<span>{state.label} - {count}</span>`\n * The `state.label` and `count` dependencies will be\n * each tracked using the `span` text content element's\n * memo.\n * \n * Same procedure for `event-handlers`\n */\n private __bindMemo__( memo: VariableSet, dependent: FGUDependency ){\n const\n deppath = dependent.deppath || dependent.nodepath,\n sharedMemo = this.FGUDMemory.get( dependent.nodepath )\n\n if( sharedMemo ){\n // Add new memory dep tracker\n sharedMemo.tracks.set( deppath, dependent.priority || 2 )\n // REVIEW: Override memo\n sharedMemo.memo = memo\n \n // Alter the existing memory\n this.FGUDMemory.set( dependent.nodepath, sharedMemo )\n }\n // Create fresh shared memo\n else {\n // List of tracked dependencies with their priority\n const tracks = new Map()\n\n tracks.set( deppath, dependent.priority )\n this.FGUDMemory.set( dependent.nodepath, { tracks, memo })\n }\n }\n private __unbindMemo__( dependent: FGUDependency ){\n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n \n // No memory bind or already cleaned up\n if( !memoslot || !memoslot.tracks.get( deppath ) ) return\n \n memoslot.tracks.delete( deppath )\n // Remove memory slot if there are no more tracks\n !memoslot.tracks.size && this.FGUDMemory.delete( dependent.nodepath )\n }\n private __trackDep__( dependencies: FGUDependencies, dep: string, memo: VariableSet, dependency: FGUDependency ){\n /**\n * Designate dependencies that assign or \n * interpolate a `let` variable.\n */\n if( memo\n && memo[ dep ]\n && memo[ dep ].type === 'let' )\n dependency.haslet = true\n\n // Assign priority based on dependency type\n if( dependency.priority === undefined ){\n /**\n * Priority 0: (Highest)\n * \n * - Elements affecting layout or visibility\n */\n if( dependency.target === 'attr'\n && dep.split('.').find( each => LAYOUT_AFFECTING_ATTRS.includes( each ) ) )\n dependency.priority = 0\n \n /**\n * Priority 1: \n * \n * - Key structural elements\n * - Conditional rendering\n */\n else if( dependency.syntax ) dependency.priority = 1\n /**\n * Priority 3: (Least urgent)\n * \n * - Event handlers\n */\n else if( ['event'].includes( dependency.nodetype ) ) dependency.priority = 3\n /**\n * Priority 2: (Default)\n * \n * - Sub components\n * - Elements\n * - Text content \n * - Other attributes\n */\n else dependency.priority = 2\n }\n\n const deppath = dependency.deppath || dependency.nodepath\n /**\n * Determine dependency hierarchy level \n * based on path depth by separators.\n */\n dependency.level = deppath.split(/\\//g).length\n /**\n * REVIEW: Combine `level` and `priority` into\n * composite to ensure top-down updates while\n * still respecting the update type priority\n * within each level.\n * \n * `MAX_PRIORITY_TYPES = 100`: This avoid having \n * priority collisions even with complex applications\n */\n dependency.priority = (dependency.level * MAX_PRIORITY_TYPES) + dependency.priority\n\n !dependencies.has( dep ) && dependencies.set( dep, new Map() )\n dependencies.get( dep )?.set( deppath, dependency )\n\n // Subscribed to shared memory\n this.__bindMemo__( memo, dependency )\n\n // Track dependency\n this.metrics.inc('dependencyTrackCount')\n }\n private __trackTranslationDep__( memo: VariableSet, dependency: I18nDependency ){\n this.__i18nDeps.set( dependency.deppath || dependency.nodepath, dependency )\n // Subscribed to shared memory\n this.__bindMemo__( memo, dependency )\n\n // i18n dependency\n this.metrics.inc('i18nTrackCount')\n }\n\n private __valueDep__( obj: any, path: string[] ): any {\n return path.reduce( ( curr, part ) => curr?.[ part ], obj )\n }\n private __shouldUpdate__( dep_scope: string, parts: string[] ): boolean {\n /**\n * Allow component's method `self.fn` call \n * evaluation\n */\n if( dep_scope === 'self' ) return true\n\n // Check metavars changes\n const\n current: InteractiveMetavars<MT> = { \n state: this.state,\n input: this.input,\n context: this.context\n },\n ovalue = this.__valueDep__( this.__previous[ dep_scope as keyof InteractiveMetavars<MT> ], parts ),\n nvalue = this.__valueDep__( current[ dep_scope as keyof InteractiveMetavars<MT> ], parts )\n\n /**\n * Skip if value hasn't changed\n */\n return !isEqual( ovalue, nvalue )\n }\n private __updateDepNodes__(){\n if( !this.FGUD?.size ) return\n \n // Track update\n this.metrics.inc('componentUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n // console.debug('FGUD --', this.FGUD )\n // console.debug('FGUDM --', this.FGUDMemory )\n\n this.FGUD.forEach( ( dependents, dep ) => {\n const [ dep_scope, ...parts ] = dep.split('.')\n\n /**\n * Handle updates for each dependent node/component\n */\n if( !this.__shouldUpdate__( dep_scope, parts ) ) return\n\n dependents.forEach( dependent => {\n try {\n /**\n * Only clean up non-syntactic dependencies \n * or node no longer in DOM\n */\n const deppath = dependent.deppath || dependent.nodepath\n if( dependent.garbage\n || (dependent.boundaries?.start && !document.contains( dependent.boundaries.start ))\n || (dependent.$fragment !== null && !dependent.$fragment.closest('body').length) ){\n dependents.delete( deppath )\n this.__unbindMemo__( dependent )\n\n return\n }\n \n this.UQS.queue({ dep, deppath, priority: dependent.priority })\n this.metrics.inc('dependencyUpdateCount')\n }\n catch( error ){\n console.error('failed to update dependency nodes --', error )\n return\n }\n })\n\n /**\n * Clean up if no more dependents\n */\n !dependents.size && this.FGUD?.delete( dep )\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n private __updateVarDepNodes__( dep: string, varPath: string, newScope: VariableSet ){\n if( !this.FGUD?.size ) return\n\n // Track update\n this.metrics.inc('partialUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n this.FGUD.get( dep )?.forEach( ( dependent, path ) => {\n // console.debug( path, varPath, this.__hasSamePathParent__( path, this.__getPathParent__( varPath ) ) )\n if( !dependent.haslet\n || !this.__hasSamePathParent__( path, this.__getPathParent__( varPath ) ) ) return\n\n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n if( !memoslot ){\n console.warn(`unexpected occurence: <${deppath}> has no memo`)\n return\n }\n\n memoslot.memo = { ...memoslot.memo, ...newScope }\n \n this.UQS.queue({ dep, deppath, priority: dependent.priority })\n this.metrics.inc('dependencyUpdateCount')\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n private __updateArgumentsDepNodes__( scopePath: string, __arguments__: VariableArguments ){\n if( !this.FGUD?.size ) return\n\n // Track update\n this.metrics.inc('partialUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n const dep = 'arguments'\n this.FGUD.get( dep )?.forEach( ( dependent, path ) => {\n if( !this.__hasSamePathParent__( path, scopePath ) ) return\n\n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n if( !memoslot ){\n console.warn(`unexpected occurence: <${deppath}> has no memo`)\n return\n }\n \n memoslot.memo.__arguments__ = __arguments__\n this.UQS.queue({ dep, deppath, priority: dependent.priority })\n\n this.metrics.inc('dependencyUpdateCount')\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n private __updateI18nDepNodes__(){\n if( !this.__i18nDeps?.size ) return\n\n // Track update\n this.metrics.inc('i18nUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n this.__i18nDeps?.forEach( ( dependent, path ) => {\n /**\n * The different of i18n dependency update\n * from other updates is that they are cleared\n * as soon as the get updated. Let for the updator\n * function to reset a track if needed.\n * \n * Advantage:\n * - No tracking of unecessarily dead node\n * - `i18n` flag or attribute changed to no-translate\n * - Keep fresh `memo` from other update processes\n * - Cleanup safety for highly interactive content UI.\n */\n if( !dependent.$fragment.closest('body').length ){\n this.__i18nDeps.delete( path )\n return\n }\n\n const memoslot = this.FGUDMemory.get( dependent.nodepath )\n if( !memoslot ){\n console.warn(`unexpected occurence: <${dependent.deppath || dependent.nodepath}> has no memo`)\n return\n }\n\n dependent.update( memoslot.memo, 'i18n-partial-updator' )\n \n this.metrics.inc('dependencyUpdateCount')\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n \n appendTo( arg: Cash | string ){\n (typeof arg == 'string' ? $(arg) : arg).append( this.node )\n // Track DOM operation\n this.metrics.inc('domOperations')\n\n return this\n }\n prependTo( arg: Cash | string ){\n typeof arg == 'string' ? $(arg) : arg.prepend( this.node )\n // Track DOM operation\n this.metrics.inc('domOperations')\n\n return this\n }\n replaceWith( arg: Cash | string ){\n (typeof arg == 'string' ? $(arg) : arg).replaceWith( this.node )\n // Track DOM operation\n this.metrics.inc('domOperations')\n\n return this\n }\n}",
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
"import type Lips from './lips'\nimport type {\n Handler,\n Metavars,\n ComponentScope,\n ComponentOptions,\n InteractiveMetavars,\n Macro,\n Variable,\n VariableSet,\n MeshRenderer,\n MeshTemplate,\n RenderedNode,\n FGUDependencies,\n FGUDependency,\n Declaration,\n FragmentBoundaries,\n VirtualEvent,\n MeshWireSetup,\n SyntaxAttributes,\n DynamicTemplate,\n I18nDependency,\n VariableArguments,\n FGUDMemory,\n SpreadOpeartor\n} from './types'\n\nimport UQS from './uqs'\nimport Events from './events'\nimport Metrics from './metrics'\nimport $, { Cash } from 'cash-dom'\nimport Stylesheet from './stylesheet'\nimport { effect, EffectControl, memo, signal } from './signal'\nimport { \n isDiff,\n isEqual,\n sterilize,\n deepClone,\n deepAssign\n} from './utils'\n\nimport {\n SPREAD_VAR_PATTERN,\n ARGUMENT_VAR_PATTERN,\n INTERPOLATE_PATTERN,\n GENERIC_TAGNAME_ATTR,\n I18N_ATTR_FLAG,\n SYNCTAX_VAR_FLAG,\n FUNCTION_ATTR_FLAG,\n EVENT_LISTENER_FLAG,\n LAYOUT_AFFECTING_ATTRS,\n MAX_PRIORITY_TYPES,\n NODE_PREFIX,\n COMPONENT_PREFIX,\n PARTIAL_ROOT_PREFIX,\n SYNTAX_COMPONENT_PREFIX,\n MACRO_PREFIX,\n DEFAULT_PARTIAL_PATH_SLOT,\n NATIVE_SYNTAX_TAGS,\n DYNAMIC_TAGNAME_ATTR\n} from './constants'\n\nexport default class Component<MT extends Metavars> extends Events {\n private declaration: Declaration\n private $?: Cash | null = null\n\n public input: MT['Input']\n public state: MT['State'] & {\n toJSON(): MT['State']\n reset(): void\n }\n public static: MT['Static']\n public context: MT['Context']\n\n public __name__: string\n public __path__: string\n private __lang__: string\n private __template__: string\n private __previous: InteractiveMetavars<MT>\n private __macros: Map<string, Macro> = new Map() // Cached macros templates\n private __i18nDeps: Map<string, I18nDependency> = new Map()\n\n // Initial FGU dependencies\n public FGUD: FGUDependencies = new Map()\n public FGUDMemory: FGUDMemory = new Map()\n // Preserved Child Components\n private PCC: Map<string, Component<MT>> = new Map()\n // Virtual Events Registry\n private VER: Array<VirtualEvent<MT>> = []\n\n private prepath = '0'\n private debug = false\n private isRendered = false\n\n private __setInput: ( input: MT['Input'] ) => void\n private __setState: ( state: MT['State'] ) => void\n private __getState: () => MT['State'] | undefined\n\n // Update Queue System for high-frequency DOM updates\n private UQS: UQS<MT>\n // Internal Component Effect\n private ICE: EffectControl\n\n public lips: Lips\n public metrics: Metrics\n public stylesheet?: Stylesheet\n\n private __inpath__ = ''\n private __inpathCounter__ = 0\n private __renderDepth__ = 0\n private __boundaries__\n\n /**\n * Allow methods of `handler` to be dynamically\n * added to `this` component object.\n */\n ;[key: string]: any\n\n constructor( name: string, template: string, { input, state, context, _static, handler, stylesheet, macros, declaration }: ComponentScope<MT>, options: ComponentOptions<any> ){\n super()\n this.lips = options.lips\n \n if( options?.debug ) this.debug = options.debug || this.lips.debug\n if( options?.prepath ) this.prepath = options.prepath\n\n this.__name__ = name\n this.__lang__ = this.lips.i18n.lang\n this.__path__ = \n this.__inpath__ = `${this.prepath}:${this.__name__}`\n this.__boundaries__ = options.boundaries\n \n this.declaration = declaration || { name }\n\n this.input = input || {}\n this.static = _static || {}\n this.context = {}\n // Detect all state mutations, including deep mutations\n this.state = this.lips.IUC.proxyState<MT['State']>( this.__path__, state || {} )\n\n macros && this.setMacros( macros )\n handler && this.setHandler( handler )\n stylesheet && this.setStylesheet( stylesheet )\n\n /**\n * IMPORTANT:\n * \n * Parse component's template only after\n * parsing macros templates for alternative macro\n * reference check during preprocessing.\n */\n this.__template__ = this.lips.preprocessor.parse( template, this.__macros )\n\n /**\n * Track rendering cycle metrics to evaluate\n * performance.\n * \n */\n this.metrics = new Metrics( this.debug )\n // Track component creation\n this.metrics.inc('componentCount')\n \n /**\n * Batch Dependencies Update handler\n */\n this.UQS = new UQS( this )\n\n /**\n * Triggered during component creation\n * \n * NOTE: Any state value set during this process\n * is considered initial state.\n */\n typeof this.onCreate == 'function'\n && this.onCreate.bind(this)()\n this.emit('component:create')\n\n /**\n * Triggered an initial input is provided\n */\n if( this.input\n && Object.keys( this.input ).length\n && typeof this.onInput == 'function' ){\n this.onInput.bind(this)()\n this.emit('component:input')\n }\n\n /**\n * Initialize previous interative metavars to initial metavars\n * \n * IMPORTANT: this prevent any update effect during\n * component creating for initial input, state and\n * context\n */\n this.__previous = {\n state: deepClone( this.state ),\n input: deepClone( this.input ),\n context: deepClone( this.context )\n }\n\n const\n [ getInput, setInput ] = signal<MT['Input']>( this.input ),\n [ getState, setState ] = signal<MT['State']>( this.state ),\n [ getContext, setContext ] = signal<MT['Context']>( this.context )\n\n this.__setInput = setInput\n this.__setState = setState\n this.__getState = getState\n\n /**\n * Register to queue & apply update only when \n * a new change occured on the state.\n * \n * Merge with initial/active state.\n */\n this.lips.IUC.register( this.__path__, () => {\n isDiff( this.__previous?.state as Record<string, any>, this.state as Record<string, any> )\n && this.__setState({ ...this.__getState(), ...this.state })\n })\n \n /**\n * Set context update effect listener\n * to merge with initial/active context\n * after any occurances.\n */\n Array.isArray( context )\n && context.length\n && this.lips.useContext<MT['Context']>( context, ctx => {\n if( !isDiff( this.context as Record<string, any>, ctx ) ) return\n\n setContext( ctx )\n /**\n * IMPORTANT: Make `ctx` data available for the\n * onContext lifecycle event before component get\n * rendered of update.\n */\n this.context = ctx\n \n /**\n * Triggered anytime component context changed\n */\n typeof this.onContext == 'function'\n && this.onContext.bind(this)()\n this.emit('component:context')\n })\n\n /**\n * Subscribe to i18n changes\n * \n * - `*` support all languages\n * - [...] TODO: Explicitly defined list of supported languages\n */\n this.lips.useTranslator( '*', lang => {\n /**\n * Run translation update only when the \n * language truly changed\n */\n if( lang === this.__lang__ ) return\n\n this.__updateI18nDepNodes__()\n this.__lang__ = lang\n })\n \n this.ICE = effect( () => {\n const\n state = getState(),\n input = this.input = getInput(),\n /**\n * `this.context` is initialized empty so it's\n * important to set it before component render \n * or update.\n */\n context = this.context = getContext()\n \n /**\n * Initial render - parse template and establish \n * dependencies\n */\n if( !this.isRendered ){\n // Reset metrics before render\n this.metrics.reset()\n \n /**\n * For non-template component or syntax component \n * that requires to self-outsource and process the \n * initial rendering.\n * \n * NOTE: `onSelfRender()` lifecycle method must \n * define and can return the initially rendered \n * component log. An empty fragment is used otherwise.\n */\n if( !this.__template__.length \n || declaration?.syntax && typeof this.onSelfRender == 'function' ){\n const $log = this.onSelfRender.bind(this)( this.input )\n\n if( !this.__boundaries__?.start || !this.__boundaries__?.end )\n throw new Error(`Undefined <${this.__name__} syntax component boundaries`)\n\n this.$ = $log || $()\n }\n /**\n * Normal component rendering\n */\n else {\n const { $log } = this.render( '', undefined, undefined, this.FGUD )\n this.$ = $log\n }\n \n /**\n * Assign CSS relationship attribute\n * for only non-syntax components.\n */\n !declaration?.syntax\n && this.$?.each( ( i, el ) => {\n typeof el.setAttribute == 'function'\n && el.setAttribute('rel', this.__name__ )\n } )\n\n this.isRendered = true\n \n /**\n * Triggered after component get mounted for\n * the first time.\n */\n typeof this.onMount == 'function'\n && this.onMount.bind(this)()\n this.emit('component:mount')\n\n /**\n * Watch when component's element get \n * attached to the DOM\n */\n this.lips.watcher.watch( this as any )\n }\n else {\n /**\n * Update only dependent nodes\n */\n this.__updateDepNodes__()\n \n /**\n * Triggered anytime component gets updated\n */\n typeof this.onUpdate == 'function' && this.onUpdate.bind(this)()\n this.emit('component:update')\n \n /**\n * Save as previous meta variables for next cycle.\n * \n * IMPORTANT: Required to check changes on the state\n * during IUC processes.\n */\n this.__previous = {\n input: deepClone( input ),\n state: deepClone( state ),\n context: deepClone( context )\n }\n }\n\n // this.metrics.log()\n\n /**\n * Triggered anytime component gets rendered\n */\n typeof this.onRender == 'function' && this.onRender.bind(this)()\n this.emit('component:render')\n })\n }\n\n setContext( arg: Partial<Record<string, any>> | string, value?: any ){\n /**\n * Set global context value from any component\n * \n * Note: `arg` if object isn't restricted to \n * this component's required context fields scope.\n */\n this.lips.setContext( arg, value )\n }\n setInput( input: MT['Input'], memo?: VariableSet ){\n /**\n * Apply update only when new input is different \n * from the incoming input\n */\n if( !isDiff( this.input as Record<string, any>, input as Record<string, any> ) )\n return\n \n // Set new input.\n this.__setInput( input )\n \n /**\n * Triggered anytime component recieve new input\n * \n * Only passed `memo` in special cases like\n * self-rendered syntax comopnent.\n */\n typeof this.onInput == 'function'\n && this.onInput.bind(this)( this.declaration.syntax ? memo : undefined )\n }\n /**\n * Inject grain/partial input to current component \n * instead of sending a whole updated input\n */\n subInput( data: Record<string, any>, memo?: VariableSet ){\n if( typeof data !== 'object' )\n throw new Error('Invalid sub input data argument')\n \n /**\n * Only passed `memo` in special cases like\n * self-rendered syntax comopnent.\n */\n this.setInput( deepAssign<MT['Input']>( this.input, data ), this.declaration.syntax ? memo : undefined )\n return this\n }\n setMacros( template: string ){\n const\n prepo = this.lips.preprocessor.parse( template ),\n $nodes = $(prepo)\n if( !$nodes.length ) return\n\n const self = this\n $nodes.each( function(){\n const\n $node = $(this),\n { argv, attrs } = self.__getAttributes__( $node )\n\n if( !Object.keys( attrs ) )\n throw new Error('Invalid macro component definition')\n\n if( !attrs.literals.name )\n throw new Error('Undefined macro `name` attribute.')\n\n if( self.__macros.get( attrs.literals.name ) )\n console.warn(`Duplicate macro <${attrs.literals.name}> will be override`)\n\n if( !$node.contents()?.length )\n throw new Error('Invalid macro component definition. Template content expected.')\n\n self.__macros.set( attrs.literals.name, { argv, $node } )\n } )\n }\n setHandler( list: Handler<MT> ){\n Object\n .entries( list )\n .map( ([ method, fn ]) => this[ method ] = fn?.bind(this) )\n }\n setStylesheet( sheet?: string ){\n const cssOptions = {\n sheet,\n /**\n * Inject root component styles into global meta\n * style tag.\n */\n meta: this.__name__ === '__ROOT__'\n }\n\n this.stylesheet = new Stylesheet( this.__name__, cssOptions )\n }\n\n get node(){\n if( !this.isRendered )\n throw new Error('node() is expected to be call after component get rendered')\n\n return this.$\n }\n get boundaries(){\n return this.__boundaries__\n }\n \n render( inpath: string, $nodes?: Cash, scope: VariableSet = {}, sharedDeps?: FGUDependencies, xmlns?: boolean ): RenderedNode<MT> {\n if( $nodes && !$nodes.length ){\n console.warn('Undefined node element to render')\n return { $log: $nodes, dependencies: sharedDeps || new Map() }\n }\n\n const\n self = this,\n dependencies: FGUDependencies = sharedDeps || new Map(),\n attachableEvents: Array<VirtualEvent<MT>> = []\n\n // Start metrics measuring\n this.metrics.startRender()\n\n /**\n * Initialize an empty cash object to \n * act like a DocumentFragment\n */\n let _$ = $()\n\n function useScope(){\n return deepClone( scope )\n }\n function generatePath( type: string, isSyntax = false ): string {\n const key = generateComponentName( type, isSyntax )\n self.__inpathCounter__++\n\n return self.__inpath__ ? `${self.__inpath__}/${key}` : `${inpath ? inpath +'/' : ''}${key}`\n }\n function generateComponentName( type: string, isSyntax = false ){\n let prefix = ''\n switch( type ){\n case 'component': prefix = isSyntax ? SYNTAX_COMPONENT_PREFIX : COMPONENT_PREFIX; break\n case 'macro': prefix = MACRO_PREFIX; break\n }\n\n return prefix + self.__inpathCounter__\n }\n function isMesh( arg: any ){\n return arg === null // Null renderer\n || (typeof arg === 'object' // Valid Renderer\n && typeof arg.mesh === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.update === 'function'\n && typeof arg.cleanup === 'function')\n }\n function isTemplate( arg: any ){\n /**\n * DO NOT SUPPORT self-rendered components\n * because the don't provide `default`.\n */\n return arg !== null\n && typeof arg === 'object'\n && typeof arg.default\n && typeof arg.default === 'string'\n }\n\n function execLog( $node: Cash ){\n const\n args = $node.attr(':args'),\n logPath = generatePath('log')\n if( !args ) return\n \n // Log context scope\n const contextScope = useScope()\n\n self.__evaluate__(`console.log(${args})`, contextScope )\n \n if( self.__isReactive__( args as string, contextScope ) ){\n const deps = self.__extractExpressionDeps__( args as string, contextScope )\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'log',\n nodepath: logPath,\n target: 'argument',\n $fragment: null,\n update: memo => self.__evaluate__(`console.log(${args})`, memo ),\n syntax: true\n }) )\n }\n }\n function execLet( $node: Cash ){\n const\n varPath = generatePath('var'),\n { attrs } = self.__getAttributes__( $node )\n if( !attrs ) return\n\n Object\n .entries( attrs.literals )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`Cannot override <const ${key}=[value]/> variable`)\n \n scope[ key ] = { value: assign, type: 'let' }\n })\n\n Object\n .entries( attrs.expressions )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`Cannot override <const ${key}=[value]/> variable`)\n\n scope[ key ] = {\n value: self.__evaluate__( assign as string, scope ),\n type: 'let'\n }\n\n if( self.__isReactive__( assign, scope ) ){\n const \n deps = self.__extractExpressionDeps__( assign, scope ),\n updateVar = ( memo: VariableSet, by?: string ) => {\n if( memo[ key ] && memo[ key ].type === 'const' )\n throw new Error(`Cannot override <const ${key}=[value]/> variable`)\n\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n\n const value = self.__evaluate__( assign as string, memo )\n if( isEqual( memo[ key ].value, value ) ) return\n\n memo[ key ] = { value, type: 'let' }\n \n /**\n * Apply update to related dependencies\n */\n self.__updateVarDepNodes__( key, varPath, memo )\n\n return sterilize({ memo })\n }\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, useScope(), {\n nodetype: 'let',\n nodepath: varPath,\n deppath: `${varPath}.${key}`,\n target: 'attr',\n $fragment: null,\n update: updateVar,\n syntax: true\n }) )\n }\n })\n \n /**\n * METRICS: Tracking total elements rendered\n */\n self.metrics.inc('elementCount')\n }\n function execConst( $node: Cash ){\n const\n { attrs } = self.__getAttributes__( $node )\n if( !attrs ) return\n \n Object\n .entries( attrs.literals )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`<const ${key}=[value]/> variable already defined`)\n \n if( !assign ) return\n\n scope[ key ] = { value: assign, type: 'const' }\n } )\n\n Object\n .entries( attrs.expressions )\n .forEach( ([ key, assign ]) => {\n if( scope[ key ] && scope[ key ].type === 'const' )\n throw new Error(`<const ${key}=[value]/> variable already defined`)\n\n if( !assign ) return\n \n scope[ key ] = {\n value: self.__evaluate__( assign as string, scope ),\n type: 'const'\n }\n } )\n \n /**\n * METRICS: Tracking total elements rendered\n */\n self.metrics.inc('elementCount')\n }\n function execDynamicElement( $node: Cash, dtag: string, verb: MeshRenderer | string | null ): Cash {\n const\n { attrs } = self.__getAttributes__( $node ),\n elementPath = generatePath('element'),\n boundaries = self.__getBoundaries__( elementPath ),\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n SPREAD_KEYSTORES: Record<string, string[]> = {}\n\n let\n contextScope = useScope(),\n $fragment = $(boundaries.start),\n renderer: MeshRenderer | null\n\n const handleMeshRendererAttributes = ( scope: VariableSet ) => {\n const \n // Keep track of the latest mesh scope\n argvalues: VariableSet = {},\n __arguments__: VariableArguments = {}\n\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => {\n __arguments__[ key ] = value\n argvalues[ key ] = { type: 'arg', value }\n } )\n\n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( !renderer ) return\n \n if( SPREAD_VAR_PATTERN.test( key ) )\n self.__evaluateSpreadAttr__( key, {\n memo: scope,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n __arguments__[ _key ] = _value\n\n // Only consume declared arguments' value\n if( !renderer?.argv.includes( _key ) ) return\n\n argvalues[ _key ] = {\n type: 'arg',\n value: _value\n }\n }\n })\n \n else {\n const evalue = value ? self.__evaluate__( value, scope ) : true\n __arguments__[ key ] = evalue\n\n // Only consume declared arguments' value\n if( !renderer.argv.includes( key ) ) return\n\n argvalues[ key ] = {\n type: 'arg',\n value: evalue\n }\n }\n })\n\n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( !renderer ) return\n \n if( SPREAD_VAR_PATTERN.test( key ) && self.__isReactive__( key, scope ) ){\n const\n deps = self.__extractExpressionDeps__( key, scope ),\n spreadPartialUpdate = ( memo: VariableSet, by?: string ) => {\n if( !renderer ) return\n\n const extracted: VariableSet = {}\n let changedDeps: string[] = []\n\n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n */\n if( attrs.map.afterSpreadAttrs.includes( _key ) ) return\n // Only update declared arguments' value\n if( !renderer?.argv.includes( _key ) ) return\n // Ignore unchanged values\n if( isEqual( _value, memo[ _key ]?.value ) ) return\n\n argvalues[ _key ] =\n extracted[ _key ] = {\n value: _value,\n type: 'arg'\n }\n\n // Update __arguments__ variable as well\n __arguments__[ _key ] = _value\n // Schedule only what changed values for updated.\n changedDeps.push( _key )\n },\n nullify: pattrs => {\n pattrs.forEach( _key => {\n extracted[ _key ] = {\n value: undefined,\n type: 'arg'\n }\n delete __arguments__[ _key ]\n } )\n\n changedDeps = pattrs\n }\n })\n \n if( changedDeps.length ){\n // Update arguments dep nodes\n renderer.argv.length\n && self.__updateArgumentsDepNodes__( elementPath, __arguments__ )\n\n // Update partial deps\n renderer.update( changedDeps, extracted, memo, boundaries )\n }\n }\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, scope, {\n nodetype: 'dynamic',\n nodepath: elementPath,\n deppath: `${elementPath}.${key}`,\n target: 'spread-attr',\n $fragment: null,\n boundaries,\n update: spreadPartialUpdate\n }) )\n }\n else if( ( renderer.argv.includes( key ) )\n && self.__isReactive__( value, scope ) ){\n const\n deps = self.__extractExpressionDeps__( value, scope ),\n partialUpdate = ( memo: VariableSet, by?: string ) => {\n if( !renderer ) return\n\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n\n const \n _value: Variable = value ? self.__evaluate__( value, memo ) : true,\n newvalue: Variable = { type: 'arg', value: _value }\n argvalues[ key ] = newvalue\n \n /**\n * Update arguments dep nodes\n */\n if( renderer.argv.length ){\n __arguments__[ key ] = _value\n self.__updateArgumentsDepNodes__( elementPath, __arguments__ )\n }\n \n renderer.update( [ key ], { [ key ]: newvalue }, memo, boundaries )\n }\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, scope, {\n nodetype: 'dynamic',\n nodepath: elementPath,\n deppath: `${elementPath}.${key}`,\n target: 'attr',\n $fragment: null,\n boundaries,\n update: partialUpdate\n }) )\n }\n } )\n\n return { argvalues, __arguments__ }\n }\n\n /**\n * Dynamic mesh rendering\n */\n if( isMesh( verb ) ){\n renderer = verb as MeshRenderer\n\n // Process argvalues and dependencies track\n const { argvalues, __arguments__ } = handleMeshRendererAttributes( contextScope )\n\n /**\n * Return all possible arguments passed to the\n * dynamic element in a single object variable \n * form that can be accessible in macro template \n * as `arguments`.\n */\n contextScope.__arguments__ = __arguments__\n\n const $log = renderer.mesh( argvalues )\n if( $log && $log.length )\n $fragment = $fragment.add( $log )\n }\n /**\n * Dynamic component, macro or element\n * rendering.\n */\n else if( typeof verb === 'string' ){\n /**\n * Process dynamic macro set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n if( self.__macros.has( verb ) )\n $fragment = $fragment.add( execMacro( $node, verb ) )\n\n /**\n * Process dynamic component tag set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n else if( self.lips.has( verb ) )\n $fragment = $fragment.add( execComponent( $node, { name: verb } ) )\n\n // Render standard HTML element\n else $fragment = $fragment.add( execElement( $node, verb ) )\n }\n\n // Track FGU dependency update on the dynamic tag\n if( self.__isReactive__( dtag as string, contextScope ) ){\n const\n updateDynamicElement = ( memo: VariableSet, by?: string ) => {\n /**\n * Re-evaluate dynamic tag expression before \n * re-rendering the element\n */\n const verb = self.__evaluate__( dtag, memo )\n let $newContent\n\n /**\n * IMPORTANT: Clean up previously rendered\n * content and its dependencies and nullify\n * the active mesh renderer if exist.\n */\n if( renderer ){\n renderer.cleanup( boundaries )\n renderer = null\n }\n else self.__emptyBoundaries__( boundaries, elementPath )\n \n /**\n * The mesh renderer changed\n */\n if( isMesh( verb ) ){\n renderer = verb as MeshRenderer\n\n // Reset attribute trackers\n const { argvalues, __arguments__ } = handleMeshRendererAttributes( memo )\n\n // Update arguments dep nodes\n renderer.argv.length\n && self.__updateArgumentsDepNodes__( elementPath, __arguments__ )\n \n // Rerender mesh content.\n $newContent = renderer.mesh( argvalues, memo )\n\n $newContent?.length\n && renderer.fill( $newContent, boundaries )\n }\n\n /**\n * Render dynamic template only when first \n * time renderer is `null` and the element's\n * dynamic update provide a component `template`\n * instead of a mesh `renderer`.\n */\n else if( isTemplate( verb ) ){\n $newContent = execComponent( $node, { template: verb }, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n \n /**\n * Process dynamic macro set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n else if( typeof verb === 'string' && self.__macros.has( verb ) ){\n $newContent = execMacro( $node, verb, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n\n /**\n * Process dynamic tag set by:\n * \n * Syntax `<{[dynamic-name]}/>`\n * processed to `<lips :dtag=\"[dynamic-name]\"></lips>`\n */\n else if( typeof verb === 'string' && self.lips.has( verb ) ){\n $newContent = execComponent( $node, { name: verb }, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n\n // Render standard HTML element\n else if( typeof verb === 'string' ){\n $newContent = execElement( $node, verb, memo )\n self.__fillBoundaries__( $newContent, boundaries )\n }\n },\n deps = self.__extractExpressionDeps__( dtag, contextScope )\n\n // Share general scope alongside the argvalues\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'dynamic',\n nodepath: elementPath,\n deppath: `${elementPath}.dtag`,\n target: 'dtag',\n $fragment: null,\n boundaries,\n update: updateDynamicElement\n }) )\n }\n\n $fragment = $fragment.add( boundaries.end )\n\n return $fragment\n }\n function execComponent( $node: Cash, dynamic?: DynamicTemplate<any>, scope?: VariableSet ): Cash {\n let\n template,\n name\n\n // Dynamic component template\n if( dynamic?.template ){\n template = dynamic.template\n name = generateComponentName('component', template.declaration?.syntax )\n }\n // Lookup component by its name\n else {\n name = dynamic?.name\n || $node.attr( GENERIC_TAGNAME_ATTR ) as string\n || $node.prop('tagName')?.toLowerCase() as string\n\n if( !name ) throw new Error('Invalid component')\n if( name === self.__name__ ) throw new Error('Render component within itself is forbidden')\n\n // Import template from lips registry\n template = self.lips.import<any>( name )\n }\n \n if( !template || !name )\n throw new Error(`<${name}> template not found`)\n\n const\n componentPath = generatePath('component', template.declaration?.syntax ),\n componentCacheId = `${componentPath}#${name}`,\n boundaries = self.__getBoundaries__( componentPath ),\n { argv, functions, attrs, events } = self.__getAttributes__( $node ),\n TRACKABLE_ATTRS: Record<string, string> = {},\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n SPREAD_KEYSTORES: Record<string, string[]> = {}\n\n /**\n * Parse assigned attributes to be injected into\n * the component as input.\n */\n let\n input: any = {},\n $fragment = $(boundaries.start),\n // Get cached component with same path if exists\n component = self.PCC.get( componentCacheId ),\n contextScope = scope || useScope()\n\n /**\n * Cast attributes to compnent inputs\n */\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => {\n if( key == 'key' ) return\n input[ key ] = value\n })\n \n functions && Object\n .entries( functions )\n .forEach( ([ key, expr ]) => {\n input[ key ] = self.__evaluateFunction__( expr, [], contextScope )\n \n template.declaration?.syntax\n ? TRACKABLE_ATTRS[ SYNCTAX_VAR_FLAG + FUNCTION_ATTR_FLAG + key ] = expr\n : TRACKABLE_ATTRS[ FUNCTION_ATTR_FLAG + key ] = expr\n })\n \n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( key == 'key' ) return\n \n if( SPREAD_VAR_PATTERN.test( key ) )\n self.__evaluateSpreadAttr__( key, {\n memo: contextScope,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => input[ _key ] = _value\n })\n\n else input[ key ] = value\n ? self.__evaluate__( value as string, contextScope )\n /**\n * IMPORTANT: An attribute without a value is\n * considered neutral but `true` of a value by\n * default.\n * \n * Eg. <counter initial=3 throttle/>\n * \n * the `throttle` attribute is hereby an input with a\n * value `true`.\n */\n : true\n\n template.declaration?.syntax\n ? TRACKABLE_ATTRS[ SYNCTAX_VAR_FLAG + key ] = value\n : TRACKABLE_ATTRS[ key ] = value\n })\n\n /**\n * Also inject component slotted body into inputs\n */\n const $nodeContents = $node.contents()\n if( $nodeContents.length ){\n // Pass in the regular body contents\n input = {\n ...input,\n ...self.__meshwire__({\n $node,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n meshPath: null,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration,\n }, TRACKABLE_ATTRS )\n }\n\n /**\n * Parse a syntactic declaration body contents\n */\n if( template.declaration ){\n /**\n * Extract node syntax component declaration tag nodes\n */\n if( template.declaration.tags ){\n let $lastNext: Cash\n\n Object\n .entries( template.declaration?.tags )\n .forEach( ([ tagname, { type, many, alts }]) => {\n switch( type ){\n case 'nexted': {\n let $next = $node.next( tagname ) // Default\n // Fish nexted only by defined `alts` (alternatives)\n if( !$next.length\n && Array.isArray( alts ) \n && $lastNext?.length\n && $lastNext.is( alts.join(',') ) )\n $next = $lastNext.next( tagname )\n \n // Nothing to do\n if( !$next.length ) return\n\n if( many ){\n input[ tagname ] = []\n\n let\n index = 0,\n reachedEndOfChain = false\n \n // Continue until we reach the end of the chain\n while( !reachedEndOfChain ){\n input[ tagname ].push( self.__meshwire__({\n $node: $next,\n meshPath: `${tagname}[${index}]`,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS ) )\n\n // Check if there's a next sibling\n if( !$next.next( tagname ).length ){\n reachedEndOfChain = true\n break\n }\n \n // Move to the next siblings\n $next = \n $lastNext = $next.next( tagname )\n index++\n }\n }\n else input[ tagname ] = self.__meshwire__({\n $node: $next,\n meshPath: tagname,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS )\n } break\n\n case 'child': {\n const $children = $node.children( tagname )\n if( many ){\n input[ tagname ] = []\n $children.each(function( index ){\n const \n $this = $(this),\n // Only allowed for child tags\n { argv } = self.__getAttributes__( $this )\n \n input[ tagname ].push( self.__meshwire__({ \n $node: $this,\n meshPath: `${tagname}[${index}]`,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS ) )\n })\n }\n else if( $node.children( tagname ).first().length ){\n const\n $this = $node.children( tagname ).first(),\n // Only allowed for child tags\n { argv } = self.__getAttributes__( $this )\n \n input[ tagname ] = self.__meshwire__({\n $node: $this,\n meshPath: tagname,\n fragmentPath: componentPath,\n fragmentBoundaries: boundaries,\n scope: contextScope,\n argv,\n xmlns,\n useAttributes: true,\n declaration: template.declaration\n }, TRACKABLE_ATTRS )\n }\n } break\n }\n } )\n }\n\n /**\n * Pass raw content nodes to component\n */\n else if( template.declaration.contents )\n input.__contents__ = $nodeContents\n }\n }\n \n /**\n * Use preserved child component is available.\n * \n * NOTE: Only employ for non-syntax components.\n */\n if( component ){\n component.setInput( deepClone( input ) )\n $fragment = $fragment.add( component.node )\n }\n // Render child component\n else {\n const { declaration, state, _static, handler, context, default: _default, stylesheet } = template\n \n component = new Component( name, _default || '', {\n state: deepClone( state ),\n input: deepClone( input ),\n context,\n _static: deepClone( _static ),\n handler,\n stylesheet,\n declaration\n }, {\n debug: self.debug,\n lips: self.lips,\n prepath: componentPath,\n /**\n * IMPORTANT: Store boundaries on component\n * object for edge case like: \n * \n * - When event-handler dependency update checks\n * whether the component is still in the DOM. \n * - \n */\n boundaries\n })\n\n $fragment = $fragment.add( component.node )\n\n /**\n * Only cache non-syntax components \n * for post-rendering reusability purpose.\n */\n !template.declaration?.syntax\n && self.PCC.set( componentCacheId, component )\n }\n\n // Close boundaries to the initial fragment when it's added to DOM\n $fragment = $fragment.add( boundaries.end )\n\n // Listen to this nexted component's events\n Object\n .entries( events )\n .forEach( ([ _event, instruction ]) => {\n self.__attachEvent__({\n nodepath: componentPath,\n element: component,\n _event,\n instruction,\n scope: contextScope,\n get __dependencies__(){ return dependencies }\n })\n })\n\n /**\n * Setup input dependency track\n */\n TRACKABLE_ATTRS && Object\n .entries( TRACKABLE_ATTRS )\n .forEach( ([ key, value ]) => {\n let \n isSyntax = false,\n isFunction = false\n\n if( key.startsWith( SYNCTAX_VAR_FLAG ) ){\n isSyntax = true\n key = key.replace( SYNCTAX_VAR_FLAG, '')\n }\n if( key.startsWith( FUNCTION_ATTR_FLAG ) ){\n isFunction = true\n key = key.replace( FUNCTION_ATTR_FLAG, '')\n }\n\n if( SPREAD_VAR_PATTERN.test( key ) ){\n if( self.__isReactive__( key, contextScope ) ){\n const\n spreadvalues = ( memo: VariableSet ) => {\n const extracted: Record<string, any> = {}\n\n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n */\n if( attrs.map.afterSpreadAttrs.includes( _key ) ) return\n \n extracted[ _key ] = _value\n },\n nullify: pattrs => pattrs.forEach( _key => extracted[ _key ] = undefined )\n })\n \n component?.subInput( extracted, memo )\n },\n deps = self.__extractExpressionDeps__( key, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'component',\n nodepath: componentPath,\n deppath: `${componentPath}.${key}`,\n target: 'spread-attr',\n $fragment: null,\n boundaries,\n update: spreadvalues,\n syntax: isSyntax\n }) )\n }\n }\n else if( self.__isReactive__( value, contextScope ) ){\n const\n evalue = ( memo: VariableSet ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n\n const _value = isFunction\n ? self.__evaluateFunction__( value, [], memo )\n : value ? self.__evaluate__( value, memo ) : true\n \n component?.subInput({ [ key ]: _value }, memo )\n },\n deps = self.__extractExpressionDeps__( value, contextScope )\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'component',\n nodepath: componentPath,\n deppath: `${componentPath}.${key}`,\n target: 'attr',\n $fragment: null,\n boundaries,\n update: evalue,\n syntax: isSyntax\n }) )\n }\n })\n\n // Track component creation\n self.metrics.inc('componentCount')\n\n return $fragment\n }\n function execMacro( $node: Cash, name?: string, scope?: VariableSet ): Cash {\n name = name || $node.attr( GENERIC_TAGNAME_ATTR ) as string\n if( !name )\n throw new Error('Invalid macro rendering call')\n \n const macro = self.__macros.get( name )\n if( !macro )\n throw new Error('Macro component not found')\n \n const\n macroPath = generatePath('macro'),\n boundaries = self.__getBoundaries__( macroPath ),\n { attrs } = self.__getAttributes__( $node ),\n TRACKABLE_ATTRS: Record<string, string> = {},\n contextScope = scope || useScope()\n \n /**\n * Parse assigned attributes to be injected into\n * the component as input.\n */\n const\n __arguments__: VariableArguments = {},\n argvalues: VariableSet = {}\n \n /**\n * Cast attributes to compnent inputs\n */\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => {\n __arguments__[ key ] = value\n argvalues[ key ] = { value, type: 'arg' }\n })\n\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n const SPREAD_KEYSTORES: Record<string, string[]> = {}\n\n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( SPREAD_VAR_PATTERN.test( key ) ){\n self.__evaluateSpreadAttr__( key, {\n memo: contextScope,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n __arguments__[ _key ] = _value\n\n if( macro.argv.includes( _key ) )\n argvalues[ _key ] = {\n value: _value,\n type: 'arg'\n }\n }\n })\n \n /**\n * Always track spread operators for their \n * content might be reactive\n */\n TRACKABLE_ATTRS[ key ] = value\n }\n\n else {\n const val = value ? self.__evaluate__( value as string, contextScope ) : true\n __arguments__[ key ] = val\n\n if( macro.argv.includes( key ) ){\n argvalues[ key ] = {\n value: val,\n type: 'arg'\n }\n \n TRACKABLE_ATTRS[ key ] = value\n }\n }\n \n /**\n * VERY IMPORTANT: Cancel out invalid argv variables \n * by `false`. It help assigning `undefined` values\n * to element's attribute that are considered `true`\n * as set.\n * \n * Eg. <div active=undefined></div> is same as <div active></div>\n * which is considered as <div active=true></div>\n * \n * REVIEW well before or during maintenance\n */\n macro.argv.forEach( each => {\n if( argvalues[ each ] !== undefined ) return\n\n argvalues[ each ] = {\n value: false, // REVIEW the `false` value assignment later.\n type: 'arg'\n }\n })\n })\n\n /**\n * Return all possible arguments passed to the macro\n * in a single object variable form that can be \n * accessible in macro template as `argvalues`.\n */\n argvalues.__arguments__ = __arguments__\n\n /**\n * - $fragment\n * - macroPath\n * - template.declaration?\n */\n let $fragment = $(boundaries.start)\n const\n setup: MeshWireSetup = {\n $node: macro.$node,\n meshPath: null,\n fragmentPath: macroPath,\n fragmentBoundaries: boundaries,\n argv: macro.argv,\n scope: contextScope,\n xmlns,\n useAttributes: true\n },\n macrowire = self.__meshwire__( setup, TRACKABLE_ATTRS ),\n $log = macrowire.renderer.mesh( argvalues, contextScope )\n\n $fragment = $fragment.add( $log )\n \n /**\n * Setup input dependency track\n */\n TRACKABLE_ATTRS && Object\n .entries( TRACKABLE_ATTRS )\n .forEach( ([ key, value ]) => {\n let isSyntax = false\n if( new RegExp(`^${SYNCTAX_VAR_FLAG}`).test( key ) ){\n isSyntax = true\n key = key.replace( SYNCTAX_VAR_FLAG, '' )\n }\n\n if( SPREAD_VAR_PATTERN.test( key ) ){\n if( !self.__isReactive__( key, contextScope ) ) return\n\n const\n deps = self.__extractExpressionDeps__( key, contextScope ),\n spreadvalues = ( memo: VariableSet ) => {\n const extracted: VariableSet = {}\n let changedDeps: string[] = []\n\n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORES[ key ] },\n set keystore( __ ){\n if( !SPREAD_KEYSTORES[ key ] )\n SPREAD_KEYSTORES[ key ] = []\n \n SPREAD_KEYSTORES[ key ] = __ \n },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n */\n if( attrs.map.afterSpreadAttrs.includes( _key ) ) return\n // Ignore unchanged values\n if( isEqual( _value, memo[ _key ]?.value ) ) return\n\n extracted[ _key ] = {\n value: _value,\n type: 'arg'\n }\n\n // Update __arguments__ variable as well\n __arguments__[ _key ] = _value\n // Schedule only what changed values for updated.\n changedDeps.push( _key )\n },\n nullify: pattrs => {\n pattrs.forEach( _key => {\n extracted[ _key ] = {\n value: undefined,\n type: 'arg'\n }\n delete __arguments__[ _key ]\n } )\n\n changedDeps = pattrs\n }\n })\n \n if( changedDeps.length ){\n // Update arguments dep nodes\n self.__updateArgumentsDepNodes__( macroPath, __arguments__ )\n // Update partial deps\n macrowire.renderer.update( changedDeps, extracted, memo )\n }\n\n return sterilize({ memo: { ...memo, ...extracted } })\n }\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, { ...contextScope, ...argvalues }, {\n nodetype: 'macro',\n nodepath: macroPath,\n deppath: `${macroPath}.${key}`,\n target: 'spread-attr',\n $fragment: null,\n boundaries,\n update: spreadvalues,\n syntax: isSyntax\n }) )\n }\n else if( self.__isReactive__( value, contextScope ) ){\n const\n deps = self.__extractExpressionDeps__( value, contextScope ),\n evalue = ( memo: VariableSet ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key=value that is assigned\n * after this attribute.\n */\n if( attrs.map.beforeSpreadAttrs.includes( key ) ) return\n \n const newvalue = value ? self.__evaluate__( value as string, memo ) : true\n \n /**\n * Update arguments dep nodes\n */\n __arguments__[ key ] = newvalue\n self.__updateArgumentsDepNodes__( macroPath, __arguments__ )\n\n // Update the whole partial\n macrowire.renderer.update( [ key ], { [ key ]: { value: newvalue, type: 'arg' } }, memo )\n\n return sterilize({ memo })\n }\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, { ...contextScope, ...argvalues }, {\n nodetype: 'macro',\n nodepath: macroPath,\n deppath: `${macroPath}.${key}`,\n target: 'attr',\n $fragment: null,\n boundaries,\n update: evalue,\n syntax: isSyntax\n }) )\n }\n })\n\n $fragment = $fragment.add( boundaries.end )\n\n /**\n * METRICS: Tracking total elements rendered\n */\n self.metrics.inc('elementCount')\n \n return $fragment\n }\n function execElement( $node: Cash, tagname?: string, scope?: VariableSet ): Cash {\n if( !$node.length || !$node.prop('tagName') && !tagname )\n return $node\n\n tagname = tagname || $node.prop('tagName').toLowerCase() as string\n\n /**\n * Special treatement for SVG xml tags\n * because of their delicate namespace\n * definition.\n * \n * Note: `xmlns` to indicate to and xmlns \n * parent tag's nexted contents, like\n * \n * - rect\n * - path\n * - circle\n * - etc\n */\n const\n isXMLNS = $node.is('svg') || xmlns,\n $fragment = isXMLNS\n ? $(document.createElementNS('http://www.w3.org/2000/svg', tagname ))\n // Standard HTML element\n : $(`<${tagname}/>`),\n $contents = $node.contents(),\n elementPath = generatePath('element'),\n contextScope = scope || useScope()\n \n // Process contents recursively if they exist\n $contents.length\n && $fragment.append( self.__withPath__( elementPath, () => self.render( elementPath + NODE_PREFIX, $contents, contextScope, dependencies, isXMLNS ).$log ) )\n\n const { attrs, events } = self.__getAttributes__( $node )\n\n /**\n * Literal value attributes\n */\n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ attr, value ]) => {\n if( attr === I18N_ATTR_FLAG ) return\n\n /**\n * Translate standard visual attributes like:\n * \n * - placeholder text\n * - title\n */\n const canTranslate = $node.is(`[${I18N_ATTR_FLAG}]`) && ['title', 'placeholder'].includes( attr )\n \n $fragment.attr( attr, canTranslate ? self.lips.i18n.translate( value ).text : value )\n\n const updateAttr = ( memo: VariableSet ) => {\n $fragment.attr( attr, canTranslate ? self.lips.i18n.translate( value ).text : value )\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttr\n })\n }\n \n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttr\n })\n })\n\n const assignAttrs = ( list: SyntaxAttributes['expressions'], track: boolean = false ) => {\n list && Object\n .entries( list )\n .forEach( ([ attr, value ]) => {\n switch( attr ){\n // Inject inner html into the element\n case '@html': {\n const updateHTML = ( memo: VariableSet ) => {\n $fragment.html( self.__evaluate__( value as string, memo ) )\n }\n\n updateHTML( contextScope )\n\n if( track && self.__isReactive__( value, contextScope ) ){\n const deps = self.__extractExpressionDeps__( value, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateHTML\n }) )\n }\n } break\n\n // Inject text into the element\n case '@text': {\n const \n canTranslate = $node.is(`[${I18N_ATTR_FLAG}]`),\n updateText = ( memo: VariableSet ) => {\n $fragment.text( self.__evaluate__( value as string, memo, { translate: canTranslate } ) )\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateText\n })\n }\n\n updateText( contextScope )\n \n if( track && self.__isReactive__( value, contextScope ) ){\n const deps = self.__extractExpressionDeps__( value, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateText\n }) )\n }\n\n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: updateText\n })\n } break\n\n // Inject formated text into the element\n case '@format': {\n const [ reference, params ] = value.split(',').map( ( part: string )=> part.trim() )\n if( !reference )\n throw new Error('Invalid @format reference')\n\n if( !params )\n throw new Error('Invalid @format parameters')\n\n const applyFormat = ( memo: VariableSet ) => {\n /**\n * IMPORTANT: Parse parameters if provided\n * with `!` flag to signal interpolation\n * exception during expression evaluation.\n */\n const _params = self.__evaluate__(`!${params.trim()}`, memo )\n if( typeof _params !== 'object' )\n throw new Error('Invalid @format parameters')\n\n // Get the translation\n const text = self.lips.i18n.format( reference, _params )\n text !== undefined && $fragment.text( text )\n \n // Track for i18n translation updates\n self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: applyFormat\n })\n }\n\n applyFormat( contextScope )\n \n // Track reactive dependencies in parameters\n self\n .__extractExpressionDeps__( params, contextScope )\n .forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'meta-attr',\n $fragment,\n update: applyFormat\n }))\n } break\n\n // Convert object style attribute to string\n case 'style': {\n if( track && self.__isReactive__( value, contextScope ) ){\n const updateStyle = ( memo: VariableSet ) => {\n const style = self.__evaluate__( value as string, memo )\n \n // Defined in object format\n if( typeof style === 'object' ){\n let str = ''\n\n Object\n .entries( style )\n .forEach( ([ k, v ]) => str += `${k}:${v};` )\n \n str.length && $fragment.attr('style', str )\n }\n // Defined in string format\n else $fragment.attr('style', style )\n }\n\n updateStyle( contextScope )\n \n const deps = self.__extractExpressionDeps__( value, contextScope )\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateStyle\n }) )\n }\n else $fragment.attr('style', value )\n } break\n\n // Inject the evaluation result of any other attributes\n default: {\n /**\n * Translate standard visual attributes like:\n * \n * - placeholder text\n * - title\n */\n const \n canTranslate = $node.is(`[${I18N_ATTR_FLAG}]`) && ['title', 'placeholder'].includes( attr ),\n updateAttrs = ( memo: VariableSet ) => {\n const res = value && self.__isReactive__( value, contextScope )\n ? self.__evaluate__( value as string, memo, { translate: canTranslate } )\n /**\n * IMPORTANT: An attribute without a value is\n * considered neutral but `true` of a value by\n * default.\n * \n * Eg. <counter initial=3 throttle/>\n * \n * the `throttle` attribute is hereby an input with a\n * value `true`.\n */\n : value !== undefined ? value : true\n\n /**\n * (?) evaluation return signal to unset the attribute.\n * \n * Very useful case where the attribute don't necessarily\n * have values by default.\n */\n if( res === undefined || res === false )\n $fragment.removeAttr( attr )\n \n else {\n $fragment.attr( attr, res )\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttrs\n })\n }\n }\n\n updateAttrs( contextScope )\n \n if( track && self.__isReactive__( value, contextScope ) ){\n const deps = self.__extractExpressionDeps__( value, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttrs\n }) )\n }\n \n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${attr}`,\n target: 'attr',\n $fragment,\n update: updateAttrs\n })\n }\n }\n })\n }\n\n // Check, process & track expression attributes\n attrs.expressions && Object\n .keys( attrs.expressions )\n .forEach( key => {\n if( !SPREAD_VAR_PATTERN.test( key ) ) return\n\n /**\n * Temporary store spread operators\n * content keys during evaluation.\n */\n let SPREAD_KEYSTORE: string[] = []\n const updateSpreadAttrs = ( memo: VariableSet, by?: string, initialize = false ) => {\n const extracted: Record<string, any> = {}\n \n self.__evaluateSpreadAttr__( key, {\n memo,\n get keystore(){ return SPREAD_KEYSTORE },\n set keystore( __ ){ SPREAD_KEYSTORE = __ },\n each: ( _key, _value ) => {\n /**\n * Attributes positioning: Shun to overriding\n * spread attributes key that is explicitly\n * defined after spread key. \n * \n * NOTE: Checks only occured during update\n */\n if( !initialize && attrs.map.afterSpreadAttrs.includes( _key ) ) return\n\n extracted[ _key ] = _value\n },\n nullify: pattrs => pattrs.forEach( attr => $fragment.removeAttr( attr ) )\n })\n\n Object.keys( extracted ).length && assignAttrs( extracted )\n }\n\n delete attrs.expressions[ key ]\n updateSpreadAttrs( contextScope, '', true )\n\n if( key && self.__isReactive__( key, contextScope ) ){\n const deps = self.__extractExpressionDeps__( key, contextScope )\n\n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'element',\n nodepath: elementPath,\n deppath: `${elementPath}.${key}`,\n target: 'spread-attr',\n $fragment,\n update: updateSpreadAttrs\n }) )\n }\n })\n\n assignAttrs( attrs.expressions, true )\n \n // Record attachable events to the element\n events && Object\n .entries( events )\n .forEach( ([ _event, value ]) => {\n attachableEvents.push({\n nodepath: elementPath,\n element: $fragment,\n _event,\n instruction: value as string,\n scope: contextScope,\n get __dependencies__(){ return dependencies }\n })\n })\n\n // Track DOM insertion\n self.metrics.inc('elementCount')\n self.metrics.inc('domInsertsCount')\n\n return $fragment\n }\n function execText( $node: Cash ): Cash {\n const\n content = $node.text(),\n contextScope = useScope(),\n textPath = generatePath('element'),\n canTranslate = $node.parent().is(`[${I18N_ATTR_FLAG}]`),\n // Initial rendering\n $fragment = $(document.createTextNode( self.__interpolate__( content, contextScope, canTranslate ) ))\n\n // Update rendering handler\n const updateTextContent = ( memo: VariableSet ) => {\n const text = self.__interpolate__( content, memo, canTranslate )\n if( !$fragment[0] ) return\n $fragment[0].textContent = text\n\n // Reset track for i18n translation if needed\n canTranslate && self.__trackTranslationDep__( memo, {\n nodetype: 'text',\n nodepath: textPath,\n target: 'value',\n $fragment,\n update: updateTextContent\n })\n }\n\n // Track for dependency update\n if( content && self.__isReactive__( content, contextScope ) ){\n const deps = self.__extractTextDeps__( content, contextScope )\n \n deps.forEach( dep => self.__trackDep__( dependencies, dep, contextScope, {\n nodetype: 'text',\n nodepath: textPath,\n deppath: `${textPath}.${dep}`,\n target: 'value',\n $fragment,\n update: updateTextContent\n }) )\n }\n\n // Track for i18n translation\n canTranslate && self.__trackTranslationDep__( contextScope, {\n nodetype: 'text',\n nodepath: textPath,\n target: 'value',\n $fragment,\n update: updateTextContent\n })\n\n // Track DOM insertion\n self.metrics.inc('elementCount')\n self.metrics.inc('domInsertsCount')\n\n return $fragment\n }\n\n function dynamicRoute( $node: Cash ){\n if( !$node.attr( DYNAMIC_TAGNAME_ATTR ) || $node.prop('tagName') !== 'LIPS' )\n throw new Error('Invalid dynamic tag name')\n \n const\n dtag = $node.attr( DYNAMIC_TAGNAME_ATTR ) as string,\n result = self.__evaluate__( dtag, scope )\n\n /**\n * Process dynamic component rendering tag set by:\n * \n * Syntax `<{[template-object]}/>`\n * processed to `<lips :dtag=\"[template-object]\"></lips>`\n */\n if( isTemplate( result ) )\n return execComponent( $node, { template: result } )\n\n /**\n * Process dynamic content rendering tag set by:\n * \n * Syntax `<{input.render}/>`\n * processed to `<lips :dtag=input.render></lips>`\n * \n * or\n * \n * Syntax `<{standard-tagname}/>`\n * processed to `<lips :dtag=\"[standard-tagname]\"></lips>`\n */\n else return execDynamicElement( $node, dtag, result )\n }\n function parse( $node: Cash ){\n if( $node.get(0)?.nodeType === Node.COMMENT_NODE )\n return $node\n\n if( $node.get(0)?.nodeType === Node.TEXT_NODE )\n return execText( $node )\n\n // Lips in-build scope variables syntax components\n if( $node.is('let') ) return execLet( $node )\n else if( $node.is('const') ) return execConst( $node )\n\n /**\n * Lips's dynamic tags like:\n * \n * - component\n * - dynamic-tag\n */\n else if( $node.is('lips') && $node.attr( DYNAMIC_TAGNAME_ATTR ) )\n return dynamicRoute( $node )\n \n /**\n * Convenient `console.log` wired into \n * template rendering\n */\n else if( $node.is('log') ) return execLog( $node )\n \n /**\n * Identify and render macro components\n * \n * Note: Always check `tagname` in registered \n * macros list before in the registered components\n * list.\n */\n else if( self.__macros.has( $node.attr( GENERIC_TAGNAME_ATTR ) as string ) )\n return execMacro( $node )\n \n /**\n * Lips in-build syntax component\n * or identify and render custom components\n */\n else if( $node.is( NATIVE_SYNTAX_TAGS.join(',') ) || self.lips.has( $node.attr( GENERIC_TAGNAME_ATTR ) as string ) )\n return execComponent( $node )\n \n /**\n * Ignore <else-if> and <else> tags as node\n * for their should be already process by <if>\n */\n else if( $node.is('else-if, else') ) return\n \n // Any other note type\n return execElement( $node )\n }\n\n try {\n this.__renderDepth__++\n\n /**\n * Create raw DOM root\n * \n * IMPORTANT:\n * Create a proper DOM tree with sibling \n * relationships when template contains\n * multiple root elements.\n */\n $nodes = !$nodes && $(this.__template__).length > 1\n ? $('<template>').html( this.__template__ ).contents()\n : $nodes || $(this.__template__)\n \n $nodes.each( function(){\n const $node = parse( $(this) )\n if( $node ) _$ = _$.add( $node )\n })\n\n /**\n * Attach extracted events listeners after\n * component get rendered.\n * \n * This to avoid loosing binding to attached\n * DOM element's events\n */\n attachableEvents.forEach( this.__attachEvent__.bind(this) )\n\n /**\n * METRICS: Tracking total occurence of recursive rendering\n */\n self.metrics.inc('renderCount')\n }\n catch( error ){\n console.error('Rendering Failed --', error ) \n self.metrics.trackError( error as Error )\n }\n finally {\n this.__renderDepth__--\n \n // End metrics measuring\n this.metrics.endRender()\n this.metrics.trackMemory()\n \n // Clear path when main render completes\n if( this.__renderDepth__ === 0 ){\n this.__inpath__ = ''\n this.__inpathCounter__ = 0\n }\n }\n \n return {\n $log: _$,\n dependencies,\n events: attachableEvents\n }\n }\n destroy(){\n /**\n * Dispose signal effect dependency of this\n * component.\n */\n this.ICE.dispose()\n /**\n * Clean up stylesheets\n */\n this.stylesheet?.clear()\n /**\n * Clean up metrics resources\n */\n this.metrics.dispose()\n /**\n * Unregister this component from IUC\n */\n this.lips.IUC.unregister( this.__path__ )\n /**\n * Stop watcher when component's element get \n * detached from the DOM\n */\n this.lips.watcher.unwatch( this as any )\n\n /**\n * Detached all events\n */\n this.VER.forEach( this.__detachEvent__.bind(this) )\n this.VER = []\n\n /**\n * Destroy nexted components as well\n */\n for( const each in this.PCC ){\n const component = this.PCC.get( each )\n\n component?.destroy()\n component?.delete( each )\n }\n\n /**\n * Cleanup\n */\n this.$?.remove()\n this.PCC?.clear()\n this.FGUD?.clear()\n this.FGUDMemory?.clear()\n // this.state.reset()\n this.__macros.clear()\n this.__i18nDeps.clear()\n\n // @ts-ignore\n this.__previous = null\n // @ts-ignore\n this.state = null\n // @ts-ignore\n this.input = null\n // @ts-ignore\n this.context = null\n\n // Clear DOM references\n if( this.$ ){\n this.$.each( ( _, el ) => {\n $(el).off() // Clear event handlers\n // $(el).removeData() // Remove custom data\n })\n \n // Clear the reference\n this.$ = null\n }\n\n // Trigger on-destroy lifecycle events\n typeof this.onDestroy === 'function'\n && this.onDestroy.bind(this)()\n this.emit('component:destroy')\n }\n \n private __meshwire__( setup: MeshWireSetup, TRACKABLE_ATTRS: Record<string, string> ){\n const\n self = this,\n {\n $node,\n meshPath,\n fragmentPath,\n fragmentBoundaries,\n argv,\n xmlns,\n declaration,\n useAttributes\n } = setup\n\n let PARTIAL_CONTENT: Cash | undefined\n const\n PARTIAL_PATHS: Map<string, Set<string>> = new Map(),\n MESH_COMPOSITE_PATH = fragmentPath + PARTIAL_ROOT_PREFIX,\n mesh = ( argvalues?: VariableSet, freshscope?: VariableSet, suffix?: string ) => {\n PARTIAL_CONTENT = $node.contents()\n if( !PARTIAL_CONTENT?.length ) return null\n\n freshscope = freshscope || setup.scope\n \n // Render the partial\n const\n partialPath = MESH_COMPOSITE_PATH + (suffix || ''),\n { $log, dependencies, events } = self.__withPath__( partialPath, () => {\n return self.render( partialPath, PARTIAL_CONTENT, { ...freshscope, ...argvalues }, undefined, xmlns )\n })\n \n /**\n * Index the path by slot for fast lookups\n * \n * NOTE: (*) is default slot for standard\n * mesh partial.\n */\n const pathSlot = suffix || DEFAULT_PARTIAL_PATH_SLOT\n // Create new slot\n !PARTIAL_PATHS.has( pathSlot ) && PARTIAL_PATHS.set( pathSlot, new Set() )\n PARTIAL_PATHS.get( pathSlot )?.add( partialPath )\n \n /**\n * Share partial FGU dependenies with main component thread\n * for parallel updates (main & partial) on the meshed node.\n * \n * 1. From main FGU dependency track\n * 2. From mesh rendering track\n */\n dependencies?.forEach( ( dependents, dep ) => {\n !self.FGUD?.has( dep ) && self.FGUD.set( dep, new Map() )\n // Add partial dependency\n dependents.forEach( ( dependent, path ) => {\n if( dependent.garbage ) return\n\n dependent.partial?.length\n ? dependent.partial.push( partialPath )\n : dependent.partial = [ partialPath ]\n \n self.FGUD.get( dep )?.set( path, dependent )\n } )\n } )\n \n self.metrics.inc('partialCount')\n return $log\n },\n update = ( deps: string[], argvalues: VariableSet, freshscope: VariableSet, boundaries: FragmentBoundaries, suffix?: string ) => {\n if( !PARTIAL_PATHS.get( suffix || DEFAULT_PARTIAL_PATH_SLOT )?.size ) return\n \n freshscope = freshscope || setup.scope\n boundaries = boundaries || fragmentBoundaries\n \n // Start measuring\n self.metrics.startRender()\n \n /**\n * IMPORTANT: Target item paths slot by \n * context to avoid unecessary dependency\n * checks or updates.\n */\n const targetedPaths = Array.from( PARTIAL_PATHS.get( suffix || DEFAULT_PARTIAL_PATH_SLOT ) || [] )\n // Execute partial mesh update\n deps.forEach( dep => {\n const dependents = self.FGUD.get( dep )\n if( !dependents ) return\n \n dependents.forEach( dependent => {\n // Process only dependents of this partial and its subpartials\n const partialPath = targetedPaths.find( p => {\n return dependent.partial?.find( pp => p == pp || self.__hasSamePathParent__( pp, p ) )\n })\n if( !dependent.partial || !partialPath ) return\n \n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n \n if( dependent.garbage || boundaries?.start && !document.contains( boundaries.start ) ){\n // console.warn(`${partialPath} -- partial boundaries missing in the DOM`)\n dependents.delete( deppath )\n self.__unbindMemo__( dependent )\n return\n }\n\n if( !memoslot ){\n console.warn(`unexpected occurence: <${deppath}> has no memo`)\n return\n }\n \n if( memoslot.memo?.[ dep ]\n && argvalues?.[ dep ]\n && !isEqual( memoslot.memo[ dep ], argvalues[ dep ] ) )\n memoslot.memo = { ...freshscope, ...memoslot.memo, ...argvalues }\n\n self.UQS.queue({ dep, deppath, priority: dependent.priority })\n self.metrics.inc('dependencyUpdateCount')\n } )\n\n /**\n * Clean up if no more dependents\n */\n !dependents.size && self.FGUD.delete( dep )\n })\n \n // Track update\n self.metrics.inc('partialUpdateCount')\n // Finish measuring\n self.metrics.endRender()\n },\n cleanup = ( boundaries?: FragmentBoundaries, suffix?: string | boolean ) => {\n /**\n * Clear all path attached to this suffix \n * or default slot.\n */\n PARTIAL_PATHS.delete( typeof suffix === 'string' && suffix || DEFAULT_PARTIAL_PATH_SLOT )\n\n /**\n * Clean rendered mesh content\n */\n boundaries = boundaries || fragmentBoundaries\n self.__emptyBoundaries__( boundaries, MESH_COMPOSITE_PATH +(suffix || '') )\n\n /**\n * Partial Mesh self-removal: Clear mesh \n * boundaries as well.\n */\n if( suffix ){\n boundaries.start.remove()\n boundaries.end.remove()\n }\n },\n wire: MeshTemplate = {\n renderer: {\n path: meshPath,\n argv,\n mesh,\n update,\n cleanup,\n\n fill( $newcontent, boundaries ){\n self.__fillBoundaries__( $newcontent, boundaries || fragmentBoundaries )\n },\n demarcate( $newcontent, suffix ){\n const boundaries = self.__getBoundaries__( MESH_COMPOSITE_PATH + (suffix || '') )\n\n // Attach boundaries\n let $partial = $(boundaries.start)\n $partial = $partial.add( $newcontent )\n $partial = $partial.add( boundaries.end )\n \n return { $partial, boundaries }\n }\n }\n }\n\n /**\n * Allow attributes consumption as input/props.\n */\n if( useAttributes && meshPath ){\n const { attrs } = self.__getAttributes__( $node )\n \n attrs.literals && Object\n .entries( attrs.literals )\n .forEach( ([ key, value ]) => wire[ key ] = value )\n \n attrs.expressions && Object\n .entries( attrs.expressions )\n .forEach( ([ key, value ]) => {\n if( SPREAD_VAR_PATTERN.test( key ) ){\n\n let SPREAD_KEYSTORE: string[] = []\n self.__evaluateSpreadAttr__( key, {\n memo: setup.scope,\n get keystore(){ return SPREAD_KEYSTORE },\n set keystore( __ ){ SPREAD_KEYSTORE = __ },\n each: ( _key, _value ) => wire[ _key ] = _value\n })\n\n TRACKABLE_ATTRS[`${declaration?.syntax ? SYNCTAX_VAR_FLAG : ''}${meshPath}.${key}`] = value\n }\n else {\n wire[ key ] = value ? self.__evaluate__( value as string, setup.scope ) : true\n // Record attribute to be tracked as FGU dependency\n TRACKABLE_ATTRS[`${declaration?.syntax ? SYNCTAX_VAR_FLAG : ''}${meshPath}.${key}`] = value\n }\n })\n }\n\n return wire\n }\n private __getBoundaries__( path: string ): FragmentBoundaries {\n // Track DOM operations for boundary creation\n this.metrics.inc('domOperations')\n this.metrics.inc('domInsertsCount')\n\n return {\n start: document.createComment(`s:${path}`),\n end: document.createComment(`e:${path}`)\n }\n }\n private __emptyBoundaries__( boundaries: FragmentBoundaries, parentPath: string ){\n /**\n * Clean tracking mesh content dependencies\n */\n this.FGUD.forEach( ( dependents, dep ) => {\n /**\n * Find and remove dependents that match \n * the branch pattern.\n */\n dependents.forEach( ( dependent, path ) => {\n // console.debug( path, MESH_COMPOSITE_PATH +(suffix || ''), self.__hasSamePathParent__( path, MESH_COMPOSITE_PATH ) )\n if( !this.__hasSamePathParent__( path, parentPath ) ) return\n \n // Unbind memo for this dependent\n this.__unbindMemo__( dependent )\n // Clear garbage dependent from the dependencies map\n dependent.garbage = true\n })\n\n // Cleanup empty dependency maps\n !dependents.size && this.FGUD.delete( dep )\n })\n \n const\n nodesToRemove = [] // Nodes between boundaries\n let currentNode = boundaries.start.nextSibling\n \n while( currentNode && currentNode !== boundaries.end ){\n nodesToRemove.push( currentNode )\n currentNode = currentNode.nextSibling\n }\n \n // Remove old content and insert new\n $(nodesToRemove).remove()\n }\n private __fillBoundaries__( $content: Cash, boundaries: FragmentBoundaries ){\n // Check if boundaries are in DOM\n if( !document.contains( boundaries.start ) || !document.contains( boundaries.end ) ){\n console.warn('Dynamic element boundaries not found')\n return\n }\n\n // this.__emptyBoundaries__( boundaries )\n // Render new content\n $content.length && $(boundaries.start).after( $content )\n }\n private __getAttributes__( $node: Cash ){\n const \n extracted = ($node as any).attrs(),\n events: Record<string, any> = {},\n functions: Record<string, any> = {},\n attrs: SyntaxAttributes = {\n literals: {},\n expressions: {},\n map: {\n explicitAttrs: [],\n spreadAttrs: [],\n beforeSpreadAttrs: [],\n afterSpreadAttrs: [],\n metaAttrs: []\n }\n },\n /**\n * Check extracted spread attribute\n * to initiate attribute positioning\n * mapping.\n */\n containSpreads = Object.keys( extracted ).find( key => SPREAD_VAR_PATTERN.test( key ) )\n\n let\n argv: string[] = [],\n spreadAttrPoint = false\n \n // Process attributes including spread operator\n extracted && Object\n .entries( extracted )\n .forEach( ([ key, value ]) => {\n if( [ GENERIC_TAGNAME_ATTR, DYNAMIC_TAGNAME_ATTR ].includes( key ) ) return\n \n if( key.startsWith(':')\n || key.startsWith( FUNCTION_ATTR_FLAG )\n || key.startsWith( EVENT_LISTENER_FLAG )\n || SPREAD_VAR_PATTERN.test( key )\n || ARGUMENT_VAR_PATTERN.test( key ) ){\n if( ARGUMENT_VAR_PATTERN.test( key ) ){\n const [ _, vars ] = key.match( ARGUMENT_VAR_PATTERN ) || []\n argv = vars.split(',')\n }\n else if( key.startsWith( EVENT_LISTENER_FLAG ) )\n events[ key.replace( EVENT_LISTENER_FLAG, '') ] = value\n\n else if( key.startsWith( FUNCTION_ATTR_FLAG ) )\n functions[ key.replace( FUNCTION_ATTR_FLAG, '') ] = value\n \n else {\n if( key.startsWith(':') )\n key = key.slice( 1, key.length )\n \n /**\n * Record attributes map the\n * extracted attribute contain\n * a spread attr.\n */\n if( containSpreads ){\n if( SPREAD_VAR_PATTERN.test( key ) ){\n attrs.map.spreadAttrs.push( key )\n spreadAttrPoint = true\n }\n else {\n attrs.map.explicitAttrs.push( key )\n !spreadAttrPoint\n ? attrs.map.beforeSpreadAttrs.push( key )\n : attrs.map.afterSpreadAttrs.push( key )\n }\n }\n\n attrs.expressions[ key ] = value || ''\n }\n }\n // Literal value attribute\n else {\n attrs.literals[ key ] = value\n\n /**\n * Record attributes map the\n * extracted attribute contain\n * a spread attr.\n */\n if( containSpreads ){\n attrs.map.explicitAttrs.push( key )\n !spreadAttrPoint\n ? attrs.map.beforeSpreadAttrs.push( key )\n : attrs.map.afterSpreadAttrs.push( key )\n }\n }\n })\n\n return { argv, events, functions, attrs }\n }\n private __withPath__<T>( path: string, fn: () => T ): T {\n const prevPath = this.__inpath__\n this.__inpath__ = path\n\n const result = fn()\n this.__inpath__ = prevPath\n\n return result\n }\n private __getPathParent__( path: string ){\n const __ = path.split('/')\n if( __.length > 1 ) __.pop()\n\n return __.join('/')\n }\n private __hasSamePathParent__( path: string, parentPath: string ){\n return (path.startsWith( parentPath ) && !path.replace( parentPath, '' ).startsWith('.'))\n /**\n * When parent is a mesh partial root element\n */\n || path.startsWith(`${parentPath + PARTIAL_ROOT_PREFIX}`)\n }\n\n private __evaluate__( expr: string, scope?: VariableSet, options?: { translate?: boolean, mute?: boolean }){\n expr = typeof expr === 'string' ? expr.trim() : expr\n try {\n const exec = ( each: string ) => {\n /**\n * Only use none-proxy state for eval\n * to avoid state mutation expression\n * during template rendering.\n */\n const\n _state = this.state.toJSON(),\n /**\n * Safe wrapper function to returns \n * undefined on errors\n */\n safeEval = ( fn: Function, ...args: any[] ) => {\n try { return fn( ...args ) }\n catch( error ){\n !options?.mute && console.error('Eval error --', error )\n return undefined\n }\n }\n\n let expression = `return ${each};`\n \n if( scope ){\n let\n __scope__: Record<string, any> = {},\n __arguments__: Record<string, any> | undefined\n\n for( const key in scope ){\n if( key === '__arguments__' ) continue\n __scope__[ key ] = scope[ key ].value\n }\n\n /**\n * IMPORTANT: `__arguments__` is use to inject\n * all an element's context variables as `arguments`.\n */\n if( typeof scope.__arguments__ === 'object' )\n __arguments__ = scope.__arguments__\n \n /**\n * Wrap expression to inject scope\n * variable.\n */\n expression = `with( scope ){ ${expression} }`\n\n const fn = new Function('self', 'input', 'state', 'static', 'context', 'scope', 'arguments', expression )\n return safeEval( fn, this, this.input, _state, this.static, this.context, __scope__ || {}, __arguments__ )\n }\n else {\n const fn = new Function('self', 'input', 'state', 'static', 'context', expression )\n return safeEval( fn, this, this.input, _state, this.static, this.context )\n }\n }\n\n // Check for interpolation or object expression\n if( /{\\s*([^{}]+)\\s*}/.test( expr ) ){\n /**\n * IMPORTANT: Object exception flag.\n * \n * Case where closures supposedly to define\n * interpolation are instead flagged with `!` \n * sign to be processed as a javascript object.\n */\n if( expr.startsWith('!{') && expr.endsWith('}') )\n return exec( expr.slice(1) )\n\n // Interpolation\n return expr.replace( INTERPOLATE_PATTERN, ( _, expr ) => exec( expr ) )\n }\n\n return exec( expr )\n }\n catch( error ){\n !options?.mute && console.error('Expression evaluation error --', error )\n return undefined\n }\n }\n private __evaluateFunction__( expr: string, params: any[], scope?: VariableSet ){\n /**\n * Execute function expression directly attach \n * as attribute.\n * \n * Eg. \n * `attr=\"() => console.log('Hello world')\"`\n * `attr=\"e => self.onChange(e)\"`\n */\n if( /(\\s*\\w+|\\s*\\([^)]*\\)|\\s*)\\s*=>\\s*(\\s*\\{[^}]*\\}|\\s*[^\\n;\"]+)/g.test( expr ) )\n return this.__evaluate__( expr, scope )( ...params )\n\n /**\n * Execute reference handler function\n * \n * Eg. \n * `attr=\"handleInputValue\"`\n * `attr=\"handleClick, this.input.count++\"`\n * \n * Note: `handleInputValue` and `handleClick` handlers\n * must be defined as `handler` at the component\n * level before any assignment or the execution\n * will throw error.\n */\n else {\n let \n [ fn, ...args ] = expr.split(/\\s*,\\s*/),\n _fn\n \n /**\n * Evaluate whether `fn` is a function itself or\n * a name of an expression resulting in a function.\n */\n const evalfn = this.__evaluate__( fn, scope, { mute: true } )\n\n if( typeof evalfn === 'function' ) _fn = evalfn\n else {\n if( typeof this[ fn ] !== 'function' )\n throw new Error(`Undefined <${fn}> handler method`)\n\n _fn = this[ fn ].bind(this)\n }\n \n if( typeof _fn !== 'function' )\n throw new Error(`Expected <${fn}> to be a function or handler method`)\n\n let _args = args.map( each => (this.__evaluate__( each, scope )) )\n\n if( params.length )\n _args = [ ..._args, ...params ]\n \n return _fn( ..._args )\n }\n }\n private __evaluateSpreadAttr__( expr: string, operator: SpreadOpeartor ){\n const spreads = this.__evaluate__( expr.replace( SPREAD_VAR_PATTERN, '' ) as string, operator.memo )\n if( !spreads ){\n if( !operator.keystore.length )\n throw new Error(`Undefined spread operator ${expr}`)\n \n /**\n * Considered previous spread got nullified\n */\n typeof operator.nullify === 'function' && operator.nullify( operator.keystore )\n return\n }\n \n if( typeof spreads !== 'object' || Array.isArray( spreads ) )\n throw new Error(`Invalid spread operator ${expr}`)\n \n operator.keystore = Object.keys( spreads ) || []\n\n if( typeof operator.each === 'function' )\n for( const key in spreads ) \n operator.each( key, spreads[ key ] )\n }\n private __interpolate__( str: string, scope?: VariableSet, translate?: boolean ){\n str = str.replace( INTERPOLATE_PATTERN, ( _, expr ) => this.__evaluate__( expr, scope ) )\n // Apply translation\n if( translate )\n str = this.lips.i18n.translate( str ).text\n\n return str\n }\n private __attachEvent__( metadata: VirtualEvent<MT> ){\n const { element, nodepath, _event, instruction, scope, __dependencies__ } = metadata \n let eventScope = scope\n\n /**\n * Execute function script directly attach \n * as the listener.\n * \n * Eg. \n * `on-click=\"() => console.log('Hello world')\"`\n * `on-change=\"e => self.onChange(e)\"`\n * \n * Or\n * \n * Execute reference handler function\n * \n * Eg. \n * `on-input=\"handleInputValue\"`\n * `on-click=\"handleClick, this.input.count++\"`\n * \n * Note: `handleInputValue` and `handleClick` handlers\n * must be defined as `handler` at the component\n * level before any assignment.\n */\n element.on( _event, ( ...params: any[] ) => this.__evaluateFunction__( instruction, params, eventScope ) )\n\n this.VER.push( metadata )\n \n // Track DOM operation\n this.metrics.inc('domUpdatesCount')\n this.metrics.inc('domRemovalsCount')\n \n // Track the event handler as a dependency\n if( this.__isReactive__( instruction, scope ) ){\n const deps = this.__extractExpressionDeps__( instruction, scope )\n deps.forEach( dep => this.__trackDep__( __dependencies__, dep, scope || {}, {\n nodetype: 'event',\n nodepath,\n deppath: `${nodepath}.${_event}`,\n target: 'event-handler',\n $fragment: !(element instanceof Component) ? element : null,\n boundaries: element instanceof Component ? element.__boundaries__ : undefined,\n /**\n * Update event's scope with fresh memo\n */\n update: memo => { eventScope = memo }\n }))\n }\n }\n private __detachEvent__({ element, nodepath, _event, instruction, scope, __dependencies__ }: VirtualEvent<MT> ){\n element.off( _event )\n\n // Clean up tracking event handler dependencies\n if( this.__isReactive__( instruction, scope ) ){\n const \n deps = this.__extractExpressionDeps__( instruction, scope ),\n eventPath = `${nodepath}.${_event}`\n \n deps.forEach( dep => {\n // From partial dependencies if there is\n __dependencies__.get( dep )?.delete( eventPath )\n // From main dependencies\n this.FGUD.get( dep )?.delete( eventPath )\n })\n }\n \n // Track DOM operation\n this.metrics.inc('domOperations')\n this.metrics.inc('domRemovalsCount')\n }\n\n private __extractTextDeps__( expr: string, scope?: VariableSet ): string[] {\n const deps = new Set<string>()\n \n // Handle interpolation expressions\n const matches = expr.match(/{\\s*([^{}]+)\\s*}/g) || []\n matches.forEach( match => {\n const\n innerExpr = match.replace(/[{}]/g, '').trim(),\n exprDeps = this.__extractExpressionDeps__( innerExpr, scope )\n\n exprDeps.forEach( dep => deps.add( dep ) )\n })\n\n return Array.from( deps )\n }\n private __extractExpressionDeps__( expr: string, scope?: VariableSet ): string[] {\n const\n /**\n * Metavars pattern\n * \n * - state.items\n * - input.name\n * - context.action\n */\n MVP = /\\b(state|input|context|arguments)(?:\\.[a-zA-Z_]\\w*)+(?=\\[|\\.|$|\\s|;|,|\\))/g,\n /**\n * Metacall pattern\n * \n * - self.getStyle()\n * - self.rule\n */\n MCP = /\\b(self)(?:\\.[a-zA-Z_]\\w*)+(?=\\()/g,\n /**\n * Scope argument pattern\n * \n * - arguments\n * - argument.<key>\n * - argument.<key>[,subkey]\n */\n SAP = /\\b(arguments)((?:\\.[a-zA-Z_]\\w*)+)?(?=\\[|\\.|$|\\s|;|,|\\))/g\n\n let matches = [\n ...Array.from( expr.matchAll( MVP ) ),\n ...Array.from( expr.matchAll( MCP ) ),\n ...Array.from( expr.matchAll( SAP ) )\n ]\n\n /**\n * Extract scope interpolation expressions\n */\n if( scope && Object.keys( scope ).length ){\n const\n scopeRegex = new RegExp(`\\\\b(?<!\\\\.)(${Object.keys( scope ).join('|')})`, 'g'),\n spreadScopeRegex = new RegExp(`(?:(?<=\\\\.\\\\.\\\\.))(${Object.keys(scope).join('|')})\\\\b`, 'g')\n \n matches = [\n ...matches,\n ...Array.from( expr.matchAll( scopeRegex ) ),\n ...Array.from( expr.matchAll( spreadScopeRegex ) )\n ]\n }\n \n // Filter out duplicate deps\n return [ ...new Set( matches.map( m => m[0] ) ) ]\n }\n private __isReactive__( expr: string, scope?: VariableSet ): boolean {\n // Reactive component variables\n if( /(self|state|input|context|arguments)(\\.[\\w.]+)?/.test( expr ) ) return true\n // Reactive internal scope\n if( scope\n && Object.keys( scope ).length\n && new RegExp( Object.keys( scope ).join('|') ).test( expr ) ) return true\n\n return false\n }\n /**\n * Store dependencies memory separately:\n * \n * IMPORTANT: Every node's tracked deps share\n * the same memo reference by the path\n * of that node.\n * \n * Example 1: `<div id=state.item.id style=\"padding: {input.size/2}\">...</div>`\n * The dependencies tracking `id` and `style` attributes\n * will respectively share the memo that is referenced by\n * the `div` element's path\n * Example 2. `<span>{state.label} - {count}</span>`\n * The `state.label` and `count` dependencies will be\n * each tracked using the `span` text content element's\n * memo.\n * \n * Same procedure for `event-handlers`\n */\n private __bindMemo__( memo: VariableSet, dependent: FGUDependency ){\n const\n deppath = dependent.deppath || dependent.nodepath,\n sharedMemo = this.FGUDMemory.get( dependent.nodepath )\n\n if( sharedMemo ){\n // Add new memory dep tracker\n sharedMemo.tracks.set( deppath, dependent.priority || 2 )\n // REVIEW: Override memo\n sharedMemo.memo = memo\n \n // Alter the existing memory\n this.FGUDMemory.set( dependent.nodepath, sharedMemo )\n }\n // Create fresh shared memo\n else {\n // List of tracked dependencies with their priority\n const tracks = new Map()\n\n tracks.set( deppath, dependent.priority )\n this.FGUDMemory.set( dependent.nodepath, { tracks, memo })\n }\n }\n private __unbindMemo__( dependent: FGUDependency ){\n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n \n // No memory bind or already cleaned up\n if( !memoslot || !memoslot.tracks.get( deppath ) ) return\n \n memoslot.tracks.delete( deppath )\n // Remove memory slot if there are no more tracks\n !memoslot.tracks.size && this.FGUDMemory.delete( dependent.nodepath )\n }\n private __trackDep__( dependencies: FGUDependencies, dep: string, memo: VariableSet, dependency: FGUDependency ){\n /**\n * Designate dependencies that assign or \n * interpolate a `let` variable.\n */\n if( memo\n && memo[ dep ]\n && memo[ dep ].type === 'let' )\n dependency.haslet = true\n\n // Assign priority based on dependency type\n if( dependency.priority === undefined ){\n /**\n * Priority 0: (Highest)\n * \n * - Elements affecting layout or visibility\n */\n if( dependency.target === 'attr'\n && dep.split('.').find( each => LAYOUT_AFFECTING_ATTRS.includes( each ) ) )\n dependency.priority = 0\n \n /**\n * Priority 1: \n * \n * - Key structural elements\n * - Conditional rendering\n */\n else if( dependency.syntax ) dependency.priority = 1\n /**\n * Priority 3: (Least urgent)\n * \n * - Event handlers\n */\n else if( ['event'].includes( dependency.nodetype ) ) dependency.priority = 3\n /**\n * Priority 2: (Default)\n * \n * - Sub components\n * - Elements\n * - Text content \n * - Other attributes\n */\n else dependency.priority = 2\n }\n\n const deppath = dependency.deppath || dependency.nodepath\n /**\n * Determine dependency hierarchy level \n * based on path depth by separators.\n */\n dependency.level = deppath.split(/\\//g).length\n /**\n * REVIEW: Combine `level` and `priority` into\n * composite to ensure top-down updates while\n * still respecting the update type priority\n * within each level.\n * \n * `MAX_PRIORITY_TYPES = 100`: This avoid having \n * priority collisions even with complex applications\n */\n dependency.priority = (dependency.level * MAX_PRIORITY_TYPES) + dependency.priority\n\n !dependencies.has( dep ) && dependencies.set( dep, new Map() )\n dependencies.get( dep )?.set( deppath, dependency )\n\n // Subscribed to shared memory\n this.__bindMemo__( memo, dependency )\n\n // Track dependency\n this.metrics.inc('dependencyTrackCount')\n }\n private __trackTranslationDep__( memo: VariableSet, dependency: I18nDependency ){\n this.__i18nDeps.set( dependency.deppath || dependency.nodepath, dependency )\n // Subscribed to shared memory\n this.__bindMemo__( memo, dependency )\n\n // i18n dependency\n this.metrics.inc('i18nTrackCount')\n }\n\n private __valueDep__( obj: any, path: string[] ): any {\n return path.reduce( ( curr, part ) => curr?.[ part ], obj )\n }\n private __shouldUpdate__( dep_scope: string, parts: string[] ): boolean {\n /**\n * Allow component's method `self.fn` call \n * evaluation\n */\n if( dep_scope === 'self' ) return true\n\n // Check metavars changes\n const\n current: InteractiveMetavars<MT> = { \n state: this.state,\n input: this.input,\n context: this.context\n },\n ovalue = this.__valueDep__( this.__previous[ dep_scope as keyof InteractiveMetavars<MT> ], parts ),\n nvalue = this.__valueDep__( current[ dep_scope as keyof InteractiveMetavars<MT> ], parts )\n\n /**\n * Skip if value hasn't changed\n */\n return !isEqual( ovalue, nvalue )\n }\n private __updateDepNodes__(){\n if( !this.FGUD?.size ) return\n \n // Track update\n this.metrics.inc('componentUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n // console.debug('FGUD --', this.FGUD )\n // console.debug('FGUDM --', this.FGUDMemory )\n\n this.FGUD.forEach( ( dependents, dep ) => {\n const [ dep_scope, ...parts ] = dep.split('.')\n\n /**\n * Handle updates for each dependent node/component\n */\n if( !this.__shouldUpdate__( dep_scope, parts ) ) return\n\n dependents.forEach( dependent => {\n try {\n /**\n * Only clean up non-syntactic dependencies \n * or node no longer in DOM\n */\n const deppath = dependent.deppath || dependent.nodepath\n if( dependent.garbage\n || (dependent.boundaries?.start && !document.contains( dependent.boundaries.start ))\n || (dependent.$fragment !== null && !dependent.$fragment.closest('body').length) ){\n dependents.delete( deppath )\n this.__unbindMemo__( dependent )\n\n return\n }\n \n this.UQS.queue({ dep, deppath, priority: dependent.priority })\n this.metrics.inc('dependencyUpdateCount')\n }\n catch( error ){\n console.error('failed to update dependency nodes --', error )\n return\n }\n })\n\n /**\n * Clean up if no more dependents\n */\n !dependents.size && this.FGUD?.delete( dep )\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n private __updateVarDepNodes__( dep: string, varPath: string, newScope: VariableSet ){\n if( !this.FGUD?.size ) return\n\n // Track update\n this.metrics.inc('partialUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n this.FGUD.get( dep )?.forEach( ( dependent, path ) => {\n // console.debug( path, varPath, this.__hasSamePathParent__( path, this.__getPathParent__( varPath ) ) )\n if( !dependent.haslet\n || !this.__hasSamePathParent__( path, this.__getPathParent__( varPath ) ) ) return\n\n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n if( !memoslot ){\n console.warn(`unexpected occurence: <${deppath}> has no memo`)\n return\n }\n\n memoslot.memo = { ...memoslot.memo, ...newScope }\n \n this.UQS.queue({ dep, deppath, priority: dependent.priority })\n this.metrics.inc('dependencyUpdateCount')\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n private __updateArgumentsDepNodes__( scopePath: string, __arguments__: VariableArguments ){\n if( !this.FGUD?.size ) return\n\n // Track update\n this.metrics.inc('partialUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n const dep = 'arguments'\n this.FGUD.get( dep )?.forEach( ( dependent, path ) => {\n if( !this.__hasSamePathParent__( path, scopePath ) ) return\n\n const\n deppath = dependent.deppath || dependent.nodepath,\n memoslot = this.FGUDMemory.get( dependent.nodepath )\n if( !memoslot ){\n console.warn(`unexpected occurence: <${deppath}> has no memo`)\n return\n }\n \n memoslot.memo.__arguments__ = __arguments__\n this.UQS.queue({ dep, deppath, priority: dependent.priority })\n\n this.metrics.inc('dependencyUpdateCount')\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n private __updateI18nDepNodes__(){\n if( !this.__i18nDeps?.size ) return\n\n // Track update\n this.metrics.inc('i18nUpdateCount')\n // Start measuring\n this.metrics.startRender()\n \n this.__i18nDeps?.forEach( ( dependent, path ) => {\n /**\n * The different of i18n dependency update\n * from other updates is that they are cleared\n * as soon as the get updated. Let for the updator\n * function to reset a track if needed.\n * \n * Advantage:\n * - No tracking of unecessarily dead node\n * - `i18n` flag or attribute changed to no-translate\n * - Keep fresh `memo` from other update processes\n * - Cleanup safety for highly interactive content UI.\n */\n if( !dependent.$fragment.closest('body').length ){\n this.__i18nDeps.delete( path )\n return\n }\n\n const memoslot = this.FGUDMemory.get( dependent.nodepath )\n if( !memoslot ){\n console.warn(`unexpected occurence: <${dependent.deppath || dependent.nodepath}> has no memo`)\n return\n }\n\n dependent.update( memoslot.memo, 'i18n-partial-updator' )\n \n this.metrics.inc('dependencyUpdateCount')\n })\n\n // Finish measuring\n this.metrics.endRender()\n }\n \n appendTo( arg: Cash | string ){\n (typeof arg == 'string' ? $(arg) : arg).append( this.node )\n // Track DOM operation\n this.metrics.inc('domOperations')\n\n return this\n }\n prependTo( arg: Cash | string ){\n typeof arg == 'string' ? $(arg) : arg.prepend( this.node )\n // Track DOM operation\n this.metrics.inc('domOperations')\n\n return this\n }\n replaceWith( arg: Cash | string ){\n (typeof arg == 'string' ? $(arg) : arg).replaceWith( this.node )\n // Track DOM operation\n this.metrics.inc('domOperations')\n\n return this\n }\n}",
|
|
38
|
-
|
|
39
|
-
"import type { Declaration, Handler, Metavars, MeshRenderer, VariableSet, FragmentBoundaries } from '../types'\nimport $ from 'cash-dom'\nimport { isEqual } from '../utils'\n\ntype ArgvTrack = {\n argvalues: VariableSet,\n boundaries: FragmentBoundaries\n}\nexport interface Input {\n in: Record<string, any> | any[]\n from?: number\n to?: number\n renderer?: MeshRenderer\n}\nexport interface State {\n argvlist: Record<string, any>[] | null\n}\nexport interface Static {\n lastIn: any\n argvlist: ArgvTrack[] | null\n initialized: boolean\n prevRenderer: MeshRenderer | null\n processingBatch: boolean\n}\n\nexport const declaration: Declaration = {\n name: 'for',\n syntax: true\n}\nexport const _static: Static = {\n lastIn: null,\n argvlist: null,\n initialized: false,\n prevRenderer: null,\n processingBatch: false\n}\n\nexport const handler: Handler<Metavars<Input, State, Static>> = {\n onInput( memo ){\n this.static.initialized\n && this.processor( this.input, memo )\n },\n onSelfRender(){\n const $content = this.processor( this.input, undefined, true )\n this.static.initialized = true\n\n return $content\n },\n\n processor( options: Input, memo?: VariableSet, init = false ){\n /**\n * Skip processing when there's an ongoing \n * processing batch to avoid duplicate work\n */\n if( this.static.processingBatch ) return\n \n if( !options.renderer )\n throw new Error('Undefined mesh renderer')\n\n let { in: _in, from: _from, to: _to } = options\n if( _in === undefined && _from === undefined )\n throw new Error('Invalid <for> arguments')\n \n this.static.processingBatch = true\n try {\n if( _from !== undefined ) return this.asFromTo( options.renderer, _from, _to, memo, init )\n else if( Array.isArray( _in ) ) return this.asArray( options.renderer, _in, memo, init )\n else if( _in instanceof Map ) return this.asMap( options.renderer, _in, memo, init )\n else if( typeof _in == 'object' ) return this.asObject( options.renderer, _in, memo, init )\n }\n finally { this.static.processingBatch = false }\n },\n\n addItem( renderer: MeshRenderer, memo: VariableSet, argvalues: VariableSet, index: number ){\n if( !this.static.argvlist )\n this.static.argvlist = []\n\n // Render new item content\n const\n suffix = `[${index}]`,\n $item = renderer.mesh( argvalues, memo, suffix )\n if( !$item ) return\n \n const { boundaries, $partial } = renderer.demarcate( $item, suffix )\n\n this.static.prevRenderer = renderer\n this.static.argvlist.push({ argvalues, boundaries })\n\n return $partial\n },\n updateItem( renderer: MeshRenderer, memo: VariableSet, argvalues: VariableSet, index: number ){\n if( !this.static.argvlist?.[ index ] ) return\n\n this.static.argvlist[ index ].argvalues = argvalues\n renderer.update( Object.keys( argvalues ), argvalues, memo, this.static.argvlist[ index ].boundaries, `[${index}]` )\n },\n removeItem( renderer: MeshRenderer, index: number ){\n if( !this.static.argvlist?.[ index ] ) return\n \n renderer.cleanup( this.static.argvlist[ index ].boundaries, `[${index}]` )\n this.static.argvlist.splice( index, 1 )\n },\n\n asFromTo( renderer: MeshRenderer, _from: number, _to: number, memo: VariableSet, init: boolean ){\n _from = parseFloat( String( _from ) )\n\n if( _to == undefined )\n throw new Error('Expected <from> <to> attributes of the for loop to be defined')\n\n _to = parseFloat( String( _to ) )\n \n const \n isAscending = _from < _to,\n expectedLength = Math.abs( _to - _from ) + 1\n \n /**\n * Optimize by just updating the values when \n * there's already an argvlist of the correct length, \n * and the range hasn't changed.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const [ ivar ] = renderer.argv\n \n if( ivar ){\n let currentValue = _from\n\n /**\n * Perform granular updates when \n * length hasn't changed\n */\n if( this.static.argvlist.length === expectedLength ){\n for( let i = 0; i < this.static.argvlist.length; i++ ){\n // Update item's dependency without re-rendering\n this.static.argvlist[ i ].argvalues[ ivar ].value !== currentValue\n && this.updateItem( renderer, memo, { [ ivar ]: { value: currentValue, type: 'arg' } }, i )\n\n currentValue = isAscending ? currentValue + 1 : currentValue - 1\n }\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, expectedLength )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, { [ ivar ]: { value: i, type: 'arg' } }, i )\n \n // Add new items in additions\n if( expectedLength > this.static.argvlist.length ){\n for( let i = this.static.argvlist.length; i < expectedLength; i++ ){\n const argvalues: VariableSet = { [ ivar ]: { value: i, type: 'arg' } }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( this.addItem( renderer, memo, argvalues, i ) )\n }\n }\n // Remove items\n else if( expectedLength < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= expectedLength; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let $content = $()\n for( let i = _from; isAscending ? i <= _to : i >= _to; isAscending ? i++ : i-- ){\n const\n argvalues: VariableSet = {},\n [ ivar ] = renderer.argv\n if( ivar )\n argvalues[ ivar ] = { value: i, type: 'arg' }\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, i ) )\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n asArray( renderer: MeshRenderer, _in: any[], memo: VariableSet, init: boolean ){\n /**\n * Reference check for array inputs to \n * avoid unnecessary processing.\n */\n if( this.static.argvlist\n && this.static.lastIn\n && _in === this.static.lastIn )\n return\n\n if( !_in.length ){\n if( !this.static.lastIn )\n console.warn('For loop with empty initial rendering <in> attribute array value will not update')\n }\n\n // Cache the input for future reference checks\n this.static.lastIn = _in\n \n /**\n * Skip full regeneration If we already have an \n * argvlist and the object keys length hasn't changed\n * and only update changed items.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const [ evar, ivar ] = renderer.argv\n \n if( evar ){\n if( this.static.argvlist.length === _in.length ){\n // Update item's dependency without re-rendering\n for( let i = 0; i < this.static.argvlist.length; i++ )\n !isEqual( this.static.argvlist[ i ].argvalues[ evar ].value, _in[ i ] )\n && this.updateItem( renderer, memo, {\n [ evar ]: { value: _in[ i ], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, _in.length )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, {\n [ evar ]: { value: _in[ i ], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n \n // Add new items in additions\n if( _in.length > this.static.argvlist.length ){\n for( let i = this.static.argvlist.length; i < _in.length; i++ ){\n const argvalues: VariableSet = {\n [ evar ]: { value: _in[ i ], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( this.addItem( renderer, memo, argvalues, i ) )\n }\n }\n // Remove items\n else if( _in.length < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= _in.length; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let\n $content = $(),\n index = 0\n\n for( const each of _in ){\n const \n argvalues: VariableSet = {},\n [ evar, ivar ] = renderer.argv\n\n if( evar ) argvalues[ evar ] = { value: each, type: 'arg' }\n if( ivar ) argvalues[ ivar ] = { value: index, type: 'arg' }\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, index ) )\n index++\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n asMap( renderer: MeshRenderer, _in: Map<any, any>, memo: VariableSet, init: boolean ){\n /**\n * Reference check for array inputs to \n * avoid unnecessary processing.\n */\n if( this.static.argvlist\n && this.static.lastIn\n && _in === this.static.lastIn )\n return\n\n if( !_in.size ){\n if( !this.static.lastIn )\n console.warn('For loop with empty initial rendering <in> attribute map value will not update')\n }\n\n // Cache the input for future reference checks\n this.static.lastIn = _in\n \n /**\n * Skip full regeneration If we already have an \n * argvlist and the object keys length hasn't changed\n * and only update changed items.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const\n [ kvar, vvar, ivar ] = renderer.argv,\n _ine = Array.from( _in.entries() )\n \n if( kvar ){\n if( this.static.argvlist.length === _ine.length ){\n // Update item's dependency without re-rendering\n for( let i = 0; i < this.static.argvlist.length; i++ )\n !isEqual( this.static.argvlist[ i ].argvalues[ kvar ].value, _ine[i][0] )\n || !isEqual( this.static.argvlist[ i ].argvalues[ vvar ].value, _ine[i][1] )\n && this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, _ine.length )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n \n // Add new items in additions\n if( _ine.length > this.static.argvlist.length ){\n for( let i = this.static.argvlist.length; i < _ine.length; i++ ){\n const argvalues: VariableSet = {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( this.addItem( renderer, memo, argvalues, i ) )\n }\n }\n // Remove items\n else if( _ine.length < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= _ine.length; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let\n $content = $(),\n index = 0\n\n for( const [ key, value ] of _in ){\n const \n argvalues: VariableSet = {},\n [ kvar, vvar, ivar ] = renderer.argv\n\n if( kvar ) argvalues[ kvar ] = { value: key, type: 'arg' } // key\n if( vvar ) argvalues[ vvar ] = { value: value, type: 'arg' } // value\n if( ivar ) argvalues[ ivar ] = { value: index, type: 'arg' } // index\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, index ) )\n index++\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n asObject( renderer: MeshRenderer, _in: Record<string, any>, memo: VariableSet, init: boolean ){\n /**\n * Reference check for object inputs to \n * avoid unnecessary processing.\n */\n if( this.static.argvlist\n && this.static.lastIn\n && _in === this.static.lastIn )\n return\n\n if( !Object.keys( _in ).length ){\n if( !this.static.lastIn )\n console.warn('For loop with empty initial rendering <in> attribute object value will not update')\n }\n\n // Cache the input for future reference checks\n this.static.lastIn = _in\n \n /**\n * Skip full regeneration If we already have an \n * argvlist and the object keys length hasn't changed\n * and only update changed items.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const \n [ kvar, vvar, ivar ] = renderer.argv,\n _ine = Object.entries( _in )\n \n if( kvar ){\n if( this.static.argvlist.length === _ine.length ){\n // Update item's dependency without re-rendering\n for( let i = 0; i < this.static.argvlist.length; i++ )\n !isEqual( this.static.argvlist[ i ].argvalues[ kvar ].value, _ine[i][0] )\n || !isEqual( this.static.argvlist[ i ].argvalues[ vvar ].value, _ine[i][1] )\n && this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, _ine.length )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n \n // Add new items in additions\n if( _ine.length > this.static.argvlist.length ){\n let $batchItems = $()\n for( let i = this.static.argvlist.length; i < _ine.length; i++ ){\n const argvalues: VariableSet = {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }\n\n const $item = this.addItem( renderer, memo, argvalues, i )\n $batchItems = $batchItems.add( $item )\n }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( $batchItems )\n }\n // Remove items\n else if( _ine.length < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= _ine.length; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let\n $content = $(),\n index = 0\n\n for( const key in _in ){\n const \n argvalues: VariableSet = {},\n [ kvar, vvar, ivar ] = renderer.argv\n\n if( kvar ) argvalues[ kvar ] = { value: key, type: 'arg' } // key\n if( vvar ) argvalues[ vvar ] = { value: _in[ key ], type: 'arg' } // value\n if( ivar ) argvalues[ ivar ] = { value: index, type: 'arg' } // index\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, index ) )\n index++\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n // Safe-guard cleanup\n onDestroy(){\n this.static.prevRenderer?.cleanup( undefined, true )\n\n this.static.prevRenderer = null\n this.static.argvlist = null\n this.static.lastIn = null\n }\n}",
|
|
40
|
-
"import type { Declaration, Handler, Metavars, MeshRenderer, VariableSet, FragmentBoundaries } from '../types'\nimport $ from 'cash-dom'\nimport { isEqual } from '../utils'\n\ntype ArgvTrack = {\n argvalues: VariableSet,\n boundaries: FragmentBoundaries\n}\nexport interface Input {\n in: Record<string, any> | any[]\n from?: number\n to?: number\n renderer?: MeshRenderer\n}\nexport interface State {\n argvlist: Record<string, any>[] | null\n}\nexport interface Static {\n lastIn: any\n argvlist: ArgvTrack[] | null\n initialized: boolean\n prevRenderer: MeshRenderer | null\n processingBatch: boolean\n}\n\nexport const declaration: Declaration = {\n name: 'for',\n syntax: true\n}\nexport const _static: Static = {\n lastIn: null,\n argvlist: null,\n initialized: false,\n prevRenderer: null,\n processingBatch: false\n}\n\nexport const handler: Handler<Metavars<Input, State, Static>> = {\n onInput( memo ){\n this.static.initialized\n && this.processor( this.input, memo )\n },\n onSelfRender(){\n const $content = this.processor( this.input, undefined, true )\n this.static.initialized = true\n\n return $content\n },\n\n processor( options: Input, memo?: VariableSet, init = false ){\n /**\n * Skip processing when there's an ongoing \n * processing batch to avoid duplicate work\n */\n if( this.static.processingBatch ) return\n \n if( !options.renderer )\n throw new Error('Undefined mesh renderer')\n\n let { in: _in, from: _from, to: _to } = options\n if( _in === undefined && _from === undefined )\n throw new Error('Invalid <for> arguments')\n \n this.static.processingBatch = true\n try {\n if( _from !== undefined ) return this.asFromTo( options.renderer, _from, _to, memo, init )\n else if( Array.isArray( _in ) ) return this.asArray( options.renderer, _in, memo, init )\n else if( _in instanceof Map ) return this.asMap( options.renderer, _in, memo, init )\n else if( typeof _in == 'object' ) return this.asObject( options.renderer, _in, memo, init )\n }\n finally { this.static.processingBatch = false }\n },\n\n addItem( renderer: MeshRenderer, memo: VariableSet, argvalues: VariableSet, index: number ){\n if( !this.static.argvlist )\n this.static.argvlist = []\n\n // Render new item content\n const\n suffix = `[${index}]`,\n $item = renderer.mesh( argvalues, memo, suffix )\n if( !$item ) return\n \n const { boundaries, $partial } = renderer.demarcate( $item, suffix )\n\n this.static.prevRenderer = renderer\n this.static.argvlist.push({ argvalues, boundaries })\n\n return $partial\n },\n updateItem( renderer: MeshRenderer, memo: VariableSet, argvalues: VariableSet, index: number ){\n if( !this.static.argvlist?.[ index ] ) return\n\n this.static.argvlist[ index ].argvalues = argvalues\n renderer.update( Object.keys( argvalues ), argvalues, memo, this.static.argvlist[ index ].boundaries, `[${index}]` )\n },\n removeItem( renderer: MeshRenderer, index: number ){\n if( !this.static.argvlist?.[ index ] ) return\n \n renderer.cleanup( this.static.argvlist[ index ].boundaries, `[${index}]` )\n this.static.argvlist.splice( index, 1 )\n },\n\n asFromTo( renderer: MeshRenderer, _from: number, _to: number, memo: VariableSet, init: boolean ){\n _from = parseFloat( String( _from ) )\n\n if( _to == undefined )\n throw new Error('Expected <from> <to> attributes of the for loop to be defined')\n\n _to = parseFloat( String( _to ) )\n \n const \n isAscending = _from < _to,\n expectedLength = Math.abs( _to - _from ) + 1\n \n /**\n * Optimize by just updating the values when \n * there's already an argvlist of the correct length, \n * and the range hasn't changed.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const [ ivar ] = renderer.argv\n \n if( ivar ){\n let currentValue = _from\n\n /**\n * Perform granular updates when \n * length hasn't changed\n */\n if( this.static.argvlist.length === expectedLength ){\n for( let i = 0; i < this.static.argvlist.length; i++ ){\n // Update item's dependency without re-rendering\n this.static.argvlist[ i ].argvalues[ ivar ].value !== currentValue\n && this.updateItem( renderer, memo, { [ ivar ]: { value: currentValue, type: 'arg' } }, i )\n\n currentValue = isAscending ? currentValue + 1 : currentValue - 1\n }\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, expectedLength )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, { [ ivar ]: { value: i, type: 'arg' } }, i )\n \n // Add new items in additions\n if( expectedLength > this.static.argvlist.length ){\n for( let i = this.static.argvlist.length; i < expectedLength; i++ ){\n const argvalues: VariableSet = { [ ivar ]: { value: i, type: 'arg' } }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( this.addItem( renderer, memo, argvalues, i ) )\n }\n }\n // Remove items\n else if( expectedLength < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= expectedLength; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let $content = $()\n for( let i = _from; isAscending ? i <= _to : i >= _to; isAscending ? i++ : i-- ){\n const\n argvalues: VariableSet = {},\n [ ivar ] = renderer.argv\n if( ivar )\n argvalues[ ivar ] = { value: i, type: 'arg' }\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, i ) )\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n asArray( renderer: MeshRenderer, _in: any[], memo: VariableSet, init: boolean ){\n /**\n * Reference check for array inputs to \n * avoid unnecessary processing.\n */\n if( this.static.argvlist\n && this.static.lastIn\n && _in === this.static.lastIn )\n return\n\n if( !_in.length ){\n if( !this.static.lastIn )\n console.warn('For loop with empty initial rendering <in> attribute array value will not update')\n }\n\n // Cache the input for future reference checks\n this.static.lastIn = _in\n \n /**\n * Skip full regeneration If we already have an \n * argvlist and the object keys length hasn't changed\n * and only update changed items.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const [ evar, ivar ] = renderer.argv\n \n if( evar ){\n if( this.static.argvlist.length === _in.length ){\n // Update item's dependency without re-rendering\n for( let i = 0; i < this.static.argvlist.length; i++ )\n !isEqual( this.static.argvlist[ i ].argvalues[ evar ].value, _in[ i ] )\n && this.updateItem( renderer, memo, {\n [ evar ]: { value: _in[ i ], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, _in.length )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, {\n [ evar ]: { value: _in[ i ], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n \n // Add new items in additions\n if( _in.length > this.static.argvlist.length ){\n for( let i = this.static.argvlist.length; i < _in.length; i++ ){\n const argvalues: VariableSet = {\n [ evar ]: { value: _in[ i ], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( this.addItem( renderer, memo, argvalues, i ) )\n }\n }\n // Remove items\n else if( _in.length < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= _in.length; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let\n $content = $(),\n index = 0\n\n for( const each of _in ){\n const \n argvalues: VariableSet = {},\n [ evar, ivar ] = renderer.argv\n\n if( evar ) argvalues[ evar ] = { value: each, type: 'arg' }\n if( ivar ) argvalues[ ivar ] = { value: index, type: 'arg' }\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, index ) )\n index++\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n asMap( renderer: MeshRenderer, _in: Map<any, any>, memo: VariableSet, init: boolean ){\n /**\n * Reference check for array inputs to \n * avoid unnecessary processing.\n */\n if( this.static.argvlist\n && this.static.lastIn\n && _in === this.static.lastIn )\n return\n\n if( !_in.size ){\n if( !this.static.lastIn )\n console.warn('For loop with empty initial rendering <in> attribute map value will not update')\n }\n\n // Cache the input for future reference checks\n this.static.lastIn = _in\n \n /**\n * Skip full regeneration If we already have an \n * argvlist and the object keys length hasn't changed\n * and only update changed items.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const\n [ kvar, vvar, ivar ] = renderer.argv,\n _ine = Array.from( _in.entries() )\n \n if( kvar ){\n if( this.static.argvlist.length === _ine.length ){\n // Update item's dependency without re-rendering\n for( let i = 0; i < this.static.argvlist.length; i++ )\n !isEqual( this.static.argvlist[ i ].argvalues[ kvar ].value, _ine[i][0] )\n || !isEqual( this.static.argvlist[ i ].argvalues[ vvar ].value, _ine[i][1] )\n && this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, _ine.length )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n \n // Add new items in additions\n if( _ine.length > this.static.argvlist.length ){\n for( let i = this.static.argvlist.length; i < _ine.length; i++ ){\n const argvalues: VariableSet = {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( this.addItem( renderer, memo, argvalues, i ) )\n }\n }\n // Remove items\n else if( _ine.length < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= _ine.length; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let\n $content = $(),\n index = 0\n\n for( const [ key, value ] of _in ){\n const \n argvalues: VariableSet = {},\n [ kvar, vvar, ivar ] = renderer.argv\n\n if( kvar ) argvalues[ kvar ] = { value: key, type: 'arg' } // key\n if( vvar ) argvalues[ vvar ] = { value: value, type: 'arg' } // value\n if( ivar ) argvalues[ ivar ] = { value: index, type: 'arg' } // index\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, index ) )\n index++\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n asObject( renderer: MeshRenderer, _in: Record<string, any>, memo: VariableSet, init: boolean ){\n /**\n * Reference check for object inputs to \n * avoid unnecessary processing.\n */\n if( this.static.argvlist\n && this.static.lastIn\n && _in === this.static.lastIn )\n return\n\n if( !Object.keys( _in ).length ){\n if( !this.static.lastIn )\n console.warn('For loop with empty initial rendering <in> attribute object value will not update')\n }\n\n // Cache the input for future reference checks\n this.static.lastIn = _in\n \n /**\n * Skip full regeneration If we already have an \n * argvlist and the object keys length hasn't changed\n * and only update changed items.\n */\n if( Array.isArray( this.static.argvlist ) ){\n const \n [ kvar, vvar, ivar ] = renderer.argv,\n _ine = Object.entries( _in )\n \n if( kvar ){\n if( this.static.argvlist.length === _ine.length ){\n // Update item's dependency without re-rendering\n for( let i = 0; i < this.static.argvlist.length; i++ )\n !isEqual( this.static.argvlist[ i ].argvalues[ kvar ].value, _ine[i][0] )\n || !isEqual( this.static.argvlist[ i ].argvalues[ vvar ].value, _ine[i][1] )\n && this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n\n return\n }\n \n /**\n * Update incrementally existing items when \n * length has changed\n */\n const existsLength = Math.min( this.static.argvlist.length, _ine.length )\n for( let i = 0; i < existsLength; i++ )\n this.updateItem( renderer, memo, {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }, i )\n \n // Add new items in additions\n if( _ine.length > this.static.argvlist.length ){\n let $batchItems = $()\n for( let i = this.static.argvlist.length; i < _ine.length; i++ ){\n const argvalues: VariableSet = {\n [ kvar ]: { value: _ine[i][0], type: 'arg' },\n [ vvar ]: { value: _ine[i][1], type: 'arg' },\n [ ivar ]: { value: i, type: 'arg' }\n }\n\n const $item = this.addItem( renderer, memo, argvalues, i )\n $batchItems = $batchItems.add( $item )\n }\n \n // Add item to the existing list\n this.boundaries\n && $(this.boundaries.end).before( $batchItems )\n }\n // Remove items\n else if( _ine.length < this.static.argvlist.length ){\n for( let i = this.static.argvlist.length - 1; i >= _ine.length; i-- )\n this.removeItem( renderer, i )\n }\n }\n\n return\n }\n \n // Clear exiting for content\n this.static.prevRenderer?.cleanup()\n /**\n * Regenerate the full list when optimization \n * conditions weren't met\n */\n this.static.argvlist = []\n let\n $content = $(),\n index = 0\n\n for( const key in _in ){\n const \n argvalues: VariableSet = {},\n [ kvar, vvar, ivar ] = renderer.argv\n\n if( kvar ) argvalues[ kvar ] = { value: key, type: 'arg' } // key\n if( vvar ) argvalues[ vvar ] = { value: _in[ key ], type: 'arg' } // value\n if( ivar ) argvalues[ ivar ] = { value: index, type: 'arg' } // index\n \n // Bundle item\n $content = $content.add( this.addItem( renderer, memo, argvalues, index ) )\n index++\n }\n\n if( !$content?.length ) return\n if( init ) return $content\n\n renderer.fill( $content )\n },\n // Safe-guard cleanup\n onDestroy(){\n this.static.prevRenderer?.cleanup( undefined, true )\n\n this.static.prevRenderer = null\n this.static.argvlist = null\n this.static.lastIn = null\n }\n}",
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
"import type { LipsConfig, Template, ComponentOptions, Metavars } from './types'\n\nimport TPS from './tps'\nimport IUC from './iuc'\nimport DWS from './dws'\nimport I18N from './i18n'\nimport Stylesheet from './stylesheet'\nimport ComponentClass from './component'\nimport { effect, signal } from './signal'\nimport { isDiff } from './utils'\nimport * as If from './syntax/if'\nimport * as For from './syntax/for'\nimport * as Async from './syntax/async'\nimport * as Switch from './syntax/switch'\nimport * as Router from './syntax/router'\n\nexport * from './types'\nexport type Component<MT extends Metavars> = ComponentClass<MT>\n\nexport default class Lips<Context extends Object = {}> {\n public debug = false\n public stylesheets: Stylesheet[] = []\n private config?: LipsConfig<Context> = {}\n private store: Map<string, Template<any>> = new Map()\n\n private __root?: ComponentClass<any>\n public preprocessor: TPS\n public i18n = new I18N()\n public watcher: DWS<any>\n public IUC: IUC\n\n private __setLang: ( lang: string ) => void\n private __getLang: () => string\n private __setContext: ( ctx: Context ) => void\n private __getContext: () => Context\n\n constructor( config?: LipsConfig<Context> ){\n this.config = config\n\n if( this.config?.debug ) \n this.debug = this.config.debug\n\n this.preprocessor = new TPS( this.store )\n this.watcher = new DWS\n this.IUC = new IUC\n \n const [ getLang, setLang ] = signal<string>( this.i18n.lang )\n const [ getContext, setContext ] = signal<Context>( config?.context || {} as Context )\n\n this.__setLang = setLang\n this.__getLang = getLang\n this.__setContext = setContext\n this.__getContext = getContext\n\n\n /**\n * Register syntax components\n * \n * `<router routers=[] global, ...></router>` -- Internal Routing Component\n */\n this.register('if', If )\n this.register('for', For )\n this.register('async', Async )\n this.register('switch', Switch )\n this.register('router', Router )\n }\n\n register<MT extends Metavars>( name: string, template: Template<MT> ){\n /**\n * TODO: Register component by providing file path.\n */\n // if( typeof template == 'string' ){\n // try { this.store[ name ] = await import( template ) as Template }\n // catch( error ){ throw new Error(`Component <${name}> template not found at ${template}`) }\n\n // return\n // }\n\n this.store.set( name, template )\n\n return this\n }\n unregister( name: string ){\n this.store.delete( name )\n\n return this\n }\n\n has( name: string ){\n return this.store.has( name )\n }\n import<MT extends Metavars>( pathname: string ): Template<MT> {\n // Fetch from registered component\n if( !this.has( pathname ) )\n throw new Error(`<${pathname}> component not found`)\n \n /**\n * Only syntactic component are allowed to \n * no have template's `default` export.\n */\n const component = this.store.get( pathname )\n if( !component?.declaration?.syntax && !component?.default )\n throw new Error(`Invalid <${pathname}> component`)\n \n return component\n \n /**\n * TODO: Import component directly from a file\n */\n // try {\n // const template = await import( pathname ) as Template\n // if( !template?.default )\n // throw null\n\n // this.register( pathname, template )\n // return template\n // }\n // catch( error ){ throw new Error(`No <${pathname}> component found`) }\n }\n render<MT extends Metavars>( name: string, template: Template<MT>, input?: MT['Input'] ){\n const\n { default: _default, ...scope } = template,\n options: ComponentOptions<Context> = {\n debug: this.debug,\n prepath: '0',\n lips: this\n },\n component = new ComponentClass<MT>( name, _default || '', { ...scope, input }, options )\n\n // Perform synchronous cleanup operations\n window.addEventListener( 'beforeunload', () => {\n this.dispose()\n component.destroy()\n\n // REVIEW: Modern browsers ignore return value\n return null\n })\n\n // Enhanced page lifecycle handling\n window.addEventListener( 'pagehide', (event) => {\n !event.persisted && this.dispose()\n });\n \n // Visibility change for edge cases\n document.addEventListener( 'visibilitychange', () => {\n // Prep for potential unload\n if( document.visibilityState !== 'hidden' ) return\n \n this.IUC.prepareForPotentialUnload()\n })\n\n return component\n }\n root<MT extends Metavars>( template: Template<MT>, selector: string ){\n this.__root = this.render('__ROOT__', template )\n this.__root.appendTo( selector )\n\n /**\n * Inject root component stylesheets with \n * global meta style tags.\n */\n if( this.config?.stylesheets )\n this.stylesheets = this.config.stylesheets.map( sheet => new Stylesheet('root', { sheet, meta: true }) )\n \n return this.__root\n }\n\n setLanguage( lang: string ){\n this.i18n.lang = lang\n this.__setLang( lang )\n }\n getLanguage(){\n return this.__getLang()\n }\n\n setContext( arg: Context | string, value?: any ){\n // Always get latest state\n const currentContext = this.__getContext()\n\n /**\n * Change context only when tangible updates\n * are detected.\n * \n * Note: Context may not be initialize at instanciation\n * of Lips.\n */\n if( typeof arg === 'string' ){\n const updates = { ...currentContext, [arg]: value }\n isDiff( currentContext, updates ) && this.__setContext( updates )\n }\n /**\n * no-array object guard\n */\n else if( !Array.isArray( arg ) ){\n const updates = { ...currentContext, ...arg }\n isDiff( currentContext, updates ) && this.__setContext( updates )\n }\n \n else throw new Error('Invalid context data')\n }\n getContext(){\n return this.__getContext()\n }\n useContext<P extends Context>( fields: (keyof P)[], fn: ( context: P ) => void ){\n if( !fields.length ) return\n\n effect( () => {\n const context = this.__getContext()\n if( !context ) return\n\n const ctx = Object.fromEntries( fields.map( field => [ field, context[ field as keyof Context ] ]) ) as unknown as P\n \n /**\n * Propagate context change effect to component \n * only when its registered scope have changed\n */\n ctx\n && typeof fn === 'function'\n && Object.keys( ctx ).length\n && fn( ctx )\n })\n }\n useTranslator( support: string | string[], fn: ( lang: string ) => void ){\n effect( () => {\n const lang = this.__getLang()\n if( !lang ) return\n \n /**\n * Propagate language change effect to \n * component that support it.\n */\n ;(support === '*' || (Array.isArray( support ) && support.includes( lang )))\n && typeof fn === 'function'\n && fn( lang )\n })\n }\n\n dispose(){\n this.watcher?.dispose()\n this.__root?.destroy()\n\n /**\n * Clear all global stylesheets if exists\n */\n this.stylesheets.forEach( stylesheet => stylesheet.clear() )\n }\n}"
|
|
5
|
+
"/**\n * Phase 2 — Expression subsystem (RFC-001 §5)\n *\n * A dedicated parser for the template expression subset with:\n * - positioned, machine-readable diagnostics (never throws)\n * - AST-derived precise dependency paths\n * - two interchangeable executors over the same AST:\n * compiled — one Function per unique expression\n * interpreted — an AST walker that never builds a Function (CSP)\n * Both are for templates you trust. Neither is a boundary: a template\n * you did not write runs under a policy instead (RFC-007, ./policy).\n *\n * Grammar (expression-only, no statements):\n * literals (number, string, boolean, null, undefined), identifiers,\n * member access (incl. optional/computed), calls, unary ! - + and\n * prefix/postfix ++ --, binary arithmetic/relational/equality,\n * && || ??, ternary, arrow functions, assignment (= += -= *= /= %=),\n * array/object literals with spread.\n */\n\n// ---------------------------------------------------------------- diagnostics\nexport interface ExprDiagnostic {\n code: string\n message: string\n loc: { offset: number, length: number }\n}\n\n// ------------------------------------------------------------------------ AST\nexport type Expr =\n | { t: 'lit', v: any }\n /** `at`: where the name (or a member's key) starts in the source — for diagnostics */\n | { t: 'id', name: string, at?: number }\n | { t: 'member', obj: Expr, prop: string | Expr, computed: boolean, optional: boolean, at?: number }\n | { t: 'call', callee: Expr, args: Expr[], optional: boolean }\n | { t: 'unary', op: '!' | '-' | '+', arg: Expr }\n | { t: 'update', op: '++' | '--', arg: Expr, prefix: boolean }\n | { t: 'bin', op: string, l: Expr, r: Expr }\n | { t: 'logic', op: '&&' | '||' | '??', l: Expr, r: Expr }\n | { t: 'cond', test: Expr, cons: Expr, alt: Expr }\n | { t: 'assign', op: string, target: Expr, value: Expr }\n | { t: 'arrow', params: string[], body: Expr }\n | { t: 'arr', items: { spread?: boolean, value: Expr }[] }\n | { t: 'obj', props: { key?: string, value: Expr, spread?: boolean, at?: number }[] }\n | { t: 'error' }\n\n// ------------------------------------------------------------------ tokenizer\ntype Token = {\n t: 'num' | 'str' | 'id' | 'punct' | 'eof'\n value: string\n start: number\n end: number\n}\n\nconst PUNCTS = [\n '===', '!==', '...', '=>', '==', '!=', '<=', '>=', '&&', '||', '??', '?.',\n '++', '--', '+=', '-=', '*=', '/=', '%=',\n '+', '-', '*', '/', '%', '<', '>', '!', '?', ':', '.', ',', '(', ')',\n '[', ']', '{', '}', '='\n]\n\nfunction tokenize( src: string, diagnostics: ExprDiagnostic[] ): Token[] {\n const tokens: Token[] = []\n let i = 0\n\n const isIdStart = ( c: string ) => /[A-Za-z_$]/.test( c )\n const isIdChar = ( c: string ) => /[A-Za-z0-9_$]/.test( c )\n\n while( i < src.length ){\n const c = src[ i ]\n\n if( /\\s/.test( c ) ){ i++; continue }\n\n // Numbers: int, float, exponent\n if( /[0-9]/.test( c ) || ( c === '.' && /[0-9]/.test( src[ i + 1 ] ) ) ){\n const start = i\n while( i < src.length && /[0-9]/.test( src[ i ] ) ) i++\n if( src[ i ] === '.' ){ i++; while( i < src.length && /[0-9]/.test( src[ i ] ) ) i++ }\n if( src[ i ] === 'e' || src[ i ] === 'E' ){\n i++\n if( src[ i ] === '+' || src[ i ] === '-' ) i++\n while( i < src.length && /[0-9]/.test( src[ i ] ) ) i++\n }\n tokens.push({ t: 'num', value: src.slice( start, i ), start, end: i })\n continue\n }\n\n // Strings: '…' or \"…\" with escapes\n if( c === \"'\" || c === '\"' ){\n const start = i\n i++\n let value = ''\n let closed = false\n while( i < src.length ){\n const ch = src[ i ]\n if( ch === '\\\\' ){\n const next = src[ i + 1 ]\n const escapes: Record<string, string> = { n: '\\n', t: '\\t', r: '\\r', b: '\\b', f: '\\f', v: '\\v', '0': '\\0' }\n if( next === 'u' ){\n const hex = src.slice( i + 2, i + 6 )\n value += String.fromCharCode( parseInt( hex, 16 ) || 0 )\n i += 6\n }\n else {\n value += escapes[ next ] ?? next\n i += 2\n }\n continue\n }\n if( ch === c ){ closed = true; i++; break }\n value += ch\n i++\n }\n if( !closed )\n diagnostics.push({ code: 'LIPS-E001', message: 'Unterminated string literal', loc: { offset: start, length: i - start } })\n tokens.push({ t: 'str', value, start, end: i })\n continue\n }\n\n // Identifiers / keywords\n if( isIdStart( c ) ){\n const start = i\n while( i < src.length && isIdChar( src[ i ] ) ) i++\n tokens.push({ t: 'id', value: src.slice( start, i ), start, end: i })\n continue\n }\n\n // Punctuators — longest match first\n let punct = PUNCTS.find( p => src.startsWith( p, i ) )\n // `a ? .5 : b` — '?.' must not swallow a ternary before a decimal\n if( punct === '?.' && /[0-9]/.test( src[ i + 2 ] ?? '' ) )\n punct = '?'\n if( punct ){\n tokens.push({ t: 'punct', value: punct, start: i, end: i + punct.length })\n i += punct.length\n continue\n }\n\n diagnostics.push({ code: 'LIPS-E002', message: `Unexpected character '${c}'`, loc: { offset: i, length: 1 } })\n i++\n }\n\n tokens.push({ t: 'eof', value: '', start: src.length, end: src.length })\n return tokens\n}\n\n// --------------------------------------------------------------------- parser\nclass Parser {\n private pos = 0\n constructor( private tokens: Token[], private diagnostics: ExprDiagnostic[] ){}\n\n private peek( offset = 0 ){ return this.tokens[ Math.min( this.pos + offset, this.tokens.length - 1 ) ] }\n private next(){ return this.tokens[ this.pos++ ] ?? this.tokens[ this.tokens.length - 1 ] }\n private at( value: string ){ const t = this.peek(); return t.t === 'punct' && t.value === value }\n private eat( value: string ){ if( this.at( value ) ){ this.pos++; return true } return false }\n private error( code: string, message: string, token = this.peek() ): Expr {\n this.diagnostics.push({ code, message, loc: { offset: token.start, length: Math.max( 1, token.end - token.start ) } })\n return { t: 'error' }\n }\n private expect( value: string, code: string ){\n if( !this.eat( value ) )\n this.error( code, `Expected '${value}'` )\n }\n\n parse(): Expr {\n const expr = this.assign()\n if( this.peek().t !== 'eof' )\n this.error( 'LIPS-E003', `Unexpected token '${this.peek().value}' after expression` )\n return expr\n }\n\n /**\n * Arrow lookahead: '(' … ')' '=>' or IDENT '=>'\n */\n private isArrowAhead(): boolean {\n const t = this.peek()\n if( t.t === 'id' ){\n const n = this.peek( 1 )\n return n.t === 'punct' && n.value === '=>'\n }\n if( t.t === 'punct' && t.value === '(' ){\n let depth = 0, k = 0\n while( true ){\n const tok = this.peek( k )\n if( tok.t === 'eof' ) return false\n if( tok.t === 'punct' && tok.value === '(' ) depth++\n if( tok.t === 'punct' && tok.value === ')' ){\n depth--\n if( depth === 0 ){\n const after = this.peek( k + 1 )\n return after.t === 'punct' && after.value === '=>'\n }\n }\n k++\n }\n }\n return false\n }\n\n private assign(): Expr {\n // Arrow functions\n if( this.isArrowAhead() ){\n const params: string[] = []\n if( this.peek().t === 'id' )\n params.push( this.next().value )\n else {\n this.expect( '(', 'LIPS-E004' )\n while( !this.at( ')' ) && this.peek().t !== 'eof' ){\n const p = this.next()\n if( p.t !== 'id' ) return this.error( 'LIPS-E005', 'Invalid arrow parameter', p )\n params.push( p.value )\n if( !this.eat( ',' ) ) break\n }\n this.expect( ')', 'LIPS-E004' )\n }\n this.expect( '=>', 'LIPS-E004' )\n return { t: 'arrow', params, body: this.assign() }\n }\n\n const target = this.conditional()\n\n const op = this.peek()\n if( op.t === 'punct' && [ '=', '+=', '-=', '*=', '/=', '%=' ].includes( op.value ) ){\n if( target.t !== 'id' && target.t !== 'member' )\n return this.error( 'LIPS-E006', 'Invalid assignment target', op )\n this.next()\n return { t: 'assign', op: op.value, target, value: this.assign() }\n }\n\n return target\n }\n\n private conditional(): Expr {\n const test = this.nullish()\n if( this.eat( '?' ) ){\n const cons = this.assign()\n this.expect( ':', 'LIPS-E007' )\n return { t: 'cond', test, cons, alt: this.assign() }\n }\n return test\n }\n\n private nullish(): Expr {\n let l = this.or()\n while( this.at( '??' ) ){ this.next(); l = { t: 'logic', op: '??', l, r: this.or() } }\n return l\n }\n private or(): Expr {\n let l = this.and()\n while( this.at( '||' ) ){ this.next(); l = { t: 'logic', op: '||', l, r: this.and() } }\n return l\n }\n private and(): Expr {\n let l = this.equality()\n while( this.at( '&&' ) ){ this.next(); l = { t: 'logic', op: '&&', l, r: this.equality() } }\n return l\n }\n private equality(): Expr {\n let l = this.relational()\n while( [ '===', '!==', '==', '!=' ].some( op => this.at( op ) ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.relational() }\n }\n return l\n }\n private relational(): Expr {\n let l = this.additive()\n while( [ '<=', '>=', '<', '>' ].some( op => this.at( op ) ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.additive() }\n }\n return l\n }\n private additive(): Expr {\n let l = this.multiplicative()\n while( this.at( '+' ) || this.at( '-' ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.multiplicative() }\n }\n return l\n }\n private multiplicative(): Expr {\n let l = this.unary()\n while( this.at( '*' ) || this.at( '/' ) || this.at( '%' ) ){\n const op = this.next().value\n l = { t: 'bin', op, l, r: this.unary() }\n }\n return l\n }\n private unary(): Expr {\n if( this.at( '!' ) || this.at( '-' ) || this.at( '+' ) ){\n const op = this.next().value as '!' | '-' | '+'\n return { t: 'unary', op, arg: this.unary() }\n }\n if( this.at( '++' ) || this.at( '--' ) ){\n const op = this.next().value as '++' | '--'\n const arg = this.unary()\n if( arg.t !== 'id' && arg.t !== 'member' )\n return this.error( 'LIPS-E006', 'Invalid update target' )\n return { t: 'update', op, arg, prefix: true }\n }\n return this.postfix()\n }\n private postfix(): Expr {\n let expr = this.callMember()\n if( this.at( '++' ) || this.at( '--' ) ){\n const op = this.next().value as '++' | '--'\n if( expr.t !== 'id' && expr.t !== 'member' )\n return this.error( 'LIPS-E006', 'Invalid update target' )\n expr = { t: 'update', op, arg: expr, prefix: false }\n }\n return expr\n }\n\n private callMember(): Expr {\n let expr = this.primary()\n\n while( true ){\n if( this.eat( '.' ) ){\n const prop = this.next()\n if( prop.t !== 'id' ) return this.error( 'LIPS-E008', 'Expected property name', prop )\n expr = { t: 'member', obj: expr, prop: prop.value, computed: false, optional: false, at: prop.start }\n }\n else if( this.eat( '?.' ) ){\n if( this.at( '(' ) ){\n expr = { t: 'call', callee: expr, args: this.argList(), optional: true }\n }\n else if( this.eat( '[' ) ){\n const at = this.peek().start\n const idx = this.assign()\n this.expect( ']', 'LIPS-E009' )\n expr = { t: 'member', obj: expr, prop: idx, computed: true, optional: true, at }\n }\n else {\n const prop = this.next()\n if( prop.t !== 'id' ) return this.error( 'LIPS-E008', 'Expected property name', prop )\n expr = { t: 'member', obj: expr, prop: prop.value, computed: false, optional: true, at: prop.start }\n }\n }\n else if( this.eat( '[' ) ){\n const at = this.peek().start\n const idx = this.assign()\n this.expect( ']', 'LIPS-E009' )\n expr = { t: 'member', obj: expr, prop: idx, computed: true, optional: false, at }\n }\n else if( this.at( '(' ) ){\n expr = { t: 'call', callee: expr, args: this.argList(), optional: false }\n }\n else break\n }\n\n return expr\n }\n private argList(): Expr[] {\n this.expect( '(', 'LIPS-E010' )\n const args: Expr[] = []\n while( !this.at( ')' ) && this.peek().t !== 'eof' ){\n args.push( this.assign() )\n if( !this.eat( ',' ) ) break\n }\n this.expect( ')', 'LIPS-E010' )\n return args\n }\n\n private primary(): Expr {\n const t = this.peek()\n\n if( t.t === 'num' ){ this.next(); return { t: 'lit', v: parseFloat( t.value ) } }\n if( t.t === 'str' ){ this.next(); return { t: 'lit', v: t.value } }\n\n if( t.t === 'id' ){\n this.next()\n switch( t.value ){\n case 'true': return { t: 'lit', v: true }\n case 'false': return { t: 'lit', v: false }\n case 'null': return { t: 'lit', v: null }\n case 'undefined': return { t: 'lit', v: undefined }\n case 'NaN': return { t: 'lit', v: NaN }\n case 'Infinity': return { t: 'lit', v: Infinity }\n default: return { t: 'id', name: t.value, at: t.start }\n }\n }\n\n if( this.eat( '(' ) ){\n const expr = this.assign()\n this.expect( ')', 'LIPS-E010' )\n return expr\n }\n\n if( this.eat( '[' ) ){\n const items: { spread?: boolean, value: Expr }[] = []\n while( !this.at( ']' ) && this.peek().t !== 'eof' ){\n const spread = this.eat( '...' )\n items.push({ spread: spread || undefined, value: this.assign() })\n if( !this.eat( ',' ) ) break\n }\n this.expect( ']', 'LIPS-E009' )\n return { t: 'arr', items }\n }\n\n if( this.eat( '{' ) ){\n const props: { key?: string, value: Expr, spread?: boolean, at?: number }[] = []\n while( !this.at( '}' ) && this.peek().t !== 'eof' ){\n if( this.eat( '...' ) ){\n props.push({ spread: true, value: this.assign() })\n }\n else {\n const key = this.next()\n if( key.t !== 'id' && key.t !== 'str' && key.t !== 'num' )\n return this.error( 'LIPS-E011', 'Invalid object key', key )\n\n if( this.eat( ':' ) )\n props.push({ key: String( key.value ), value: this.assign(), at: key.start })\n else if( key.t === 'id' ) // shorthand { a }\n props.push({ key: key.value, value: { t: 'id', name: key.value, at: key.start }, at: key.start })\n else\n return this.error( 'LIPS-E011', 'Invalid shorthand property', key )\n }\n if( !this.eat( ',' ) ) break\n }\n this.expect( '}', 'LIPS-E011' )\n return { t: 'obj', props }\n }\n\n this.next()\n return this.error( 'LIPS-E012', t.t === 'eof' ? 'Unexpected end of expression' : `Unexpected token '${t.value}'`, t )\n }\n}\n\nexport function parseExpression( src: string ): { ast: Expr, diagnostics: ExprDiagnostic[] } {\n const diagnostics: ExprDiagnostic[] = []\n const tokens = tokenize( src, diagnostics )\n const ast = new Parser( tokens, diagnostics ).parse()\n\n return { ast, diagnostics }\n}\n\n/**\n * Split an instruction (`on-click( fn, a, b )`, `<log( a, b )>`) on its\n * top-level commas — strings and brackets are opaque.\n */\nexport function splitTopLevel( src: string ): string[] {\n const out: string[] = []\n let depth = 0, start = 0\n\n for( let i = 0; i < src.length; i++ ){\n const c = src[ i ]\n if( c === \"'\" || c === '\"' || c === '`' ){\n i++\n while( i < src.length && src[ i ] !== c ){\n if( src[ i ] === '\\\\' ) i++\n i++\n }\n continue\n }\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ) depth--\n else if( c === ',' && depth === 0 ){\n out.push( src.slice( start, i ) )\n start = i + 1\n }\n }\n out.push( src.slice( start ) )\n return out.map( s => s.trim() ).filter( Boolean )\n}\n\n// ------------------------------------------------------------ dep extraction\nconst METAVAR_ROOTS = new Set([ 'state', 'input', 'context', 'self', 'arguments' ])\n\n/**\n * Every root identifier an expression reads that is not bound by an\n * arrow parameter — the head of each member chain, plus bare reads.\n *\n * The complement of `extractDeps`, which drops names it does not\n * recognise. Callers that need to REPORT an unresolvable name (a\n * stylesheet has no template position, so a `<for>` iterator in one\n * can never resolve — RFC-004 §7.2) need to see them instead.\n */\nexport function freeRoots( ast: Expr ): string[] {\n const roots = new Set<string>()\n\n const walk = ( node: Expr, shadow: Set<string> ) => {\n switch( node.t ){\n case 'id':\n !shadow.has( node.name ) && roots.add( node.name )\n return\n case 'member':\n walk( node.obj, shadow )\n typeof node.prop !== 'string' && walk( node.prop, shadow )\n return\n case 'call':\n walk( node.callee, shadow )\n node.args.forEach( a => walk( a, shadow ) )\n return\n case 'unary': case 'update': walk( node.arg, shadow ); return\n case 'bin': case 'logic': walk( node.l, shadow ); walk( node.r, shadow ); return\n case 'cond':\n walk( node.test, shadow ); walk( node.cons, shadow ); walk( node.alt, shadow )\n return\n case 'assign': walk( node.target, shadow ); walk( node.value, shadow ); return\n case 'arrow': walk( node.body, new Set([ ...shadow, ...node.params ]) ); return\n case 'arr': node.items.forEach( i => walk( i.value, shadow ) ); return\n case 'obj': node.props.forEach( p => walk( p.value, shadow ) ); return\n }\n }\n\n walk( ast, new Set() )\n return [ ...roots ]\n}\n\n/**\n * Precise dependency paths from the AST: dotted member paths\n * rooted at metavars (up to the first computed/call boundary),\n * plus bare scope-variable reads. Arrow params shadow.\n */\nexport function extractDeps( ast: Expr, scopeNames: string[] = [] ): string[] {\n const\n deps = new Set<string>(),\n scope = new Set( scopeNames )\n\n const walk = ( node: Expr, shadow: Set<string> ) => {\n switch( node.t ){\n case 'id': {\n if( shadow.has( node.name ) ) return\n if( scope.has( node.name ) || node.name === 'arguments' ) deps.add( node.name )\n return\n }\n case 'member': {\n // Collect the static dotted chain\n const parts: string[] = []\n let cur: Expr = node\n while( cur.t === 'member' && !cur.computed && typeof cur.prop === 'string' ){\n parts.unshift( cur.prop )\n cur = cur.obj\n }\n // Computed segments: record the object chain and the index deps\n if( cur.t === 'member' ){\n walk( cur.obj, shadow )\n typeof cur.prop !== 'string' && walk( cur.prop, shadow )\n // Re-anchor: deps of the computed base were recorded above\n if( cur.obj.t === 'id' || cur.obj.t === 'member' ) { /* recorded via recursion */ }\n }\n else if( cur.t === 'id' && !shadow.has( cur.name ) ){\n if( METAVAR_ROOTS.has( cur.name ) )\n deps.add( parts.length ? `${cur.name}.${parts.join('.')}` : cur.name )\n else if( scope.has( cur.name ) )\n deps.add( cur.name )\n }\n else if( cur.t !== 'id' ) walk( cur, shadow )\n return\n }\n case 'call':\n walk( node.callee, shadow )\n node.args.forEach( a => walk( a, shadow ) )\n return\n case 'unary': walk( node.arg, shadow ); return\n case 'update': walk( node.arg, shadow ); return\n case 'bin': case 'logic': walk( node.l, shadow ); walk( node.r, shadow ); return\n case 'cond': walk( node.test, shadow ); walk( node.cons, shadow ); walk( node.alt, shadow ); return\n case 'assign': walk( node.target, shadow ); walk( node.value, shadow ); return\n case 'arrow': {\n const inner = new Set([ ...shadow, ...node.params ])\n walk( node.body, inner )\n return\n }\n case 'arr': node.items.forEach( i => walk( i.value, shadow ) ); return\n case 'obj': node.props.forEach( p => walk( p.value, shadow ) ); return\n }\n }\n\n walk( ast, new Set() )\n return [ ...deps ]\n}\n\n// -------------------------------------------------------------------- codegen\n/**\n * AST → JS source (fully parenthesized — semantics over beauty).\n * Reserved-as-parameter roots are renamed at the identifier node\n * (`static` → `__static`, `arguments` → `__args__`) — renaming in\n * codegen, never via regex on emitted source, keeps string literals\n * containing those words intact.\n */\n/**\n * Name tables are prototype-free (`__proto__: null`): looked up by an\n * author's identifier, a `{}` answered `constructor` with `Object`\n * (RFC-007 §8). A literal, not a helper call, so a bundle that never\n * reads a table can still drop it.\n */\nconst ID_RENAMES: Record<string, string> = { __proto__: null, static: '__static', arguments: '__args__' } as any\n\nfunction gen( node: Expr ): string {\n switch( node.t ){\n case 'lit':\n if( typeof node.v === 'string' ) return JSON.stringify( node.v )\n if( node.v === undefined ) return 'undefined'\n if( Number.isNaN( node.v ) ) return 'NaN'\n return String( node.v )\n case 'id': return ID_RENAMES[ node.name ] ?? node.name\n case 'member': {\n const obj = gen( node.obj )\n if( node.computed ) return `(${obj})${node.optional ? '?.' : ''}[${gen( node.prop as Expr )}]`\n return `(${obj})${node.optional ? '?.' : '.'}${node.prop}`\n }\n case 'call': return `(${gen( node.callee )})${node.optional ? '?.' : ''}(${node.args.map( gen ).join(',')})`\n case 'unary': return `(${node.op}(${gen( node.arg )}))`\n case 'update': return node.prefix ? `(${node.op}${genTarget( node.arg )})` : `(${genTarget( node.arg )}${node.op})`\n case 'bin': return `((${gen( node.l )})${node.op}(${gen( node.r )}))`\n case 'logic': return `((${gen( node.l )})${node.op}(${gen( node.r )}))`\n case 'cond': return `((${gen( node.test )})?(${gen( node.cons )}):(${gen( node.alt )}))`\n case 'assign': return `(${genTarget( node.target )}${node.op}(${gen( node.value )}))`\n case 'arrow': return `((${node.params.join(',')})=>(${gen( node.body )}))`\n case 'arr': return `[${node.items.map( i => ( i.spread ? '...' : '' ) + gen( i.value ) ).join(',')}]`\n case 'obj': return `({${node.props.map( p =>\n p.spread ? `...${gen( p.value )}` : `${JSON.stringify( p.key )}:${gen( p.value )}` ).join(',')}})`\n case 'error': return 'undefined'\n }\n}\n/** Assignment/update targets must not be over-parenthesized */\nfunction genTarget( node: Expr ): string {\n if( node.t === 'id' ) return ID_RENAMES[ node.name ] ?? node.name\n if( node.t === 'member' ){\n const obj = gen( node.obj )\n return node.computed ? `${obj}[${gen( node.prop as Expr )}]` : `${obj}.${node.prop}`\n }\n return gen( node )\n}\n\n// ------------------------------------------------------------------ executors\nexport interface ExprEnv {\n state?: any\n input?: any\n context?: any\n static?: any\n self?: any\n arguments?: any\n scope?: Record<string, any>\n /**\n * Effective language for this subtree, read reactively (RFC-005 §4).\n * Set by `<i18n lang=…>`; absent means \"the global language\". Not an\n * expression root — the evaluator only binds the named roots, so this\n * rides along for the runtime's own use.\n */\n lang?: () => string\n}\n\nexport interface CompiledExpr {\n run( env: ExprEnv ): any\n source: string\n}\n\nconst\nCOMPILE_CACHE = new Map<string, CompiledExpr>(),\nROOT_PARAMS = [ 'state', 'input', 'context', '__static', 'self' ]\n\n/**\n * Compiled mode: one Function per unique (source, scopeNames) —\n * strict-compatible, no `with`. Trusted contexts only.\n */\nexport function compileExpression( src: string, scopeNames: string[] = [] ): CompiledExpr {\n const key = `${scopeNames.join(',')}\\0${src}`\n const cached = COMPILE_CACHE.get( key )\n if( cached ) return cached\n\n const { ast, diagnostics } = parseExpression( src )\n if( diagnostics.length )\n console.warn( `[lips-ir] expression diagnostics for \"${src}\":`, diagnostics )\n\n const\n code = `return (${gen( ast )});`,\n params = [ ...ROOT_PARAMS, '__args__', ...scopeNames ],\n fn = new Function( ...params, code )\n\n const compiled: CompiledExpr = {\n source: src,\n run( env: ExprEnv ){\n const scope = env.scope || {}\n return fn(\n env.state, env.input, env.context, env.static, env.self, env.arguments,\n ...scopeNames.map( name => scope[ name ] )\n )\n }\n }\n\n COMPILE_CACHE.set( key, compiled )\n return compiled\n}\n\n/**\n * Interpreted mode: an AST walker. CSP-safe — it never builds a Function\n * and never calls eval — and names resolve only to the scope, the\n * metavars and the globals below.\n *\n * It is NOT a sandbox. Members, calls and writes are unrestricted, and\n * these globals are the page's own objects. For a template you did not\n * write, use `new Lips({ untrusted })` (RFC-007).\n */\nconst GLOBALS: Record<string, any> = {\n __proto__: null,\n Math, JSON, Object, Array, String, Number, Boolean, Date,\n parseInt, parseFloat, isNaN, isFinite,\n encodeURIComponent, decodeURIComponent, console\n} as any\n\nexport function interpretExpression( ast: Expr, env: ExprEnv ): any {\n const scope = env.scope || Object.create( null )\n\n const resolveId = ( name: string, locals: Record<string, any>[] ): any => {\n for( const frame of locals )\n if( name in frame ) return frame[ name ]\n\n if( name in scope ) return scope[ name ]\n\n switch( name ){\n case 'state': return env.state\n case 'input': return env.input\n case 'context': return env.context\n case 'static': return env.static\n case 'self': return env.self\n case 'arguments': return env.arguments\n }\n\n if( name in GLOBALS ) return GLOBALS[ name ]\n return undefined\n }\n\n const assignId = ( name: string, value: any, locals: Record<string, any>[] ) => {\n for( const frame of locals )\n if( name in frame ){ frame[ name ] = value; return value }\n scope[ name ] = value\n return value\n }\n\n const ev = ( node: Expr, locals: Record<string, any>[] ): any => {\n switch( node.t ){\n case 'lit': return node.v\n case 'id': return resolveId( node.name, locals )\n\n case 'member': {\n const obj = ev( node.obj, locals )\n if( node.optional && obj == null ) return undefined\n const prop = node.computed ? ev( node.prop as Expr, locals ) : node.prop as string\n return obj?.[ prop ]\n }\n\n case 'call': {\n // Member calls bind `this` to the object\n if( node.callee.t === 'member' ){\n const obj = ev( node.callee.obj, locals )\n if( ( node.callee.optional || node.optional ) && obj == null ) return undefined\n const prop = node.callee.computed ? ev( node.callee.prop as Expr, locals ) : node.callee.prop as string\n const fn = obj?.[ prop ]\n if( node.optional && fn == null ) return undefined\n return fn.apply( obj, node.args.map( a => ev( a, locals ) ) )\n }\n const fn = ev( node.callee, locals )\n if( node.optional && fn == null ) return undefined\n return fn( ...node.args.map( a => ev( a, locals ) ) )\n }\n\n case 'unary': {\n const v = ev( node.arg, locals )\n switch( node.op ){\n case '!': return !v\n case '-': return -v\n case '+': return +v\n }\n }\n\n case 'update': {\n const cur = ev( node.arg, locals )\n const nextVal = node.op === '++' ? cur + 1 : cur - 1\n setTarget( node.arg, nextVal, locals )\n return node.prefix ? nextVal : cur\n }\n\n case 'bin': {\n const l = ev( node.l, locals ), r = ev( node.r, locals )\n switch( node.op ){\n case '+': return l + r\n case '-': return l - r\n case '*': return l * r\n case '/': return l / r\n case '%': return l % r\n case '<': return l < r\n case '>': return l > r\n case '<=': return l <= r\n case '>=': return l >= r\n // eslint-disable-next-line eqeqeq\n case '==': return l == r\n // eslint-disable-next-line eqeqeq\n case '!=': return l != r\n case '===': return l === r\n case '!==': return l !== r\n }\n return undefined\n }\n\n case 'logic': {\n const l = ev( node.l, locals )\n switch( node.op ){\n case '&&': return l ? ev( node.r, locals ) : l\n case '||': return l ? l : ev( node.r, locals )\n case '??': return l != null ? l : ev( node.r, locals )\n }\n }\n\n case 'cond': return ev( node.test, locals ) ? ev( node.cons, locals ) : ev( node.alt, locals )\n\n case 'assign': {\n let value = ev( node.value, locals )\n if( node.op !== '=' ){\n const cur = ev( node.target, locals )\n switch( node.op ){\n case '+=': value = cur + value; break\n case '-=': value = cur - value; break\n case '*=': value = cur * value; break\n case '/=': value = cur / value; break\n case '%=': value = cur % value; break\n }\n }\n return setTarget( node.target, value, locals )\n }\n\n case 'arrow':\n return ( ...args: any[] ) => {\n const frame: Record<string, any> = Object.create( null )\n node.params.forEach( ( p, k ) => frame[ p ] = args[ k ] )\n return ev( node.body, [ frame, ...locals ] )\n }\n\n case 'arr': {\n const out: any[] = []\n for( const item of node.items ){\n const v = ev( item.value, locals )\n item.spread ? out.push( ...v ) : out.push( v )\n }\n return out\n }\n\n case 'obj': {\n const out: Record<string, any> = {}\n for( const p of node.props ){\n if( p.spread ) Object.assign( out, ev( p.value, locals ) )\n else out[ p.key as string ] = ev( p.value, locals )\n }\n return out\n }\n\n case 'error': return undefined\n }\n }\n\n const setTarget = ( target: Expr, value: any, locals: Record<string, any>[] ) => {\n if( target.t === 'id' ) return assignId( target.name, value, locals )\n if( target.t === 'member' ){\n const obj = ev( target.obj, locals )\n const prop = target.computed ? ev( target.prop as Expr, locals ) : target.prop as string\n if( obj != null ) obj[ prop ] = value\n return value\n }\n return value\n }\n\n return ev( ast, [] )\n}\n",
|
|
6
|
+
"/**\n * Phase 2 — reactivity core (RFC-001 §6)\n *\n * Minimal per-key signals: no history (that's the opt-in\n * `historySignal` wrapper, later), no deep proxies, no digest.\n * A write notifies exactly the effects that read that signal.\n */\n\ntype Effect = {\n run: () => void\n deps: Set<Set<Effect>>\n disposed: boolean\n}\n\nlet CURRENT: Effect | null = null\n\n/**\n * Batching. Inside `batch()` a notification is queued on its signal\n * rather than run, and the queue is a Set — so N writes to the same key\n * collapse to ONE notification when the outermost batch exits.\n *\n * This is what turns an animation loop over a reactive list from O(N²)\n * into O(N): a nested write force-notifies its top key's subscribers\n * (see `deepWrap`), and the keyed `<for>` is one of them.\n */\nlet BATCH_DEPTH = 0\n\n/**\n * Queued EFFECTS, not queued signals. One effect commonly subscribes to\n * many channels — a keyed `<for>` reads `length` and every index — so\n * deduplicating per signal would still run it once per channel. The\n * Set collapses to one run per effect.\n */\nconst PENDING = new Set<Effect>()\n\n/**\n * Drain iteratively: an effect may itself write, queueing more work.\n * Re-enter the batch around each pass so those collapse too, instead of\n * running eagerly one at a time.\n */\nfunction drain(){\n while( PENDING.size ){\n const queued = [ ...PENDING ]\n PENDING.clear()\n BATCH_DEPTH++\n try { for( const e of queued ) !e.disposed && e.run() }\n finally { BATCH_DEPTH-- }\n }\n}\n\nexport function batch<T>( fn: () => T ): T {\n BATCH_DEPTH++\n // NB: never `return` from the finally — it would discard fn()'s value\n try { return fn() }\n finally {\n BATCH_DEPTH--\n !BATCH_DEPTH && drain()\n }\n}\n\nexport function signal<T>( value: T ): [ () => T, ( next: T ) => void, () => void ] {\n const subs = new Set<Effect>()\n\n const notify = () => {\n if( BATCH_DEPTH ){\n for( const e of subs ) PENDING.add( e )\n return\n }\n // Copy: effects may retrack while running\n for( const e of [ ...subs ] )\n !e.disposed && e.run()\n }\n\n const read = () => {\n if( CURRENT && !CURRENT.disposed ){\n subs.add( CURRENT )\n CURRENT.deps.add( subs )\n }\n return value\n }\n const write = ( next: T ) => {\n if( Object.is( next, value ) ) return\n value = next\n notify()\n }\n /**\n * Force-notify without a value change — the deep-reactive\n * facade uses this when nested content mutates in place.\n */\n const touch = () => notify()\n\n return [ read, write, touch ]\n}\n\nexport interface EffectHandle {\n dispose(): void\n}\n\nexport function effect( fn: () => void ): EffectHandle {\n const e: Effect = {\n deps: new Set(),\n disposed: false,\n run(){\n if( e.disposed ) return\n\n // Re-track from scratch each run\n for( const subs of e.deps ) subs.delete( e )\n e.deps.clear()\n\n const prev = CURRENT\n CURRENT = e\n try { fn() }\n finally { CURRENT = prev }\n }\n }\n\n e.run()\n\n return {\n dispose(){\n e.disposed = true\n for( const subs of e.deps ) subs.delete( e )\n e.deps.clear()\n }\n }\n}\n\n/** Run `fn` without dependency tracking */\nexport function untrack<T>( fn: () => T ): T {\n const prev = CURRENT\n CURRENT = null\n try { return fn() }\n finally { CURRENT = prev }\n}\n\nconst IS_REACTIVE = Symbol('lips.reactive')\n/** Marks a collection proxy and exposes its notifier + raw target */\nconst COLLECTION_META = Symbol('lips.collection')\n\ninterface CollectionMeta {\n raw: Map<any, any> | Set<any>\n notify: Set<() => void>\n}\n\n/**\n * Per-key reactive facade over a plain object:\n * reading a key inside an effect subscribes to that key;\n * writing notifies only that key's subscribers.\n * Idempotent — wrapping a reactive object returns it as-is.\n *\n * Shallow by default (RFC §6). `deep: true` opts into nested\n * mutation tracking: plain objects/arrays read through a key are\n * lazily proxied, and any nested write force-notifies that top\n * key's subscribers (coarse but O(subscribers-of-key)).\n */\n/**\n * Shared across every reactive store: a collection reached from two\n * stores (parent `state.x`, child `input.x`) must resolve to ONE\n * proxy, so a mutation through either notifies both.\n */\nconst COLLECTION_PROXIES = new WeakMap<object, any>()\n\n/** Plain objects/arrays are deep-wrapped (Date/class instances pass through) */\nconst isPlain = ( v: any ) =>\n v !== null && typeof v === 'object'\n && ( Array.isArray( v ) || Object.getPrototypeOf( v ) === Object.prototype )\n\nconst isCollection = ( v: any ) =>\n v instanceof Map || v instanceof Set\n || !!( v && typeof v === 'object' && v[ COLLECTION_META ] )\n\n/**\n * Array mutators write several times (push sets an index AND length).\n * Run them atomically so one operation is one notification, not one per\n * internal write.\n */\nconst ARRAY_MUTATORS = new Set([ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin' ])\n/** Map/Set methods that mutate — each notifies once */\nconst COLLECTION_MUTATORS = new Set([ 'set', 'delete', 'clear', 'add' ])\n\n/**\n * Channel for \"which keys exist\" — subscribed by `ownKeys` (Object.keys,\n * Object.entries, `<for>` over an object) and fired when a key is added\n * or removed. Separate from the per-key channels, which only cover value\n * changes on keys that already exist.\n */\nconst KEYS = Symbol('lips.keys')\n\n/**\n * ONE proxy per raw object, shared across every deep store.\n *\n * The same object is commonly reachable from two stores — a parent's\n * `state.rows` and the child's `input.rows` are the same array. A\n * per-store registry would hand each a private proxy with private\n * channels, so a write through one would be invisible to the other.\n */\nconst OBJECT_PROXIES = new WeakMap<object, any>()\n\n/**\n * Map/Set proxies break internal-slot access ([[MapData]]), so\n * collections are wrapped by BINDING their methods to the target:\n * reads work natively; mutators notify. Values read out of the\n * collection are deep-wrapped in turn, so nested trees of Maps\n * (e.g. a recursive layers tree) stay reactive.\n */\nfunction wrapCollection( coll: any, touch: () => void ): any {\n /**\n * Identity-stable wrapping, for the same reason as OBJECT_PROXIES:\n * ONE proxy is reused and every interested store adds its notifier.\n */\n const existing: CollectionMeta | undefined = coll[ COLLECTION_META ]\n if( existing ){\n existing.notify.add( touch )\n return coll\n }\n\n const hit = COLLECTION_PROXIES.get( coll )\n if( hit ){\n ;( hit as any )[ COLLECTION_META ].notify.add( touch )\n return hit\n }\n\n const meta: CollectionMeta = { raw: coll, notify: new Set([ touch ]) }\n const notifyAll = () => meta.notify.forEach( fn => fn() )\n\n const proxy = new Proxy( coll, {\n get( t: any, k ){\n if( k === COLLECTION_META ) return meta\n\n // size and other data properties\n const v = ( t as any )[ k ]\n if( typeof v !== 'function' ) return v\n\n if( typeof k === 'string' && COLLECTION_MUTATORS.has( k ) )\n return ( ...args: any[] ) => {\n const result = v.apply( t, args )\n notifyAll()\n return result\n }\n\n /**\n * Readers hand out WRAPPED values. Iteration matters as much as\n * `get`: a `<for>` over a Map reads `entries()`, and an unwrapped\n * value there is an object nothing can track — its mutations would\n * be invisible now that a nested write no longer force-notifies\n * the whole collection.\n */\n const wrapVal = ( out: any ) =>\n isPlain( out ) ? deepWrap( out, notifyAll )\n : isCollection( out ) ? wrapCollection( out, notifyAll )\n : out\n\n const isMap = t instanceof Map\n\n if( k === 'get' ) return ( key: any ) => wrapVal( t.get( key ) )\n\n if( k === 'forEach' )\n return ( fn: any, thisArg?: any ) =>\n t.forEach( ( val: any, key: any ) => fn.call( thisArg, wrapVal( val ), key, proxy ) )\n\n if( k === 'values' || ( !isMap && ( k === 'keys' || k === Symbol.iterator ) ) )\n return function*(){ for( const val of t.values() ) yield wrapVal( val ) }\n\n if( k === 'entries' || ( isMap && k === Symbol.iterator ) )\n return isMap\n ? function*(){ for( const [ key, val ] of t.entries() ) yield [ key, wrapVal( val ) ] }\n : function*(){ for( const val of t.values() ) yield [ wrapVal( val ), wrapVal( val ) ] }\n\n return v.bind( t )\n }\n })\n\n COLLECTION_PROXIES.set( coll, proxy )\n return proxy\n}\n\n/**\n * Per-key channels for ONE nested object (RFC-004 follow-up).\n *\n * Each key gets its own subscription list, so `rows[3].x = v` notifies\n * exactly the bindings that read `rows[3].x` — not everything that read\n * `rows`. Previously every nested write force-notified the top key, and\n * the keyed `<for>` is one of its subscribers, so a single field write\n * re-ran the whole list: O(list) per write, O(N²) per animation frame.\n *\n * A channel is a signal used purely as a subscription list — reading\n * subscribes, touching notifies. The VALUE always comes from the target,\n * so the proxy and the underlying object can never diverge.\n */\nfunction nestedProxy( target: any ): any {\n const hit = OBJECT_PROXIES.get( target )\n if( hit ) return hit\n\n const chans = new Map<PropertyKey, ReturnType<typeof signal<number>>>()\n\n const track = ( k: PropertyKey ) => {\n let c = chans.get( k )\n if( !c ){\n c = signal( 0 )\n chans.set( k, c )\n }\n c[0]()\n }\n /** Fire only if someone actually subscribed — an unread key has no channel */\n const fire = ( k: PropertyKey ) => chans.get( k )?.[2]()\n\n /**\n * A STABLE notifier per key. Collections keep their subscribers in a\n * Set, so handing them a fresh closure on every read would grow that\n * Set without bound — one entry per read, never deduplicated.\n */\n const touches = new Map<PropertyKey, () => void>()\n const touchFor = ( k: PropertyKey ) => {\n let f = touches.get( k )\n if( !f ){\n f = () => fire( k )\n touches.set( k, f )\n }\n return f\n }\n /**\n * A structural change invalidates everything. Batched, so an effect\n * subscribed to many channels (a `<for>` reads length and every index)\n * runs ONCE rather than once per channel.\n */\n const fireAll = () => batch( () => { for( const c of chans.values() ) c[2]() })\n\n let muted = false\n\n const proxy = new Proxy( target, {\n get( t: any, k ){\n const v = t[ k ]\n\n // Symbols (Symbol.iterator, …) pass through untracked; the\n // iterator's own reads of length/indices are tracked below.\n if( typeof k === 'symbol' ) return v\n\n if( Array.isArray( t ) && ARRAY_MUTATORS.has( k ) && typeof v === 'function' )\n return ( ...args: any[] ) => {\n muted = true\n try { return v.apply( t, args ) }\n finally {\n muted = false\n fireAll()\n }\n }\n\n /**\n * Methods are returned unbound on purpose: `proxy.map(fn)` then\n * runs with `this` = proxy, so its internal length/index reads go\n * through this trap and subscribe.\n */\n if( typeof v === 'function' ) return v\n\n track( k )\n return isPlain( v ) || isCollection( v ) ? deepWrap( v, touchFor( k ) ) : v\n },\n set( t: any, k, v ){\n const had = k in t\n const prev = t[ k ]\n t[ k ] = v\n\n if( muted ) return true\n if( !Object.is( prev, v ) ) fire( k )\n /**\n * A new key changes the key set, and on an array it also moves\n * `length` — both are what iterators subscribed to.\n */\n if( !had ){\n fire( KEYS )\n Array.isArray( t ) && fire('length')\n }\n return true\n },\n deleteProperty( t: any, k ){\n const had = k in t\n delete t[ k ]\n\n if( !muted && had ){\n fire( k )\n fire( KEYS )\n }\n return true\n },\n has( t: any, k ){\n typeof k !== 'symbol' && track( k )\n return k in t\n },\n ownKeys( t: any ){\n track( KEYS )\n return Reflect.ownKeys( t )\n }\n })\n\n OBJECT_PROXIES.set( target, proxy )\n return proxy\n}\n\nfunction deepWrap( value: any, touch: () => void ): any {\n if( isCollection( value ) ) return wrapCollection( value, touch )\n if( !isPlain( value ) ) return value\n return nestedProxy( value )\n}\n\n/**\n * Per-key reactive facade over a plain object:\n * reading a key inside an effect subscribes to that key;\n * writing notifies only that key's subscribers.\n * Idempotent — wrapping a reactive object returns it as-is.\n *\n * Shallow by default (RFC-001 §6). `deep: true` opts into nested\n * mutation tracking: plain objects/arrays read through a key are lazily\n * given their OWN per-key channels (see `nestedProxy`), so a nested\n * write stays O(subscribers-of-that-key) rather than invalidating the\n * whole top-level key.\n */\nexport function reactive<T extends object>( obj: T, deep = false ): T {\n if( ( obj as any )[ IS_REACTIVE ] ) return obj\n\n const sigs = new Map<PropertyKey, [ () => any, ( v: any ) => void, () => void ]>()\n\n const sigFor = ( key: PropertyKey, initial: any ) => {\n let s = sigs.get( key )\n if( !s ){\n s = signal( initial )\n sigs.set( key, s )\n }\n return s\n }\n\n return new Proxy( obj, {\n get( target: any, key ){\n if( key === IS_REACTIVE ) return true\n if( typeof key === 'string' ){\n const s = sigFor( key, target[ key ] )\n return deep ? deepWrap( s[0](), s[2] ) : s[0]()\n }\n return target[ key ]\n },\n set( target: any, key, value ){\n const prev = target[ key ]\n target[ key ] = value\n\n if( typeof key !== 'string' ) return true\n\n const sig = sigFor( key, value )\n /**\n * Re-assigning the SAME collection is not a no-op: collections\n * mutate in place, so an unchanged reference can still hold new\n * contents (a parent's `.set()` reaching a child's input). The\n * signal's Object.is check would swallow it — touch instead.\n */\n Object.is( prev, value ) && isCollection( value )\n ? sig[2]()\n : sig[1]( value )\n\n return true\n },\n has( target, key ){ return key in target },\n deleteProperty( target: any, key ){\n delete target[ key ]\n typeof key === 'string' && sigs.get( key )?.[1]( undefined )\n return true\n }\n }) as T\n}\n",
|
|
7
|
+
"/**\n * The host seam (RFC-006 §4.1).\n *\n * The IR runtime never touches a node itself. It creates, places, walks\n * and mutates nodes through a `Host`, so one runtime drives the DOM, an\n * in-memory tree (`./tree`) or a native element API. The node type is\n * the host's own and opaque to the runtime.\n *\n * What a host must provide is what the runtime actually does with\n * nodes, no more:\n *\n * - instantiate a block's skeleton (`clone`), and create the few nodes\n * the runtime adds itself: markers, text runs, unresolved elements\n * - a sibling-linked tree with parents: block instances are ranges\n * between two markers, walked and moved whole (`range`, `insertAfter`)\n * - attributes, text, inline custom properties, listeners\n * - two host decisions: how a stylesheet scope marks an element\n * (`rel` here, a class on Lynx) and whether markup can be parsed\n * (`html` is optional — the `'tree'` compile target rejects `@html`)\n *\n * Stylesheet injection is not here: it already reaches the runtime as\n * `RuntimeOptions.createStylesheet`, supplied by the facade.\n */\n\nimport type { BlockIR } from './compiler'\n\nexport interface Host<N = any> {\n /** A detached container holding a fresh copy of the block's skeleton */\n clone( block: BlockIR ): N\n /** An empty detached container */\n fragment(): N\n element( tag: string ): N\n text( value: string ): N\n /** An invisible node: block boundaries and control-flow anchors */\n marker( label: string ): N\n\n /** The child at `index` — skeleton paths are child-index walks */\n child( parent: N, index: number ): N\n next( node: N ): N | null\n /** `first`, its following siblings, up to and including `last` */\n range( first: N, last: N ): N[]\n /** Insert `node` before `ref`, or at the end when `ref` is null */\n insert( parent: N, node: N, ref: N | null ): void\n /** Place `nodes`, in order, right after `ref` — nothing when `ref` has no parent */\n insertAfter( ref: N, nodes: N[] ): void\n /**\n * `gone`: the node will never be inserted again — the runtime is\n * destroying it, not moving it. A host may release what it holds for\n * it (the Lynx host frees its ids); the DOM has nothing to free.\n */\n remove( node: N, gone?: boolean ): void\n isElement( node: N ): boolean\n /** In the live tree — what `onAttach` waits for */\n connected( node: N ): boolean\n /** `a` comes before `b` in tree order; false when they share no tree */\n precedes( a: N, b: N ): boolean\n\n /** A text node's value — the hot path of every text bind */\n setText( node: N, value: string ): void\n /** Replace an element's children with one text run (`@text`, `@format`) */\n content( el: N, value: string ): void\n /** `null` removes the attribute */\n attr( el: N, name: string, value: string | null ): void\n /** Replace the element's children with parsed markup (`@html`) — DOM only */\n html?( el: N, value: string ): void\n /** Set an inline custom property, or remove it when `null` (RFC-004 §8) */\n styleVar( el: N, prop: string, value: string | null ): void\n /** Mark a component root with its stylesheet scope. An inner scope already set wins */\n scope( el: N, nsp: string ): void\n /** Returns the unlisten function */\n listen( el: N, name: string, fn: ( event: any ) => void ): () => void\n /** Capture focus before a swap moves nodes; the returned function restores it */\n keepFocus?(): () => void\n}\n\n// ---------------------------------------------------------------- DOM host\nconst SKELETONS = new WeakMap<BlockIR, HTMLTemplateElement>()\n\n/**\n * Today's behaviour, unchanged: skeletons parsed once per block into a\n * `<template>` and cloned per instance, scope stamped as `rel`.\n */\nexport const domHost: Host<Node> = {\n clone( block ){\n let tpl = SKELETONS.get( block )\n if( !tpl ){\n tpl = document.createElement('template')\n tpl.innerHTML = block.html\n SKELETONS.set( block, tpl )\n }\n return tpl.content.cloneNode( true )\n },\n fragment: () => document.createDocumentFragment(),\n element: tag => document.createElement( tag ),\n text: value => document.createTextNode( value ),\n marker: label => document.createComment( label ),\n\n child: ( parent, index ) => parent.childNodes[ index ],\n next: node => node.nextSibling,\n /**\n * Range walks and range moves are the hottest node work there is (a\n * keyed list walks every row's range on every change), so they are ONE\n * host call per range with the loop inside, not a host call per node.\n */\n range( first, last ){\n const out: Node[] = []\n for( let n: Node | null = first; n; n = n.nextSibling ){\n out.push( n )\n if( n === last ) break\n }\n return out\n },\n insert: ( parent, node, ref ) => { parent.insertBefore( node, ref ) },\n /**\n * The reference is re-read after every insert rather than captured\n * once: `nodes` may already contain `ref`'s next sibling, and a fixed\n * reference would put the rest of the range in front of it.\n */\n insertAfter( ref, nodes ){\n const parent = ref.parentNode\n if( !parent ) return\n let anchor = ref\n for( const n of nodes ){\n parent.insertBefore( n, anchor.nextSibling )\n anchor = n\n }\n },\n remove: node => ( node as ChildNode ).remove(),\n isElement: node => node.nodeType === 1,\n connected: node => node.isConnected,\n /**\n * Nodes in different trees compare as DISCONNECTED plus an arbitrary\n * but consistent order, so a range test `precedes( from, n ) &&\n * precedes( n, to )` still fails for them: one side always does.\n */\n precedes: ( a, b ) => !!( a.compareDocumentPosition( b ) & 4 /* FOLLOWING */ ),\n\n attr: ( el, name, value ) => value === null\n ? ( el as Element ).removeAttribute( name )\n : ( el as Element ).setAttribute( name, value ),\n /** `.data`: the direct write, as before the seam — no node-type dispatch */\n setText: ( node, value ) => { ( node as Text ).data = value },\n content: ( el, value ) => { el.textContent = value },\n html: ( el, value ) => { ( el as Element ).innerHTML = value },\n styleVar: ( el, prop, value ) => value === null\n ? ( el as HTMLElement ).style.removeProperty( prop )\n : ( el as HTMLElement ).style.setProperty( prop, value ),\n scope: ( el, nsp ) => { ( el as Element ).hasAttribute('rel') || ( el as Element ).setAttribute('rel', nsp ) },\n listen( el, name, fn ){\n el.addEventListener( name, fn )\n return () => el.removeEventListener( name, fn )\n },\n /**\n * Salvaged nodes are detached and re-inserted, which drops focus. The\n * element survives the move, so put the caret back where the user left it.\n */\n keepFocus(){\n const focused = document.activeElement as HTMLElement | null\n return () => { focused && focused.isConnected && focused !== document.activeElement && focused.focus() }\n }\n}\n",
|
|
8
|
+
"/**\n * The tags a reader of `tag` is served from, most specific first — RFC 4647\n * §3.4 Lookup: the tag, then each shorter prefix, a single-letter subtag\n * left at the end dropped with what followed it. `zh-Hant-TW` reads\n * `zh-Hant` before `zh`, so a script is never skipped for its language.\n *\n * It is the same chain AB's `lookupTags` walks for a translatable name, and\n * both are held to the RFC's own example, so a dictionary and a name stored\n * on the platform fall back the same way for the same reader.\n */\nexport function lookupTags( tag: string ): string[] {\n const\n subtags = tag.split('-'),\n tags: string[] = []\n\n while( subtags.length ){\n tags.push( subtags.join('-') )\n subtags.pop()\n subtags[ subtags.length - 1 ]?.length === 1 && subtags.pop()\n }\n return tags\n}\n\n/** A name said in more than one language: one text per language tag, and the one to fall back to. */\nexport type TranslatableName = {\n readonly default: string\n readonly names: Readonly<Record<string, string>>\n}\n\n/**\n * The text of `name` a reader of `lang` reads: the first tag of its lookup\n * chain the name has, matched whatever its casing, and the default text\n * when none is. What a template shows for a platform name, as `self.pick( … )`.\n */\nexport function pick( name: TranslatableName, lang: string ): string {\n const texts = new Map( Object.entries( name.names ).map( ([ tag, text ]) => [ tag.toLowerCase(), text ] ) )\n for( const tag of lookupTags( lang.toLowerCase() ) )\n if( texts.has( tag ) ) return texts.get( tag )!\n\n return name.names[ name.default ] ?? ''\n}\n",
|
|
9
|
+
"/**\n * Phase 2 — hot-swap support (RFC-001 §8)\n *\n * Structural IR comparison by EXPRESSION SOURCE: two compilations\n * of related templates produce different expression-table indices,\n * so equality must resolve every `E` through its own table before\n * comparing. These normalizers produce plain comparable shapes.\n */\n\nimport type { BlockIR, BindIR, ChildIR, CompInput } from './compiler'\n\nexport interface SwapChange {\n kind: 'skeleton' | 'binds' | 'block'\n /** Block-tree coordinates, e.g. 'root', 'root/2', 'root/2/0' */\n path: string\n}\nexport interface SwapReport {\n changes: SwapChange[]\n /**\n * Components carried through the swap instead of being remounted —\n * one entry per instance, by component name.\n */\n salvaged: string[]\n}\n\n// ------------------------------------------------------------- normalizers\nconst normInput = ( ci: CompInput | null | undefined, x: string[] ): any =>\n ci == null ? ci : 'e' in ci ? { $: x[ ci.e ] } : ci\n\nexport const normBind = ( b: BindIR, x: string[] ): any => ({ ...b, e: x[ b.e ] })\n\nexport function normChild( c: ChildIR, x: string[] ): any {\n switch( c.t ){\n case 'macro':\n return { t: c.t, name: c.name, args: c.args,\n sets: c.sets.map( s => 'spread' in s\n ? { spread: x[ s.spread ] }\n : { name: s.name, ci: normInput( s.ci, x ) } ),\n block: normBlock( c.block, x ) }\n case 'if':\n return { t: c.t, branches: c.branches.map( b => ({\n when: b.when == null ? null : x[ b.when ],\n block: normBlock( b.block, x )\n }) ) }\n case 'for':\n return {\n t: c.t, args: c.args,\n of: c.of === undefined ? undefined : x[ c.of ],\n from: normInput( c.from, x ), to: normInput( c.to, x ), by: normInput( c.by, x ),\n block: normBlock( c.block, x )\n }\n case 'switch':\n return { t: c.t, on: x[ c.on ], cases: c.cases.map( k => ({\n is: k.is === null ? null : normInput( k.is, x ),\n block: normBlock( k.block, x )\n }) ) }\n case 'async':\n return {\n t: c.t, awaitE: x[ c.awaitE ],\n then: c.then && { args: c.then.args, block: normBlock( c.then.block, x ) },\n catch: c.catch && { args: c.catch.args, block: normBlock( c.catch.block, x ) },\n loading: c.loading && normBlock( c.loading, x )\n }\n case 'let':\n return { t: c.t, const: c.const,\n vars: Object.fromEntries( Object.entries( c.vars ).map( ( [ k, v ] ) => [ k, normInput( v, x ) ] ) ) }\n case 'log':\n return { t: c.t, e: x[ c.e ] }\n case 'provide':\n return {\n t: c.t,\n vars: Object.fromEntries( Object.entries( c.vars ).map( ( [ k, v ] ) => [ k, normInput( v, x ) ] ) ),\n lang: normInput( c.lang, x ),\n block: normBlock( c.block, x )\n }\n case 'comp':\n case 'dynamic':\n return {\n t: c.t,\n name: c.t === 'comp' ? c.name : undefined,\n tag: c.t === 'dynamic' ? x[ c.tag ] : undefined,\n inputs: Object.fromEntries( Object.entries( c.inputs ).map( ( [ k, v ] ) => [ k, normInput( v, x ) ] ) ),\n spreads: c.spreads.map( e => x[ e ] ),\n events: c.events.map( ev => ({ name: ev.name, e: x[ ev.e ] }) ),\n contents: c.contents && { args: c.contents.args, block: normBlock( c.contents.block, x ) }\n }\n }\n}\n\nexport const normBlock = ( b: BlockIR, x: string[] ): any => ({\n html: b.html,\n scope: b.scope,\n binds: b.binds.map( bind => normBind( bind, x ) ),\n blocks: b.blocks.map( c => normChild( c, x ) )\n})\n\n// ------------------------------------------------------------- comparators\nexport const sameChild = ( a: ChildIR, ax: string[], b: ChildIR, bx: string[] ) =>\n a.t === b.t && JSON.stringify( normChild( a, ax ) ) === JSON.stringify( normChild( b, bx ) )\n\nexport const sameBinds = ( a: BindIR[], ax: string[], b: BindIR[], bx: string[] ) =>\n JSON.stringify( a.map( x => normBind( x, ax ) ) ) === JSON.stringify( b.map( x => normBind( x, bx ) ) )\n\nexport const sameLets = ( a: BlockIR, ax: string[], b: BlockIR, bx: string[] ) => {\n const lets = ( blk: BlockIR, x: string[] ) =>\n JSON.stringify( blk.blocks.filter( c => c.t === 'let' ).map( c => normChild( c, x ) ) )\n return lets( a, ax ) === lets( b, bx )\n}\n",
|
|
10
|
+
"/**\n * Phase 2 — IR runtime (RFC-001 §6, §8)\n *\n * TemplateIR → live nodes, through a `Host` (RFC-006 §4.1; the DOM\n * unless told otherwise):\n * - skeletons instantiated per use by the host (on the DOM: parsed\n * ONCE per block into <template>, then cloned) + a bind walk over\n * precomputed integer paths\n * - every bind is its own effect over per-key signals — updates are\n * O(changed bindings), no digest, no clones, no deep equality\n * - block instances are bracketed by owned comment markers so\n * control-flow content moves/disposes as a range\n * - dual expression modes over the same IR: 'compiled' (Function) /\n * 'interpreted' (AST walker, CSP-safe) — both for trusted templates;\n * an untrusted one runs through a `guard` instead (RFC-007)\n *\n * Hot-swap (§8): instances retain their structure (bind handles,\n * child handles, resolved path nodes) so `instance.swap( newIR )`\n * can diff old vs new by expression source and update surgically:\n * - identical subtrees → kept wholesale (zero DOM work)\n * - bind-only changes → effects rewired onto the SAME nodes\n * - skeleton changes → that block re-rendered in place\n * State lives outside the IR, so it survives by construction.\n */\n\nimport type { TemplateIR, BlockIR, BindIR, ChildIR, ArmIR, CompInput, E, Path } from './compiler'\nimport type { ExprEnv, Expr } from './expression'\nimport { parseExpression, compileExpression, interpretExpression, splitTopLevel } from './expression'\nimport { signal, effect, untrack, reactive } from './signal'\nimport type { SwapChange, SwapReport } from './swap'\nimport type { StyleIR } from './style'\nimport type { Host } from './host'\nimport { domHost } from './host'\nimport { pick, type TranslatableName } from '../i18n/lookup'\nimport { sameBinds, sameChild, sameLets } from './swap'\n\n// ------------------------------------------------------------------- types\nexport interface IRComponentDef {\n ir: TemplateIR\n state?: Record<string, any>\n statics?: Record<string, any>\n /** Context fields this component subscribes to (fires onContext) */\n context?: string[]\n /** Compiled stylesheet (RFC-004) + scope name (the `rel` value) */\n stylesheet?: StyleIR\n nsp?: string\n /** Deep-reactive component state (old-engine parity) */\n deep?: boolean\n /**\n * Methods bound to the component self — lifecycle keys\n * (onCreate/onInput/onMount/onDestroy) are invoked by the\n * runtime at the matching moments.\n */\n handlers?: Record<string, ( this: any, ...args: any[] ) => any>\n}\n\n/**\n * How an untrusted template's expressions run (RFC-007): `run` replaces\n * the executor, and `self` decides which members of the component a bare\n * handler name in an event instruction may reach. Built by `./policy`.\n */\nexport interface Guard {\n run( src: string ): ( env: ExprEnv ) => any\n /** A refusal (truthy) keeps the instruction off `self[ key ]` */\n self( key: string ): unknown\n}\n\nexport interface RuntimeOptions {\n mode?: 'compiled' | 'interpreted'\n /** Untrusted templates only — set by `new Lips({ untrusted })` */\n guard?: Guard\n /**\n * What the IR renders into (RFC-006 §4.1). Defaults to the DOM. A host\n * that builds nodes one by one (`treeHost` in `./tree`) needs IR compiled\n * with `{ target: 'tree' }`, which carries the node tree it builds from.\n */\n host?: Host\n components?: Record<string, IRComponentDef>\n /**\n * Resolve a plain template object (e.g. a route's `template`)\n * into a component definition — the host owns compilation and\n * caching. Enables `<{state.page}/>` with template objects.\n */\n resolveTemplate?( value: any ): IRComponentDef | undefined\n /** Extra members merged onto every component's self (e.g. setContext) */\n expose?: Record<string, any>\n /**\n * Host-provided stylesheet injector (full build wires Stylis; the\n * precompiled `./runtime` build omits it). Returns a handle whose\n * `clear()` releases one reference.\n */\n createStylesheet?( nsp: string, css: string ): { clear(): void }\n /**\n * i18n plugin hook (RFC §6). Every call must READ a language signal\n * so translated binds re-run on language change — including `lang()`,\n * which is what makes `<span text=self.lang>` live.\n *\n * `key` is a STABLE translation id (RFC-005 §3): given one, the\n * dictionary is consulted for it first and `text` is only the\n * fallback wording. `lang` overrides the active language for one\n * call — how `<i18n lang=…>` translates its subtree.\n */\n i18n?: {\n translate( text: string, key?: string, lang?: string ): string\n format( reference: string, params: any, lang?: string ): string\n /** Active language, read reactively */\n lang(): string\n }\n}\n\nexport interface RenderSetup {\n state?: Record<string, any>\n input?: Record<string, any>\n context?: Record<string, any>\n static?: Record<string, any>\n handlers?: Record<string, ( this: any, ...args: any[] ) => any>\n /** Deep-reactive root state (old-engine parity) */\n deep?: boolean\n /** Extra members merged onto self before handlers bind (e.g. emit) */\n expose?: Record<string, any>\n /** Compiled stylesheet (RFC-004) + scope name (the `rel` value) */\n stylesheet?: StyleIR\n nsp?: string\n}\n\n/** `N` is the host's node type — `Node` on the DOM */\nexport interface IRInstance<N = Node> {\n state: Record<string, any>\n self: Record<string, any>\n nodes: N[]\n mount( container: N ): void\n swap( newIR: TemplateIR ): SwapReport\n dispose(): void\n}\n\ntype RunEnv = ExprEnv\n\n/** A host node — opaque to the runtime */\ntype N = any\n\ninterface BindHandle {\n bind: BindIR\n node: N\n textNode?: N\n dispose: () => void\n}\ninterface ChildHandle {\n child: ChildIR\n exprs: string[]\n anchor: N\n dispose: () => void\n}\n\n/**\n * A live component instance, tracked so a swap can re-home it\n * instead of destroying and recreating it (RFC-002 §salvage).\n *\n * `gen` is the ownership token: whoever wired the instance captures\n * the current value, and only a holder of the current token may tear\n * it down. Releasing a component into a salvage pass bumps `gen`, so\n * the old parent's disposal walks straight past it.\n */\ninterface LiveComp {\n name: string\n /** Explicit `key` input — identity across revisions, when given */\n key: any\n self: any\n input: Record<string, any>\n inst: BlockInstance\n /** Anchor of the child that currently owns it */\n anchor: N\n /** Parent-side wiring: input effects + event listeners */\n wiring: ( () => void )[]\n gen: number\n claimed: boolean\n teardown(): void\n}\n\n/** A rendered block: bracketed range + retained structure for swap */\ninterface BlockInstance {\n start: N\n end: N\n block: BlockIR\n exprs: string[]\n penv: RunEnv // parent env (for full re-render)\n benv: RunEnv // env with this block's scope layer\n pathNodes: Map<string, N> // pathKey → resolved node (binds + anchors)\n bindHandles: BindHandle[]\n childHandles: ChildHandle[]\n}\n\n// ----------------------------------------------------------------- helpers\n/** Marks a slot renderer handed to a child as `input.renderer` */\nconst SLOT = Symbol('lips.slot')\n\ninterface SlotRenderer {\n [ SLOT ]: true\n args: string[]\n render( argvalues?: Record<string, any> ): BlockInstance\n}\nconst isSlot = ( v: any ): v is SlotRenderer => !!v && typeof v === 'object' && v[ SLOT ] === true\n\n/**\n * Component lifecycle plumbing (RFC §6: ownership events, not\n * document-wide observation). One hooks object per component\n * instance; nested components get their own.\n */\ninterface ComponentHooks {\n notifyUpdate(): void\n onError( error: unknown ): void\n /** Called once the component's first render completes */\n ready(): void\n}\n\nfunction makeHooks( self: any ): ComponentHooks {\n let scheduled = false\n let isReady = false\n\n const onError = ( error: unknown ) =>\n typeof self.onError === 'function'\n ? self.onError( error )\n : console.error('[lips:ir]', error )\n\n return {\n onError,\n ready(){ isReady = true },\n notifyUpdate(){\n // Suppress during the initial render pass\n if( !isReady || scheduled ) return\n scheduled = true\n\n /**\n * A promise job, not `queueMicrotask`: Lynx's native background\n * engine has no `queueMicrotask`, and this runs outside the effect's\n * error guard, so a throw here aborted the effects after it.\n */\n Promise.resolve().then( () => {\n scheduled = false\n try {\n typeof self.onUpdate === 'function' && self.onUpdate()\n typeof self.onRender === 'function' && self.onRender()\n }\n catch( error ){ onError( error ) }\n })\n }\n }\n}\n\n/**\n * Attach callbacks queued during render, flushed once the nodes\n * are actually in the document (root mount, or immediate when the\n * insertion point is already live).\n */\nconst PENDING_ATTACH: { live: () => boolean, fn: () => void }[] = []\n\n/**\n * `entry.fn()` runs `onAttach`, and an `onAttach` may RENDER — that is\n * exactly what `<router>` does when it navigates on attach. Rendering\n * appends new entries here, and rendering under an already-live parent\n * re-enters this function, so the array mutates arbitrarily mid-pass.\n *\n * Walking it by index is unsound in both directions:\n * - an index outlives a shrunken array → `PENDING_ATTACH[i]` is\n * undefined and the flush throws\n * - entries appended during the pass sit below the descending index →\n * their `onAttach` silently never fires\n *\n * So drain by IDENTITY over a snapshot, and repeat while a pass settles\n * anything. Reverse order is preserved: a component pushes after the\n * children rendered inside it, so walking back attaches parents first.\n */\nfunction flushAttach(){\n let progressed = true\n\n while( progressed ){\n progressed = false\n\n for( const entry of [ ...PENDING_ATTACH ].reverse() ){\n if( !entry.live() ) continue\n\n // A re-entrant pass may have claimed it already\n const at = PENDING_ATTACH.indexOf( entry )\n if( at < 0 ) continue\n\n PENDING_ATTACH.splice( at, 1 )\n entry.fn()\n progressed = true\n }\n }\n}\n\nconst AST_CACHE = new Map<string, Expr>()\nfunction astOf( src: string ): Expr {\n let ast = AST_CACHE.get( src )\n if( !ast ){\n ast = parseExpression( src ).ast\n AST_CACHE.set( src, ast )\n }\n return ast\n}\n\nconst pathKey = ( p: Path ) => p.join(',')\n\nfunction resolvePath( h: Host, root: N, p: Path ): N {\n let node = root\n for( const i of p ) node = h.child( node, i )\n return node\n}\n\nconst nodesOf = ( h: Host, inst: BlockInstance ): N[] => h.range( inst.start, inst.end )\n/**\n * Does `n` sit between two markers in document order? Position, not\n * ancestry — a component nested deep in the skeleton's markup still\n * counts, which is what makes a region-wide sweep possible. Nodes in\n * another tree compare as disconnected, so both bits fail.\n */\nconst within = ( h: Host, from: N, to: N, n: N ) =>\n n === from // a child's own component is anchored on the marker itself\n || ( h.precedes( from, n ) && h.precedes( n, to ) )\n\n/**\n * Hand a live component to a salvage pass: its old owner loses the\n * right to destroy it, and its nodes are parked in a fragment. The\n * parking matters — an enclosing block that disposes before the\n * adoption runs would otherwise sweep those nodes out of the DOM\n * along with its own range.\n */\nfunction release( h: Host, rec: LiveComp ){\n rec.gen++\n for( const d of rec.wiring ) d()\n rec.wiring = []\n const park = h.fragment()\n for( const n of nodesOf( h, rec.inst ) ) h.insert( park, n, null )\n}\n\n/** Put a rendered block's range right after `ref` */\nfunction place( h: Host, ref: N, inst: BlockInstance ){\n h.insertAfter( ref, nodesOf( h, inst ) )\n return inst\n}\n\n/** The element roots a scoped sheet matches, and its variables live on */\nconst scopeRoots = ( h: Host, inst: BlockInstance ) => nodesOf( h, inst ).filter( n => h.isElement( n ) )\n\n/**\n * Scoped stylesheet: mark the component's top-level element roots with\n * the scope so the injected sheet matches — on the DOM `rel=\"<nsp>\"` for\n * `[rel=\"<nsp>\"] { … }`, where an inner component's scope wins on a\n * shared root (the host decides, RFC-006 §4.1).\n */\nfunction stampScope( h: Host, inst: BlockInstance, nsp: string ){\n for( const n of scopeRoots( h, inst ) ) h.scope( n, nsp )\n}\n\n/**\n * RFC-004 §8 — write a reactive declaration's custom property on the\n * scope roots. Every element the sheet matches is a root or a descendant,\n * and custom properties inherit (an inline one applying to the element\n * itself as well), so one write per root covers every match.\n *\n * A nullish value REMOVES the property rather than blanking it, so the\n * declaration falls through to an ancestor's value — that is what makes\n * \"use mine if given, otherwise inherit\" free (RFC-004 §7.3, §12.2).\n */\nfunction writeStyleVar( h: Host, roots: N[], prop: string, value: any, unit = '' ){\n for( const root of roots )\n h.styleVar( root, prop, value === null || value === undefined || value === false ? null : value + unit )\n}\n\n/** Stamp the scope, then inject via the facade's factory. Returns a clear disposer */\nfunction applyScopedStyles(\n h: Host,\n options: RuntimeOptions,\n inst: BlockInstance,\n nsp: string,\n style: StyleIR\n): ( () => void ) | undefined {\n stampScope( h, inst, nsp )\n\n const sheet = style.css ? options.createStylesheet?.( nsp, style.css ) : undefined\n return sheet ? () => sheet.clear() : undefined\n}\nfunction disposeInstance( inst: BlockInstance ){\n for( const h of inst.bindHandles ) h.dispose()\n for( const h of inst.childHandles ) h.dispose()\n}\nfunction destroy( h: Host, inst: BlockInstance | null ){\n if( !inst ) return\n disposeInstance( inst )\n for( const n of nodesOf( h, inst ) ) h.remove( n, true )\n}\n\nconst applyAttr = ( h: Host, el: N, name: string, v: any ) =>\n h.attr( el, name, v === false || v == null ? null : v === true ? '' : String( v ) )\n\nconst defineGetter = ( scope: any, name: string, get: () => any ) =>\n Object.defineProperty( scope, name, { get, enumerable: true, configurable: true } )\n\n/**\n * Marks a component `self`. A guard needs to tell it apart from data: the\n * policy has its own rules for members of `self` (RFC-007 §5.2).\n */\nexport const SELF = Symbol.for('lips.self') // registered: `./untrusted` is a bundle of its own, and asks for it by name\n\n/** Marks a `<context>` layer and carries its owned-key setters */\nconst LAYER = Symbol('lips.ctx.layer')\n\n/**\n * Write a context key to the nearest enclosing `<context>` layer that\n * declares it, falling back to the global store.\n *\n * The walk is over the prototype chain the layers already form, so\n * ownership needs no registry: a layer owns exactly the keys it wrote\n * into its own `LAYER` map, and both vanish when the block is disposed.\n * `global` is the host's setter — reached when no layer claims the key,\n * which is every write in a tree with no providers.\n */\nfunction writeContext( ctx: any, key: string, value: any, global?: ( k: string, v: any ) => void ){\n for( let o = ctx; o; o = Object.getPrototypeOf( o ) ){\n const owned: Map<string, ( v: any ) => void> | undefined = o[ LAYER ]\n const set = owned?.get( key )\n if( set ){ set( value ); return }\n }\n global?.( key, value )\n}\n\n/**\n * The half of `self` that is identical for a root and a nested\n * component: the live-node view, the language getter, and the event bus.\n * Both selves carried their own byte-identical copy of these six\n * members, in every bundle.\n *\n * Handed back as a PROTOTYPE rather than something to spread — `node`\n * and `lang` are getters, and a spread (or Object.assign) would evaluate\n * them once and freeze the result. Own properties still shadow it, so\n * the host's `expose` and a template's handlers keep winning.\n */\nfunction selfBus( h: Host, langOf: () => string ){\n const listeners = new Map<string, ( ( ...args: any[] ) => void )[]>()\n const fire = ( event: string, ...args: any[] ) => listeners.get( event )?.forEach( fn => fn( ...args ) )\n\n let self: any\n let instOf: () => BlockInstance | null = () => null\n\n const proto = {\n [ SELF ]: true,\n /**\n * Live element nodes — the handle external controls (drag/resize/\n * sort) bind to. Elements only: comment boundaries are an\n * implementation detail.\n */\n get node(){\n const inst = instOf()\n return inst ? scopeRoots( h, inst ) : []\n },\n /** Active language, read reactively — scoped when under `<i18n lang=…>` */\n get lang(){ return langOf() },\n /** A translatable name's text in the active language, by the same lookup as dictionaries */\n pick: ( name: TranslatableName ) => pick( name, langOf() ),\n emit: fire,\n /** Always the runtime-local bus — a host `emit` chains into it */\n emitLocal: fire,\n on( event: string, fn: ( ...args: any[] ) => void ){\n listeners.set( event, [ ...( listeners.get( event ) || [] ), fn ])\n return self\n },\n once( event: string, fn: ( ...args: any[] ) => void ){\n const wrapped = ( ...args: any[] ) => {\n self.off( event, wrapped )\n fn( ...args )\n }\n return self.on( event, wrapped )\n },\n off( event: string, fn?: ( ...args: any[] ) => void ){\n if( !fn ) listeners.delete( event )\n else {\n const rest = ( listeners.get( event ) || [] ).filter( f => f !== fn )\n rest.length ? listeners.set( event, rest ) : listeners.delete( event )\n }\n return self\n }\n }\n\n /** Adopt the finished self and tell the bus where its nodes live */\n const bind = ( owner: any, inst: () => BlockInstance | null ) => {\n self = owner\n instOf = inst\n return owner\n }\n return { proto, bind }\n}\n\n// ---------------------------------------------------------------- renderer\nclass IRRenderer {\n constructor(\n readonly ir: TemplateIR,\n private options: RuntimeOptions,\n private hooks?: ComponentHooks,\n /**\n * Components alive under this renderer. A swap builds a new\n * renderer over the new IR and inherits this array, so the\n * instances outlive the IR that first rendered them.\n */\n readonly live: LiveComp[] = []\n ){\n this.h = options.host || domHost\n }\n\n /** Every node operation goes through here (RFC-006 §4.1) */\n readonly h: Host\n\n /** Records offered to the render pass currently running, if any */\n private pool: LiveComp[] | null = null\n /** Names salvaged during this renderer's lifetime (read by swap) */\n readonly salvaged: string[] = []\n\n /**\n * Render with `records` offered for adoption. Whatever nobody\n * claims is destroyed for real once the pass ends — so a component\n * the revision dropped still runs its teardown.\n */\n private withSalvage<T>( records: LiveComp[], fn: () => T ): T {\n const prev = this.pool\n this.pool = records\n try { return fn() }\n finally {\n this.pool = prev\n for( const r of records ) !r.claimed && r.teardown()\n }\n }\n\n /**\n * Take the record belonging to this call site. An explicit `key`\n * is identity; without one, position among same-name components\n * decides — the rule keyless JSX lists already follow.\n */\n private claim( name: string, key: any ): LiveComp | undefined {\n const rec = this.pool?.find( r => !r.claimed && r.name === name && r.key === key )\n if( !rec ) return\n\n rec.claimed = true\n this.salvaged.push( name )\n return rec\n }\n\n /** The `key` input, evaluated off the dependency graph */\n private keyOf( inputs: Record<string, CompInput>, benv: RunEnv, scopeNames: string[] ){\n const ci = inputs.key\n return ci === undefined\n ? undefined\n : 'lit' in ci ? ci.lit : untrack( () => this.runner( ci.e, scopeNames )( benv ) )\n }\n\n /**\n * Bind effects run inside the component's error boundary and\n * report post-initial re-runs as component updates.\n */\n private guarded( fn: () => void ){\n let first = true\n return effect( () => {\n try { fn() }\n catch( error ){\n this.hooks ? this.hooks.onError( error ) : console.error('[lips:ir]', error )\n }\n first ? first = false : this.hooks?.notifyUpdate()\n })\n }\n\n /**\n * RFC-004 §8 — wire a compiled stylesheet's reactive declarations.\n * These are ordinary binds: same guarded() effect, same dispose handle,\n * same onError boundary. No parallel reactive system.\n *\n * Roots are captured here, so a rebuild must re-bind (see swap()).\n */\n bindStyle( style: StyleIR, inst: BlockInstance, env: RunEnv ): () => void {\n if( !style.binds.length ) return () => {}\n\n const\n roots = scopeRoots( this.h, inst ),\n handles = style.binds.map( b => {\n const run = this.srcRunner( style.exprs[ b.e ], [] )\n return this.guarded( () => writeStyleVar( this.h, roots, b.prop, run( env ), b.u ) )\n })\n\n return () => { for( const h of handles ) h.dispose() }\n }\n\n /** Expression runner for a table entry, honoring the execution mode */\n private runner( e: E, scopeNames: string[] ): ( env: RunEnv ) => any {\n return this.srcRunner( this.ir.exprs[ e ], scopeNames )\n }\n private srcRunner( src: string, scopeNames: string[] ): ( env: RunEnv ) => any {\n if( this.options.guard ) return this.options.guard.run( src )\n if( this.options.mode === 'interpreted' ){\n const ast = astOf( src )\n return env => interpretExpression( ast, env )\n }\n const compiled = compileExpression( src, scopeNames )\n return env => compiled.run( env )\n }\n\n renderBlock( block: BlockIR, env: RunEnv ): BlockInstance {\n const\n h = this.h,\n frag = h.clone( block )\n\n /**\n * Resolve every bind/anchor path BEFORE any mutation —\n * runtime insertions (text nodes, markers, arm content)\n * shift childNodes indices.\n */\n const pathNodes = new Map<string, N>()\n const bindNodes = block.binds.map( b => {\n const node = resolvePath( h, frag, b.p )\n pathNodes.set( pathKey( b.p ), node )\n return node\n })\n const anchorNodes = block.blocks.map( b => {\n const node = resolvePath( h, frag, b.p )\n pathNodes.set( pathKey( b.p ), node )\n return node\n })\n\n /**\n * Bracket the block content as an owned range. `end` goes in first\n * so the container is never empty when `start` looks for its first\n * child.\n */\n const start = h.marker('^')\n const end = h.marker('$')\n h.insert( frag, end, null )\n h.insert( frag, start, h.child( frag, 0 ) )\n\n // Scope chain for this block\n const scope = Object.create( env.scope ?? null )\n const benv: RunEnv = { ...env, scope }\n\n const inst: BlockInstance = {\n start, end, block,\n exprs: this.ir.exprs,\n penv: env, benv,\n pathNodes,\n bindHandles: [],\n childHandles: []\n }\n\n /**\n * <let>/<const> pass first — their names are visible to\n * every bind of this block (RFC decision #1)\n */\n block.blocks.forEach( ( child, i ) => {\n if( child.t !== 'let' ) return\n\n const letDisposers: ( () => void )[] = []\n for( const [ name, input ] of Object.entries( child.vars ) ){\n if( 'lit' in input ){\n const [ get ] = signal( input.lit )\n defineGetter( scope, name, get )\n }\n else {\n const [ get, set ] = signal<any>( undefined )\n defineGetter( scope, name, get )\n const run = this.runner( input.e, block.scope )\n letDisposers.push( effect( () => set( run( benv ) ) ).dispose )\n }\n }\n\n inst.childHandles[ i ] = {\n child, exprs: this.ir.exprs, anchor: anchorNodes[ i ],\n dispose: () => letDisposers.forEach( d => d() )\n }\n })\n\n // Binds — one effect each\n inst.bindHandles = block.binds.map( ( bind, i ) =>\n this.bindOne( bind, bindNodes[ i ], benv, block.scope ) )\n\n // Control-flow / component blocks\n block.blocks.forEach( ( child, i ) => {\n if( child.t === 'let' ) return\n inst.childHandles[ i ] = {\n child, exprs: this.ir.exprs, anchor: anchorNodes[ i ],\n dispose: this.execBlock( child, anchorNodes[ i ], benv, block.scope )\n }\n })\n\n return inst\n }\n\n /** Wire one bind onto its node; returns a swap-capable handle */\n private bindOne( bind: BindIR, node: N, benv: RunEnv, scopeNames: string[], reuseText?: N ): BindHandle {\n const h = this.h\n\n switch( bind.t ){\n case 'text': {\n const textNode = reuseText ?? h.text('')\n !reuseText && h.insertAfter( node, [ textNode ] )\n const run = this.runner( bind.e, scopeNames )\n const i18n = bind.i18n ? this.options.i18n : undefined\n const eff = this.guarded( () => {\n const v = run( benv )\n const text = v == null ? '' : String( v )\n h.setText( textNode, i18n ? i18n.translate( text, bind.ik, benv.lang?.() ) : text )\n })\n return { bind, node, textNode, dispose: eff.dispose }\n }\n case 'attr': {\n const run = this.runner( bind.e, scopeNames )\n const i18n = bind.i18n ? this.options.i18n : undefined\n const eff = this.guarded( () => {\n const v = run( benv )\n applyAttr( h, node, bind.name,\n i18n && v != null ? i18n.translate( String( v ), bind.ik, benv.lang?.() ) : v )\n })\n return { bind, node, dispose: eff.dispose }\n }\n case 'prop': {\n const run = this.runner( bind.e, scopeNames )\n\n if( bind.name === 'format' ){\n const ref = bind.ref || ''\n const eff = this.guarded( () => {\n const params = run( benv )\n const text = this.options.i18n?.format( ref, params, benv.lang?.() )\n h.content( node, text == null ? '' : String( text ) )\n })\n return { bind, node, dispose: eff.dispose }\n }\n\n const eff = this.guarded( () => {\n const v = run( benv )\n const s = v == null ? '' : String( v )\n /**\n * 'text' | 'format' — format is the i18n plugin hook (Phase 3).\n * A host with no HTML parser renders `@html` as text: the\n * `'tree'` target already reported it (LIPS-C021), and text is\n * the reading that can never inject anything.\n */\n bind.name === 'html' && h.html ? h.html( node, s ) : h.content( node, s )\n })\n return { bind, node, dispose: eff.dispose }\n }\n case 'event': {\n const handler = this.eventDispatcher( this.ir.exprs[ bind.e ], scopeNames, benv )\n return { bind, node, dispose: h.listen( node, bind.name, handler ) }\n }\n case 'spread': {\n const run = this.runner( bind.e, scopeNames )\n let prev = new Set<string>()\n const eff = this.guarded( () => {\n const obj = run( benv ) || {}\n const next = new Set<string>( Object.keys( obj ) )\n for( const k of prev ) !next.has( k ) && h.attr( node, k, null )\n for( const k of next ) applyAttr( h, node, k, obj[ k ] )\n prev = next\n })\n return { bind, node, dispose: eff.dispose }\n }\n }\n }\n\n // ----------------------------------------------------------------- swap\n /**\n * Diff-and-patch a live block against a new BlockIR (whose E\n * indices refer to THIS renderer's expression table). Returns\n * the live instance — a fresh one when a rebuild was needed.\n */\n swapBlock( inst: BlockInstance, newBlock: BlockIR, report: SwapChange[], path: string ): BlockInstance {\n /**\n * Structural rebuild triggers: skeleton, scope shape, or\n * let wiring changed — re-render this block in place.\n * (Worst case equals a fresh render — never worse.)\n */\n if( inst.block.html !== newBlock.html\n || JSON.stringify( inst.block.scope ) !== JSON.stringify( newBlock.scope )\n || !sameLets( inst.block, inst.exprs, newBlock, this.ir.exprs ) )\n return this.rebuild( inst, newBlock, report, path )\n\n // Bind-only changes: rewire effects onto the SAME nodes\n if( !sameBinds( inst.block.binds, inst.exprs, newBlock.binds, this.ir.exprs ) ){\n const nodes = newBlock.binds.map( b => inst.pathNodes.get( pathKey( b.p ) ) )\n\n // A bind on a path we never resolved → degrade to rebuild\n if( nodes.some( n => !n ) )\n return this.rebuild( inst, newBlock, report, path )\n\n const oldTexts = new Map<string, N>()\n inst.bindHandles.forEach( h => h.textNode && oldTexts.set( pathKey( h.bind.p ), h.textNode ) )\n inst.bindHandles.forEach( h => h.dispose() )\n\n const reused = new Set<string>()\n inst.bindHandles = newBlock.binds.map( ( b, i ) => {\n const key = pathKey( b.p )\n const reuse = b.t === 'text' ? oldTexts.get( key ) : undefined\n reuse && reused.add( key )\n return this.bindOne( b, nodes[ i ]!, inst.benv, newBlock.scope, reuse )\n })\n // Text nodes whose bind disappeared\n oldTexts.forEach( ( tn, key ) => !reused.has( key ) && this.h.remove( tn, true ) )\n\n report.push({ kind: 'binds', path })\n }\n\n /**\n * Children pairwise (equal html ⇒ equal anchor count):\n * identical-by-source subtrees are kept wholesale; changed\n * subtrees re-execute at their existing anchor.\n */\n for( let i = 0; i < newBlock.blocks.length; i++ ){\n const newChild = newBlock.blocks[ i ]\n const oldH = inst.childHandles[ i ]\n if( newChild.t === 'let' ) continue // covered by sameLets above\n\n if( oldH && sameChild( oldH.child, oldH.exprs, newChild, this.ir.exprs ) ) continue\n\n /**\n * Components this child rendered survive its re-execution.\n * The sweep spans the child's whole region, not just its own\n * anchor: a custom tag like `<mblock>` is itself a child, and\n * everything the template puts inside it lives under there.\n */\n const records = this.live.filter( r =>\n within( this.h, oldH.anchor, inst.childHandles[ i + 1 ]?.anchor ?? inst.end, r.anchor ) )\n for( const r of records ) release( this.h, r )\n\n oldH?.dispose()\n inst.childHandles[ i ] = {\n child: newChild, exprs: this.ir.exprs, anchor: oldH.anchor,\n dispose: this.withSalvage( records,\n () => this.execBlock( newChild, oldH.anchor, inst.benv, newBlock.scope ) )\n }\n report.push({ kind: 'block', path: `${path}/${i}` })\n }\n\n inst.block = newBlock\n inst.exprs = this.ir.exprs\n return inst\n }\n\n private rebuild( inst: BlockInstance, newBlock: BlockIR, report: SwapChange[], path: string ): BlockInstance {\n /**\n * Salvage: every component living in the region about to be\n * rebuilt is released from it first and offered to the fresh\n * render. What the revision still wants keeps its state and its\n * DOM subtree; what it dropped is destroyed by `withSalvage`.\n */\n const records = this.live.filter( r => within( this.h, inst.start, inst.end, r.anchor ) )\n for( const r of records ) release( this.h, r )\n\n const fresh = this.withSalvage( records, () => this.renderBlock( newBlock, inst.penv ) )\n\n place( this.h, inst.end, fresh )\n destroy( this.h, inst )\n report.push({ kind: 'skeleton', path })\n return fresh\n }\n\n // -------------------------------------------------------------- executors\n /** Execute a control-flow/component block; returns its disposer */\n private execBlock( child: ChildIR, anchor: N, benv: RunEnv, scopeNames: string[] ): () => void {\n const\n h = this.h,\n disposers: ( () => void )[] = []\n\n switch( child.t ){\n case 'if': {\n const runs = child.branches.map( b => b.when != null ? this.runner( b.when, scopeNames ) : null )\n let current: BlockInstance | null = null\n let activeIdx = -2\n\n const eff = effect( () => {\n let idx = -1\n for( let i = 0; i < child.branches.length; i++ ){\n const run = runs[ i ]\n if( !run || run( benv ) ){ idx = i; break }\n }\n if( idx === activeIdx ) return\n activeIdx = idx\n\n untrack( () => {\n destroy( h, current )\n current = null\n if( idx >= 0 ){\n current = place( h, anchor, this.renderBlock( child.branches[ idx ].block, benv ) )\n }\n })\n })\n\n disposers.push( () => { eff.dispose(); destroy( h, current ) } )\n break\n }\n\n case 'switch': {\n const onRun = this.runner( child.on, scopeNames )\n const caseRuns = child.cases.map( c =>\n c.is && 'e' in c.is ? this.runner( c.is.e, scopeNames ) : null )\n let current: BlockInstance | null = null\n let activeIdx = -2\n\n const eff = effect( () => {\n const value = onRun( benv )\n let idx = -1, defaultIdx = -1\n\n for( let i = 0; i < child.cases.length; i++ ){\n const c = child.cases[ i ]\n if( c.is === null ){ defaultIdx = i; continue }\n\n const is = 'lit' in c.is ? c.is.lit : caseRuns[ i ]!( benv )\n if( Array.isArray( is ) ? is.includes( value ) : is === value ){ idx = i; break }\n }\n if( idx === -1 ) idx = defaultIdx\n if( idx === activeIdx ) return\n activeIdx = idx\n\n untrack( () => {\n destroy( h, current )\n current = null\n if( idx >= 0 ){\n current = place( h, anchor, this.renderBlock( child.cases[ idx ].block, benv ) )\n }\n })\n })\n\n disposers.push( () => { eff.dispose(); destroy( h, current ) } )\n break\n }\n\n case 'macro': {\n /**\n * Inlined macro body: declared argv become block-scoped\n * reactive vars; every call-site attribute also lands in\n * `arguments` (per-key reactive, so `arguments.x` binds\n * track only that key).\n *\n * `sets` apply in SOURCE ORDER — spreads (`...each`) and\n * explicit attrs override each other left to right, JS\n * object-literal style.\n */\n const scope = Object.create( benv.scope ?? null )\n const args = reactive( {} as Record<string, any> )\n\n // One signal per declared argv (undeclared → stays undefined)\n const argSignals: Record<string, ReturnType<typeof signal<any>>> = {}\n for( const name of child.args ){\n argSignals[ name ] = signal<any>( undefined )\n defineGetter( scope, name, argSignals[ name ][0] )\n }\n\n type SetRunner =\n | { kind: 'spread', run: ( env: RunEnv ) => any }\n | { kind: 'value', name: string, value: () => any }\n\n const runners: SetRunner[] = child.sets.map( s => {\n if( 'spread' in s )\n return { kind: 'spread', run: this.runner( s.spread, scopeNames ) }\n\n if( 'lit' in s.ci ){\n const lit = s.ci.lit\n return { kind: 'value', name: s.name, value: () => lit }\n }\n\n const run = this.runner( s.ci.e, scopeNames )\n return { kind: 'value', name: s.name, value: () => run( benv ) }\n })\n\n let prevKeys = new Set<string>()\n\n disposers.push( effect( () => {\n // Evaluate every set in order into one flat view\n const next: Record<string, any> = {}\n\n for( const r of runners ){\n if( r.kind === 'spread' ){\n const obj = r.run( benv )\n if( obj && typeof obj === 'object' )\n for( const [ k, v ] of ( obj instanceof Map ? obj : Object.entries( obj ) ) )\n next[ k ] = v\n }\n else next[ r.name ] = r.value()\n }\n\n untrack( () => {\n // Feed declared argv signals (Object.is skips no-ops)\n for( const name of child.args )\n argSignals[ name ][1]( next[ name ] )\n\n // Mirror everything into `arguments`; drop vanished keys\n const nextKeys = new Set( Object.keys( next ) )\n for( const k of prevKeys ) !nextKeys.has( k ) && delete args[ k ]\n for( const k of nextKeys ) args[ k ] = next[ k ]\n prevKeys = nextKeys\n })\n }).dispose )\n\n const inst = place( h, anchor, this.renderBlock( child.block, { ...benv, arguments: args, scope }) )\n disposers.push( () => destroy( h, inst ) )\n break\n }\n\n case 'for':\n this.execFor( child, anchor, benv, scopeNames, disposers )\n break\n\n case 'async': {\n const awaitRun = this.runner( child.awaitE, scopeNames )\n let current: BlockInstance | null = null\n let token = 0\n\n const swapTo = ( arm: { args: string[], block: BlockIR } | BlockIR | undefined, value?: any ) => {\n destroy( h, current )\n current = null\n if( !arm ) return\n\n const isArm = 'block' in arm\n const scope2 = Object.create( benv.scope ?? null )\n if( isArm && arm.args[0] !== undefined ){\n const [ get ] = signal( value )\n defineGetter( scope2, arm.args[0], get )\n }\n current = place( h, anchor, this.renderBlock( isArm ? arm.block : arm, { ...benv, scope: scope2 } ) )\n }\n\n const eff = effect( () => {\n const p = awaitRun( benv )\n const my = ++token\n\n untrack( () => {\n child.loading ? swapTo( child.loading ) : swapTo( undefined )\n\n Promise.resolve( p ).then(\n v => my === token && untrack( () => swapTo( child.then, v ) ),\n err => my === token && untrack( () => swapTo( child.catch, err ) )\n )\n })\n })\n\n disposers.push( () => { token++; eff.dispose(); destroy( h, current ) } )\n break\n }\n\n /**\n * Scoped context / scoped language (RFC-005 §4).\n *\n * The layer is a plain object whose PROTOTYPE is the enclosing\n * context, with one reactive getter per provided key. That single\n * choice buys the whole feature:\n *\n * - a read of a provided key hits the own getter and tracks the\n * layer's signal;\n * - a read of anything else walks the chain into the global\n * reactive store and tracks THERE, so unprovided keys stay live;\n * - `Object.create` costs nothing per read, so a component under\n * a provider pays no lookup penalty.\n *\n * Nesting composes for free — an inner `<context>` prototypes off\n * the outer layer, so the nearest provider wins.\n */\n case 'provide': {\n const ctx = Object.create( benv.context ?? null )\n /**\n * Keys this layer OWNS, key → setter. `setContext` from anywhere\n * inside the subtree walks the prototype chain looking for these\n * (RFC-005 §4.1), so a write lands on the nearest layer that\n * declares the key instead of on the global store. The signals\n * die with the block, so the ownership is torn down with it —\n * no unregister step, nothing left behind.\n */\n const owned = new Map<string, ( v: any ) => void>()\n Object.defineProperty( ctx, LAYER, { value: owned })\n\n for( const [ name, input ] of Object.entries( child.vars ) ){\n const [ get, set ] = signal<any>( 'lit' in input ? input.lit : undefined )\n defineGetter( ctx, name, get )\n owned.set( name, set )\n\n /**\n * An expression-bound key is DERIVED: the effect re-syncs it\n * from the source, so a local write holds only until the\n * source next changes. A literal has no effect at all, so a\n * write to it simply sticks — which is how a subtree gets\n * state of its own, seeded once.\n */\n if( 'lit' in input ) continue\n const run = this.runner( input.e, scopeNames )\n disposers.push( effect( () => set( run( benv ) ) ).dispose )\n }\n\n /**\n * The scoped language rides on the env rather than on the\n * context object: it is framework state, not a user-space key,\n * so `<i18n lang=…>` must not collide with a `context.lang` the\n * app happens to own.\n */\n let lang = benv.lang\n if( child.lang ){\n if( 'lit' in child.lang ){\n const v = String( child.lang.lit )\n lang = () => v\n }\n else {\n const [ get, set ] = signal<any>( undefined )\n const run = this.runner( child.lang.e, scopeNames )\n disposers.push( effect( () => set( run( benv ) ) ).dispose )\n // Nullish falls back to the enclosing language, not to ''\n lang = () => get() ?? benv.lang?.()\n }\n }\n\n const inner = place( h, anchor, this.renderBlock( child.block, { ...benv, context: ctx, lang }) )\n disposers.push( () => destroy( h, inner ) )\n break\n }\n\n case 'log': {\n const segs = splitTopLevel( this.ir.exprs[ child.e ] ).map( s => this.srcRunner( s, scopeNames ) )\n disposers.push( effect( () => console.log( ...segs.map( run => run( benv ) ) ) ).dispose )\n break\n }\n\n case 'comp': {\n const def = this.options.components?.[ child.name ]\n def\n ? this.execComponent( def, child, anchor, benv, scopeNames, disposers, child.name )\n : this.execElement( child, anchor, benv, scopeNames, disposers )\n break\n }\n\n case 'dynamic': {\n const tagRun = this.runner( child.tag, scopeNames )\n let inner: ( () => void )[] = []\n let activeVerb: any = Symbol('init')\n\n const eff = effect( () => {\n const verb = tagRun( benv )\n if( verb === activeVerb ) return\n activeVerb = verb\n\n untrack( () => {\n for( const d of inner ) d()\n inner = []\n\n if( verb == null ) return\n\n /**\n * Slot placement: `<{input.renderer} …/>` renders the\n * parent's slotted body here; this tag's inputs become\n * the slot's argument values.\n */\n if( isSlot( verb ) ){\n const argvalues: Record<string, any> = {}\n for( const [ name, ci ] of Object.entries( child.inputs ) )\n argvalues[ name ] = 'lit' in ci ? ci.lit : this.runner( ci.e, scopeNames )( benv )\n\n const slotInst = place( h, anchor, verb.render( argvalues ) )\n inner.push( () => destroy( h, slotInst ) )\n return\n }\n\n /**\n * Component name, a ready IRComponentDef, or a plain\n * template object resolved through the host hook.\n */\n const def = typeof verb === 'string'\n ? this.options.components?.[ verb ]\n : verb && typeof verb === 'object'\n ? ( verb.ir ? verb as IRComponentDef : this.options.resolveTemplate?.( verb ) )\n : undefined\n\n if( def ) this.execComponent( def, child, anchor, benv, scopeNames, inner,\n typeof verb === 'string' ? verb : '#dynamic' )\n else if( typeof verb === 'string' )\n this.execElement( { ...child, name: verb } as any, anchor, benv, scopeNames, inner )\n })\n })\n\n disposers.push( () => { eff.dispose(); for( const d of inner ) d() } )\n break\n }\n }\n\n return () => disposers.forEach( d => d() )\n }\n\n /** Keyed <for> — per-item scope signals, range moves, natural entry keys */\n private execFor(\n child: ChildIR & { t: 'for' },\n anchor: N,\n benv: RunEnv,\n scopeNames: string[],\n disposers: ( () => void )[]\n ){\n const h = this.h\n type Item = {\n key: any\n sigs: [ () => any, ( v: any ) => void, () => void ][]\n inst: BlockInstance\n /** The pass that last kept it — see the removal sweep */\n pass: number\n }\n\n const\n ofRun = child.of !== undefined ? this.runner( child.of, scopeNames ) : null,\n byRun = child.by && 'e' in child.by ? this.runner( child.by.e, scopeNames ) : null,\n byPath = child.by && 'lit' in child.by ? String( child.by.lit ).split('.') : null,\n inputVal = ( ci: CompInput | undefined, env: RunEnv ) =>\n ci === undefined ? undefined : 'lit' in ci ? ci.lit : this.runner( ci.e, scopeNames )( env )\n\n let items: Item[] = [], pass = 0\n const byKey = new Map<any, Item>()\n\n /** Normalize source → [{ key, values(aligned with args) }] */\n const tuples = (): { key: any, values: any[] }[] => {\n // Numeric range\n if( ofRun === null ){\n const from = Number( inputVal( child.from, benv ) ?? 0 )\n const to = Number( inputVal( child.to, benv ) ?? from )\n const asc = from <= to\n const out: { key: any, values: any[] }[] = []\n for( let v = from; asc ? v <= to : v >= to; asc ? v++ : v-- )\n out.push({ key: v, values: [ v ] })\n return out\n }\n\n const src = ofRun( benv )\n const keyFor = ( item: any, fallback: any, index: number ) => {\n if( byRun ){\n const fn = byRun( benv )\n return typeof fn === 'function' ? fn( item, index ) : fallback\n }\n if( byPath ) return byPath.reduce( ( v: any, k ) => v?.[ k ], item )\n return fallback\n }\n\n if( Array.isArray( src ) )\n return src.map( ( item, i ) => ({ key: keyFor( item, i, i ), values: [ item, i ] }) )\n\n if( src instanceof Map )\n return [ ...src.entries() ].map( ( [ k, v ], i ) => ({ key: k, values: [ k, v, i ] }) )\n\n /** Sets iterate like arrays: [ value, index ] */\n if( src instanceof Set )\n return [ ...src ].map( ( item, i ) => ({ key: keyFor( item, item, i ), values: [ item, i ] }) )\n\n if( src && typeof src === 'object' )\n return Object.entries( src ).map( ( [ k, v ], i ) => ({ key: k, values: [ k, v, i ] }) )\n\n return []\n }\n\n const eff = effect( () => {\n const next = tuples() // tracked reads\n untrack( () => {\n const seen = new Set<any>()\n const ordered: Item[] = []\n const mark = ++pass\n\n for( const t of next ){\n let key = t.key\n // Duplicate keys degrade to positional identity\n if( seen.has( key ) ){\n console.warn(`<for> duplicate key '${String( key )}' — falling back to positional identity`)\n key = `#dup:${ordered.length}`\n }\n seen.add( key )\n\n const existing = byKey.get( key )\n if( existing ){\n existing.sigs.forEach( ( [ get, set, touch ], j ) => {\n const nv = t.values[ j ]\n /**\n * Same object reference may have mutated in place\n * (deep-reactive mode) — force the item's binds to\n * re-evaluate; unchanged primitives stay silent.\n */\n Object.is( get(), nv ) && typeof nv === 'object' && nv !== null\n ? touch()\n : set( nv )\n })\n existing.pass = mark\n ordered.push( existing )\n }\n else {\n const scope2 = Object.create( benv.scope ?? null )\n const sigs = t.values.map( v => signal( v ) )\n child.args.forEach( ( name, j ) => sigs[ j ] && defineGetter( scope2, name, sigs[ j ][0] ) )\n\n const inst = this.renderBlock( child.block, { ...benv, scope: scope2 } )\n const item: Item = { key, sigs, inst, pass: mark }\n byKey.set( key, item )\n ordered.push( item )\n }\n }\n\n /**\n * Remove disappeared keys. Kept items carry this pass's stamp, so\n * the test is O(1) — `ordered.includes( item )` made every update\n * O(n²): at 10k rows, 50M comparisons to remove ONE row.\n */\n for( const item of items )\n if( item.pass !== mark ){\n byKey.delete( item.key )\n destroy( h, item.inst )\n }\n\n // Pointer walk: enforce order with range moves\n let pointer: N = anchor\n for( const item of ordered ){\n if( h.next( pointer ) !== item.inst.start )\n place( h, pointer, item.inst )\n pointer = item.inst.end\n }\n\n items = ordered\n })\n })\n\n disposers.push( () => {\n eff.dispose()\n for( const item of items ) destroy( h, item.inst )\n items = []\n byKey.clear()\n })\n }\n\n // ------------------------------------------------------- component wiring\n /**\n * Parent-side input wiring: call-site expressions write into the\n * component's reactive `input`. Kept separate from creation so an\n * adopted instance can be re-wired to a new call site.\n * `written` collects the keys this call site supplies.\n */\n private wireInputs(\n child: { inputs: Record<string, CompInput>, spreads: E[] },\n benv: RunEnv,\n scopeNames: string[],\n input: Record<string, any>,\n wiring: ( () => void )[],\n written?: Set<string>\n ){\n for( const [ name, ci ] of Object.entries( child.inputs ) ){\n written?.add( name )\n\n if( 'lit' in ci ) input[ name ] = ci.lit\n else {\n const run = this.runner( ci.e, scopeNames )\n wiring.push( effect( () => input[ name ] = run( benv ) ).dispose )\n }\n }\n for( const e of child.spreads ){\n const run = this.runner( e, scopeNames )\n wiring.push( effect( () => {\n const obj = run( benv ) || {}\n untrack( () => Object.entries( obj ).forEach( ( [ k, v ] ) => {\n written?.add( k )\n input[ k ] = v\n }) )\n }).dispose )\n }\n }\n\n /** Parent `on-*( … )` instructions → listeners on the child's bus */\n private wireEvents(\n events: { name: string, e: E }[] | undefined,\n benv: RunEnv,\n scopeNames: string[],\n self: any,\n wiring: ( () => void )[]\n ){\n events?.forEach( ev => {\n const dispatch = this.eventDispatcher( this.ir.exprs[ ev.e ], scopeNames, benv )\n self.on( ev.name, dispatch )\n wiring.push( () => self.off( ev.name, dispatch ) )\n })\n }\n\n /**\n * Slotted body → `input.renderer` (old-engine convention):\n * the child template places it with `<{input.renderer}/>`.\n * Content renders in the PARENT scope — a slot closes over\n * where it was written, not where it is placed.\n */\n private slotRenderer( contents: ArmIR, penv: RunEnv ): SlotRenderer {\n const parent = this\n\n return {\n [ SLOT ]: true,\n args: contents.args,\n render( argvalues?: Record<string, any> ){\n const scope = Object.create( penv.scope ?? null )\n\n contents.args.forEach( name => {\n const [ get ] = signal( argvalues?.[ name ] )\n defineGetter( scope, name, get )\n })\n\n return parent.renderBlock( contents.block, { ...penv, scope } )\n }\n }\n }\n\n /**\n * Re-home a salvaged instance: same state, same DOM, same handlers\n * — only the parent-side wiring is rebuilt, against the new call\n * site and the new expression table. No lifecycle hook fires: from\n * the component's point of view nothing happened.\n */\n private adoptComponent(\n rec: LiveComp,\n child: { inputs: Record<string, CompInput>, spreads: E[], events?: { name: string, e: E }[], contents?: ArmIR },\n anchor: N,\n benv: RunEnv,\n scopeNames: string[],\n disposers: ( () => void )[]\n ){\n const\n wiring: ( () => void )[] = [],\n written = new Set<string>()\n\n this.wireInputs( child, benv, scopeNames, rec.input, wiring, written )\n\n if( child.contents ){\n rec.input.renderer = this.slotRenderer( child.contents, benv )\n written.add('renderer')\n }\n // Inputs the revision dropped must not linger on the instance\n for( const k of Object.keys( rec.input ) )\n !written.has( k ) && delete rec.input[ k ]\n\n this.wireEvents( child.events, benv, scopeNames, rec.self, wiring )\n\n rec.wiring = wiring\n rec.anchor = anchor\n\n const gen = rec.gen\n place( this.h, anchor, rec.inst )\n\n disposers.push( () => {\n if( gen !== rec.gen ) return // salvaged away; wiring already released\n\n for( const d of rec.wiring ) d()\n rec.wiring = []\n rec.teardown()\n })\n }\n\n /** Registered component: reactive inputs, slots, events, own env */\n private execComponent(\n def: IRComponentDef,\n child: { inputs: Record<string, CompInput>, spreads: E[], events?: { name: string, e: E }[], contents?: ArmIR },\n anchor: N,\n benv: RunEnv,\n scopeNames: string[],\n disposers: ( () => void )[],\n cname: string\n ){\n /**\n * A live instance released by a swap is re-homed here rather\n * than rebuilt from scratch. Only ever true mid-swap, so a\n * normal render pays nothing for it.\n */\n const salvaged = this.pool?.length\n ? this.claim( cname, this.keyOf( child.inputs, benv, scopeNames ) )\n : undefined\n\n if( salvaged )\n return this.adoptComponent( salvaged, child, anchor, benv, scopeNames, disposers )\n\n const\n input = reactive( {} as Record<string, any> ),\n wiring: ( () => void )[] = []\n\n this.wireInputs( child, benv, scopeNames, input, wiring )\n if( child.contents ) input.renderer = this.slotRenderer( child.contents, benv )\n\n const state = reactive( { ...( def.state || {} ) }, def.deep ?? false )\n\n /**\n * Component event bus: the child emits, the parent's\n * `on-*( … )` instructions receive the emitted arguments.\n */\n /** Set once the block renders — backs `self.node` */\n let selfInst: BlockInstance | null = null\n\n // `this` inside the bus closures is the literal, not the renderer\n const irr = this\n /**\n * `lang` for THIS component is the scoped one when it sits under\n * `<i18n lang=…>`, the global one otherwise. Without it there is no\n * way to show the current language, which is what pushed apps into\n * mirroring it into context by hand (RFC-005 §2).\n */\n const bus = selfBus( this.h, () => benv.lang?.() ?? irr.options.i18n?.lang() ?? '' )\n\n const self: any = bus.bind( Object.assign( Object.create( bus.proto ), {\n ...( this.options.expose || {} ),\n state, input, static: def.statics, context: benv.context,\n /**\n * Overrides the host's global `setContext` (merged in by the\n * spread above): a write goes to the nearest `<context>` layer\n * that declares the key, and only reaches the global store when\n * no layer claims it. A component under a provider therefore\n * mutates ITS OWN context — two canvases writing `selection` no\n * longer collide (RFC-005 §4.1).\n */\n setContext( arg: any, value?: any ){\n const write = ( k: string, v: any ) =>\n writeContext( benv.context, k, v, ( irr.options.expose as any )?.setContext )\n\n typeof arg === 'string'\n ? write( arg, value )\n : Object.entries( arg || {} ).forEach( ( [ k, v ] ) => write( k, v ) )\n }\n }), () => selfInst )\n def.handlers && Object.entries( def.handlers ).forEach( ( [ k, fn ] ) => self[ k ] = fn.bind( self ) )\n\n this.wireEvents( child.events, benv, scopeNames, self, wiring )\n\n const hooks = makeHooks( self )\n\n // Lifecycle: creation → (initial input) → render → mount → attach\n try { typeof self.onCreate === 'function' && self.onCreate() }\n catch( error ){ hooks.onError( error ) }\n\n // Handlers receive the input object (Modela: onInput({ host, settings }))\n try { Object.keys( input ).length && typeof self.onInput === 'function' && self.onInput( input ) }\n catch( error ){ hooks.onError( error ) }\n\n /**\n * `context` and `lang` are INHERITED from the call site, not reset:\n * a component placed inside `<context …>` or `<i18n lang=…>` renders\n * under that layer. `scope` is not — a component is a fresh\n * expression scope, unlike a block.\n */\n const cenv: RunEnv = {\n state, input, context: benv.context, lang: benv.lang,\n static: def.statics, self, scope: undefined\n }\n const renderer = new IRRenderer( def.ir, this.options, hooks )\n const inst = renderer.renderBlock( def.ir.root, cenv )\n selfInst = inst // backs self.node\n\n /**\n * Scoped stylesheet — stamp `rel` and write the reactive declarations'\n * variables BEFORE the nodes go live, or the first paint resolves\n * `var()` against nothing (RFC-004 §8).\n */\n const\n clearStyles = def.stylesheet\n ? applyScopedStyles( this.h, this.options, inst, def.stylesheet.nsp || def.nsp || 'lips', def.stylesheet )\n : undefined,\n clearStyleBinds = def.stylesheet\n ? renderer.bindStyle( def.stylesheet, inst, cenv )\n : undefined\n\n place( this.h, anchor, inst )\n hooks.ready()\n\n try {\n typeof self.onMount === 'function' && self.onMount()\n typeof self.onRender === 'function' && self.onRender()\n self.emit('component:mount')\n }\n catch( error ){ hooks.onError( error ) }\n\n /**\n * Declared context subscription — fires onContext only when one of\n * the component's own fields changes.\n *\n * Tracked against the EFFECTIVE context, not the host's global\n * store: reading a key off `cenv.context` hits the layer's own\n * getter when a `<context>` provides it and falls through to the\n * global proxy when it does not, so both notify through the same\n * effect. Watching the host directly (as this did) meant a scoped\n * override never fired the hook while binds reading the same key\n * updated — the one place where declared and rendered context\n * disagreed (RFC-005 §4.2).\n */\n let unwatchContext: ( () => void ) | undefined\n if( def.context?.length && typeof self.onContext === 'function' ){\n let first = true\n const { dispose } = effect( () => {\n for( const f of def.context! ) cenv.context?.[ f ] // track\n if( first ){ first = false; return }\n\n untrack( () => {\n try { self.onContext() }\n catch( error ){ hooks.onError( error ) }\n })\n })\n unwatchContext = dispose\n }\n\n /**\n * Attachment is always tracked (not only when onAttach is\n * defined): external controls subscribe via the event bus with\n * `self.on('component:attached', …)`.\n */\n let attached = false\n {\n PENDING_ATTACH.push({\n live: () => this.h.connected( inst.start ),\n fn: () => {\n attached = true\n try {\n typeof self.onAttach === 'function' && self.onAttach()\n self.emit('component:attached')\n }\n catch( error ){ hooks.onError( error ) }\n }\n })\n // Parent already live → attach now\n this.h.connected( inst.start ) && flushAttach()\n }\n\n /**\n * The instance is now tracked for salvage. `teardown` is the one\n * real destruction path — idempotent, because an unclaimed\n * record and its old owner may both reach for it.\n */\n let torn = false\n const rec: LiveComp = {\n name: cname,\n key: input.key, // already wired — no second evaluation\n self, input, inst, anchor, wiring,\n gen: 0,\n claimed: false,\n teardown: () => {\n if( torn ) return\n torn = true\n\n const i = this.live.indexOf( rec )\n i > -1 && this.live.splice( i, 1 )\n\n unwatchContext?.()\n clearStyleBinds?.()\n clearStyles?.()\n destroy( this.h, inst )\n try {\n if( attached ){\n typeof self.onDetach === 'function' && self.onDetach()\n self.emit('component:detached')\n }\n typeof self.onDestroy === 'function' && self.onDestroy()\n self.emit('component:destroy')\n }\n catch( error ){ hooks.onError( error ) }\n }\n }\n this.live.push( rec )\n\n const gen = rec.gen\n disposers.push( () => {\n if( gen !== rec.gen ) return // salvaged away; wiring already released\n\n for( const d of rec.wiring ) d()\n rec.wiring = []\n rec.teardown()\n })\n }\n\n /** Unresolved component candidate → plain element with binds */\n private execElement(\n child: ChildIR & { t: 'comp' },\n anchor: N,\n benv: RunEnv,\n scopeNames: string[],\n disposers: ( () => void )[]\n ){\n const\n h = this.h,\n el = h.element( child.name )\n\n for( const [ name, ci ] of Object.entries( child.inputs ) ){\n if( 'lit' in ci ) applyAttr( h, el, name, ci.lit )\n else {\n const run = this.runner( ci.e, scopeNames )\n disposers.push( effect( () => applyAttr( h, el, name, run( benv ) ) ).dispose )\n }\n }\n for( const ev of child.events )\n disposers.push( h.listen( el, ev.name, this.eventDispatcher( this.ir.exprs[ ev.e ], scopeNames, benv ) ) )\n\n if( child.contents ){\n const inst = this.renderBlock( child.contents.block, benv )\n for( const n of nodesOf( h, inst ) ) h.insert( el, n, null )\n disposers.push( () => destroy( h, inst ) )\n }\n\n h.insertAfter( anchor, [ el ] )\n disposers.push( () => h.remove( el, true ) )\n }\n\n /**\n * Event instruction dispatch (lazy — evaluated per event):\n * - `on-click( expr )` → value must be a function, called with (…params)\n * - `on-click( name, ...args )` → resolves `name` (expression, then\n * self method fallback) and calls with (...args, ...params)\n *\n * `params` are the DOM event for element listeners, or the emitted\n * arguments for component events — same append-after-declared-args\n * rule either way.\n * Scope getters read live values at dispatch — no stale memos.\n */\n private eventDispatcher( instruction: string, scopeNames: string[], benv: RunEnv ){\n const segs = splitTopLevel( instruction )\n\n return ( ...params: any[] ) => untrack( () => {\n const resolveFn = ( src: string ) => {\n let v: any\n try { v = this.srcRunner( src, scopeNames )( benv ) }\n catch( e ){ v = undefined }\n if( typeof v !== 'function' && benv.self && !this.options.guard?.self( src ) && typeof benv.self[ src ] === 'function' )\n v = benv.self[ src ]\n return v\n }\n\n if( !segs.length ) return\n\n const fn = resolveFn( segs[0] )\n if( typeof fn !== 'function' ) return\n\n const args = segs.slice( 1 ).map( src => this.srcRunner( src, scopeNames )( benv ) )\n fn( ...args, ...params )\n })\n }\n}\n\n// -------------------------------------------------------------------- API\nexport function renderIR<T = Node>( ir: TemplateIR, setup: RenderSetup = {}, options: RuntimeOptions = {} ): IRInstance<T> {\n const\n h = options.host || domHost,\n state = reactive( setup.state || {}, setup.deep ?? false ),\n input = setup.input ? reactive( setup.input, setup.deep ?? false ) : undefined\n\n /** Set after the first render — backs `self.node` */\n let rootInst: BlockInstance | null = null\n\n const bus = selfBus( h, () => options.i18n?.lang() ?? '' )\n\n const self: any = bus.bind( Object.assign( Object.create( bus.proto ), {\n state, input, static: setup.static,\n /**\n * `options.expose` is what every NESTED component self gets\n * (setContext, setLanguage). The root is a component too, so it\n * gets the same — otherwise `self.setLanguage(…)` would work\n * everywhere except the top of the tree.\n */\n ...( options.expose || {} ),\n // Host-provided members (e.g. the facade's emit → Events) win\n ...( setup.expose || {} )\n }), () => rootInst )\n\n setup.handlers && Object.entries( setup.handlers ).forEach( ( [ k, fn ] ) => self[ k ] = fn.bind( self ) )\n\n const env: RunEnv = {\n state,\n input,\n context: setup.context,\n static: setup.static,\n self,\n scope: undefined\n }\n\n const hooks = makeHooks( self )\n\n /**\n * Root lifecycle mirrors the nested path exactly:\n * create → (initial input) → render → mount/render → attach.\n */\n try { typeof self.onCreate === 'function' && self.onCreate() }\n catch( error ){ hooks.onError( error ) }\n\n try { input && Object.keys( input ).length && typeof self.onInput === 'function' && self.onInput( input ) }\n catch( error ){ hooks.onError( error ) }\n\n let renderer = new IRRenderer( ir, options, hooks )\n let current = renderer.renderBlock( ir.root, env )\n rootInst = current // backs self.node\n hooks.ready()\n\n // Scoped stylesheet for the root component\n const clearStyles = setup.stylesheet\n ? applyScopedStyles( h, options, current, setup.stylesheet.nsp || setup.nsp || 'lips', setup.stylesheet )\n : undefined\n\n /**\n * Style binds capture the scope roots, so a swap that rebuilds the root\n * has to re-bind against the fresh ones.\n */\n let clearStyleBinds = setup.stylesheet\n ? renderer.bindStyle( setup.stylesheet, current, env )\n : undefined\n\n try {\n typeof self.onMount === 'function' && self.onMount()\n typeof self.onRender === 'function' && self.onRender()\n }\n catch( error ){ hooks.onError( error ) }\n\n let attached = false\n const attachSelf = () => {\n if( attached ) return\n attached = true\n try {\n typeof self.onAttach === 'function' && self.onAttach()\n self.emit('component:attached')\n }\n catch( error ){ hooks.onError( error ) }\n }\n\n return {\n state,\n self,\n get nodes(){ return nodesOf( h, current ) },\n mount( container: T ){\n for( const n of nodesOf( h, current ) ) h.insert( container, n, null )\n /**\n * Ownership-based attach (RFC §6): mounting a live tree\n * settles this component and every child queued during\n * render — no document-wide MutationObserver.\n */\n if( h.connected( current.start ) ){\n attachSelf()\n flushAttach()\n }\n },\n swap( newIR: TemplateIR ): SwapReport {\n const\n changes: SwapChange[] = [],\n // Salvage moves nodes, which can drop focus — the host puts it back\n restoreFocus = h.keepFocus?.()\n\n // The new renderer inherits the live components: they outlive the IR\n renderer = new IRRenderer( newIR, options, hooks, renderer.live )\n current = renderer.swapBlock( current, newIR.root, changes, 'root' )\n rootInst = current // a rebuild replaces the instance\n\n /**\n * A rebuild produces fresh element roots, which arrive without\n * the `rel` the scoped sheet selects on — re-stamp them, or the\n * component silently loses its styles on the first revision.\n */\n if( setup.stylesheet ){\n stampScope( h, current, setup.stylesheet.nsp || setup.nsp || 'lips' )\n clearStyleBinds?.()\n clearStyleBinds = renderer.bindStyle( setup.stylesheet, current, env )\n }\n\n restoreFocus?.()\n\n return { changes, salvaged: renderer.salvaged }\n },\n dispose(){\n clearStyleBinds?.()\n clearStyles?.()\n destroy( h, current )\n try {\n if( attached ){\n typeof self.onDetach === 'function' && self.onDetach()\n self.emit('component:detached')\n }\n typeof self.onDestroy === 'function' && self.onDestroy()\n }\n catch( error ){ hooks.onError( error ) }\n }\n }\n}\n",
|
|
11
|
+
"import type { EventListener } from './types'\n\nexport type EventOptions = {\n emit?: boolean\n}\n\nexport default class Events {\n private options: EventOptions = {\n emit: true\n }\n private __events: Record<string, EventListener[]> = {}\n private __once_events: Record<string, EventListener[]> = {}\n\n constructor( options?: EventOptions ){\n if( options )\n this.options = options\n }\n\n on( _event: string, fn: EventListener ){\n if( !Array.isArray( this.__events[ _event ] ) )\n this.__events[ _event ] = []\n\n this.__events[ _event ].push( fn )\n return this\n }\n once( _event: string, fn: EventListener ){\n if( !Array.isArray( this.__once_events[ _event ] ) )\n this.__once_events[ _event ] = []\n\n this.__once_events[ _event ].push( fn )\n return this\n }\n off( _event: string, fn?: EventListener ){\n /**\n * Remove a single listener when provided,\n * otherwise clear every listener of the event.\n */\n if( fn ){\n if( Array.isArray( this.__events[ _event ] ) ){\n this.__events[ _event ] = this.__events[ _event ].filter( each => each !== fn )\n !this.__events[ _event ].length && delete this.__events[ _event ]\n }\n\n if( Array.isArray( this.__once_events[ _event ] ) ){\n this.__once_events[ _event ] = this.__once_events[ _event ].filter( each => each !== fn )\n !this.__once_events[ _event ].length && delete this.__once_events[ _event ]\n }\n }\n else {\n delete this.__events[ _event ]\n delete this.__once_events[ _event ]\n }\n\n return this\n }\n emit( _event: string, ...params: any[] ){\n if( !this.options.emit ) return\n\n /**\n * DO NOT ALLOW any proxied variables\n * to be emitted out of a component.\n *\n * Non-mutating: plain objects/arrays are cloned as\n * they are unwrapped — emitted arguments are never\n * altered in place. Class instances (Error, DOM\n * nodes, …) pass through untouched.\n */\n const\n deepclean = ( each: any ): any => {\n if( !each || typeof each !== 'object' ) return each\n\n if( typeof each.toJSON === 'function' ) return each.toJSON()\n\n if( Array.isArray( each ) )\n return each.map( deepclean )\n\n if( each.constructor === Object || each.constructor === undefined ){\n const clone: Record<string, any> = {}\n for( const key in each )\n clone[ key ] = deepclean( each[ key ] )\n\n return clone\n }\n\n return each\n },\n serialized = params.map( deepclean )\n\n this.__events[ _event ]?.forEach( fn => fn( ...serialized ) )\n\n // Once listeners\n this.__once_events[ _event ]?.forEach( fn => fn( ...serialized ) )\n delete this.__once_events[ _event ]\n }\n}",
|
|
12
|
+
"/**\n * Component stylesheets — injected once per namespace and reference\n * counted so shared components clean up correctly. Native DOM only.\n *\n * Compilation lives in `ir/style.ts` and happens at COMPILE time: what\n * arrives here is final, scoped, compact CSS (StyleIR.css). That\n * is what lets the precompiled-only `./runtime` build ship styles with\n * no CSS preprocessor at all — see RFC-004 §1.\n */\n\nexport type StyleSettings = {\n /** Final CSS — already scoped and preprocessed */\n sheet?: string\n /** Marks a globally-injected sheet (prepended, so authors can override) */\n meta?: boolean\n}\n\nexport default class Stylesheet {\n private nsp: string\n private settings: StyleSettings\n\n constructor( nsp: string, settings?: StyleSettings ){\n if( typeof nsp !== 'string' || !nsp )\n throw new Error('Undefined or invalid stylesheet namespace')\n\n this.nsp = nsp\n this.settings = settings || {}\n\n this.settings.sheet && this.load( this.settings )\n }\n\n private get rel(){\n return `${this.settings.meta ? '@' : ''}${this.nsp}`\n }\n /** Quoted, so a name can only ever select its own `<style>` */\n private get styleElement(){\n return document.head.querySelector<HTMLStyleElement>(`style[rel=\"${ this.rel.replace( /[\"\\\\]/g, '\\\\$&' ) }\"]`)\n }\n\n /**\n * Inject. `dindex` counts live instances sharing this namespace: it\n * increases per instance and decreases on clear, so the element is\n * removed only by the last one out.\n */\n load( settings: StyleSettings ){\n this.settings = settings\n if( !settings.sheet ) return\n\n const existing = this.styleElement\n if( existing ){\n // Already injected — just take a reference\n existing.setAttribute('dindex', String( Number( existing.getAttribute('dindex') || 0 ) + 1 ) )\n return existing\n }\n\n const element = document.createElement('style')\n element.setAttribute('rel', this.rel )\n element.setAttribute('dindex', '0')\n element.textContent = settings.sheet\n\n settings.meta\n ? document.head.prepend( element )\n : document.head.appendChild( element )\n\n return element\n }\n\n /** Release this instance's reference; removes the element at zero */\n clear(){\n const element = this.styleElement\n if( !element ) return\n\n const dindex = Number( element.getAttribute('dindex') || 0 )\n\n dindex <= 0\n ? element.remove()\n : element.setAttribute('dindex', String( dindex - 1 ) )\n }\n}\n",
|
|
13
|
+
"import type { MessageFormat } from 'messageformat'\nimport type { MessageFunction } from 'messageformat/functions'\nimport type { Dictionary, MessageFormatEngine } from '../types'\nimport { lookupTags, pick, type TranslatableName } from './lookup'\n\nexport { lookupTags, pick, type TranslatableName }\n\n/**\n * Last-resort language. Only reached when the host has no\n * `navigator` (SSR, a worker, a test runner) and the caller named\n * no language either.\n */\nconst DEFAULT_LANG = 'en-US'\n\n/**\n * Every message is Unicode MessageFormat 2 (CLDR 47), formatted by\n * `messageformat` — the same implementation the platform that serves\n * the dictionaries checks them with, so a message means one thing on\n * both sides of the wire. The engine is handed in (`./engine`), so a\n * build that never translates ships without it. An entry is MF2 source:\n *\n * 'cart.items': `.input {$count :integer}\n * .match $count\n * 0 {{Your cart is empty}}\n * one {{One item in your cart}}\n * * {{{$count} items in your cart}}`\n *\n * or the same message as its data model (`parseMessage`'s JSON), which is\n * how a server that parsed it once serves it.\n *\n * Dictionaries are keyed by full language tag (`fr`, `fr-CA`, `zh-Hant`)\n * and read through RFC 4647 Lookup: a `fr-CA` reader is served from\n * `fr-CA`, then `fr`, so a regional dictionary carries only what differs.\n */\nexport default class I18N {\n private currentLang: string\n private DICTIONARIES: Record<string, Dictionary> = {}\n\n /**\n * MF2 functions a message may call, beyond the default ones built in\n * (`:number`, `:integer`, `:currency`, `:percent`, `:offset`,\n * `:string`). Starts with the draft set — `:date`, `:time`,\n * `:datetime`, `:unit` — and takes a host's own, named with a\n * namespace (`:app:money`) as MF2 asks of custom functions.\n */\n public functions: Record<string, MessageFunction<any, any>>\n\n /**\n * Reports a stable key that no dictionary entry answers. Left unset\n * translation stays silent; the facade wires it to a console warning\n * under `debug`, and a generator can wire it to collect the gaps.\n */\n public onMissing?: ( key: string, lang: string ) => void\n\n /**\n * Reports a message that does not parse, or that fails as it formats:\n * a variable not given, an unknown function, a value its function\n * cannot take. Rendering never throws for it — MF2 writes a fallback\n * (`{$name}`) where the failing part was — so this is where it shows.\n */\n public onError?: ( error: unknown, key: string, lang: string ) => void\n\n /**\n * Fires whenever the dictionary set changes. The facade bumps a\n * revision signal from here, which is what makes a dictionary that\n * arrives LATE — an async load resolving after the language already\n * switched — re-translate what is already on screen.\n */\n public onChange?: () => void\n\n /** Async dictionary source, set by `setLoader` */\n private loader?: ( tag: string ) => Promise<Dictionary | undefined>\n /** In-flight and settled loads, keyed by language tag */\n private loading = new Map<string, Promise<void>>()\n /** Each message as read by one language, parsed once: `null` where it does not parse */\n private formatters = new Map<string, MessageFormat<any, any> | null>()\n\n /**\n * `lang` is the initial language, normally `LipsConfig.lang`. Left\n * out, it is read from the browser — which is the right default for\n * an app that should follow the user's locale, but is not something\n * a server render or a test can rely on being there.\n */\n constructor( lang?: string, private engine?: MessageFormatEngine ){\n this.currentLang = lang\n || ( typeof navigator !== 'undefined' && navigator.language )\n || DEFAULT_LANG\n this.functions = { ...engine?.functions }\n }\n\n set lang( value: string ){\n if( this.currentLang === value ) return\n this.currentLang = value\n }\n get lang(){\n return this.currentLang\n }\n\n /** Register the dictionary for one language tag — `fr`, `fr-CA`, `zh-Hant` — whatever its casing. */\n setDictionary( tag: string, dico: Dictionary ){\n /**\n * Refused rather than read some other way: a dictionary is MF2, and\n * without the engine there is nothing that reads MF2.\n */\n if( !this.engine ) throw new Error(`[lips:i18n] <${tag}> dictionary without a MessageFormat engine — pass \\`messageFormat\\` from '@lipsjs/lips/i18n' to new Lips()`)\n this.DICTIONARIES[ tag.toLowerCase() ] = dico\n this.formatters.clear()\n this.onChange?.()\n }\n /** Is a dictionary registered that a reader of `lang` is served from? */\n has( lang: string ){ return lookupTags( lang.toLowerCase() ).some( tag => !!this.DICTIONARIES[ tag ] ) }\n\n /**\n * Register an async dictionary source, asked once per language tag:\n *\n * lips.i18n.setLoader( tag => import(`./languages/${tag}.json`).then( m => m.default ) )\n *\n * Bundling every language up front costs every user all of them. With\n * a loader, `setLanguage()` switches immediately (untranslated source\n * text is a fine placeholder — it is real wording, not a blank) and\n * the strings resolve when the dictionary lands. A `fr-CA` reader asks\n * for `fr-CA` and `fr`: a source with no `fr-CA` answers `undefined`.\n */\n setLoader( fn: ( tag: string ) => Promise<Dictionary | undefined> ){\n this.loader = fn\n return this\n }\n\n /**\n * Ensure the dictionaries a reader of `lang` is served from are\n * registered. Resolves immediately when they are, or when no loader is\n * set — a missing dictionary is not an error, it just means\n * untranslated output. Each tag is attempted ONCE: a rejected load is\n * remembered so a missing language file does not re-fetch on every\n * switch.\n */\n load( lang: string ): Promise<void> {\n return Promise.all( lookupTags( lang ).map( tag => {\n const id = tag.toLowerCase()\n if( this.DICTIONARIES[ id ] || !this.loader ) return\n\n let inflight = this.loading.get( id )\n if( !inflight ){\n inflight = this.loader( tag )\n .then( dico => { dico && this.setDictionary( tag, dico ) } )\n .catch( error => console.warn(`[lips:i18n] <${tag}> dictionary failed to load —`, error ) )\n this.loading.set( id, inflight )\n }\n return inflight\n }) ).then( () => {} )\n }\n\n /**\n * The message `key` as a reader of `lang` reads it: from the first\n * dictionary of the lookup chain that has it, formatting in `lang`\n * itself — a `fr-CA` reader of a `fr` message still gets Canadian\n * number and date conventions. `undefined` when no dictionary has it;\n * `null` when the one that does holds a message that does not parse.\n */\n private message( key: string, lang: string ){\n const id = `${lang}\\n${key}`\n if( this.formatters.has( id ) ) return this.formatters.get( id )\n\n let mf: MessageFormat<any, any> | null | undefined\n for( const tag of lookupTags( lang.toLowerCase() ) ){\n const dico = this.DICTIONARIES[ tag ]\n if( !dico || !Object.prototype.hasOwnProperty.call( dico, key ) ) continue\n\n try { mf = new this.engine!.MessageFormat( lang, dico[ key ], { functions: this.functions } ) }\n catch( error ){\n this.onError?.( error, key, lang )\n mf = null\n }\n break\n }\n mf !== undefined && this.formatters.set( id, mf )\n return mf\n }\n\n /**\n * Translate a source string into `lang`, defaulting to the current\n * language. A missing dictionary or a missing key is not an error: the\n * source text passes through unchanged, so a partially translated\n * dictionary degrades to the original wording rather than to a blank.\n *\n * `key` is a STABLE id (RFC-005 §3). Given one, it is what the\n * dictionary is consulted for, and `text` becomes only the fallback\n * wording — so rewording the source string keeps the translation.\n * Without it the source text IS the key (the gettext model), which is\n * fine for hand-written UI and lossy for generated UI.\n *\n * The entry is an MF2 message with nothing to fill: plain text, its\n * `{`, `}` and `\\` escaped as MF2 has them.\n *\n * NB: naming the current language explicitly must behave exactly like\n * omitting it — an earlier guard returned the source text whenever\n * `lang === currentLang`, which is precisely when a translation IS wanted.\n */\n translate( text: string, lang?: string, key?: string ){\n const\n as = lang || this.currentLang,\n lookup = key || text,\n mf = this.message( lookup, as )\n\n if( mf ) text = mf.format( undefined, error => this.onError?.( error, lookup, as ) )\n /**\n * A key that resolves to nothing is a real authoring fault — the\n * template names an id the dictionary does not carry — whereas a\n * missing source-text entry is just an untranslated string. Only\n * the first is worth reporting.\n */\n else if( mf === undefined && key ) this.onMissing?.( key, as )\n\n return { text, lang: as }\n }\n\n /**\n * The message `reference` formatted with `params` in `lang`, defaulting\n * to the current language — what `@format=\"reference, { params }\"`\n * renders. `undefined` when no dictionary has it, reported as missing.\n */\n format( reference: string, params: Record<string, unknown>, lang?: string ){\n const\n as = lang || this.currentLang,\n mf = this.message( reference, as )\n\n if( mf ) return mf.format( params, error => this.onError?.( error, reference, as ) )\n mf === undefined && this.onMissing?.( reference, as )\n }\n\n /** The text of a translatable name a reader of `lang` reads, defaulting to the current language. */\n pick( name: TranslatableName, lang?: string ){ return pick( name, lang || this.currentLang ) }\n}\n",
|
|
14
|
+
"/**\n * Phase 2 — engine facade (RFC-001 §9)\n *\n * The old public Lips API backed by the IR engine, activated via\n * `new Lips({ engine: 'ir' })`. Templates are the same plain\n * objects ({ default, state, handler, _static, stylesheet, … });\n * behind the API: parse → IR → renderIR with deep-reactive state.\n *\n * Parity gaps this facade does not yet cover (tracked in ROADMAP):\n * router, i18n, macros, component contents/slots + events,\n * declaration-driven syntax components.\n */\n\nimport type { TemplateIR, CompileResult, CompileOptions } from './compiler'\n\n/**\n * The template compiler is INJECTED, not imported, so a\n * precompiled-only build can tree-shake the parser and compiler out\n * entirely (see src/runtime.ts vs src/lips.ts).\n */\ntype CompilerFn = ( src: string, options?: CompileOptions ) => CompileResult\nlet COMPILER: CompilerFn | null = null\n\nexport function setCompiler( fn: CompilerFn ){ COMPILER = fn }\n\n/**\n * The style compiler is INJECTED for the same reason the template one is:\n * a static import would pull the CSS scanner (and Stylis behind it) into\n * the `./runtime` bundle, which exists precisely to ship neither.\n */\ntype StyleCompilerFn = ( src: string, options: StyleCompileOptions ) => StyleCompileResult\nlet STYLE_COMPILER: StyleCompilerFn | null = null\nexport function setStyleCompiler( fn: StyleCompilerFn ){ STYLE_COMPILER = fn }\n\n/**\n * The MessageFormat 2 engine is INJECTED too: `messageformat` is ~7.2 KB\n * gzipped, which `./runtime` should not ship to apps that never\n * translate. The full entry sets it; `LipsConfig.messageFormat` passes\n * it to a `./runtime` app that does.\n */\nlet MESSAGE_FORMAT: MessageFormatEngine | undefined\nexport function setMessageFormat( engine: MessageFormatEngine ){ MESSAGE_FORMAT = engine }\n\n/**\n * Built-in components (e.g. `<router>`) are INJECTED by the full\n * entry rather than imported here, so the precompiled-only\n * `./runtime` build — which can't compile their source templates\n * anyway — tree-shakes them out.\n */\nconst BUILTINS: Record<string, any> = {}\nexport function registerBuiltin( name: string, template: any ){ BUILTINS[ name ] = template }\n\nimport type { IRComponentDef, IRInstance, RuntimeOptions } from './runtime'\nimport type { Untrusted } from './policy'\nimport { renderIR } from './runtime'\nimport { reactive, effect, signal } from './signal'\nimport Events from '../events'\nimport Stylesheet from '../stylesheet'\nimport type { StyleIR, StyleCompileResult, StyleCompileOptions } from './style'\nimport type { Template, Metavars, LipsConfig, Handler, MessageFormatEngine } from '../types'\nimport I18N from '../i18n'\n\n/**\n * The authoring shape IS the public `Template<MT>` — one type, not a\n * parallel internal one. `FacadeTemplate` remains as the erased form\n * used where the metavars are not known (caches, dynamic resolution).\n */\ntype FacadeTemplate = Template<any>\ntype FacadeConfig<Context extends Object = Record<string, any>> =\n LipsConfig<Context> & { mode?: 'compiled' | 'interpreted' }\n\n/**\n * Names template handlers must not override on the component\n * self — mirrors the old engine's reserved-member guard.\n */\nconst RESERVED_MEMBERS = new Set([\n 'state', 'input', 'static', 'context', 'emit', 'on', 'once', 'off',\n 'node', 'lang', 'setContext', 'setLanguage',\n 'destroy', 'appendTo', 'prependTo', 'replaceWith', 'render', 'swap'\n])\n\nfunction guardHandlers( handler?: Handler<any> ){\n if( !handler ) return undefined\n\n for( const name of Object.keys( handler ) )\n if( RESERVED_MEMBERS.has( name ) )\n throw new Error(`Handler <${name}> is a reserved component member name`)\n\n return handler as Record<string, ( this: any, ...args: any[] ) => any>\n}\n\n// --------------------------------------------------------------- component\nexport class IRFacadeComponent<MT extends Metavars = Metavars> extends Events {\n readonly state: MT['State']\n private instance: IRInstance\n private contextWatcher?: () => void\n private destroyed = false\n\n constructor(\n private lips: IRLips<any>,\n name: string,\n private template: Template<MT>,\n input: MT['Input'] | undefined,\n ir: TemplateIR,\n options: RuntimeOptions\n ){\n super()\n const handlers = guardHandlers( template.handler )\n\n this.state = reactive( { ...( template.state || {} ) }, true )\n const inputR = input ? reactive( { ...input }, true ) : undefined\n\n /**\n * The runtime owns the whole lifecycle (create → input →\n * render → mount → attach → destroy) for root and nested\n * components alike — the facade only supplies wiring.\n */\n /**\n * The OUTWARD half only. Deliberately `super.emit`, not `this.emit`:\n * `this.emit` now also drives the inward half, so routing through it\n * would deliver every internal emission to the local bus twice.\n */\n const emitExternal = ( event: string, ...args: any[] ) => super.emit( event, ...args )\n\n this.instance = renderIR( ir, {\n state: this.state,\n input: inputR,\n context: lips.getContext(),\n static: template.static ?? template._static,\n handlers,\n deep: true,\n // Compiled stylesheet — the runtime stamps `rel`, injects, and binds\n stylesheet: lips.styleFor( name, template ),\n nsp: name,\n expose: {\n /**\n * Component emissions reach BOTH buses: the facade's Events\n * (external `component.on(…)`) and the runtime's own bus\n * (`self.on(…)` inside handlers/controls). `emitLocal` is\n * installed by the runtime before expose is merged.\n */\n emit( this: any, event: string, ...args: any[] ){\n this.emitLocal?.( event, ...args )\n emitExternal( event, ...args )\n },\n context: lips.getContext()\n }\n }, options )\n\n /**\n * Context subscription: components declaring `context: [...]`\n * get onContext whenever a declared field changes.\n */\n const watched = template.watchContext ?? template.context\n if( watched?.length && typeof handlers?.onContext === 'function' )\n this.contextWatcher = lips.watchContext( watched, () => {\n try { handlers.onContext!.call( this.instance.self ) }\n catch( error ){ console.error('[lips:ir]', error ) }\n })\n\n this.emit('component:mount')\n }\n\n /**\n * The component bus is bidirectional.\n *\n * Outward has always worked: a handler's `this.emit('save')` reaches\n * `component.on('save')`. Inward is this override — `component.emit(\n * 'reset')` also reaches `this.on('reset')` registered inside the\n * component, so a holder of the handle can send a command without\n * mutating state or reaching into internals.\n *\n * Argument handling matches what an internal emit already does:\n * inward is raw (the caller owns the data), outward is deep-cleaned by\n * `Events` so reactive proxies never escape the component.\n */\n emit( event: string, ...args: any[] ){\n // instance is unset only while renderIR is still running (e.g. onCreate)\n this.instance?.self?.emitLocal?.( event, ...args )\n return super.emit( event, ...args )\n }\n\n /**\n * Live root ELEMENTS — matching `this.node` inside a handler. The\n * instance's node list also carries the block's range markers, which\n * are an internal detail no consumer should have to filter out.\n */\n get node(): Element[] {\n return this.instance.nodes.filter( n => n.nodeType === 1 ) as Element[]\n }\n\n appendTo( selector: string | Element ){\n const target = typeof selector === 'string' ? document.querySelector( selector ) : selector\n target && this.instance.mount( target as Element )\n return this\n }\n\n swap( newIR: TemplateIR ){ return this.instance.swap( newIR ) }\n\n destroy(){\n if( this.destroyed ) return\n this.destroyed = true\n\n this.contextWatcher?.()\n // dispose() runs onDetach/onDestroy and clears the scoped stylesheet\n this.instance.dispose()\n this.emit('component:destroy')\n }\n}\n\n// -------------------------------------------------------------------- lips\nexport class IRLips<Context extends Object = Record<string, any>> {\n public debug: boolean\n private store = new Map<string, FacadeTemplate>()\n private irCache = new WeakMap<FacadeTemplate, TemplateIR>()\n private defCache = new WeakMap<FacadeTemplate, IRComponentDef>()\n private styleCache = new WeakMap<FacadeTemplate, StyleIR>()\n private context: Context\n private __root?: IRFacadeComponent<any>\n /**\n * `new Lips({ untrusted: untrusted() })` — every template this instance\n * renders is held to it (RFC-007). Passed by value from\n * `@lipsjs/lips/untrusted`, so only an app that renders untrusted\n * templates ships the policy.\n */\n private u?: Untrusted\n\n public i18n: I18N\n /** Language signal — translated binds subscribe through it */\n private getLang: () => string\n private setLang: ( v: string ) => void\n /** Dictionary revision — bumped whenever a dictionary is registered */\n private getRev!: () => number\n\n /**\n * Registered components resolved lazily — the runtime looks\n * names up per render, so registration order doesn't matter.\n */\n private componentsProxy: Record<string, IRComponentDef>\n\n constructor( private config?: FacadeConfig<Context> ){\n this.u = config?.untrusted\n\n this.debug = !!config?.debug\n this.context = reactive( { ...( config?.context || {} ) }, true ) as Context\n\n this.i18n = new I18N( config?.lang, config?.messageFormat ?? MESSAGE_FORMAT )\n if( this.debug ){\n this.i18n.onMissing = ( key, lang ) => console.warn(`[lips:i18n] no <${lang}> entry for key \"${key}\"`)\n this.i18n.onError = ( error, key, lang ) => console.warn(`[lips:i18n] <${lang}> message \"${key}\" —`, error )\n }\n\n const [ getLang, setLang ] = signal( this.i18n.lang )\n this.getLang = getLang\n this.setLang = setLang\n\n /**\n * Dictionary revision. Translated binds track it alongside the\n * language, so a dictionary registered AFTER render — a lazy load\n * resolving, or a plain `setDictionary` call at runtime — re-runs\n * them. Without it the language signal alone would not fire: the\n * language never changed, only what it resolves to.\n */\n const [ getRev, setRev ] = signal( 0 )\n this.getRev = getRev\n this.i18n.onChange = () => setRev( getRev() + 1 )\n\n // Built-in components (their templates are source — need the compiler)\n COMPILER && Object.entries( BUILTINS ).forEach( ( [ name, template ] ) => this.register( name, template ) )\n\n const self = this\n this.componentsProxy = new Proxy( {} as Record<string, IRComponentDef>, {\n get( _, name: string ){\n const template = self.store.get( name )\n return template ? self.defFor( name, template ) : undefined\n },\n has( _, name: string ){ return self.store.has( name as string ) }\n })\n }\n\n // ---- registry\n register<MT extends Metavars = Metavars>( name: string, template: Template<MT> ){\n this.store.set( name, template )\n return this\n }\n unregister( name: string ){\n this.store.delete( name )\n return this\n }\n has( name: string ){ return this.store.has( name ) }\n\n private compile( template: FacadeTemplate ): TemplateIR {\n // Precompiled: nothing to parse\n if( template.ir ) return template.ir\n\n let ir = this.irCache.get( template )\n if( !ir ){\n if( !COMPILER )\n throw new Error(\n 'This build has no template compiler — templates must be precompiled to `ir` '\n + '(import from \"@lipsjs/lips\" instead of \"@lipsjs/lips/runtime\")' )\n\n const result = COMPILER( template.default || '', { macros: template.macros, check: this.u?.check })\n result.diagnostics.length\n && console.warn('[lips:ir] template diagnostics —', result.diagnostics )\n\n ir = result.ir\n this.irCache.set( template, ir )\n }\n return ir\n }\n /**\n * Compile `stylesheet` source to StyleIR, or take a precompiled `style`\n * as-is. Cached per template object like the template IR — the sheet is\n * per component type, so this runs once no matter how many instances.\n */\n styleFor( name: string, template: FacadeTemplate ): StyleIR | undefined {\n if( template.style ) return template.style\n if( !template.stylesheet ) return\n\n if( !STYLE_COMPILER ){\n console.warn(\n `[lips:ir] <${name}> stylesheet skipped — this build has no style compiler. `\n + 'Precompile it to StyleIR, or import \"@lipsjs/lips\" instead of \"@lipsjs/lips/runtime\".' )\n return\n }\n\n let style = this.styleCache.get( template )\n if( !style ){\n const result = ( this.u ? this.u.style( STYLE_COMPILER ) : STYLE_COMPILER )( template.stylesheet, {\n nsp: name,\n layer: this.config?.styleLayer,\n preprocess: this.config?.stylePreprocessor\n })\n result.diagnostics.length\n && console.warn('[lips:ir] style diagnostics —', result.diagnostics )\n\n style = result.ir\n this.styleCache.set( template, style )\n }\n return style\n }\n\n private defFor( name: string, template: FacadeTemplate ): IRComponentDef {\n let def = this.defCache.get( template )\n if( !def ){\n def = {\n ir: this.compile( template ),\n state: template.state,\n statics: template.static ?? template._static,\n context: template.watchContext ?? template.context,\n stylesheet: this.styleFor( name, template ),\n nsp: name,\n handlers: guardHandlers( template.handler ),\n deep: true\n }\n this.defCache.set( template, def )\n }\n return def\n }\n\n // ---- rendering\n render<MT extends Metavars = Metavars>( name: string, template: Template<MT>, input?: MT['Input'] ){\n const options: RuntimeOptions = {\n mode: this.config?.mode,\n components: this.componentsProxy,\n /**\n * Route pages (and any `<{templateObject}/>`) are plain\n * template objects — compile + cache them on demand.\n */\n resolveTemplate: ( value: any ) =>\n value && ( typeof value.default === 'string' || value.ir )\n ? this.defFor( value.name || 'dynamic', value as FacadeTemplate )\n : undefined,\n expose: {\n setContext: ( arg: any, value?: any ) => this.setContext( arg, value ),\n /**\n * `self.setLanguage('fr-FR')` — a switcher is UI, so it needs to\n * be reachable from a template's `on-click`, not just from the\n * Lips instance.\n */\n setLanguage: ( lang: string ) => this.setLanguage( lang )\n },\n /**\n * Scoped-stylesheet factory. Undefined in a build without a CSS\n * preprocessor (`./runtime`), so the runtime skips injection.\n */\n createStylesheet: ( nsp: string, css: string ) => {\n const sheet = new Stylesheet( nsp, { sheet: css })\n return { clear: () => sheet.clear() }\n },\n i18n: {\n /**\n * The language signal is read INSIDE the bind effect and handed\n * to i18n as the language to use. That read is what re-runs every\n * translated bind on setLanguage(), and passing the value on —\n * rather than letting i18n fall back to its own `currentLang` —\n * keeps what is rendered equal to what was tracked.\n *\n * `scoped` is the `<i18n lang=…>` override for this subtree. It\n * still tracks the global signal first: a scoped subtree whose\n * expression reads nothing else must not go stale, and tracking\n * one extra signal only costs a re-run that recomputes the same\n * string.\n */\n translate: ( text: string, key?: string, scoped?: string ) => {\n const global = this.getLang() // track unconditionally — see above\n this.getRev() // …and re-run when a dictionary lands\n return this.i18n.translate( text, scoped || global, key ).text\n },\n format: ( reference: string, params: any, scoped?: string ) => {\n const global = this.getLang()\n this.getRev()\n return this.i18n.format( reference, params, scoped || global ) ?? ''\n },\n lang: () => this.getLang()\n }\n }\n\n return new IRFacadeComponent( this, name, template, input, this.compile( template ), this.u ? this.u.runtime( options ) : options )\n }\n root<MT extends Metavars = Metavars>( template: Template<MT>, selector: string ){\n this.__root = this.render<MT>( '__ROOT__', template )\n this.__root.appendTo( selector )\n return this.__root\n }\n\n // ---- i18n\n /**\n * The only way to change language. Writing `lips.i18n.lang` directly\n * updates the dictionary lookup but not the signal, so nothing already\n * rendered re-translates.\n */\n setLanguage( lang: string ){\n this.i18n.lang = lang\n this.setLang( lang )\n /**\n * Switch first, resolve second. The UI changes language immediately\n * — showing source wording, which is real text rather than a blank —\n * and the loaded dictionary bumps the revision to re-translate. A\n * language already registered resolves synchronously and this is a\n * no-op.\n */\n this.i18n.load( lang )\n return this\n }\n getLanguage(){ return this.getLang() }\n useTranslator( support: string | string[], fn: ( lang: string ) => void ){\n let first = true\n const { dispose } = effect( () => {\n const lang = this.getLang()\n if( first ){ first = false; return }\n ;( support === '*' || ( Array.isArray( support ) && support.includes( lang ) ) ) && fn( lang )\n })\n return dispose\n }\n\n // ---- context\n /** Reactive store, indexed dynamically — Context only types the surface */\n private get ctx(){ return this.context as Record<string, any> }\n\n getContext(): Context { return this.context }\n setContext( arg: ( keyof Context & string ) | Partial<Context>, value?: any ){\n typeof arg === 'string'\n ? this.ctx[ arg ] = value\n : Object.entries( arg as object ).forEach( ( [ k, v ] ) => this.ctx[ k ] = v )\n }\n /**\n * Subscribe to a subset of context fields — the effect tracks\n * exactly those keys, so unrelated context writes don't fire it.\n * Returns an unsubscribe function.\n */\n watchContext( fields: ( keyof Context & string )[] | string[], fn: () => void ){\n let first = true\n const { dispose } = effect( () => {\n ;( fields as string[] ).forEach( f => this.ctx[ f ] ) // track\n first ? first = false : fn()\n })\n return dispose\n }\n useContext( fields: string[], fn: ( ctx: Partial<Context> ) => void ){\n return this.watchContext( fields, () =>\n fn( Object.fromEntries( fields.map( f => [ f, this.ctx[ f ] ] ) ) as Partial<Context> ) )\n }\n\n dispose(){\n this.__root?.destroy()\n }\n}\n",
|
|
15
|
+
"/**\n * The least of `Intl` that MessageFormat 2 needs, for an engine with none\n * — Lynx's PrimJS is not known to have it (design/lynx-binding.md §3.6).\n * Each member is installed only where it is missing, so an engine with a\n * real `Intl` is never touched.\n *\n * It writes numbers and dates plainly, selects every plural category as\n * `other`, and reads every language as left-to-right. An exact key still\n * selects (`0 {{…}}`, `1 {{…}}`), so a message can say \"none\" and \"one\"\n * without plural rules. A host that has real formatting registers it as\n * functions in `i18n.functions` — that is the seam this stands in for.\n */\nconst\ng = globalThis as any,\nI = g.Intl ??= {},\nlisted = ( locales: unknown ) => ( Array.isArray( locales ) ? locales : locales ? [ locales ] : [] ).map( String ),\nplain = ( write: ( value: any ) => string ) => class {\n options: Record<string, unknown>\n constructor( locales?: unknown, options?: object ){\n this.options = { ...options, locale: listed( locales )[0] ?? 'und' }\n }\n static supportedLocalesOf( locales: unknown ){ return listed( locales ) }\n resolvedOptions(){ return this.options }\n format( value: unknown ){ return write( value ) }\n formatToParts( value: unknown ){ return [{ type: 'literal', value: write( value ) }] }\n select(){ return 'other' }\n}\n\nI.Locale ??= class {\n readonly baseName: string\n readonly language: string\n constructor( tag: unknown ){\n this.baseName = String( tag )\n this.language = this.baseName.split('-')[0]\n }\n maximize(){ return this }\n toString(){ return this.baseName }\n}\nI.NumberFormat ??= plain( String )\nI.PluralRules ??= plain( String )\nI.DateTimeFormat ??= plain( value => {\n const date = new Date( value )\n return isNaN( date.getTime() ) ? String( value ) : date.toISOString()\n})\n\nexport {}\n",
|
|
16
|
+
"const bidiChars = /^[\\u061c\\u200e\\u200f\\u2066-\\u2069]+/;\nconst nameChars = /^[-.+0-9A-Z_a-z\\u{a1}-\\u{61b}\\u{61d}-\\u{167f}\\u{1681}-\\u{1fff}\\u{200b}-\\u{200d}\\u{2010}-\\u{2027}\\u{2030}-\\u{205e}\\u{2060}-\\u{2065}\\u{206a}-\\u{2fff}\\u{3001}-\\u{d7ff}\\u{e000}-\\u{fdcf}\\u{fdf0}-\\u{fffd}\\u{10000}-\\u{1fffd}\\u{20000}-\\u{2fffd}\\u{30000}-\\u{3fffd}\\u{40000}-\\u{4fffd}\\u{50000}-\\u{5fffd}\\u{60000}-\\u{6fffd}\\u{70000}-\\u{7fffd}\\u{80000}-\\u{8fffd}\\u{90000}-\\u{9fffd}\\u{a0000}-\\u{afffd}\\u{b0000}-\\u{bfffd}\\u{c0000}-\\u{cfffd}\\u{d0000}-\\u{dfffd}\\u{e0000}-\\u{efffd}\\u{f0000}-\\u{ffffd}\\u{100000}-\\u{10fffd}]+/u;\nconst notNameStart = /^[-.0-9]/;\nexport function parseNameValue(source, start) {\n let pos = start;\n const startBidi = source.slice(pos).match(bidiChars);\n if (startBidi)\n pos += startBidi[0].length;\n const match = source.slice(pos).match(nameChars);\n if (!match)\n return null;\n const name = match[0];\n if (notNameStart.test(name))\n return null;\n pos += name.length;\n const endBidi = source.slice(pos).match(bidiChars);\n if (endBidi)\n pos += endBidi[0].length;\n return { value: name.normalize(), end: pos };\n}\nexport function isValidUnquotedLiteral(str) {\n const match = str.match(nameChars);\n return !!match && match[0].length === str.length;\n}\nexport const parseUnquotedLiteralValue = (source, start) => source.slice(start).match(nameChars)?.[0] ?? '';\n",
|
|
17
|
+
"import { MessageSyntaxError } from \"../errors.js\";\n/**\n * Shared symbol used as a key on message data model nodes\n * to reference their CST source.\n *\n * Only set on message data model nodes when parsed by {@link messageFromCST}.\n */\nexport const cstKey = Symbol.for('CST');\n/**\n * Convert a CST message structure into its data model representation.\n *\n * In the returned {@link Model.Message},\n * all nodes include a reference to their source {@link CST} node\n * as a {@link cstKey} symbol-keyed property.\n */\nexport function messageFromCST(msg) {\n for (const error of msg.errors)\n throw error;\n const declarations = msg.declarations\n ? msg.declarations.map(asDeclaration)\n : [];\n if (msg.type === 'select') {\n return {\n type: 'select',\n declarations,\n selectors: msg.selectors.map(sel => asValue(sel)),\n variants: msg.variants.map(variant => ({\n keys: variant.keys.map(key => key.type === '*' ? { type: '*', [cstKey]: key } : asValue(key)),\n value: asPattern(variant.value),\n [cstKey]: variant\n })),\n [cstKey]: msg\n };\n }\n else {\n return {\n type: 'message',\n declarations,\n pattern: asPattern(msg.pattern),\n [cstKey]: msg\n };\n }\n}\nfunction asDeclaration(decl) {\n switch (decl.type) {\n case 'input': {\n const value = asExpression(decl.value, false);\n if (value.arg?.type !== 'variable') {\n const { start, end } = decl.value;\n throw new MessageSyntaxError('parse-error', start, end);\n }\n return {\n type: 'input',\n name: value.arg.name,\n value: value,\n [cstKey]: decl\n };\n }\n case 'local':\n return {\n type: 'local',\n name: asValue(decl.target).name,\n value: asExpression(decl.value, false),\n [cstKey]: decl\n };\n default:\n throw new MessageSyntaxError('parse-error', decl.start, decl.end);\n }\n}\nconst asPattern = (pattern) => pattern.body.map(el => el.type === 'text' ? el.value : asExpression(el, true));\nfunction asExpression(exp, allowMarkup) {\n if (exp.type === 'expression') {\n if (allowMarkup && exp.markup) {\n const cm = exp.markup;\n const name = asName(cm.name);\n const kind = cm.open.value === '/' ? 'close' : cm.close ? 'standalone' : 'open';\n const markup = { type: 'markup', kind, name };\n if (cm.options.length)\n markup.options = asOptions(cm.options);\n if (exp.attributes.length) {\n markup.attributes = asAttributes(exp.attributes);\n }\n markup[cstKey] = exp;\n return markup;\n }\n const arg = exp.arg ? asValue(exp.arg) : undefined;\n let functionRef;\n const ca = exp.functionRef;\n if (ca) {\n if (ca.type === 'function') {\n functionRef = { type: 'function', name: asName(ca.name) };\n if (ca.options.length)\n functionRef.options = asOptions(ca.options);\n }\n else {\n throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n }\n }\n let expression = arg\n ? { type: 'expression', arg }\n : undefined;\n if (functionRef) {\n functionRef[cstKey] = ca;\n if (expression)\n expression.functionRef = functionRef;\n else\n expression = { type: 'expression', functionRef: functionRef };\n }\n if (expression) {\n if (exp.attributes.length) {\n expression.attributes = asAttributes(exp.attributes);\n }\n expression[cstKey] = exp;\n return expression;\n }\n }\n throw new MessageSyntaxError('parse-error', exp.start, exp.end);\n}\nfunction asOptions(options) {\n const map = {};\n for (const opt of options) {\n const name = asName(opt.name);\n if (Object.hasOwn(map, name)) {\n throw new MessageSyntaxError('duplicate-option-name', opt.start, opt.end);\n }\n map[name] = asValue(opt.value);\n }\n return map;\n}\nfunction asAttributes(attributes) {\n const map = {};\n for (const attr of attributes) {\n const name = asName(attr.name);\n if (Object.hasOwn(map, name)) {\n throw new MessageSyntaxError('duplicate-attribute', attr.start, attr.end);\n }\n map[name] = attr.value ? asValue(attr.value) : true;\n }\n return map;\n}\nfunction asName(id) {\n switch (id.length) {\n case 1:\n return id[0].value;\n case 3:\n return `${id[0].value}:${id[2].value}`;\n default:\n throw new MessageSyntaxError('parse-error', id[0]?.start ?? -1, id.at(-1)?.end ?? -1);\n }\n}\nfunction asValue(value) {\n switch (value.type) {\n case 'literal':\n return { type: 'literal', value: value.value, [cstKey]: value };\n case 'variable':\n return { type: 'variable', name: value.name, [cstKey]: value };\n default:\n throw new MessageSyntaxError('parse-error', value.start, value.end);\n }\n}\n",
|
|
18
|
+
"import { cstKey } from \"./data-model/from-cst.js\";\n/**\n * Base error class used by MessageFormat\n *\n * @category Errors\n */\nexport class MessageError extends Error {\n type;\n constructor(type, message) {\n super(message);\n this.type = type;\n }\n}\n/**\n * Errors in the message syntax.\n *\n * @category Errors\n */\nexport class MessageSyntaxError extends MessageError {\n start;\n end;\n /** @private */\n constructor(type, start, end, expected) {\n let message = expected ? `Missing ${expected}` : type;\n if (start >= 0)\n message += ` at ${start}`;\n super(type, message);\n this.start = start;\n this.end = end ?? start + 1;\n }\n}\n/**\n * Errors in the message data model.\n *\n * @category Errors\n */\nexport class MessageDataModelError extends MessageSyntaxError {\n /** @private */\n constructor(type, node) {\n const { start, end } = node[cstKey] ?? { start: -1, end: -1 };\n super(type, start, end);\n }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageResolutionError extends MessageError {\n source;\n cause;\n constructor(type, message, source, cause) {\n super(type, message);\n this.source = source;\n if (cause !== undefined)\n this.cause = cause;\n }\n}\n/**\n * Message runtime resolution errors\n *\n * @category Errors\n */\nexport class MessageFunctionError extends MessageError {\n source;\n cause;\n constructor(type, message) {\n super(type, message);\n this.source = '�';\n }\n}\n",
|
|
19
|
+
"import { parseNameValue, parseUnquotedLiteralValue } from \"../cst/names.js\";\nimport { MessageSyntaxError } from \"../errors.js\";\nconst bidiChars = new Set('\\u061C\\u200E\\u200F\\u2066\\u2067\\u2068\\u2069');\nconst whitespaceChars = new Set('\\t\\n\\r \\u3000');\n//// Parser State ////\nlet pos;\nlet source;\n//// Utilities & Error Wrappers ////\n// These indirections allow for the function names to be mangled,\n// while keeping the error class name intact.\nconst MissingSyntax = (pos, expected) => new MessageSyntaxError('missing-syntax', pos, pos + expected.length, expected);\nconst SyntaxError = (...args) => new MessageSyntaxError(...args);\nfunction expect(searchString, consume) {\n if (source.startsWith(searchString, pos)) {\n if (consume)\n pos += searchString.length;\n }\n else {\n throw MissingSyntax(pos, searchString);\n }\n}\nexport function parseMessage(source_) {\n pos = 0;\n source = source_;\n const decl = declarations();\n if (source.startsWith('.match', pos))\n return selectMessage(decl);\n const quoted = decl.length > 0 || source.startsWith('{{', pos);\n if (!quoted && pos > 0)\n pos = 0;\n const pattern_ = pattern(quoted);\n if (quoted) {\n ws();\n if (pos < source.length) {\n throw SyntaxError('extra-content', pos, source.length);\n }\n }\n return { type: 'message', declarations: decl, pattern: pattern_ };\n}\nfunction selectMessage(declarations) {\n pos += 6; // '.match'\n ws(true);\n const selectors = [];\n while (source[pos] === '$') {\n selectors.push(variable());\n ws(true);\n }\n if (selectors.length === 0)\n throw SyntaxError('empty-token', pos);\n const variants = [];\n while (pos < source.length) {\n variants.push(variant());\n ws();\n }\n return { type: 'select', declarations, selectors, variants };\n}\nfunction variant() {\n const keys = [];\n while (pos < source.length) {\n ws(keys.length ? '{' : false);\n const next = source[pos];\n if (next === '{')\n break;\n if (next === '*') {\n keys.push({ type: '*' });\n pos += 1;\n }\n else {\n const key = literal(true);\n key.value = key.value.normalize();\n keys.push(key);\n }\n }\n return { keys, value: pattern(true) };\n}\nfunction pattern(quoted) {\n if (quoted) {\n if (source.startsWith('{{', pos))\n pos += 2;\n else\n throw MissingSyntax(pos, '{{');\n }\n const pattern = [];\n loop: while (pos < source.length) {\n switch (source[pos]) {\n case '{': {\n pattern.push(expression(true));\n break;\n }\n case '}':\n if (!quoted)\n throw SyntaxError('parse-error', pos);\n break loop;\n default: {\n pattern.push(text());\n }\n }\n }\n if (quoted) {\n if (source.startsWith('}}', pos))\n pos += 2;\n else\n throw MissingSyntax(pos, '}}');\n }\n return pattern;\n}\nfunction declarations() {\n const declarations = [];\n ws();\n loop: while (source[pos] === '.') {\n const keyword = source.substr(pos, 6);\n switch (keyword) {\n case '.input':\n declarations.push(inputDeclaration());\n break;\n case '.local':\n declarations.push(localDeclaration());\n break;\n case '.match':\n break loop;\n default:\n throw SyntaxError('parse-error', pos);\n }\n ws();\n }\n return declarations;\n}\nfunction inputDeclaration() {\n pos += 6; // '.input'\n ws();\n expect('{', false);\n const valueStart = pos;\n const value = expression(false);\n if (value.type === 'expression' && value.arg?.type === 'variable') {\n // @ts-expect-error TS isn't catching that value is Expression<VariableRef>\n return { type: 'input', name: value.arg.name, value };\n }\n throw SyntaxError('bad-input-expression', valueStart, pos);\n}\nfunction localDeclaration() {\n pos += 6; // '.local'\n ws(true);\n expect('$', true);\n const name_ = name();\n ws();\n expect('=', true);\n ws();\n expect('{', false);\n const value = expression(false);\n return { type: 'local', name: name_, value };\n}\nfunction expression(allowMarkup) {\n const start = pos;\n pos += 1; // '{'\n ws();\n const arg = value(false);\n if (arg)\n ws('}');\n const sigil = source[pos];\n let functionRef;\n let markup;\n switch (sigil) {\n case '@':\n case '}':\n break;\n case ':': {\n pos += 1; // ':'\n functionRef = { type: 'function', name: identifier() };\n const options_ = options();\n if (options_)\n functionRef.options = options_;\n break;\n }\n case '#':\n case '/': {\n if (arg || !allowMarkup)\n throw SyntaxError('parse-error', pos);\n pos += 1; // '#' or '/'\n const kind = sigil === '#' ? 'open' : 'close';\n markup = { type: 'markup', kind, name: identifier() };\n const options_ = options();\n if (options_)\n markup.options = options_;\n break;\n }\n default:\n throw SyntaxError('parse-error', pos);\n }\n const attributes_ = attributes();\n if (markup?.kind === 'open' && source[pos] === '/') {\n markup.kind = 'standalone';\n pos += 1; // '/'\n }\n expect('}', true);\n if (functionRef) {\n const exp = arg\n ? { type: 'expression', arg, functionRef: functionRef }\n : { type: 'expression', functionRef: functionRef };\n if (attributes_)\n exp.attributes = attributes_;\n return exp;\n }\n if (markup) {\n if (attributes_)\n markup.attributes = attributes_;\n return markup;\n }\n if (!arg)\n throw SyntaxError('empty-token', start, pos);\n return attributes_\n ? { type: 'expression', arg, attributes: attributes_ }\n : { type: 'expression', arg };\n}\n/** Requires and consumes leading and trailing whitespace. */\nfunction options() {\n ws('/}');\n const options = {};\n let isEmpty = true;\n while (pos < source.length) {\n const next = source[pos];\n if (next === '@' || next === '/' || next === '}')\n break;\n const start = pos;\n const name_ = identifier();\n if (Object.hasOwn(options, name_)) {\n throw SyntaxError('duplicate-option-name', start, pos);\n }\n ws();\n expect('=', true);\n ws();\n options[name_] = value(true);\n isEmpty = false;\n ws('/}');\n }\n return isEmpty ? null : options;\n}\nfunction attributes() {\n const attributes = {};\n let isEmpty = true;\n while (source[pos] === '@') {\n const start = pos;\n pos += 1; // '@'\n const name_ = identifier();\n if (Object.hasOwn(attributes, name_)) {\n throw SyntaxError('duplicate-attribute', start, pos);\n }\n ws('=/}');\n if (source[pos] === '=') {\n pos += 1; // '='\n ws();\n attributes[name_] = literal(true);\n ws('/}');\n }\n else {\n attributes[name_] = true;\n }\n isEmpty = false;\n }\n return isEmpty ? null : attributes;\n}\nfunction text() {\n let value = '';\n let i = pos;\n loop: for (; i < source.length; ++i) {\n switch (source[i]) {\n case '\\\\': {\n const esc = source[i + 1];\n if (!'\\\\{|}'.includes(esc))\n throw SyntaxError('bad-escape', i, i + 2);\n value += source.substring(pos, i) + esc;\n i += 1;\n pos = i + 1;\n break;\n }\n case '{':\n case '}':\n break loop;\n }\n }\n value += source.substring(pos, i);\n pos = i;\n return value;\n}\nfunction value(required) {\n return source[pos] === '$' ? variable() : literal(required);\n}\nfunction variable() {\n pos += 1; // '$'\n return { type: 'variable', name: name() };\n}\nfunction literal(required) {\n if (source[pos] === '|')\n return quotedLiteral();\n const value = parseUnquotedLiteralValue(source, pos);\n if (!value) {\n if (required)\n throw SyntaxError('empty-token', pos);\n else\n return undefined;\n }\n pos += value.length;\n return { type: 'literal', value };\n}\nfunction quotedLiteral() {\n pos += 1; // '|'\n let value = '';\n for (let i = pos; i < source.length; ++i) {\n switch (source[i]) {\n case '\\\\': {\n const esc = source[i + 1];\n if (!'\\\\{|}'.includes(esc))\n throw SyntaxError('bad-escape', i, i + 2);\n value += source.substring(pos, i) + esc;\n i += 1;\n pos = i + 1;\n break;\n }\n case '|':\n value += source.substring(pos, i);\n pos = i + 1;\n return { type: 'literal', value };\n }\n }\n throw MissingSyntax(source.length, '|');\n}\nfunction identifier() {\n const name_ = name();\n if (source[pos] === ':') {\n pos += 1;\n return name_ + ':' + name();\n }\n return name_;\n}\nfunction name() {\n const name = parseNameValue(source, pos);\n if (!name)\n throw SyntaxError('empty-token', pos);\n pos = name.end;\n return name.value;\n}\nfunction ws(req = false) {\n let next = source[pos];\n let hasWS = false;\n if (req) {\n while (bidiChars.has(next))\n next = source[++pos];\n while (whitespaceChars.has(next)) {\n next = source[++pos];\n hasWS = true;\n }\n }\n while (bidiChars.has(next) || whitespaceChars.has(next))\n next = source[++pos];\n if (req && !hasWS && (req === true || !req.includes(source[pos]))) {\n throw MissingSyntax(pos, \"' '\");\n }\n}\n",
|
|
20
|
+
"/**\n * Apply visitor functions to message nodes.\n *\n * The visitors are applied in source order, starting from the root.\n * Visitors for nodes that contain other nodes may return a callback function\n * that will be called with no arguments when exiting the node.\n *\n * If set, the `node` visitor is called for all {@link Node} values\n * for which an explicit visitor is not defined.\n *\n * Many visitors will be called with additional arguments\n * identifying some of the context for the visited node.\n *\n * @category Message Data Model\n */\nexport function visit(msg, visitors) {\n const { node, pattern } = visitors;\n const { functionRef = node, attributes = null, declaration = node, expression = node, key = node, markup = node, options = null, value = node, variant = node } = visitors;\n const handleOptions = (options_, context) => {\n if (options_) {\n const end = options?.(options_, context);\n if (value) {\n for (const value_ of Object.values(options_)) {\n value(value_, context, 'option');\n }\n }\n end?.();\n }\n };\n const handleAttributes = (attributes_, context) => {\n if (attributes_) {\n const end = attributes?.(attributes_, context);\n if (value) {\n for (const value_ of Object.values(attributes_)) {\n if (value_ !== true)\n value(value_, context, 'attribute');\n }\n }\n end?.();\n }\n };\n const handleElement = (exp, context) => {\n if (typeof exp === 'object') {\n let end;\n switch (exp.type) {\n case 'expression': {\n end = expression?.(exp, context);\n if (exp.arg)\n value?.(exp.arg, context, 'arg');\n if (exp.functionRef) {\n const endA = functionRef?.(exp.functionRef, context, exp.arg);\n handleOptions(exp.functionRef.options, context);\n endA?.();\n }\n handleAttributes(exp.attributes, context);\n break;\n }\n case 'markup': {\n end = markup?.(exp, context);\n handleOptions(exp.options, context);\n handleAttributes(exp.attributes, context);\n break;\n }\n }\n end?.();\n }\n };\n const handlePattern = (pat) => {\n const end = pattern?.(pat);\n for (const el of pat)\n handleElement(el, 'placeholder');\n end?.();\n };\n for (const decl of msg.declarations) {\n const end = declaration?.(decl);\n if (decl.value)\n handleElement(decl.value, 'declaration');\n end?.();\n }\n if (msg.type === 'message') {\n handlePattern(msg.pattern);\n }\n else {\n if (value)\n for (const sel of msg.selectors)\n value(sel, 'selector', 'arg');\n for (const vari of msg.variants) {\n const end = variant?.(vari);\n if (key)\n vari.keys.forEach(key);\n handlePattern(vari.value);\n end?.();\n }\n }\n}\n",
|
|
21
|
+
"import { MessageDataModelError } from \"../errors.js\";\nimport { visit } from \"./visit.js\";\n/**\n * Ensure that the `msg` data model is _valid_, calling `onError` on errors.\n * If `onError` is not defined, a {@link MessageDataModelError} will be thrown on error.\n *\n * Detects the following errors:\n *\n * - `'key-mismatch'`: **Variant Key Mismatch**<br>\n * The number of keys on a _variant_ does not equal the number of _selectors_.\n *\n * - `'missing-fallback'`: **Missing Fallback Variant**<br>\n * The message does not include a _variant_ with only catch-all keys.\n *\n * - `'missing-selector-annotation'`: **Missing Selector Annotation**<br>\n * A _selector_ does not contains a _variable_ that directly or indirectly\n * reference a _declaration_ with a _function_.\n *\n * - `'duplicate-declaration'`: **Duplicate Declaration**<br>\n * A _variable_ appears in two _declarations_.\n *\n * - `'duplicate-variant'`: **Duplicate Variant**<br>\n * The same list of _keys_ is used for more than one _variant_.\n *\n * @category Message Data Model\n * @returns The sets of runtime `functions` and `variables` used by the message.\n */\nexport function validate(msg, onError = (type, node) => {\n throw new MessageDataModelError(type, node);\n}) {\n let selectorCount = 0;\n let missingFallback = null;\n /** Tracks directly & indirectly annotated variables for `missing-selector-annotation` */\n const annotated = new Set();\n /** Tracks declared variables for `duplicate-declaration` */\n const declared = new Set();\n const functions = new Set();\n const localVars = new Set();\n const variables = new Set();\n const variants = new Set();\n let setArgAsDeclared = true;\n visit(msg, {\n declaration(decl) {\n // Skip all ReservedStatement\n if (!decl.name)\n return undefined;\n if (decl.value.functionRef ||\n (decl.type === 'local' &&\n decl.value.arg?.type === 'variable' &&\n annotated.has(decl.value.arg.name))) {\n annotated.add(decl.name);\n }\n if (decl.type === 'local')\n localVars.add(decl.name);\n setArgAsDeclared = decl.type === 'local';\n return () => {\n if (declared.has(decl.name))\n onError('duplicate-declaration', decl);\n else\n declared.add(decl.name);\n };\n },\n expression({ functionRef }) {\n if (functionRef)\n functions.add(functionRef.name);\n },\n value(value, context, position) {\n if (value.type !== 'variable')\n return;\n variables.add(value.name);\n switch (context) {\n case 'declaration':\n if (position !== 'arg' || setArgAsDeclared) {\n declared.add(value.name);\n }\n break;\n case 'selector':\n selectorCount += 1;\n missingFallback = value;\n if (!annotated.has(value.name)) {\n onError('missing-selector-annotation', value);\n }\n }\n },\n variant(variant) {\n const { keys } = variant;\n if (keys.length !== selectorCount)\n onError('key-mismatch', variant);\n const strKeys = JSON.stringify(keys.map(key => (key.type === 'literal' ? key.value : 0)));\n if (variants.has(strKeys))\n onError('duplicate-variant', variant);\n else\n variants.add(strKeys);\n missingFallback &&= keys.every(key => key.type === '*') ? null : variant;\n }\n });\n if (missingFallback)\n onError('missing-fallback', missingFallback);\n for (const lv of localVars)\n variables.delete(lv);\n return { functions, variables };\n}\n",
|
|
22
|
+
"export const LRI = '\\u2066';\nexport const RLI = '\\u2067';\nexport const FSI = '\\u2068';\nexport const PDI = '\\u2069';\n// Data source: RECOMMENDED and LIMITED_USE scripts from\n// https://github.com/unicode-org/cldr/blob/1a914d1/common/properties/scriptMetadata.txt\nconst RTL = 'Adlm,Arab,Hebr,Mand,Nkoo,Rohg,Syrc,Thaa';\n/** Get a default text direction for `locale`. */\nexport function getLocaleDir(locale) {\n if (locale) {\n try {\n if (typeof locale === 'string')\n locale = new Intl.Locale(locale);\n // @ts-expect-error -- New feature, API changed during Stage 3\n const info = locale.getTextInfo?.() ?? locale.textInfo;\n if (info?.direction)\n return info.direction;\n const script = locale.maximize().script;\n if (script)\n return RTL.includes(script) ? 'rtl' : 'ltr';\n }\n catch {\n // Use 'auto' on error\n }\n }\n return 'auto';\n}\n",
|
|
23
|
+
"/**\n * Utility function for custom functions.\n * Cast a value as a Boolean,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts `'true'` and `'false'`.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asBoolean(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (typeof value === 'boolean')\n return value;\n if (value && typeof value === 'object')\n value = String(value);\n if (value === 'true')\n return true;\n if (value === 'false')\n return false;\n throw new RangeError('Not a boolean');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a non-negative integer,\n * unwrapping objects using their `valueOf()` methods.\n * Also accepts JSON string reprentations of integers.\n * Throws a `RangeError` for invalid inputs.\n *\n * The default functions use this to validate _digit size options_.\n */\nexport function asPositiveInteger(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (value && typeof value === 'object')\n value = String(value);\n if (typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value)) {\n value = Number(value);\n }\n if (typeof value === 'number' && value >= 0 && Number.isInteger(value)) {\n return value;\n }\n throw new RangeError('Not a positive integer');\n}\n/**\n * Utility function for custom functions.\n * Cast a value as a string,\n * unwrapping objects using their `valueOf()` methods.\n * Throws a `RangeError` for invalid inputs.\n */\nexport function asString(value) {\n if (value && typeof value === 'object')\n value = value.valueOf();\n if (typeof value === 'string')\n return value;\n if (value && typeof value === 'object')\n return String(value);\n throw new RangeError('Not a string');\n}\n",
|
|
24
|
+
"import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\nexport function readNumericOperand(value) {\n let options = undefined;\n if (typeof value === 'object') {\n const valueOf = value?.valueOf;\n if (typeof valueOf === 'function') {\n options = value.options;\n value = valueOf.call(value);\n }\n }\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value);\n }\n catch {\n // handled below\n }\n }\n if (typeof value !== 'bigint' && typeof value !== 'number') {\n throw new MessageFunctionError('bad-operand', 'Input is not numeric');\n }\n return { value, options };\n}\nexport function getMessageNumber(ctx, value, options, canSelect) {\n let { dir, locales } = ctx;\n // @ts-expect-error We may have been a bit naughty earlier.\n if (options.useGrouping === 'never')\n options.useGrouping = false;\n if (canSelect &&\n 'select' in options &&\n !ctx.literalOptionKeys.has('select')) {\n ctx.onError('bad-option', 'The option select may only be set by a literal value');\n canSelect = false;\n }\n let locale;\n let nf;\n let cat;\n let str;\n return {\n type: 'number',\n get dir() {\n if (dir == null) {\n locale ??= Intl.NumberFormat.supportedLocalesOf(locales, options)[0];\n dir = getLocaleDir(locale);\n }\n return dir;\n },\n get options() {\n return { ...options };\n },\n selectKey: canSelect\n ? keys => {\n let numVal = value;\n if (options.style === 'percent') {\n if (typeof numVal === 'bigint')\n numVal *= 100n;\n else\n numVal *= 100;\n }\n const str = String(numVal);\n if (keys.has(str))\n return str;\n if (options.select === 'exact')\n return null;\n const pluralOpt = options.select\n ? { ...options, select: undefined, type: options.select }\n : options;\n // Intl.PluralRules needs a number, not bigint\n cat ??= new Intl.PluralRules(locales, pluralOpt).select(Number(numVal));\n return keys.has(cat) ? cat : null;\n }\n : undefined,\n toParts() {\n nf ??= new Intl.NumberFormat(locales, options);\n const parts = nf.formatToParts(value);\n locale ??= nf.resolvedOptions().locale;\n dir ??= getLocaleDir(locale);\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'number', dir, locale, parts }]\n : [{ type: 'number', locale, parts }];\n },\n toString() {\n nf ??= new Intl.NumberFormat(locales, options);\n str ??= nf.format(value);\n return str;\n },\n valueOf: () => value\n };\n}\nexport function number(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const value = input.value;\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'decimal'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'minimumIntegerDigits':\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n case 'roundingMode':\n case 'roundingPriority':\n case 'select': // Called 'type' in Intl.PluralRules\n case 'signDisplay':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :number option ${name}`);\n }\n }\n return getMessageNumber(ctx, value, options, true);\n}\nexport function integer(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const value = Number.isFinite(input.value)\n ? Math.round(input.value)\n : input.value;\n const options = Object.assign({}, input.options, {\n //localeMatcher: ctx.localeMatcher,\n maximumFractionDigits: 0,\n minimumFractionDigits: undefined,\n minimumSignificantDigits: undefined,\n style: 'decimal'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'minimumIntegerDigits':\n case 'maximumSignificantDigits':\n options[name] = asPositiveInteger(optval);\n break;\n case 'select': // Called 'type' in Intl.PluralRules\n case 'signDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :integer option ${name}`);\n }\n }\n return getMessageNumber(ctx, value, options, true);\n}\n",
|
|
25
|
+
"import { MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `currency` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `currency` property.\n *\n * @beta\n */\nexport function currency(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'currency'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'currency':\n case 'currencySign':\n case 'roundingMode':\n case 'roundingPriority':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumIntegerDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n case 'currencyDisplay': {\n const strval = asString(optval);\n if (strval === 'never') {\n ctx.onError('unsupported-operation', 'Currency display \"never\" is not yet supported');\n }\n else {\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = strval;\n }\n break;\n }\n case 'fractionDigits': {\n const strval = asString(optval);\n if (strval === 'auto') {\n options.minimumFractionDigits = undefined;\n options.maximumFractionDigits = undefined;\n }\n else {\n const numval = asPositiveInteger(strval);\n options.minimumFractionDigits = numval;\n options.maximumFractionDigits = numval;\n }\n break;\n }\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n }\n }\n if (!options.currency) {\n throw new MessageFunctionError('bad-operand', 'A currency code is required for :currency');\n }\n return getMessageNumber(ctx, input.value, options, false);\n}\n",
|
|
26
|
+
"import { getLocaleDir } from \"../dir-utils.js\";\nimport { MessageFunctionError } from \"../errors.js\";\nimport { asBoolean, asString } from \"./utils.js\";\nconst dateFieldsValues = new Set([\n 'weekday',\n 'day-weekday',\n 'month-day',\n 'month-day-weekday',\n 'year-month-day',\n 'year-month-day-weekday'\n]);\nconst dateLengthValues = new Set(['long', 'medium', 'short']);\nconst timePrecisionValues = new Set(['hour', 'minute', 'second']);\nconst timeZoneStyleValues = new Set(['long', 'short']);\n/**\n * The function `:datetime` is used to format a date/time value.\n * Its formatted result will always include both the date and the time, and optionally a timezone.\n *\n * @beta\n */\nexport const datetime = (ctx, options, operand) => dateTimeImplementation('datetime', ctx, options, operand);\n/**\n * The function `:date` is used to format the date portion of date/time values.\n *\n * @beta\n */\nexport const date = (ctx, options, operand) => dateTimeImplementation('date', ctx, options, operand);\n/**\n * The function `:time` is used to format the time portion of date/time values.\n * Its formatted result will always include the time, and optionally a timezone.\n *\n * @beta\n */\nexport const time = (ctx, options, operand) => dateTimeImplementation('time', ctx, options, operand);\nfunction dateTimeImplementation(functionName, ctx, exprOpt, operand) {\n const options = {\n localeMatcher: ctx.localeMatcher\n };\n let value = operand;\n if (typeof value === 'object' && value !== null) {\n const opt = value.options;\n if (opt) {\n options.calendar = opt.calendar;\n if (functionName !== 'date')\n options.hour12 = opt.hour12;\n options.timeZone = opt.timeZone;\n }\n if (typeof value.valueOf === 'function')\n value = value.valueOf();\n }\n switch (typeof value) {\n case 'number':\n case 'string':\n value = new Date(value);\n }\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new MessageFunctionError('bad-operand', 'Input is not a valid date');\n }\n // Override options\n if (exprOpt.calendar !== undefined) {\n try {\n options.calendar = asString(exprOpt.calendar);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} calendar option value`);\n }\n }\n if (exprOpt.hour12 !== undefined && functionName !== 'date') {\n try {\n options.hour12 = asBoolean(exprOpt.hour12);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} hour12 option value`);\n }\n }\n if (exprOpt.timeZone !== undefined) {\n let tz;\n try {\n tz = asString(exprOpt.timeZone);\n }\n catch {\n ctx.onError('bad-option', `Invalid :${functionName} timeZone option value`);\n }\n if (tz === 'input') {\n if (options.timeZone === undefined) {\n ctx.onError('bad-operand', `Missing input timeZone value for :${functionName}`);\n }\n }\n else if (tz !== undefined) {\n if (options.timeZone !== undefined && tz !== options.timeZone) {\n // Use fallback value for expression\n throw new MessageFunctionError('bad-option', 'Time zone conversion is not supported');\n }\n options.timeZone = tz;\n }\n }\n // Date formatting options\n if (functionName !== 'time') {\n const dfName = functionName === 'date' ? 'fields' : 'dateFields';\n const dlName = functionName === 'date' ? 'length' : 'dateLength';\n const dateFieldsValue = readStringOption(ctx, exprOpt, dfName, dateFieldsValues) ??\n 'year-month-day';\n const dateLength = readStringOption(ctx, exprOpt, dlName, dateLengthValues);\n const dateFields = new Set(dateFieldsValue.split('-'));\n if (dateFields.has('year'))\n options.year = 'numeric';\n if (dateFields.has('month')) {\n options.month =\n dateLength === 'long'\n ? 'long'\n : dateLength === 'short'\n ? 'numeric'\n : 'short';\n }\n if (dateFields.has('day'))\n options.day = 'numeric';\n if (dateFields.has('weekday')) {\n options.weekday = dateLength === 'long' ? 'long' : 'short';\n }\n }\n // Time formatting options\n if (functionName !== 'date') {\n const tpName = functionName === 'time' ? 'precision' : 'timePrecision';\n switch (readStringOption(ctx, exprOpt, tpName, timePrecisionValues)) {\n case 'hour':\n options.hour = 'numeric';\n break;\n case 'second':\n options.hour = 'numeric';\n options.minute = 'numeric';\n options.second = 'numeric';\n break;\n default:\n options.hour = 'numeric';\n options.minute = 'numeric';\n }\n options.timeZoneName = readStringOption(ctx, exprOpt, 'timeZoneStyle', timeZoneStyleValues);\n }\n // Resolved value\n const dtf = new Intl.DateTimeFormat(ctx.locales, options);\n let dir = ctx.dir;\n let locale;\n let str;\n return {\n type: 'datetime',\n get dir() {\n if (dir == null) {\n locale ??= dtf.resolvedOptions().locale;\n dir = getLocaleDir(locale);\n }\n return dir;\n },\n get options() {\n return { ...options };\n },\n toParts() {\n const parts = dtf.formatToParts(value);\n locale ??= dtf.resolvedOptions().locale;\n dir ??= getLocaleDir(locale);\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'datetime', dir, locale, parts }]\n : [{ type: 'datetime', locale, parts }];\n },\n toString() {\n str ??= dtf.format(value);\n return str;\n },\n valueOf: () => value\n };\n}\nfunction readStringOption(ctx, options, name, allowed) {\n const value = options[name];\n if (value !== undefined) {\n try {\n const str = asString(value);\n if (allowed && !allowed.has(str))\n throw Error();\n return str;\n }\n catch {\n ctx.onError('bad-option', `Invalid value for ${name} option`);\n }\n }\n return undefined;\n}\n",
|
|
27
|
+
"import { MessageFunctionError } from \"../errors.js\";\nimport { number, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger } from \"./utils.js\";\n/**\n * `offset` accepts a numeric value as input and adds or subtracts an integer value from it\n *\n * @beta\n */\nexport function offset(ctx, exprOpt, operand) {\n let { value, options } = readNumericOperand(operand);\n let add;\n try {\n add = 'add' in exprOpt ? asPositiveInteger(exprOpt.add) : -1;\n }\n catch {\n throw new MessageFunctionError('bad-option', `Value ${exprOpt.add} is not valid for :offset option add`);\n }\n let sub;\n try {\n sub = 'subtract' in exprOpt ? asPositiveInteger(exprOpt.subtract) : -1;\n }\n catch {\n throw new MessageFunctionError('bad-option', `Value ${exprOpt.subtract} is not valid for :offset option subtract`);\n }\n if (add < 0 === sub < 0) {\n const msg = 'Exactly one of \"add\" or \"subtract\" is required as an :offset option';\n throw new MessageFunctionError('bad-option', msg);\n }\n const delta = add < 0 ? -sub : add;\n if (typeof value === 'number')\n value += delta;\n else\n value += BigInt(delta);\n return number(ctx, {}, { valueOf: () => value, options });\n}\n",
|
|
28
|
+
"import { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * The function `:percent` is a selector and formatter for percent values.\n *\n * @beta\n */\nexport function percent(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'percent'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'roundingMode':\n case 'roundingPriority':\n case 'signDisplay':\n case 'trailingZeroDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n options[name] = asPositiveInteger(optval);\n break;\n }\n }\n catch {\n ctx.onError('bad-option', `Value ${optval} is not valid for :percent option ${name}`);\n }\n }\n return getMessageNumber(ctx, input.value, options, true);\n}\n",
|
|
29
|
+
"export function string(ctx, _options, operand) {\n const str = operand === undefined ? '' : String(operand);\n const selStr = str.normalize();\n return {\n type: 'string',\n dir: ctx.dir ?? 'auto',\n selectKey: keys => (keys.has(selStr) ? selStr : null),\n toParts() {\n const { dir } = ctx;\n const locale = ctx.locales[0];\n return dir === 'ltr' || dir === 'rtl'\n ? [{ type: 'string', dir, locale, value: str }]\n : [{ type: 'string', locale, value: str }];\n },\n toString: () => str,\n valueOf: () => str\n };\n}\n",
|
|
30
|
+
"import { MessageError, MessageFunctionError } from \"../errors.js\";\nimport { getMessageNumber, readNumericOperand } from \"./number.js\";\nimport { asPositiveInteger, asString } from \"./utils.js\";\n/**\n * `unit` accepts as input numerical values as well as\n * objects wrapping a numerical value that also include a `unit` property.\n *\n * @beta\n */\nexport function unit(ctx, exprOpt, operand) {\n const input = readNumericOperand(operand);\n const options = Object.assign({}, input.options, {\n localeMatcher: ctx.localeMatcher,\n style: 'unit'\n });\n for (const [name, optval] of Object.entries(exprOpt)) {\n if (optval === undefined)\n continue;\n try {\n switch (name) {\n case 'signDisplay':\n case 'roundingMode':\n case 'roundingPriority':\n case 'trailingZeroDisplay':\n case 'unit':\n case 'unitDisplay':\n case 'useGrouping':\n // @ts-expect-error Let Intl.NumberFormat construction fail\n options[name] = asString(optval);\n break;\n case 'minimumIntegerDigits':\n case 'minimumFractionDigits':\n case 'maximumFractionDigits':\n case 'minimumSignificantDigits':\n case 'maximumSignificantDigits':\n case 'roundingIncrement':\n // @ts-expect-error TS types don't know about roundingIncrement\n options[name] = asPositiveInteger(optval);\n break;\n }\n }\n catch (error) {\n if (error instanceof MessageError) {\n ctx.onError(error);\n }\n else {\n ctx.onError('bad-option', `Value ${optval} is not valid for :currency option ${name}`);\n }\n }\n }\n if (!options.unit) {\n throw new MessageFunctionError('bad-operand', 'A unit identifier is required for :unit');\n }\n return getMessageNumber(ctx, input.value, options, false);\n}\n",
|
|
31
|
+
"/**\n * Implementations for :number, :string, and other default functions,\n * along with some utilities for building custom function handlers.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgSrc, { functions: DraftFunctions });\n * ```\n *\n * @module\n */\nexport { getLocaleDir } from \"../dir-utils.js\";\nexport { asBoolean, asPositiveInteger, asString } from \"./utils.js\";\nimport { currency } from \"./currency.js\";\nimport { date, datetime, time } from \"./datetime.js\";\nimport { integer, number } from \"./number.js\";\nimport { offset } from \"./offset.js\";\nimport { percent } from \"./percent.js\";\nimport { string } from \"./string.js\";\nimport { unit } from \"./unit.js\";\n/**\n * Functions classified as REQUIRED by the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48.2 MessageFormat specification}.\n */\nexport let DefaultFunctions = {\n /**\n * Supports formatting as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-currency-function | :currency function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n *\n * The `currency` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n */\n currency,\n /**\n * Supports formatting and selection as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-integer-function | :integer function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n integer,\n /**\n * Supports formatting and selection as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-number-function | :number function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n number,\n /**\n * Supports formatting and selection as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-offset-function | :offset function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n offset,\n /**\n * Supports formatting as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-percent-function | :percent function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n percent,\n /**\n * Supports formatting and selection as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-string-function | :string function}.\n *\n * The `operand` must be a stringifiable value.\n * An `undefined` value is resolved as an empty string.\n */\n string\n};\nDefaultFunctions = Object.freeze(Object.assign(Object.create(null), DefaultFunctions));\n/**\n * Functions classified as DRAFT by the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48.2 MessageFormat specification}.\n *\n * These are liable to change, and are **_not_** covered by any stability guarantee.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const mf = new MessageFormat(locale, msgsrc, { functions: DraftFunctions });\n * ```\n *\n * @beta\n */\nexport let DraftFunctions = {\n /**\n * Supports formatting as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-date-function | :date function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n date,\n /**\n * Supports formatting as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-datetime-function | :datetime function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n datetime,\n /**\n * Supports formatting as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-time-function | :time function}.\n *\n * The `operand` must be a Date, number, or string representing a date,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n */\n time,\n /**\n * Supports formatting as defined in LDML 48.2 for the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#the-unit-function | :unit function}.\n *\n * The `operand` must be a number, BigInt, or string representing a JSON number,\n * or an object wrapping such a value, with a `valueOf()` accessor and an optional `options` object.\n *\n * The `unit` option must be provided by either the operand's `options` or the `exprOpt` expression options.\n */\n unit\n};\nDraftFunctions = Object.freeze(Object.assign(Object.create(null), DraftFunctions));\n",
|
|
32
|
+
"export const BIDI_ISOLATE = Symbol('bidi-isolate');\n",
|
|
33
|
+
"export const fallback = (source = '�') => ({\n type: 'fallback',\n source,\n toParts: () => [{ type: 'fallback', source }],\n toString: () => `{${source}}`\n});\n",
|
|
34
|
+
"export const unknown = (source, input) => ({\n type: 'unknown',\n source,\n dir: 'auto',\n toParts: () => [{ type: 'unknown', value: input }],\n toString: () => String(input),\n valueOf: () => input\n});\n",
|
|
35
|
+
"import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport class MessageFunctionContext {\n #ctx;\n #litKeys;\n #source;\n dir;\n id;\n constructor(ctx, source, options) {\n this.#ctx = ctx;\n this.#source = source;\n this.dir = undefined;\n const dirOpt = options && Object.hasOwn(options, 'u:dir') ? options['u:dir'] : undefined;\n if (dirOpt) {\n const dir = String(resolveValue(ctx, dirOpt));\n if (dir === 'ltr' || dir === 'rtl' || dir === 'auto') {\n this.dir = dir;\n }\n else if (dir !== 'inherit') {\n const error = new MessageFunctionError('bad-option', 'Unsupported value for u:dir option');\n error.source = getValueSource(dirOpt);\n ctx.onError(error);\n }\n }\n const idOpt = options && Object.hasOwn(options, 'u:id') ? options['u:id'] : undefined;\n this.id = idOpt ? String(resolveValue(ctx, idOpt)) : undefined;\n if (options) {\n this.#litKeys = new Set();\n for (const [key, value] of Object.entries(options)) {\n if (value.type === 'literal')\n this.#litKeys.add(key);\n }\n }\n }\n get literalOptionKeys() {\n return new Set(this.#litKeys);\n }\n get localeMatcher() {\n return this.#ctx.localeMatcher;\n }\n get locales() {\n return this.#ctx.locales.map(String);\n }\n onError(error, message) {\n let mfError;\n if (error instanceof MessageFunctionError) {\n mfError = error;\n }\n else if (typeof error === 'string' && typeof message === 'string') {\n mfError = new MessageFunctionError(error, message);\n }\n else {\n mfError = new MessageFunctionError('function-error', String(error));\n mfError.cause = error;\n }\n mfError.source = this.#source;\n this.#ctx.onError(mfError);\n }\n}\n",
|
|
36
|
+
"import { MessageError, MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { BIDI_ISOLATE } from \"../message-value.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function resolveFunctionRef(ctx, operand, { name, options }) {\n const fnSource = `:${name}`;\n const source = getValueSource(operand) ?? fnSource;\n try {\n const fnInput = operand ? [resolveValue(ctx, operand)] : [];\n const rf = ctx.functions[name];\n if (!rf) {\n throw new MessageResolutionError('unknown-function', `Unknown function ${fnSource}`, source);\n }\n const msgCtx = new MessageFunctionContext(ctx, source, options);\n const opt = resolveOptions(ctx, options);\n const res = rf(msgCtx, opt, ...fnInput);\n if (res === null ||\n typeof res !== 'object' ||\n typeof res.type !== 'string') {\n throw new MessageResolutionError('bad-function-result', `Function ${fnSource} did not return a MessageValue`, source);\n }\n const override = { source };\n if (msgCtx.dir) {\n override.dir = msgCtx.dir;\n override[BIDI_ISOLATE] = true;\n }\n if (msgCtx.id && typeof res.toParts === 'function') {\n override.toParts = () => {\n const parts = res.toParts();\n for (const part of parts)\n part.id = msgCtx.id;\n return parts;\n };\n }\n return { ...res, ...override };\n }\n catch (error) {\n ctx.onError(error instanceof MessageError\n ? error\n : new MessageResolutionError('bad-function-result', String(error), source, error));\n return fallback(source);\n }\n}\nfunction resolveOptions(ctx, options) {\n const opt = Object.create(null);\n if (options) {\n for (const [name, value] of Object.entries(options)) {\n if (!name.startsWith('u:'))\n opt[name] = resolveValue(ctx, value);\n }\n }\n return opt;\n}\n",
|
|
37
|
+
"import { string } from \"../functions/string.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveFunctionRef } from \"./resolve-function-ref.js\";\nimport { resolveVariableRef } from \"./resolve-variable.js\";\nexport function resolveExpression(ctx, { arg, functionRef }) {\n if (functionRef) {\n return resolveFunctionRef(ctx, arg, functionRef);\n }\n switch (arg?.type) {\n case 'literal': {\n const source = `|${arg.value}|`;\n const msgCtx = new MessageFunctionContext(ctx, source);\n const msgStr = string(msgCtx, {}, arg.value);\n msgStr.source = source;\n return msgStr;\n }\n case 'variable':\n return resolveVariableRef(ctx, arg);\n default:\n // @ts-expect-error - should never happen\n throw new Error(`Unsupported expression: ${arg?.type}`);\n }\n}\n",
|
|
38
|
+
"import { MessageResolutionError } from \"../errors.js\";\nimport { fallback } from \"../functions/fallback.js\";\nimport { unknown } from \"../functions/unknown.js\";\nimport { MessageFunctionContext } from \"./function-context.js\";\nimport { resolveExpression } from \"./resolve-expression.js\";\n/**\n * Declarations aren't resolved until they're requierd,\n * and their resolution order matters for variable resolution.\n * This internal class is used to store any required data,\n * and to allow for `instanceof` detection.\n *\n * @internal\n */\nexport class UnresolvedExpression {\n expression;\n scope;\n constructor(expression, scope) {\n this.expression = expression;\n this.scope = scope;\n }\n}\nconst isScope = (scope) => scope !== null && (typeof scope === 'object' || typeof scope === 'function');\n/**\n * Looks for the longest matching `.` delimited starting substring of name.\n * @returns `undefined` if value not found\n */\nfunction getValue(scope, name) {\n if (isScope(scope)) {\n if (name in scope)\n return scope[name];\n const parts = name.split('.');\n for (let i = parts.length - 1; i > 0; --i) {\n const head = parts.slice(0, i).join('.');\n if (head in scope) {\n const tail = parts.slice(i).join('.');\n return getValue(scope[head], tail);\n }\n }\n for (const [key, value] of Object.entries(scope)) {\n if (key.normalize() === name)\n return value;\n }\n }\n return undefined;\n}\n/**\n * Get the raw value of a variable.\n * Resolves declarations as necessary\n *\n * @internal\n * @returns `unknown` or `any` for input values;\n * `MessageValue` for `.input` and `.local` declaration values.\n */\nexport function lookupVariableRef(ctx, { name }) {\n const value = getValue(ctx.scope, name);\n if (value === undefined) {\n const source = '$' + name;\n const msg = `Variable not available: ${source}`;\n ctx.onError(new MessageResolutionError('unresolved-variable', msg, source));\n }\n else if (value instanceof UnresolvedExpression) {\n const local = resolveExpression(value.scope ? { ...ctx, scope: value.scope } : ctx, value.expression);\n ctx.scope[name] = local;\n ctx.localVars.add(local);\n return local;\n }\n return value;\n}\nexport function resolveVariableRef(ctx, ref) {\n const source = '$' + ref.name;\n const value = lookupVariableRef(ctx, ref);\n if (value === undefined)\n return fallback(source);\n let type = typeof value;\n if (type === 'object') {\n const mv = value;\n if (mv.type === 'fallback')\n return fallback(source);\n if (ctx.localVars.has(mv)) {\n mv.source = source;\n return mv;\n }\n if (value instanceof Number)\n type = 'number';\n else if (value instanceof String)\n type = 'string';\n }\n let msgFn;\n switch (type) {\n case 'bigint':\n case 'number':\n msgFn = ctx.functions.number;\n break;\n case 'string':\n msgFn = ctx.functions.string;\n break;\n default:\n return unknown(source, value);\n }\n const msgCtx = new MessageFunctionContext(ctx, source);\n const mv = msgFn(msgCtx, {}, value);\n mv.source = source;\n return mv;\n}\n",
|
|
39
|
+
"import { lookupVariableRef } from \"./resolve-variable.js\";\nexport function resolveValue(ctx, value) {\n switch (value.type) {\n case 'literal':\n return value.value;\n case 'variable':\n return lookupVariableRef(ctx, value);\n default:\n // @ts-expect-error - should never happen\n throw new Error(`Unsupported value: ${value.type}`);\n }\n}\nexport function getValueSource(value) {\n switch (value?.type) {\n case 'literal':\n return ('|' + value.value.replaceAll('\\\\', '\\\\\\\\').replaceAll('|', '\\\\|') + '|');\n case 'variable':\n return '$' + value.name;\n default:\n return undefined;\n }\n}\n",
|
|
40
|
+
"import { MessageFunctionError } from \"../errors.js\";\nimport { getValueSource, resolveValue } from \"./resolve-value.js\";\nexport function formatMarkup(ctx, { kind, name, options }) {\n const part = { type: 'markup', kind, name };\n const entries = options ? Object.entries(options) : null;\n if (entries?.length) {\n part.options = {};\n for (const [name, value] of entries) {\n if (name === 'u:dir') {\n const error = new MessageFunctionError('bad-option', `The option ${name} is not valid for markup`);\n error.source = getValueSource(value);\n ctx.onError(error);\n }\n else {\n let rv = resolveValue(ctx, value);\n if (typeof rv === 'object' && typeof rv?.valueOf === 'function') {\n rv = rv.valueOf();\n }\n if (name === 'u:id')\n part.id = String(rv);\n else\n part.options[name] = rv;\n }\n }\n }\n return part;\n}\n",
|
|
41
|
+
"import { MessageResolutionError } from \"./errors.js\";\nimport { resolveVariableRef } from \"./resolve/resolve-variable.js\";\nexport function selectPattern(context, message) {\n if (message.type === 'message')\n return message.pattern;\n // message.type === 'select'\n const ctx = message.selectors.map(sel => {\n const selector = resolveVariableRef(context, sel);\n let selectKey;\n if (typeof selector.selectKey === 'function') {\n selectKey = selector.selectKey.bind(selector);\n }\n else {\n const msg = 'Selector does not support selection';\n context.onError(new MessageResolutionError('bad-selector', msg, selector.source));\n selectKey = () => null;\n }\n return {\n selectKey,\n source: selector.source,\n best: null,\n keys: null\n };\n });\n let candidates = message.variants;\n loop: for (let i = 0; i < ctx.length; ++i) {\n const sc = ctx[i];\n if (!sc.keys) {\n sc.keys = new Set();\n for (const { keys } of candidates) {\n const key = keys[i];\n if (!key)\n break loop; // key-mismatch error\n if (key.type !== '*')\n sc.keys.add(key.value);\n }\n }\n try {\n sc.best = sc.keys.size ? sc.selectKey(sc.keys) : null;\n }\n catch (error) {\n const msg = 'Selection failed';\n context.onError(new MessageResolutionError('bad-selector', msg, sc.source, error));\n sc.selectKey = () => null;\n sc.best = null;\n }\n // Leave out all candidate variants that aren't the best,\n // or only the catchall ones, if nothing else matches.\n candidates = candidates.filter(v => {\n const k = v.keys[i];\n if (k.type === '*')\n return sc.best == null;\n return sc.best === k.value;\n });\n // If we've run out of candidates,\n // drop the previous best key of the preceding selector,\n // reset all subsequent key sets,\n // and restart the loop.\n if (candidates.length === 0) {\n if (i === 0)\n break; // No match; should not happen\n const prev = ctx[i - 1];\n if (prev.best == null)\n prev.keys?.clear();\n else\n prev.keys?.delete(prev.best);\n for (let j = i; j < ctx.length; ++j)\n ctx[j].keys = null;\n candidates = message.variants;\n i = -1;\n }\n }\n const res = candidates[0];\n if (!res) {\n // This should not be possible with a valid message.\n const msg = 'No variant was selected!?';\n context.onError(new MessageResolutionError('no-match', msg, '.match'));\n return [];\n }\n return res.value;\n}\n",
|
|
42
|
+
"import { parseMessage } from \"./data-model/parse.js\";\nimport { validate } from \"./data-model/validate.js\";\nimport { FSI, LRI, PDI, RLI, getLocaleDir } from \"./dir-utils.js\";\nimport { MessageFunctionError } from \"./errors.js\";\nimport { DefaultFunctions } from \"./functions/index.js\";\nimport { BIDI_ISOLATE } from \"./message-value.js\";\nimport { formatMarkup } from \"./resolve/format-markup.js\";\nimport { resolveExpression } from \"./resolve/resolve-expression.js\";\nimport { UnresolvedExpression } from \"./resolve/resolve-variable.js\";\nimport { selectPattern } from \"./select-pattern.js\";\n/**\n * A message formatter for that implements the\n * {@link https://www.unicode.org/reports/tr35/tr35-78/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48.2 MessageFormat}\n * specification as well as the {@link https://github.com/tc39/proposal-intl-messageformat/ | TC39 Intl.MessageFormat proposal}.\n *\n * @category Formatting\n * @typeParam T - The `type` used by custom message functions, if any.\n * These extend the {@link DefaultFunctions | default functions}.\n * @typeParam P - The formatted-parts `type` used by any custom message values.\n */\nexport class MessageFormat {\n #bidiIsolation;\n #dir;\n #localeMatcher;\n #locales;\n #message;\n #functions;\n constructor(locales, source, options) {\n this.#bidiIsolation = options?.bidiIsolation !== 'none';\n this.#localeMatcher = options?.localeMatcher ?? 'best fit';\n this.#locales = Array.isArray(locales)\n ? locales.map(lc => new Intl.Locale(lc))\n : locales\n ? [new Intl.Locale(locales)]\n : [];\n this.#dir = options?.dir ?? getLocaleDir(this.#locales[0]);\n this.#message = typeof source === 'string' ? parseMessage(source) : source;\n validate(this.#message);\n this.#functions = options?.functions\n ? Object.assign(Object.create(null), DefaultFunctions, options.functions)\n : DefaultFunctions;\n }\n /**\n * Format a message to a string.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n * mf.format({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n * ```\n *\n * ```js\n * 'Hello Kat, today is March 1, 2025'\n * ```\n *\n * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n * To refer to an inner property of an object value,\n * use `.` as a separator; in case of conflict, the longest starting substring wins.\n * @param onError - Called in case of error.\n * If not set, errors are by default logged as warnings.\n */\n format(msgParams, onError) {\n const ctx = this.#createContext(msgParams, onError);\n let res = '';\n for (const elem of selectPattern(ctx, this.#message)) {\n if (typeof elem === 'string') {\n res += elem;\n }\n else if (elem.type === 'markup') {\n // Handle errors, but discard results\n formatMarkup(ctx, elem);\n }\n else {\n let mv;\n try {\n mv = resolveExpression(ctx, elem);\n if (typeof mv.toString === 'function') {\n if (this.#bidiIsolation &&\n (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n res += pre + mv.toString() + PDI;\n }\n else {\n res += mv.toString();\n }\n }\n else {\n const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n error.source = mv.source;\n throw error;\n }\n }\n catch (error) {\n ctx.onError(error);\n const errStr = `{${mv?.source ?? '�'}}`;\n res += this.#bidiIsolation ? FSI + errStr + PDI : errStr;\n }\n }\n }\n return res;\n }\n /**\n * Format a message to a sequence of parts.\n *\n * ```js\n * import { MessageFormat } from 'messageformat';\n * import { DraftFunctions } from 'messageformat/functions';\n *\n * const msg = 'Hello {$user.name}, today is {$date :date style=long}';\n * const mf = new MessageFormat('en', msg, { functions: DraftFunctions });\n * mf.formatToParts({ user: { name: 'Kat' }, date: new Date('2025-03-01') });\n * ```\n *\n * ```js\n * [\n * { type: 'text', value: 'Hello ' },\n * { type: 'bidiIsolation', value: '\\u2068' },\n * { type: 'string', locale: 'en', value: 'Kat' },\n * { type: 'bidiIsolation', value: '\\u2069' },\n * { type: 'text', value: ', today is ' },\n * {\n * type: 'datetime',\n * dir: 'ltr',\n * locale: 'en',\n * parts: [\n * { type: 'month', value: 'March' },\n * { type: 'literal', value: ' ' },\n * { type: 'day', value: '1' },\n * { type: 'literal', value: ', ' },\n * { type: 'year', value: '2025' }\n * ]\n * }\n * ]\n * ```\n *\n * @param msgParams - Values that may be referenced by `$`-prefixed variable references.\n * To refer to an inner property of an object value,\n * use `.` as a separator; in case of conflict, the longest starting substring wins.\n * @param onError - Called in case of error.\n * If not set, errors are by default logged as warnings.\n */\n formatToParts(msgParams, onError) {\n const ctx = this.#createContext(msgParams, onError);\n const parts = [];\n for (const elem of selectPattern(ctx, this.#message)) {\n if (typeof elem === 'string') {\n parts.push({ type: 'text', value: elem });\n }\n else if (elem.type === 'markup') {\n parts.push(formatMarkup(ctx, elem));\n }\n else {\n let mv;\n try {\n mv = resolveExpression(ctx, elem);\n if (typeof mv.toParts === 'function') {\n // Let's presume that parts that look like MessageNumberPart or MessageStringPart are such.\n const mp = mv.toParts();\n if (this.#bidiIsolation &&\n (this.#dir !== 'ltr' || mv.dir !== 'ltr' || mv[BIDI_ISOLATE])) {\n const pre = mv.dir === 'ltr' ? LRI : mv.dir === 'rtl' ? RLI : FSI;\n parts.push({ type: 'bidiIsolation', value: pre }, ...mp, {\n type: 'bidiIsolation',\n value: PDI\n });\n }\n else {\n parts.push(...mp);\n }\n }\n else {\n const error = new MessageFunctionError('not-formattable', 'Message part is not formattable');\n error.source = mv.source;\n throw error;\n }\n }\n catch (error) {\n ctx.onError(error);\n const fb = {\n type: 'fallback',\n source: mv?.source ?? '�'\n };\n if (this.#bidiIsolation) {\n parts.push({ type: 'bidiIsolation', value: FSI }, fb, {\n type: 'bidiIsolation',\n value: PDI\n });\n }\n else {\n parts.push(fb);\n }\n }\n }\n }\n return parts;\n }\n #createContext(msgParams, onError = (error) => {\n // Emit warning for errors by default\n try {\n process.emitWarning(error);\n }\n catch {\n console.warn(error);\n }\n }) {\n const scope = { ...msgParams };\n for (const decl of this.#message.declarations) {\n scope[decl.name] = new UnresolvedExpression(decl.value, decl.type === 'input' ? (msgParams ?? {}) : undefined);\n }\n const ctx = {\n onError,\n localeMatcher: this.#localeMatcher,\n locales: this.#locales,\n localVars: new WeakSet(),\n functions: this.#functions,\n scope\n };\n return ctx;\n }\n}\n",
|
|
43
|
+
"/**\n * The MessageFormat 2 engine: `messageformat` v4 with every function the\n * standard defines — the default set (`:number`, `:integer`, `:currency`,\n * `:percent`, `:offset`, `:string`) built in, and the draft set (`:date`,\n * `:time`, `:datetime`, `:unit`) added. An engine without `Intl` gets the\n * least of it first (`./intl`).\n *\n * It is a value handed to `I18N`, not an import of it, so the `./runtime`\n * entry ships without it: the full build wires it in, and an app on\n * `./runtime` that translates passes it from `@lipsjs/lips/i18n`.\n */\nimport './intl'\nimport { MessageFormat } from 'messageformat'\nimport { DraftFunctions } from 'messageformat/functions'\nimport type { MessageFormatEngine } from '../types'\n\nexport const messageFormat: MessageFormatEngine = { MessageFormat, functions: DraftFunctions }\n",
|
|
44
|
+
"/**\n * Style IR (RFC-004 Layer 1) — reactive declarations for component stylesheets.\n *\n * stylesheet source\n * │ scanner — lifts {expr} out of declaration VALUES only, hoists the\n * │ at-rules that cannot nest, compacts the text\n * ▼\n * scope wrap `[rel=\"x\"]{…}` — resolved by native CSS nesting, or\n * flattened by an opt-in preprocessor (`@lipsjs/lips/stylis`)\n * ▼\n * StyleIR ──────────► JSON (precompiled module)\n * │\n * ▼\n * runtime: inject `css` verbatim, bind each custom property on the scope roots\n *\n * The sheet is IMMUTABLE once injected. Updates write custom properties on the\n * component's own roots — one shared rule, N per-instance values. Rule-level\n * revision (insert/delete) is Layer 2 and deliberately absent here.\n *\n * Like the template compiler, the CSS preprocessor is INJECTED rather than\n * imported, so the precompiled-only `./runtime` build tree-shakes Stylis out.\n */\n\nimport type { TemplateDiagnostic } from './parser'\nimport { parseExpression, freeRoots } from './expression'\n\n// ------------------------------------------------------------------- types\nexport interface StyleBindIR {\n /** Custom property to write on the scope roots (e.g. '--card-0') */\n prop: string\n /** Index into StyleIR.exprs */\n e: number\n /**\n * Unit appended to the value when it is written: a full-value bind, for\n * engines whose `calc()` cannot multiply a number back into it (Lynx,\n * RFC-006 §3.2)\n */\n u?: string\n}\n\nexport interface PropertyIR {\n name: string\n syntax: string\n inherits: boolean\n initial: string\n}\n\nexport interface StyleIR {\n v: 1\n /**\n * Scope name baked in at compile time. The runtime stamps `rel` with\n * THIS, not the registration name — a precompiled sheet is already\n * scoped to it, and the two must agree.\n */\n nsp: string\n /** Scoped and compact — nested, or flat if a preprocessor ran. Injected verbatim, never re-parsed. */\n css: string\n exprs: string[]\n binds: StyleBindIR[]\n /** @property registrations — makes the variables interpolable (RFC-004 §10) */\n props?: PropertyIR[]\n}\n\nexport interface StyleCompileOptions {\n /** Scope name — the `rel` attribute value, and the variable-name prefix */\n nsp: string\n /** Inject globally instead of scoping to `[rel=\"<nsp>\"]` */\n meta?: boolean\n /** Emit inside `@layer <name>` so utility frameworks can win (RFC-004 §9) */\n layer?: string\n /**\n * CSS preprocessor for this call, overriding any process-wide one.\n *\n * Passed per call rather than only set globally because the opt-in\n * preprocessor ships as a SEPARATE bundle: `@lipsjs/lips/stylis` and\n * `@lipsjs/lips` each carry their own copy of this module, so a global\n * set from one is invisible to the other. Handing the function across\n * the call is the only wiring that survives that boundary.\n */\n preprocess?: StylePreprocessor\n /**\n * The scope wrap's selector, for a host that does not scope by `rel`\n * (Lynx scopes by class, RFC-006 §4.4). Default `[rel=\"<nsp>\"]`.\n */\n scope?: string\n /**\n * What the target cannot do, reported on the source. Passed per call,\n * like the preprocessor, so a target's rules — and their bytes — stay\n * out of the DOM bundles.\n */\n lint?: StyleLint\n}\n\n/**\n * Called on every selector (`text`), at-rule prelude (`text` starting\n * with `@`) and declaration (`text` the property, plus its `value`).\n * Returns its diagnostics; the compiler adds where it is in the source.\n */\nexport type StyleLint = ( text: string, value?: string ) => Omit<TemplateDiagnostic, 'loc'>[] | undefined\n\nexport interface StyleCompileResult {\n ir: StyleIR\n diagnostics: TemplateDiagnostic[]\n}\n\n// ------------------------------------------------------------- preprocessor\nexport type StylePreprocessor = ( css: string ) => string\nlet PREPROCESSOR: StylePreprocessor | null = null\n\n/**\n * Process-wide default preprocessor, `null` to clear it. Only reaches\n * `compileStyle` in the SAME module graph — each published entry bundles\n * its own copy of this module — so outside of tests and source builds,\n * pass `preprocess` per call (`LipsConfig.stylePreprocessor`,\n * `precompile(…, { preprocess })`) instead.\n */\nexport function setStylePreprocessor( fn: StylePreprocessor | null ){ PREPROCESSOR = fn }\nexport function hasStylePreprocessor(){ return !!PREPROCESSOR }\n\n// ------------------------------------------------------------------ scanner\nconst PROP_NAME = /^[-\\w]+$/\nconst UNIT = /^(%|[a-zA-Z]+)/\n\n/**\n * A unit-suffixed slot is registered as `<number>`, NOT as the unit's own\n * type: the unit was lifted into `calc(var(--x) * 1unit)`, so what the bind\n * writes is a bare number. Registering `<percentage>` and then writing `75`\n * makes the value invalid — the property silently falls back to its\n * initial-value and the declaration computes to zero.\n *\n * `<number>` is still the whole §10 payoff: it is what makes the variable\n * interpolable, so transitions through it animate.\n */\nconst NUMBER_SYNTAX: [ string, string ] = [ '<number>', '0' ]\n\nfunction skipString( src: string, i: number ){\n const q = src[ i ]\n i++\n while( i < src.length ){\n if( src[ i ] === '\\\\' ){ i += 2; continue }\n if( src[ i ] === q ) return i + 1\n i++\n }\n return i\n}\nfunction skipComment( src: string, i: number ){\n const end = src.indexOf( '*/', i + 2 )\n return end < 0 ? src.length : end + 2\n}\n/** `// …` up to (not including) the newline — Stylis syntax, not CSS */\nfunction skipLine( src: string, i: number ){\n const end = src.indexOf( '\\n', i + 2 )\n return end < 0 ? src.length : end\n}\n/** A value safe inside a double-quoted CSS string */\nconst quote = ( value: string ) => value.replace( /[\"\\\\]/g, '\\\\$&' )\n\nexport function locOf( src: string, offset: number, length: number ){\n let line = 1, last = -1\n for( let i = 0; i < offset; i++ ) if( src[ i ] === '\\n' ){ line++; last = i }\n return { line, col: offset - last, offset, length }\n}\n\n/**\n * Read a `{…}` at `open` as an interpolation, or return null if it is\n * really a block. The discriminator: expression-shaped content —\n * non-empty, no nested brace, no `;`, and no top-level `:` unless a `?`\n * precedes it (a ternary). That is what tells `color: {state.x}` apart\n * from a nested `a:hover { color: red }`.\n */\nfunction readInterpolation( src: string, open: number ){\n let i = open + 1, nest = 0, question = false, colon = false\n\n while( i < src.length ){\n const c = src[ i ]\n\n if( c === '\"' || c === \"'\" ){ i = skipString( src, i ); continue }\n if( c === '{' || c === ';' ) return null\n if( c === '}' ) break\n\n if( c === '(' || c === '[' ) nest++\n else if( c === ')' || c === ']' ) nest--\n else if( nest === 0 ){\n if( c === '?' ) question = true\n else if( c === ':' && !question ) colon = true\n }\n i++\n }\n\n if( i >= src.length || colon ) return null\n\n const expr = src.slice( open + 1, i ).trim()\n return expr ? { end: i, expr } : null\n}\n\n/**\n * Names a stylesheet expression may read. A sheet is per component and\n * has no template position, so `<for>` iterators and `<let>` names —\n * which are position-local — can never resolve in one.\n */\nconst STYLE_SCOPE = new Set([ 'state', 'input', 'static', 'context', 'self' ])\n\ntype ValuePart = string | { expr: string, unit: string, at: number }\n\n/**\n * Scan a declaration value from `from` to its `;`/`}` terminator, lifting\n * interpolations out. Returns null when the \"declaration\" turns out to be a\n * selector — `a:hover {` enters here on the `:` and aborts at the block.\n */\nfunction readValue(\n src: string,\n from: number,\n keepComments: boolean,\n onUnterminated?: ( at: number ) => void\n): { end: number, parts: ValuePart[] } | null {\n const parts: ValuePart[] = []\n let i = from, lit = from, paren = 0\n\n while( i < src.length ){\n const c = src[ i ]\n\n if( c === '\"' || c === \"'\" ){ i = skipString( src, i ); continue }\n /**\n * A comment is cut to a space — it separates tokens, so `1px`, a\n * comment and `solid` must not fuse into `1pxsolid` — unless a\n * preprocessor will read it.\n * `//` is NOT a comment here: `--api: https://x` is a valid value.\n */\n if( c === '/' && src[ i + 1 ] === '*' ){\n const end = skipComment( src, i )\n if( !keepComments ){\n parts.push( src.slice( lit, i ), ' ' )\n lit = end\n }\n i = end\n continue\n }\n if( c === '(' ){ paren++; i++; continue }\n if( c === ')' ){ paren--; i++; continue }\n\n if( paren === 0 && ( c === ';' || c === '}' ) ){\n parts.push( src.slice( lit, i ) )\n return { end: i, parts }\n }\n\n if( c === '{' ){\n const interp = readInterpolation( src, i )\n if( !interp ){\n // No closing brace at all → an unterminated interpolation, not a block\n src.indexOf( '}', i + 1 ) < 0 && onUnterminated?.( i )\n return null\n }\n\n parts.push( src.slice( lit, i ) )\n\n const m = UNIT.exec( src.slice( interp.end + 1 ) )\n const unit = m ? m[ 1 ] : ''\n\n parts.push({ expr: interp.expr, unit, at: i })\n i = interp.end + 1 + unit.length\n lit = i\n continue\n }\n\n i++\n }\n\n /**\n * Ran to EOF. Harmless for a plain trailing declaration (`--a: red`\n * with no semicolon), but if an interpolation was consumed on the way\n * then its closing brace almost certainly ate the block's — report it\n * rather than emitting silently broken CSS.\n */\n parts.some( p => typeof p !== 'string' ) && onUnterminated?.( from )\n return null\n}\n\n// --------------------------------------------------------------- structure\n/**\n * At-rules that are NOT valid inside a style rule.\n *\n * CSS nesting only admits at-rules whose body is itself a rule list, so a\n * `@keyframes` left inside `[rel=\"x\"] { … }` is dropped by the parser and\n * the animation silently does nothing. These are lifted out of the scope\n * wrap — they are document-global anyway, exactly like the `@property`\n * registrations emitted outside it.\n */\nconst HOISTED_BLOCK = /^@(-\\w+-)?(keyframes|font-face|property|counter-style|font-feature-values|font-palette-values|page|view-transition|position-try|color-profile|function)\\b/i\n/**\n * Statement at-rules that must open the sheet: `@import` is ignored after\n * any other rule, `@charset` must be first, `@namespace` must precede\n * every style rule.\n */\nconst HOISTED_STATEMENT = /^@(import|charset|namespace)\\b/i\n/**\n * Conditional group rules. Their body holds style rules, they nest\n * natively, and they stay INSIDE the scope wrap so what they contain\n * remains scoped. A hoisted at-rule found inside one carries the\n * condition out with it.\n */\nconst GROUP_AT = /^@(media|supports|container|layer|scope|starting-style|document)\\b/i\n\n/**\n * Engines that shipped the FIRST cut of CSS nesting (Chrome 112–119,\n * Safari 16.5–17.1) parse a nested line that starts with an identifier\n * as a declaration, so `button { … }` inside the scope wrap is silently\n * dropped. `& button` is the same selector — a nested relative selector\n * gets an implicit `& ` anyway — and parses wherever nesting does.\n */\nconst TYPE_LEAD = /^([a-zA-Z_*\\\\]|[^\\x00-\\x7f])/\n/** The identifier-ish token a selector opens with — `div`, `svg|rect`, `*` */\nconst LEAD_TOKEN = /^(?:[-\\w*|]|[^\\x00-\\x7f]|\\\\[\\s\\S])+/\n/**\n * Stylis/Sass `&-suffix` / `&__elem` concatenation. Native nesting reads\n * `-suffix` as a type selector instead, so the rule silently matches\n * nothing. (`&div` is fine natively — `&` may precede a type selector.)\n */\nconst CONCAT = /&[-_]/\n\nconst WS = /\\s/\nconst BREAK = /[{};]/\nconst IDENT_CHAR = /[-\\w]/\nconst QUOTED = /\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"|'(?:\\\\[\\s\\S]|[^'\\\\])*'/g\nconst STRING_OR_SPACE = new RegExp(`(${ QUOTED.source })|\\\\s+`, 'g')\nconst COMMENTS = /\\/\\*[\\s\\S]*?\\*\\//g\nconst LAYER = /^@layer\\b/i\n\n/** Fold whitespace runs outside strings to one space */\nconst squash = ( text: string ) => text.replace( STRING_OR_SPACE, ( _, str ) => str || ' ' )\n\n/** Prefix every identifier-led selector in a list with `& ` (see TYPE_LEAD) */\nfunction nestSelector( prelude: string ){\n const parts: string[] = []\n let from = 0, nest = 0\n\n for( let i = 0; i < prelude.length; i++ ){\n const c = prelude[ i ]\n\n if( c === '\\\\' ){ i++; continue }\n if( c === '\"' || c === \"'\" ){ i = skipString( prelude, i ) - 1; continue }\n if( c === '(' || c === '[' ) nest++\n else if( c === ')' || c === ']' ) nest--\n else if( c === ',' && !nest ){\n parts.push( prelude.slice( from, i ) )\n from = i + 1\n }\n }\n parts.push( prelude.slice( from ) )\n\n return parts\n .map( p => {\n // Trim — but not an escaped trailing space (`.a\\ `), which is part of the name\n let s = p.trimStart(), e = s.length\n while( e && WS.test( s[ e - 1 ] ) && s[ e - 2 ] !== '\\\\' ) e--\n s = s.slice( 0, e )\n\n if( !TYPE_LEAD.test( s ) ) return s\n /**\n * `div &` places its parent itself, so `& ` cannot go in front;\n * wrapping the leading token (`:is(div) &`) is the same selector,\n * same specificity, and no longer starts with an identifier.\n */\n return s.includes('&') ? s.replace( LEAD_TOKEN, ':is($&)' ) : `& ${s}`\n })\n .join(',')\n}\n\ninterface Block {\n /**\n * What a selector directly inside this block is: nested in a style\n * rule (`style`), at the top of a global sheet (`top`), or not a style\n * selector at all — keyframe selectors, `@page` margin boxes (`opaque`).\n */\n ctx: 'style' | 'top' | 'opaque'\n /** Prelude of a conditional group rule, carried out by anything hoisted from inside it */\n group?: string\n /** Output offsets of a group's prelude and body — to drop it if hoisting empties it */\n at?: number\n body?: number\n /** Offset in the output where an at-rule being hoisted starts */\n hoist?: number\n}\n\ninterface ScanResult {\n /** The sheet body, still to be wrapped in the scope rule */\n css: string\n /** Statement at-rules that must open the sheet (`@import`, …) */\n statements: string\n /** Block at-rules lifted out of the scope wrap (`@keyframes`, …) */\n hoisted: string\n exprs: string[]\n binds: StyleBindIR[]\n props: PropertyIR[]\n}\n\nfunction scan( src: string, options: StyleCompileOptions, native: boolean, diagnostics: TemplateDiagnostic[] ): ScanResult {\n const\n exprs: string[] = [],\n binds: StyleBindIR[] = [],\n props: PropertyIR[] = [],\n /**\n * Variable names are namespaced by component. @property registration is\n * document-global, so a bare `--0` would collide across components and the\n * last registration would silently win.\n */\n prefix = `--${ options.nsp.replace( /[^a-zA-Z0-9_-]/g, '-' ) }`,\n report = ( code: string, message: string, offset: number, length: number, hint?: string ) =>\n diagnostics.push({ code, severity: 'error', message, hint, loc: locOf( src, offset, length ) }),\n warn = ( code: string, message: string, offset: number, length: number, hint?: string ) =>\n diagnostics.push({ code, severity: 'warning', message, hint, loc: locOf( src, offset, length ) }),\n /** The target's lint, located on the statement `from`…`to` */\n lint = ( text: string, from: number, to: number, value?: string ) =>\n options.lint?.( text, value )?.forEach( d => diagnostics.push({ ...d, loc: locOf( src, from, to - from ) }) )\n\n const slot = ( expr: string ) => {\n let e = exprs.indexOf( expr )\n if( e < 0 ) e = exprs.push( expr ) - 1\n return e\n }\n\n /**\n * Static checks on a lifted expression: names that cannot resolve\n * where a sheet runs, and a unit suffix on a value that is plainly\n * not a number.\n */\n const checkExpr = ( s: { expr: string, unit: string, at: number } ) => {\n const { ast, diagnostics: errors } = parseExpression( s.expr )\n const length = s.expr.length + 2\n\n if( errors.length ){\n report( 'LIPS-S004', `Invalid expression: ${errors[0].message}`, s.at, length )\n return\n }\n\n for( const name of freeRoots( ast ) )\n if( !STYLE_SCOPE.has( name ) && !( name in globalThis ) )\n report( 'LIPS-S003',\n `'${name}' is not readable from a stylesheet`,\n s.at, length,\n 'Stylesheets see state, input, static, context and self — not <for> iterators or <let> names, '\n + 'which are local to a template position.' )\n\n s.unit && ast.t === 'lit' && typeof ast.v === 'string'\n && warn( 'LIPS-S005',\n `Unit '${s.unit}' after a string value`,\n s.at, length,\n `A unit suffix multiplies a number: drop the unit, or return ${s.unit === '%' ? '50' : '8'} instead of a string.` )\n }\n\n /**\n * The output is emitted compact: comments dropped, whitespace runs\n * folded to one space, and dropped entirely beside `{`, `}` and `;`.\n * Without a preprocessor nothing else would minify it, and the sheet\n * would ship as authored — banners, indentation and all — in every\n * `<style>` and every precompiled module.\n *\n * The statement being built (`cur`) is kept apart from the output so\n * far, so reading or rewriting a prelude never copies the whole sheet.\n * A statement always starts right after `{`, `}`, `;` or at the top,\n * where no space is wanted — hence `tail = ''` whenever one is dropped.\n */\n let out = '', cur = '', tail = '', gap = false\n\n const emit = ( text: string ) => {\n if( !text ) return\n if( gap && tail && !BREAK.test( tail ) && !BREAK.test( text[ 0 ] ) ) cur += ' '\n gap = false\n cur += text\n tail = text[ text.length - 1 ]\n }\n /** End the statement: it joins the output, followed by its terminator */\n const flush = ( end: string ) => {\n out += cur + end\n cur = ''\n tail = end\n gap = false\n }\n /** Drop the statement being built, returning it */\n const drop = () => {\n const text = cur\n cur = tail = ''\n gap = false\n return text\n }\n\n /** Declaration values: folded, trimmed, never emptied (`--x: ;` is a value) */\n const value = ( text: string ) => ':' + ( squash( text ).trim() || ' ' )\n\n let\n i = 0, paren = 0,\n /** Statement start in the source */\n stmt = 0,\n statements = '', hoisted = '',\n /** Conditions the last hoisted rule was carried out with */\n lastGroups = '',\n /** An interpolation that ate a closing brace — already reported as the cause */\n unterminated = false\n\n const\n stack: Block[] = [{ ctx: options.meta ? 'top' : 'style' }]\n\n const open = () => {\n const\n parent = stack[ stack.length - 1 ],\n prelude = cur\n\n let block: Block\n\n // Keyframe selectors (`from`, `50%`) are not style selectors\n parent.ctx === 'opaque' || lint( prelude, stmt, i )\n\n if( prelude[ 0 ] === '@' ){\n if( parent.ctx !== 'opaque' && HOISTED_BLOCK.test( prelude ) ) block = { ctx: 'opaque', hoist: out.length }\n else if( GROUP_AT.test( prelude ) ) block = { ctx: parent.ctx, group: prelude, at: out.length }\n else block = { ctx: 'opaque' }\n }\n else {\n if( parent.ctx === 'style' ){\n /**\n * Only a sheet that ships nested needs the rewrite. A preprocessor\n * resolves `div &` itself, and `:is()` does not match everywhere\n * (Lynx, RFC-006 §3.1).\n */\n if( native ){\n CONCAT.test( prelude.replace( QUOTED, '' ) )\n && warn( 'LIPS-S008', `'${prelude}' joins '&' to a name`, stmt, i - stmt,\n 'Native nesting cannot: write the full selector, or use stylisPreprocessor.' )\n\n cur = nestSelector( prelude )\n }\n }\n\n block = { ctx: parent.ctx === 'opaque' ? 'opaque' : 'style' }\n }\n\n stack.push( block )\n flush('{')\n block.group && ( block.body = out.length )\n }\n\n const close = () => {\n const block = stack.pop()!\n\n /**\n * A group that hoisting emptied conditions nothing — drop it. Not an\n * `@layer`: an empty one still declares the layer order.\n */\n if( block.group && !cur && out.length === block.body && !LAYER.test( block.group ) ){\n out = out.slice( 0, block.at )\n tail = ''\n gap = false\n return\n }\n\n flush('}')\n\n if( block.hoist === undefined ) return\n\n // Carry any enclosing conditions out with it — `@media (…) { @keyframes … }`\n const\n text = out.slice( block.hoist ),\n groups = stack.filter( b => b.group ),\n key = groups.map( b => b.group ).join('{'),\n shut = '}'.repeat( groups.length )\n\n out = out.slice( 0, block.hoist )\n tail = ''\n\n // Consecutive rules hoisted from the same conditions share one copy of them\n hoisted = key && key === lastGroups\n ? hoisted.slice( 0, hoisted.length - shut.length ) + text + shut\n : hoisted + groups.map( b => b.group + '{' ).join('') + text + shut\n\n lastGroups = key\n }\n\n while( i < src.length ){\n const c = src[ i ]\n\n // An escape is one unit: `\\,` does not split a list, `\\ ` is not folded\n if( c === '\\\\' ){\n emit( src.slice( i, i + 2 ) )\n i += 2\n continue\n }\n\n /**\n * Block comments are dropped — or kept, when a preprocessor will read\n * them (`rtl:ignore`-style directives). `//` is not CSS, but Stylis\n * accepted it as a line comment and sheets were written against\n * Stylis: at the start of a statement it is stripped, where left in\n * it would glue itself onto the next selector and void the rule.\n * Anywhere else it is left alone — `--api: https://x` is a value.\n */\n const leading = c === '/' && !src.slice( stmt, i ).trim()\n\n if( c === '/' && ( src[ i + 1 ] === '*' || ( src[ i + 1 ] === '/' && leading ) ) ){\n const\n line = src[ i + 1 ] === '/',\n end = line ? skipLine( src, i ) : skipComment( src, i )\n\n if( !line && !native ){\n // Between statements it goes straight out, so preludes stay clean\n cur ? emit( src.slice( i, end ) ) : ( out += src.slice( i, end ) )\n }\n // It separated two tokens — `screen`, comment, `and` must not fuse\n else IDENT_CHAR.test( tail ) && IDENT_CHAR.test( src[ end ] || '' ) && ( gap = true )\n\n /**\n * A comment before a declaration must not become part of the\n * property name, or `PROP_NAME` rejects it, the value is never\n * scanned, and any interpolation inside it is misread further\n * down (an at-rule condition, at worst) instead of being lifted.\n */\n leading && ( stmt = end )\n i = end\n continue\n }\n if( c === '\"' || c === \"'\" ){\n const end = skipString( src, i )\n emit( src.slice( i, end ) )\n i = end\n continue\n }\n if( WS.test( c ) ){\n // A statement starts at its first character, for its diagnostics\n stmt === i && stmt++\n gap = true\n i++\n continue\n }\n\n if( c === '(' ) paren++\n else if( c === ')' ) paren--\n\n /**\n * Declaration? At statement level, outside parens, after a property\n * name. Depth is NOT part of the test: a component sheet is implicitly\n * inside its own block, so top-level `--accent: {…}` is a declaration.\n * A selector that gets this far (`a:hover {`) is rejected by readValue.\n */\n if( c === ':' && paren === 0 ){\n // `color/* … */: …` is still the property `color`\n const name = src.slice( stmt, i ).replace( COMMENTS, '' ).trim()\n\n if( PROP_NAME.test( name ) ){\n const parsed = readValue( src, i + 1, !native, at => {\n unterminated = true\n report( 'LIPS-S004',\n 'Unterminated interpolation',\n at, src.length - at,\n 'Close the expression with `}`.' )\n })\n\n if( parsed ){\n const slots = parsed.parts.filter( p => typeof p !== 'string' ) as\n { expr: string, unit: string, at: number }[]\n\n for( const s of slots ) checkExpr( s )\n\n // `color :red` — the space before the colon carries nothing\n gap = false\n\n /**\n * RFC-004 §7.4 — a custom property whose value is one bare\n * interpolation binds the AUTHOR's name directly. Aliasing it\n * through a generated variable would break cross-component\n * inheritance (§12.2) and Tailwind interop (§13), because both\n * depend on the name being stable and meaningful.\n */\n const bare =\n name.startsWith('--')\n && slots.length === 1\n && !slots[ 0 ].unit\n && parsed.parts.every( p => typeof p !== 'string' || !p.trim() )\n\n if( bare ){\n binds.push({ prop: name, e: slot( slots[ 0 ].expr ) })\n // drop the declaration entirely — the value lives inline on the root\n drop()\n i = parsed.end + ( src[ parsed.end ] === ';' ? 1 : 0 )\n stmt = i\n continue\n }\n\n let text = ''\n for( const part of parsed.parts ){\n if( typeof part === 'string' ){ text += part; continue }\n\n const\n e = slot( part.expr ),\n prop = `${prefix}-${e}`\n\n if( !binds.some( b => b.prop === prop ) ){\n binds.push({ prop, e })\n\n if( part.unit && !props.some( p => p.name === prop ) )\n props.push({\n name: prop,\n syntax: NUMBER_SYNTAX[ 0 ],\n inherits: true,\n initial: NUMBER_SYNTAX[ 1 ]\n })\n }\n\n /**\n * RFC-004 §7.1 — the source disambiguates. A bare `{expr}` is\n * used verbatim; a unit suffix means the expression yields a\n * number, so multiply it back into the unit.\n */\n text += part.unit ? `calc(var(${prop}) * 1${part.unit})` : `var(${prop})`\n }\n\n lint( name, stmt, parsed.end, text )\n emit( value( text ) )\n i = parsed.end\n continue\n }\n // readValue aborted — this was a selector (`a:hover {`), fall through\n }\n }\n\n if( c === '{' ){\n // An interpolation inside a prelude's parens is an at-rule condition.\n if( paren > 0 ){\n const interp = readInterpolation( src, i )\n if( interp ){\n report( 'LIPS-S002',\n 'Interpolation in an at-rule condition',\n i, interp.end - i + 1,\n 'Media and container conditions cannot read custom properties. Keep the condition static.' )\n\n // drop a unit suffix too, so the rest still parses as CSS\n const m = UNIT.exec( src.slice( interp.end + 1 ) )\n i = interp.end + 1 + ( m ? m[ 1 ].length : 0 )\n continue\n }\n }\n\n // A block opener with a blank prelude and expression-shaped content\n // is `{state.sel} { … }` — a dynamic selector.\n if( !src.slice( stmt, i ).trim() ){\n const interp = readInterpolation( src, i )\n if( interp ){\n report( 'LIPS-S001',\n 'Interpolation in a selector',\n i, interp.end - i + 1,\n 'Selectors are static in Layer 1. Bind a value inside the rule instead.' )\n i = interp.end + 1\n stmt = i\n continue\n }\n }\n\n open()\n stmt = ++i\n continue\n }\n\n if( c === '}' ){\n /**\n * A stray `}` would close the scope wrap early and leak every rule\n * after it out unscoped. Drop it, loudly.\n */\n if( stack.length > 1 ) close()\n else {\n warn( 'LIPS-S007', 'Unmatched `}` dropped', i, 1 )\n // it still ended whatever declaration it followed\n cur && flush(';')\n }\n\n stmt = ++i\n continue\n }\n\n if( c === ';' ){\n cur[ 0 ] === '@' && lint( cur, stmt, i )\n\n if( stack.length === 1 && HOISTED_STATEMENT.test( cur ) ) statements += drop() + ';'\n else flush(';')\n\n stmt = ++i\n continue\n }\n\n emit( c )\n i++\n }\n\n if( stack.length > 1 ){\n unterminated || warn( 'LIPS-S007', 'Unclosed `{` closed at the end', src.length, 0 )\n while( stack.length > 1 ) close()\n }\n\n // A statement at-rule may end at EOF without its `;`\n HOISTED_STATEMENT.test( cur ) && ( statements += drop() + ';' )\n // A trailing declaration with no `;`\n flush('')\n\n return { css: out, statements, hoisted, exprs, binds, props }\n}\n\n// ------------------------------------------------------------------ compile\n/**\n * Compile a component stylesheet to StyleIR.\n *\n * The scanner MUST run before any preprocessor: a brace in a declaration\n * value breaks Stylis's block parsing, so interpolations are replaced\n * with `var()` first.\n */\nexport function compileStyle( src: string, options: StyleCompileOptions ): StyleCompileResult {\n const\n diagnostics: TemplateDiagnostic[] = [],\n preprocess = options.preprocess || PREPROCESSOR,\n { css, statements, hoisted, exprs, binds, props } = scan( src, options, !preprocess, diagnostics )\n\n const empty: StyleIR = { v: 1, nsp: options.nsp, css: '', exprs: [], binds: [] }\n\n /**\n * The scope wrap IS nesting — `[rel=\"x\"] { .a { … } }`. Without a\n * preprocessor the sheet ships nested and the browser's own CSS nesting\n * resolves it: same selectors, same cascade. A preprocessor (opt-in,\n * `@lipsjs/lips/stylis`) flattens it instead, for engines that predate\n * nesting.\n *\n * Hoisting happens either way, so a preprocessor of your own — a\n * minifier, say — is never handed a `@keyframes` stuck inside a style\n * rule.\n */\n const\n /**\n * The name is quoted: it can come from a template object, and a quote in\n * it would close the attribute selector and scope the sheet to the page.\n */\n scoped = options.meta || !css ? css : `${options.scope || `[rel=\"${ quote( options.nsp ) }\"]`}{${css}}`,\n body = hoisted + scoped,\n source = options.layer ? `@layer ${options.layer}{${body}}` : body\n\n let sheet: string\n\n try { sheet = preprocess ? preprocess( source ) : source }\n catch( error: any ){\n diagnostics.push({\n code: 'LIPS-S006', severity: 'error',\n message: `Style compilation failed: ${error.message}`,\n loc: locOf( src, 0, src.length )\n })\n return { ir: empty, diagnostics }\n }\n\n /**\n * @property registration is document-global, so it sits OUTSIDE the scope\n * wrap. Without it a custom property is an uninterpolable token and\n * `transition: --x` does nothing (RFC-004 §10).\n */\n const registrations = props\n .map( p => `@property ${p.name}{syntax:\"${p.syntax}\";inherits:${p.inherits};initial-value:${p.initial}}` )\n .join('')\n\n /**\n * Statement at-rules go first, ahead of the registrations and outside\n * any `@layer` block — anywhere else the browser ignores them.\n */\n const ir: StyleIR = { v: 1, nsp: options.nsp, css: statements + registrations + sheet, exprs, binds }\n if( props.length ) ir.props = props\n\n return { ir, diagnostics }\n}\n",
|
|
45
|
+
"/**\n * Phase 2 — Template parser (RFC-001 §3–4)\n *\n * A dedicated recursive-descent parser for Lips templates:\n * - owns the syntax (no innerHTML, no regex preprocessing) — immune to\n * table-context hoisting, host-parser attribute lenience, whitespace\n * corruption\n * - positioned machine-readable diagnostics with error recovery\n * (`parse` never throws; broken templates yield partial ASTs)\n * - accepts the `.lips` SFC layout (frontscript + template) per\n * RFC-001 decision #5\n *\n * Attribute value semantics (predictable, no heuristics):\n * - `name=\"text\"` → literal string\n * - `name=\"a {expr} b\"` → interpolated parts\n * - `name=expr` → expression (whitespace-free, depth-aware)\n * - `name={ expr }` → expression (braced — spaces allowed)\n * - `name` / `!name` → boolean true / false\n * - `on-click( … )` → event instruction\n * - `await( … )` etc. → callable (fn) attribute\n * - `[a, b]` → iterator argument names\n * - `...expr` → spread\n */\n\n// ------------------------------------------------------------------- shared\nexport interface Loc {\n offset: number\n length: number\n}\nexport interface TemplateDiagnostic {\n code: string\n severity: 'error' | 'warning'\n message: string\n hint?: string\n loc: { line: number, col: number, offset: number, length: number }\n}\n\nexport type ExprSlot = { expr: string, loc: Loc }\n\n// ---------------------------------------------------------------------- AST\nexport type TemplateNode =\n | ElementNode\n | FragmentNode\n | { t: 'text', value: string, loc: Loc }\n | { t: 'interp', parts: ( string | ExprSlot )[], loc: Loc }\n | { t: 'comment', value: string, loc: Loc }\n\nexport interface FragmentNode {\n t: 'fragment'\n children: TemplateNode[]\n loc: Loc\n}\nexport interface ElementNode {\n t: 'element'\n tag: string // '#dynamic' for <{expr}>\n dynamicTag?: ExprSlot\n head?: ExprSlot // <if( … )>, <switch( … )>, <log( … )>\n attrs: AttrNode[]\n children: TemplateNode[]\n selfClosed: boolean\n loc: Loc\n}\n\nexport type AttrNode =\n | { k: 'literal', name: string, value: string, loc: Loc }\n | { k: 'interp', name: string, parts: ( string | ExprSlot )[], loc: Loc }\n | { k: 'expr', name: string, source: string, loc: Loc }\n | { k: 'bool', name: string, value: boolean, loc: Loc }\n | { k: 'event', name: string, source: string, loc: Loc }\n | { k: 'fn', name: string, source: string, loc: Loc }\n | { k: 'args', names: string[], loc: Loc }\n | { k: 'spread', source: string, loc: Loc }\n\nexport interface ParseResult {\n root: FragmentNode\n diagnostics: TemplateDiagnostic[]\n}\nexport interface SFCResult extends ParseResult {\n script: string\n}\n\n// ------------------------------------------------------------------- tables\nconst VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n])\nconst RAW_WHITESPACE_TAGS = new Set([ 'pre', 'textarea' ])\nconst HEAD_SUGAR_TAGS = new Set([ 'if', 'else-if', 'switch', 'log' ])\n\nconst NAMED_ENTITIES: Record<string, string> = {\n '&': '&', '<': '<', '>': '>', '"': '\"', ''': \"'\", ' ': ' '\n}\nfunction decodeEntities( text: string ){\n return text.replace( /&(?:amp|lt|gt|quot|#39|nbsp);/g, m => NAMED_ENTITIES[ m ] )\n}\n\n// ------------------------------------------------------------------- parser\nclass TemplateParser {\n private pos = 0\n private lineStarts: number[] | null = null\n\n readonly diagnostics: TemplateDiagnostic[] = []\n\n constructor( private src: string ){}\n\n // ---- diagnostics helpers\n private locate( offset: number ){\n if( !this.lineStarts ){\n this.lineStarts = [ 0 ]\n for( let i = 0; i < this.src.length; i++ )\n if( this.src[ i ] === '\\n' ) this.lineStarts.push( i + 1 )\n }\n\n let lo = 0, hi = this.lineStarts.length - 1\n while( lo < hi ){\n const mid = ( lo + hi + 1 ) >> 1\n this.lineStarts[ mid ] <= offset ? lo = mid : hi = mid - 1\n }\n\n return { line: lo + 1, col: offset - this.lineStarts[ lo ] + 1 }\n }\n private report( code: string, severity: 'error' | 'warning', message: string, offset: number, length = 1, hint?: string ){\n const { line, col } = this.locate( offset )\n this.diagnostics.push({ code, severity, message, hint, loc: { line, col, offset, length } })\n }\n\n // ---- scanning helpers\n private eof(){ return this.pos >= this.src.length }\n private peek( offset = 0 ){ return this.src[ this.pos + offset ] }\n private startsWith( str: string ){ return this.src.startsWith( str, this.pos ) }\n private skipSpace(){ while( !this.eof() && /\\s/.test( this.src[ this.pos ] ) ) this.pos++ }\n\n /**\n * Scan a balanced region: from an opening delimiter already\n * consumed, up to (not including) its matching closer at depth 0.\n * String literals are opaque; (), [], {} all nest.\n */\n private scanBalanced( closer: string, code: string ): { content: string, loc: Loc } | null {\n const start = this.pos\n let depth = 0\n\n while( !this.eof() ){\n const c = this.src[ this.pos ]\n\n if( c === \"'\" || c === '\"' || c === '`' ){\n this.pos++\n while( !this.eof() && this.src[ this.pos ] !== c ){\n if( this.src[ this.pos ] === '\\\\' ) this.pos++\n this.pos++\n }\n this.pos++\n continue\n }\n\n if( depth === 0 && c === closer ){\n const content = this.src.slice( start, this.pos )\n this.pos++ // consume closer\n return { content, loc: { offset: start, length: content.length } }\n }\n\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ){\n if( depth === 0 && c !== closer ){\n this.report( code, 'error', `Unbalanced '${c}'`, this.pos )\n this.pos++\n continue\n }\n depth--\n }\n\n this.pos++\n }\n\n this.report( code, 'error', `Unterminated — expected '${closer}'`, start, this.pos - start )\n return null\n }\n\n // ---- entry\n parse(): ParseResult {\n const children: TemplateNode[] = []\n\n while( !this.eof() ){\n children.push( ...this.parseNodes( [] ) )\n\n // Root-level stray closing tag: report, consume, resume\n if( this.startsWith('</') ){\n const closeStart = this.pos\n this.pos += 2\n while( !this.eof() && this.peek() !== '>' ) this.pos++\n !this.eof() && this.pos++\n this.report( 'LIPS-P005', 'error',\n `Stray closing tag ${this.src.slice( closeStart, this.pos )}`, closeStart, this.pos - closeStart )\n }\n }\n\n return {\n root: { t: 'fragment', children, loc: { offset: 0, length: this.src.length } },\n diagnostics: this.diagnostics\n }\n }\n\n /**\n * Parse siblings until EOF or a closing tag belonging to\n * an ancestor. `stack` holds open ancestor tag names for\n * mismatch recovery.\n */\n private parseNodes( stack: string[] ): TemplateNode[] {\n const nodes: TemplateNode[] = []\n\n while( !this.eof() ){\n if( this.startsWith('</') ) break\n\n const before = this.pos\n\n if( this.peek() === '<' && this.peek( 1 ) !== undefined ){\n const node = this.parseTag( stack )\n node && nodes.push( node )\n }\n else {\n const text = this.parseText( stack )\n text && nodes.push( text )\n }\n\n /**\n * Progress guard: recovery paths must never stall the\n * loop (e.g. a lone '<' at EOF yields no node and no\n * consumption) — force one character forward.\n */\n if( this.pos === before ) this.pos++\n }\n\n return nodes\n }\n\n // ---- text & interpolation\n private parseText( stack: string[] ): TemplateNode | null {\n const start = this.pos\n const parts: ( string | ExprSlot )[] = []\n let buffer = ''\n\n while( !this.eof() && this.peek() !== '<' ){\n if( this.peek() === '{' ){\n this.pos++ // consume '{'\n const region = this.scanBalanced( '}', 'LIPS-P007' )\n if( region ){\n buffer && parts.push( buffer )\n buffer = ''\n parts.push({ expr: region.content.trim(), loc: region.loc })\n }\n continue\n }\n\n buffer += this.peek()\n this.pos++\n }\n buffer && parts.push( buffer )\n\n const loc: Loc = { offset: start, length: this.pos - start }\n\n // Interpolated text\n if( parts.some( p => typeof p !== 'string' ) )\n return {\n t: 'interp',\n parts: parts.map( p => typeof p === 'string' ? decodeEntities( p ) : p ),\n loc\n }\n\n const raw = parts.length ? parts[0] as string : ''\n /**\n * Drop whitespace-only text except inside <pre>/<textarea>\n */\n const inRaw = stack.some( tag => RAW_WHITESPACE_TAGS.has( tag ) )\n if( !raw || ( !inRaw && !raw.trim() ) ) return null\n\n return { t: 'text', value: decodeEntities( raw ), loc }\n }\n\n // ---- tags\n private parseTag( stack: string[] ): TemplateNode | null {\n const start = this.pos\n\n // Comment\n if( this.startsWith('<!--') ){\n const end = this.src.indexOf( '-->', this.pos + 4 )\n if( end === -1 ){\n this.report( 'LIPS-P003', 'error', 'Unterminated comment', start, this.src.length - start )\n this.pos = this.src.length\n return null\n }\n const value = this.src.slice( this.pos + 4, end )\n this.pos = end + 3\n return { t: 'comment', value, loc: { offset: start, length: this.pos - start } }\n }\n\n // Fragment open <>\n if( this.startsWith('<>') ){\n this.pos += 2\n const children: TemplateNode[] = []\n\n while( true ){\n children.push( ...this.parseNodes( [ ...stack, '#fragment' ] ) )\n if( this.closeStatus( '#fragment', start, stack ) !== 'stray' ) break\n }\n\n return { t: 'fragment', children, loc: { offset: start, length: this.pos - start } }\n }\n\n // Dynamic tag <{expr} …>\n if( this.startsWith('<{') ){\n this.pos += 2\n const region = this.scanBalanced( '}', 'LIPS-P008' )\n if( !region ) return null\n\n const el: ElementNode = {\n t: 'element',\n tag: '#dynamic',\n dynamicTag: { expr: region.content.trim(), loc: region.loc },\n attrs: [],\n children: [],\n selfClosed: false,\n loc: { offset: start, length: 0 }\n }\n this.finishTag( el, stack, start )\n return el\n }\n\n // Named tag\n this.pos++ // consume '<'\n const nameStart = this.pos\n while( !this.eof() && /[A-Za-z0-9_-]/.test( this.peek() ) ) this.pos++\n const tag = this.src.slice( nameStart, this.pos )\n\n if( !tag || !/^[A-Za-z]/.test( tag ) ){\n this.report( 'LIPS-P002', 'error', 'Invalid tag name', start, this.pos - start + 1 )\n // Recovery: emit the '<' as literal text\n return { t: 'text', value: '<', loc: { offset: start, length: 1 } }\n }\n\n const el: ElementNode = {\n t: 'element',\n tag: tag.toLowerCase(),\n attrs: [],\n children: [],\n selfClosed: false,\n loc: { offset: start, length: 0 }\n }\n\n // Sugar head: <if( … )>, <else-if( … )>, <switch( … )>, <log( … )>\n if( this.peek() === '(' ){\n if( HEAD_SUGAR_TAGS.has( el.tag ) ){\n this.pos++ // consume '('\n const region = this.scanBalanced( ')', 'LIPS-P012' )\n region && ( el.head = { expr: region.content.trim(), loc: region.loc } )\n }\n else this.report( 'LIPS-P011', 'error', `Head expression is not allowed on <${el.tag}>`, this.pos,\n 1, `Only ${[ ...HEAD_SUGAR_TAGS ].map( t => `<${t}(…)>` ).join(', ')} take a head` )\n }\n\n this.finishTag( el, stack, start )\n return el\n }\n\n /** attrs → '>' | '/>' → children → closing tag */\n private finishTag( el: ElementNode, stack: string[], start: number ){\n this.parseAttrs( el )\n\n // Self closing / void\n if( el.selfClosed || VOID_ELEMENTS.has( el.tag ) ){\n el.selfClosed = true\n el.loc = { offset: start, length: this.pos - start }\n return\n }\n\n const stackName = el.tag === '#dynamic' ? '#dynamic' : el.tag\n el.children = []\n\n /**\n * Loop so a stray closing tag inside the element is\n * consumed (with a diagnostic) and children parsing\n * resumes — the element doesn't silently end early.\n */\n while( true ){\n el.children.push( ...this.parseNodes( [ ...stack, stackName ] ) )\n if( this.closeStatus( stackName, start, stack ) !== 'stray' ) break\n }\n\n el.loc = { offset: start, length: this.pos - start }\n }\n\n /**\n * Consume the closing tag for `tag`. Recovery rules:\n * - `</>` closes fragments and dynamic tags (and anything, with a warning)\n * - mismatch that matches an ancestor → auto-close (warning), leave input\n * for the ancestor to consume\n * - stray close → report, consume, caller resumes children\n * - EOF → unclosed element (error)\n */\n private closeStatus( tag: string, openOffset: number, stack: string[] ): 'closed' | 'ancestor' | 'stray' | 'eof' {\n if( this.eof() ){\n this.report( 'LIPS-P006', 'error', `Unclosed <${tag === '#fragment' ? '' : tag}> — reached end of template`, openOffset,\n 1, `Add </${tag === '#fragment' || tag === '#dynamic' ? '' : tag}>` )\n return 'eof'\n }\n\n if( !this.startsWith('</') ) return 'closed' // parseNodes stopped for another reason\n\n const closeStart = this.pos\n this.pos += 2\n\n // Generic close </>\n if( this.peek() === '>' ){\n this.pos++\n if( tag !== '#fragment' && tag !== '#dynamic' )\n this.report( 'LIPS-P004', 'warning', `Generic '</>' closes <${tag}>`, closeStart, 3, `Prefer </${tag}>` )\n return 'closed'\n }\n\n const nameStart = this.pos\n while( !this.eof() && /[A-Za-z0-9_-]/.test( this.peek() ) ) this.pos++\n const closeTag = this.src.slice( nameStart, this.pos ).toLowerCase()\n this.skipSpace()\n this.peek() === '>' ? this.pos++ : this.report( 'LIPS-P001', 'error', `Malformed closing tag`, closeStart, this.pos - closeStart )\n\n if( closeTag === tag ) return 'closed'\n\n // Mismatch: ancestor match → rewind so the ancestor consumes it\n if( stack.includes( closeTag ) ){\n this.report( 'LIPS-P004', 'warning', `</${closeTag}> auto-closes <${tag}>`, closeStart, this.pos - closeStart,\n `Add the missing </${tag}> before </${closeTag}>` )\n this.pos = closeStart\n return 'ancestor'\n }\n\n this.report( 'LIPS-P005', 'error', `Stray closing tag </${closeTag}> — <${tag}> is open`, closeStart, this.pos - closeStart )\n return 'stray'\n }\n\n // ---- attributes\n private parseAttrs( el: ElementNode ){\n while( true ){\n this.skipSpace()\n if( this.eof() ){\n this.report( 'LIPS-P001', 'error', 'Unexpected end of template inside tag', el.loc.offset )\n return\n }\n\n if( this.startsWith('/>') ){ this.pos += 2; el.selfClosed = true; return }\n if( this.peek() === '>' ){ this.pos++; return }\n\n const attrStart = this.pos\n\n // Spread: ...expr\n if( this.startsWith('...') ){\n this.pos += 3\n const source = this.readUnquotedValue()\n el.attrs.push({ k: 'spread', source, loc: { offset: attrStart, length: this.pos - attrStart } })\n continue\n }\n\n // Iterator args: [a, b]\n if( this.peek() === '[' ){\n this.pos++\n const region = this.scanBalanced( ']', 'LIPS-P009' )\n if( region ){\n const names = region.content.split(',').map( s => s.trim() ).filter( Boolean )\n el.attrs.push({ k: 'args', names, loc: { offset: attrStart, length: this.pos - attrStart } })\n }\n continue\n }\n\n // Boolean negation: !name\n let negated = false\n if( this.peek() === '!' ){ negated = true; this.pos++ }\n\n // Attribute name\n const nameStart = this.pos\n while( !this.eof() && /[^\\s=/>()]/.test( this.peek() ) ) this.pos++\n const name = this.src.slice( nameStart, this.pos )\n\n if( !name ){\n this.report( 'LIPS-P009', 'error', `Invalid attribute syntax at '${this.peek()}'`, this.pos )\n this.pos++\n continue\n }\n\n // Callable form: on-click( … ), await( … )\n if( this.peek() === '(' ){\n this.pos++\n const region = this.scanBalanced( ')', 'LIPS-P010' )\n const source = region ? region.content.trim() : ''\n const loc: Loc = { offset: attrStart, length: this.pos - attrStart }\n\n name.startsWith('on-')\n ? el.attrs.push({ k: 'event', name: name.slice( 3 ), source, loc })\n : el.attrs.push({ k: 'fn', name, source, loc })\n continue\n }\n\n // Valued: name=…\n if( this.peek() === '=' ){\n this.pos++\n this.parseAttrValue( el, name, attrStart )\n continue\n }\n\n // Bare boolean\n el.attrs.push({ k: 'bool', name, value: !negated, loc: { offset: attrStart, length: this.pos - attrStart } })\n }\n }\n\n private parseAttrValue( el: ElementNode, name: string, attrStart: number ){\n const q = this.peek()\n\n // Quoted: literal or interpolated\n if( q === '\"' || q === \"'\" ){\n this.pos++\n const valueStart = this.pos\n const parts: ( string | ExprSlot )[] = []\n let buffer = ''\n\n while( !this.eof() && this.peek() !== q ){\n if( this.peek() === '{' ){\n this.pos++\n const region = this.scanBalanced( '}', 'LIPS-P007' )\n if( region ){\n buffer && parts.push( buffer )\n buffer = ''\n parts.push({ expr: region.content.trim(), loc: region.loc })\n }\n continue\n }\n buffer += this.peek()\n this.pos++\n }\n buffer && parts.push( buffer )\n\n this.eof()\n ? this.report( 'LIPS-P010', 'error', `Unterminated value for '${name}'`, valueStart, this.pos - valueStart )\n : this.pos++ // consume quote\n\n const loc: Loc = { offset: attrStart, length: this.pos - attrStart }\n\n parts.some( p => typeof p !== 'string' )\n ? el.attrs.push({ k: 'interp', name, parts: parts.map( p => typeof p === 'string' ? decodeEntities( p ) : p ), loc })\n : el.attrs.push({ k: 'literal', name, value: decodeEntities( ( parts[0] as string ) ?? '' ), loc })\n return\n }\n\n // Braced expression: name={ expr } — spaces allowed\n if( q === '{' ){\n this.pos++\n const region = this.scanBalanced( '}', 'LIPS-P007' )\n el.attrs.push({\n k: 'expr', name,\n source: region ? region.content.trim() : '',\n loc: { offset: attrStart, length: this.pos - attrStart }\n })\n return\n }\n\n // Unquoted expression — whitespace-free, depth-aware\n const source = this.readUnquotedValue()\n source\n ? el.attrs.push({ k: 'expr', name, source, loc: { offset: attrStart, length: this.pos - attrStart } })\n : this.report( 'LIPS-P010', 'error', `Missing value for attribute '${name}'`, attrStart )\n }\n\n /** Read an unquoted value: until whitespace/'>'/'/>' at depth 0 */\n private readUnquotedValue(): string {\n const start = this.pos\n let depth = 0\n\n while( !this.eof() ){\n const c = this.peek()\n\n if( c === \"'\" || c === '\"' || c === '`' ){\n this.pos++\n while( !this.eof() && this.peek() !== c ){\n if( this.peek() === '\\\\' ) this.pos++\n this.pos++\n }\n this.pos++\n continue\n }\n\n if( depth === 0 ){\n if( /\\s/.test( c ) || c === '>' ) break\n if( c === '/' && this.peek( 1 ) === '>' ) break\n }\n\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ) depth--\n\n this.pos++\n }\n\n return this.src.slice( start, this.pos ).trim()\n }\n}\n\n// -------------------------------------------------------------------- API\nexport function parseTemplate( src: string ): ParseResult {\n return new TemplateParser( src || '' ).parse()\n}\n\n/**\n * `.lips` single-file component: frontscript (JS/TS) followed by the\n * template. The template starts at the first line-leading `<` that sits\n * at top-level script depth (outside strings, comments, and brackets).\n */\nexport function parseSFC( src: string ): SFCResult {\n const splitAt = findTemplateStart( src || '' )\n const script = ( src || '' ).slice( 0, splitAt ).trimEnd()\n const templateSrc = ( src || '' ).slice( splitAt )\n\n const result = new TemplateParser( templateSrc ).parse()\n /**\n * Re-anchor diagnostic lines to the full SFC source\n */\n const lineOffset = script ? script.split('\\n').length + ( /\\n\\s*\\n$/.test( src.slice( 0, splitAt ) ) ? 1 : 0 ) : 0\n result.diagnostics.forEach( d => {\n d.loc.line += script ? src.slice( 0, splitAt ).split('\\n').length - 1 : 0\n d.loc.offset += splitAt\n })\n\n return { script, ...result }\n}\n\nfunction findTemplateStart( src: string ): number {\n let\n depth = 0,\n lineStart = true\n\n for( let i = 0; i < src.length; i++ ){\n const c = src[ i ]\n\n // Strings are opaque\n if( c === \"'\" || c === '\"' || c === '`' ){\n const quote = c\n i++\n while( i < src.length && src[ i ] !== quote ){\n if( src[ i ] === '\\\\' ) i++\n i++\n }\n lineStart = false\n continue\n }\n // Comments are opaque\n if( c === '/' && src[ i + 1 ] === '/' ){\n while( i < src.length && src[ i ] !== '\\n' ) i++\n lineStart = true\n continue\n }\n if( c === '/' && src[ i + 1 ] === '*' ){\n const end = src.indexOf( '*/', i + 2 )\n i = end === -1 ? src.length : end + 1\n continue\n }\n\n if( c === '\\n' ){ lineStart = true; continue }\n\n if( lineStart && depth === 0 && c === '<' && /[A-Za-z{>!]/.test( src[ i + 1 ] || '' ) )\n return i\n\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ) depth = Math.max( 0, depth - 1 )\n\n if( !/\\s/.test( c ) ) lineStart = false\n }\n\n return 0 // no script section — whole source is template\n}\n",
|
|
46
|
+
"/**\n * Phase 2 — IR compiler (RFC-001 §4)\n *\n * TemplateAST → TemplateIR:\n * - static HTML skeletons per block, ready for one-time <template>\n * parsing + per-instance cloneNode\n * - integer-path bind table (childNodes index walks — no string paths)\n * - control-flow block nodes anchored by comment placeholders whose\n * paths are precomputed (the compiler simulates browser text-node\n * coalescing so paths survive the HTML round-trip)\n * - deduped expression table; every authored expression is validated\n * at compile time and its diagnostics re-anchored to template\n * line/col\n *\n * The output is JSON-serializable and deterministic — it is the\n * Modela artifact, the runtime render program, and the hot-swap\n * diff unit.\n *\n * With `target: 'tree'` every block also carries `nodes`, the same\n * skeleton as a structural tree, for hosts that build nodes one by\n * one rather than parse markup (RFC-006 §4.1).\n */\n\nimport type {\n TemplateNode,\n ElementNode,\n AttrNode,\n ExprSlot,\n TemplateDiagnostic\n} from './parser'\nimport { parseTemplate } from './parser'\nimport { parseExpression } from './expression'\n\n// ------------------------------------------------------------------- types\nexport type Path = number[]\nexport type E = number\n\nexport type CompInput =\n | { e: E }\n | { lit: unknown }\n\nexport interface TemplateIR {\n v: 1\n exprs: string[]\n root: BlockIR\n}\n\n/**\n * One node of a block's structural skeleton (RFC-006 §4.1): the tree\n * `html` encodes, for hosts with no HTML parser. Bind and block paths\n * index it exactly as they index the parsed `html`.\n *\n * 'text' a static text run\n * 0 an anchor — where a text bind or a block attaches\n * [ tag, attrs?, children? ] an element and its static attributes\n */\nexport type NodeIR = string | 0 | [ tag: string, attrs?: Record<string, string>, children?: NodeIR[] ]\n\nexport interface BlockIR {\n html: string\n /** The skeleton as a tree — present when compiled with `target: 'tree'` */\n nodes?: NodeIR[]\n /**\n * Scope variable names visible to this block's binds\n * (iterator args, async arm args, let/const names —\n * let names are block-scoped from block start, see RFC)\n */\n scope: string[]\n binds: BindIR[]\n blocks: ChildIR[]\n}\n\n/**\n * `i18n` marks a bind as translatable; `ik` carries the STABLE key to\n * look it up by (RFC-005 §3). Without `ik` the rendered text is its own\n * key — reword the source and the translation is orphaned.\n */\nexport type BindIR =\n | { t: 'text', p: Path, e: E, i18n?: 1, ik?: string } // anchor; runtime inserts a text node after it\n | { t: 'attr', p: Path, name: string, e: E, i18n?: 1, ik?: string }\n | { t: 'prop', p: Path, name: string, e: E, i18n?: 1, ik?: string, ref?: string } // @html / @text / @format\n | { t: 'event', p: Path, name: string, e: E } // raw instruction — runtime resolves handler form\n | { t: 'spread', p: Path, e: E }\n\nexport interface ArmIR {\n args: string[]\n block: BlockIR\n}\n\n/**\n * One macro call-site assignment, in SOURCE ORDER so later\n * entries override earlier ones (`<option key=k ...each/>` —\n * the spread wins over `key` for keys it contains).\n */\nexport type MacroSet =\n | { name: string, ci: CompInput }\n | { spread: E }\n\nexport type ChildIR =\n | { t: 'macro', p: Path, name: string, sets: MacroSet[], args: string[], block: BlockIR }\n | { t: 'if', p: Path, branches: { when: E | null, block: BlockIR }[] }\n | { t: 'for', p: Path, of?: E, from?: CompInput, to?: CompInput, by?: CompInput, args: string[], block: BlockIR }\n | { t: 'switch', p: Path, on: E, cases: { is: CompInput | null, block: BlockIR }[] }\n | { t: 'async', p: Path, awaitE: E, then?: ArmIR, catch?: ArmIR, loading?: BlockIR }\n | { t: 'let', p: Path, const: boolean, vars: Record<string, CompInput> }\n | { t: 'log', p: Path, e: E }\n /**\n * `<context …>` / `<i18n lang=…>` — a context layer over the subtree\n * (RFC-005 §4). `vars` are the provided keys; `lang` is the scoped\n * language. One IR kind, two spellings: they differ only in which\n * field they fill.\n */\n | { t: 'provide', p: Path, vars: Record<string, CompInput>, lang?: CompInput, block: BlockIR }\n | { t: 'comp', p: Path, name: string, inputs: Record<string, CompInput>, spreads: E[], events: { name: string, e: E }[], contents?: ArmIR }\n | { t: 'dynamic', p: Path, tag: E, inputs: Record<string, CompInput>, spreads: E[], events: { name: string, e: E }[], contents?: ArmIR }\n\nexport interface CompileResult {\n ir: TemplateIR\n diagnostics: TemplateDiagnostic[]\n}\n\nexport interface CompileOptions {\n /** `<macro [argv] name=\"X\">…</macro>` definitions, inlined at call sites */\n macros?: string\n /**\n * The kind of host the IR is for. `'dom'` (default) needs only the\n * `html` skeletons. `'tree'` is for hosts with no HTML parser\n * (RFC-006 §4.1): blocks also carry `nodes`, comments are dropped\n * (they mean nothing off the DOM), and `@html` is an error.\n */\n target?: 'dom' | 'tree'\n /**\n * Rewrites the parsed template before it compiles, reporting into\n * `diagnostics` — how a host adapts the HTML-shaped vocabulary\n * (`compileLynxTemplate`, RFC-006 §4.3). Macro bodies are not passed.\n */\n transform?: ( nodes: TemplateNode[], diagnostics: TemplateDiagnostic[] ) => void\n /**\n * Inspects — and may rewrite — the parsed template AND the macros\n * source before either compiles, reporting into `diagnostics` located\n * against `src`, the source the nodes came from. How an untrusted\n * template is held to its policy (RFC-007 §5.1): a refusal is reported\n * where it is written, and the refused construct never compiles.\n */\n check?: ( nodes: TemplateNode[], diagnostics: TemplateDiagnostic[], src: string ) => void\n}\n\ninterface MacroDef {\n name: string\n argv: string[]\n children: TemplateNode[]\n}\n\n// ------------------------------------------------------------------ tables\nconst ANCHOR = '<!--$-->'\n\nexport const CONTROL_TAGS = new Set([\n 'if', 'else-if', 'else', 'for', 'switch', 'async', 'let', 'const', 'log',\n // RFC-005 §4 — scoped context / scoped language\n 'context', 'i18n'\n])\nexport const ARM_TAGS = new Set([ 'case', 'default', 'then', 'catch', 'loading' ])\n\n/** Standard HTML + common SVG tags — anything else is a component candidate */\nexport const HTML_TAGS = new Set([\n 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo',\n 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col',\n 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl',\n 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2',\n 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img',\n 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu',\n 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p',\n 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section',\n 'select', 'slot', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup',\n 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title',\n 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr',\n // SVG\n 'svg', 'circle', 'clippath', 'defs', 'ellipse', 'foreignobject', 'g', 'image', 'line',\n 'lineargradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline',\n 'radialgradient', 'rect', 'stop', 'symbol', 'text', 'tspan', 'use'\n])\n\nconst VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n])\n\n// ----------------------------------------------------------------- helpers\nconst escText = ( s: string ) => s.replace( /&/g, '&' ).replace( /</g, '<' ).replace( />/g, '>' )\nconst escAttr = ( s: string ) => s.replace( /&/g, '&' ).replace( /\"/g, '"' ).replace( /</g, '<' )\n\nconst isNumeric = ( s: string ) => s !== '' && !isNaN( Number( s ) )\n\n/**\n * Does this source denote an OBJECT LITERAL rather than a value?\n *\n * Two spellings arrive here and both are the same React habit:\n *\n * style=\"{ margin: '3rem' }\" — braces eaten as an interpolation slot,\n * so the source is bare `margin: '3rem'`\n * style={{ margin: '3rem' }} — a real object expression\n *\n * The discriminator is a top-level `:` reached before any top-level `?`,\n * which is what keeps the forms that DO work out of it: a ternary\n * (`{state.on ? 'color:red' : ''}`), `??` and `?.` all hit the `?` first,\n * and a `:` inside a string (`{!state.on && 'color: red'}`) is skipped.\n */\nconst isObjectLiteral = ( src: string ): boolean => {\n const s = src.trim()\n let depth = 0\n\n for( let i = 0; i < s.length; i++ ){\n const c = s[ i ]\n\n if( c === \"'\" || c === '\"' || c === '`' ){\n i++\n while( i < s.length && s[ i ] !== c ){\n if( s[ i ] === '\\\\' ) i++\n i++\n }\n continue\n }\n\n if( c === '(' || c === '[' || c === '{' ) depth++\n else if( c === ')' || c === ']' || c === '}' ){\n depth--\n // A leading `{` that closes on the last char wraps the whole value\n if( depth === 0 && s[ 0 ] === '{' && i === s.length - 1 )\n return isObjectLiteral( s.slice( 1, -1 ) )\n }\n else if( depth === 0 ){\n if( c === '?' ) return false\n if( c === ':' ) return true\n }\n }\n return false\n}\n\n/**\n * The attribute's value as ONE expression source, or '' when it is not a\n * single bare expression. `width: {state.w}px` has literal text around\n * its slot, so it is CSS with a value interpolated in — not a candidate.\n */\nconst objectishAttr = ( attr: AttrNode ) => {\n if( attr.k === 'expr' ) return attr.source\n if( attr.k !== 'interp' ) return ''\n\n const slots = attr.parts.filter( ( p ): p is ExprSlot => typeof p !== 'string' )\n\n return slots.length === 1\n && attr.parts.every( p => typeof p !== 'string' || !p.trim() )\n ? slots[ 0 ].expr\n : ''\n}\n\n// ---------------------------------------------------------------- compiler\nclass Compiler {\n private exprs: string[] = []\n private exprIndex = new Map<string, E>()\n private lineStarts: number[] | null = null\n /** Guards against macros that (indirectly) call themselves */\n private macroStack: string[] = []\n\n readonly diagnostics: TemplateDiagnostic[] = []\n\n constructor(\n private src: string,\n private macros = new Map<string, MacroDef>(),\n /** `target: 'tree'` — emit `BlockIR.nodes` alongside `html` */\n private tree = false\n ){}\n\n // ---- diagnostics\n private locate( offset: number ){\n if( !this.lineStarts ){\n this.lineStarts = [ 0 ]\n for( let i = 0; i < this.src.length; i++ )\n if( this.src[ i ] === '\\n' ) this.lineStarts.push( i + 1 )\n }\n\n let lo = 0, hi = this.lineStarts.length - 1\n while( lo < hi ){\n const mid = ( lo + hi + 1 ) >> 1\n this.lineStarts[ mid ] <= offset ? lo = mid : hi = mid - 1\n }\n\n return { line: lo + 1, col: offset - this.lineStarts[ lo ] + 1 }\n }\n private report( code: string, severity: 'error' | 'warning', message: string, offset: number, length = 1, hint?: string ){\n const { line, col } = this.locate( offset )\n this.diagnostics.push({ code, severity, message, hint, loc: { line, col, offset, length } })\n }\n\n // ---- expression table\n /** Register an authored expression: validate + dedupe */\n private expr( source: string, at?: { offset: number, length?: number } ): E {\n const cached = this.exprIndex.get( source )\n if( cached !== undefined ) return cached\n\n const { diagnostics } = parseExpression( source )\n for( const d of diagnostics ){\n const offset = ( at?.offset ?? 0 ) + d.loc.offset\n this.report( d.code, 'error', d.message, offset, d.loc.length )\n }\n\n const idx = this.exprs.length\n this.exprs.push( source )\n this.exprIndex.set( source, idx )\n return idx\n }\n /** Register a synthesized expression (parts already validated) */\n private synth( source: string ): E {\n const cached = this.exprIndex.get( source )\n if( cached !== undefined ) return cached\n\n const idx = this.exprs.length\n this.exprs.push( source )\n this.exprIndex.set( source, idx )\n return idx\n }\n /**\n * Interpolation parts → one concat expression.\n * Nullish parts render '' (RFC decision #4).\n */\n private concat( parts: ( string | ExprSlot )[] ): E {\n parts\n .filter( ( p ): p is ExprSlot => typeof p !== 'string' )\n .forEach( p => {\n const { diagnostics } = parseExpression( p.expr )\n for( const d of diagnostics )\n this.report( d.code, 'error', d.message, p.loc.offset + d.loc.offset, d.loc.length )\n })\n\n const source = parts\n .map( p => typeof p === 'string' ? JSON.stringify( p ) : `((${p.expr})??\"\")` )\n .join('+')\n\n return this.synth( source )\n }\n private compInput( attr: AttrNode & { k: 'literal' | 'expr' | 'interp' | 'bool' } ): CompInput {\n switch( attr.k ){\n case 'literal': return { lit: attr.value }\n case 'bool': return { lit: attr.value }\n case 'expr': return { e: this.expr( attr.source, attr.loc ) }\n case 'interp': return { e: this.concat( attr.parts ) }\n }\n }\n\n // ---- entry\n compile( children: TemplateNode[] ): TemplateIR {\n return { v: 1, exprs: this.exprs, root: this.block( children, [] ) }\n }\n\n /**\n * Compile a node list into a BlockIR: static HTML with\n * precomputed paths for every bind/anchor. `scope` may\n * grow when <let>/<const> introduce names.\n */\n private block( children: TemplateNode[], scope: string[] ): BlockIR {\n const\n block: BlockIR = { html: '', scope: [ ...scope ], binds: [], blocks: [] },\n html: string[] = [],\n tree = this.tree,\n roots: NodeIR[] = []\n\n /**\n * Emit a sibling list at `path` depth. Returns nothing —\n * appends to html / block.binds / block.blocks, and to `kids`\n * (this level of the node tree) for the tree target.\n * The index simulation must match browser parsing:\n * consecutive static text coalesces into ONE node — and the node\n * tree coalesces the same way, so one path fits both.\n */\n const emitSiblings = ( nodes: TemplateNode[], path: Path, kids: NodeIR[], i18nParent = false, i18nKey?: string ) => {\n let index = 0\n let lastWasText = false\n\n const anchor = (): Path => {\n html.push( ANCHOR )\n tree && kids.push( 0 )\n lastWasText = false\n return [ ...path, index++ ]\n }\n\n for( let i = 0; i < nodes.length; i++ ){\n const node = nodes[ i ]\n\n switch( node.t ){\n case 'text': {\n /**\n * Static text under an `i18n` element still needs a\n * bind — there is nothing to translate in a skeleton.\n */\n if( i18nParent ){\n const bind: BindIR = { t: 'text', p: anchor(), e: this.synth( JSON.stringify( node.value ) ), i18n: 1 }\n if( i18nKey ) bind.ik = i18nKey\n block.binds.push( bind )\n break\n }\n\n html.push( escText( node.value ) )\n tree && ( lastWasText ? kids[ kids.length - 1 ] += node.value : kids.push( node.value ) )\n if( !lastWasText ) index++\n lastWasText = true\n break\n }\n case 'comment': {\n /**\n * Dropped from BOTH forms for the tree target, so the text\n * on either side coalesces alike and paths still agree.\n */\n if( tree ) break\n\n /**\n * Round-trip it as ONE comment. `--` would close it early, and\n * a leading `>` or `->` makes `<!-->` / `<!--->` — an empty\n * comment for the browser, followed by the rest as markup.\n */\n const text = node.value.replace( /--/g, '- -' )\n html.push( `<!--${ /^-?>/.test( text ) ? ' ' + text : text }-->` )\n lastWasText = false\n index++\n break\n }\n case 'interp': {\n const bind: BindIR = { t: 'text', p: anchor(), e: this.concat( node.parts ) }\n if( i18nParent ) bind.i18n = 1\n if( i18nParent && i18nKey ) bind.ik = i18nKey\n block.binds.push( bind )\n break\n }\n case 'fragment': {\n /**\n * Nested fragments are transparent: children emit\n * into the current index space. Rebuild sibling\n * numbering by splicing children inline.\n */\n nodes = [ ...nodes.slice( 0, i ), ...node.children, ...nodes.slice( i + 1 ) ]\n i--\n break\n }\n case 'element': {\n // Control flow → anchored child block\n if( CONTROL_TAGS.has( node.tag ) ){\n this.controlBlock( node, nodes, i, anchor(), block, scope )\n\n // if-chains consume their else-if/else siblings\n if( node.tag === 'if' ){\n let j = i + 1\n while( j < nodes.length ){\n const sib = nodes[ j ]\n if( sib.t === 'element' && ( sib.tag === 'else-if' || sib.tag === 'else' ) ) j++\n else break\n }\n nodes = [ ...nodes.slice( 0, i + 1 ), ...nodes.slice( j ) ]\n }\n break\n }\n\n // Arm tags outside their parents\n if( ARM_TAGS.has( node.tag ) ){\n this.report( 'LIPS-C002', 'error',\n `<${node.tag}> is only valid inside its parent construct`, node.loc.offset, node.loc.length )\n break\n }\n\n // Dynamic tag\n if( node.tag === '#dynamic' ){\n block.blocks.push( this.compLike( node, anchor(), scope, 'dynamic' ) )\n break\n }\n\n // Macro call → inline the definition body\n if( this.macros.has( node.tag ) ){\n const macroBlock = this.macroCall( node, anchor(), scope )\n macroBlock && block.blocks.push( macroBlock )\n break\n }\n\n // Component candidate\n if( !HTML_TAGS.has( node.tag ) ){\n block.blocks.push( this.compLike( node, anchor(), scope, 'comp' ) )\n break\n }\n\n // Plain HTML element\n this.emitElement( node, path, index++, html, block, emitSiblings, kids )\n lastWasText = false\n break\n }\n }\n }\n }\n\n emitSiblings( children, [], roots )\n block.html = html.join('')\n if( tree ) block.nodes = roots\n return block\n }\n\n /** Static open tag + dynamic binds + children recursion */\n private emitElement(\n node: ElementNode,\n path: Path,\n index: number,\n html: string[],\n block: BlockIR,\n emitSiblings: ( nodes: TemplateNode[], path: Path, kids: NodeIR[], i18nParent?: boolean, i18nKey?: string ) => void,\n kids: NodeIR[]\n ){\n const p: Path = [ ...path, index ]\n let open = `<${node.tag}`\n\n /**\n * Tree target: the same element as a node. A repeated attribute\n * keeps its FIRST value, which is what the HTML parser does with\n * the `html` form.\n */\n const\n el: [ string, Record<string, string>?, NodeIR[]? ] = [ node.tag ],\n attrs: Record<string, string> = {},\n put = ( name: string, value: string ) => {\n Object.prototype.hasOwnProperty.call( attrs, name ) || ( attrs[ name ] = value )\n }\n this.tree && kids.push( el )\n\n /**\n * `i18n` marks an element's own text and its visual\n * attributes (title/placeholder) as translatable.\n */\n /** `args` (`[a,b]`) is the one attribute form with no name */\n const named = node.attrs.filter( a => 'name' in a ) as ( AttrNode & { name: string } )[]\n\n const i18n = named.some( a =>\n a.name === 'i18n' && ( ( a.k === 'bool' && a.value ) || a.k === 'literal' ) )\n const translatableAttr = ( name: string ) => i18n && ( name === 'title' || name === 'placeholder' )\n\n /**\n * Stable translation ids (RFC-005 §3).\n *\n * <h1 i18n=\"hero.title\">Welcome</h1>\n * <input i18n i18n-placeholder=\"search.hint\" placeholder=\"Search…\">\n *\n * `i18n=\"key\"` ids the element's own text; `i18n-<attr>=\"key\"` ids\n * that attribute. Bare `i18n` keeps the gettext model where the\n * source text is the key — fine when a human owns the wording,\n * lossy when a generator rewrites it.\n */\n const keyOf = ( name: string ) => {\n const a = named.find( x => x.name === name && x.k === 'literal' )\n return a && 'value' in a && a.value ? String( a.value ) : undefined\n }\n const textKey = keyOf('i18n')\n const attrKey = ( name: string ) => keyOf(`i18n-${name}`)\n\n /** `i18n-<attr>` on an element that never opted in translates nothing */\n !i18n && named.some( a => a.name.startsWith('i18n-') )\n && this.report( 'LIPS-C014', 'warning',\n `i18n-* key on <${node.tag}> without the 'i18n' marker — the attribute will not be translated`,\n node.loc.offset, node.loc.length )\n\n for( const attr of node.attrs ){\n /**\n * `@html` hands markup to the host's HTML parser. A tree host has\n * none, so the bind could only ever render as text — say so here\n * rather than let the content arrive silently unparsed.\n */\n if( this.tree && 'name' in attr && attr.name === '@html' ){\n this.report( 'LIPS-C021', 'error',\n `@html on <${node.tag}>: the 'tree' target has no HTML parser`,\n attr.loc.offset, attr.loc.length,\n 'Write the markup in the template, or use @text' )\n continue\n }\n\n /**\n * On an ELEMENT, `style=` is CSS text — `{…}` in it is an\n * interpolation slot, so a React-style object literal never reaches\n * the DOM: it goes to the expression compiler, which rejects the\n * `:` (LIPS-E003, naming the token and not the mistake) and the\n * element renders unstyled. Say what the fix is instead.\n *\n * Components are untouched: there `style` is an input like any\n * other, and an object is a perfectly good value for it.\n */\n if( 'name' in attr && attr.name === 'style' ){\n const source = objectishAttr( attr )\n\n if( source && isObjectLiteral( source ) ){\n this.report( 'LIPS-C019', 'error',\n `style= on <${node.tag}> takes CSS text, not an object literal`,\n attr.loc.offset, attr.loc.length,\n 'Write the declarations as CSS — style=\"border: 2px solid gray; margin: 3rem\" — '\n + 'and interpolate values into it where they vary: style=\"margin: {state.gap}rem\". '\n + 'Styles that need pseudo-classes, media queries or keyframes belong in the '\n + \"component's stylesheet.\" )\n continue\n }\n }\n\n // Quoted handler — reported and dropped, never emitted as a dead attribute\n if( this.quotedEvent( node.tag, attr ) ) continue\n\n switch( attr.k ){\n case 'literal':\n if( attr.name === '@format' ){\n block.binds.push( this.formatBind( p, attr ) )\n break\n }\n if( attr.name.startsWith('@') ){\n block.binds.push({ t: 'prop', p, name: attr.name.slice( 1 ), e: this.synth( JSON.stringify( attr.value ) ) })\n break\n }\n // `i18n=\"key\"` / `i18n-<attr>=\"key\"` are directives, not output\n if( attr.name === 'i18n' || attr.name.startsWith('i18n-') ) break\n // Literal title/placeholder under i18n must become a bind to be translated\n if( translatableAttr( attr.name ) ){\n const bind: BindIR = { t: 'attr', p, name: attr.name, e: this.synth( JSON.stringify( attr.value ) ), i18n: 1 }\n const k = attrKey( attr.name )\n if( k ) bind.ik = k\n block.binds.push( bind )\n break\n }\n open += ` ${attr.name}=\"${escAttr( attr.value )}\"`\n put( attr.name, attr.value )\n break\n case 'bool':\n // `i18n` is a compiler directive, not an output attribute\n if( attr.name !== 'i18n' && attr.value ){\n open += ` ${attr.name}`\n put( attr.name, '' )\n }\n break\n case 'expr': {\n if( attr.name === '@format' ){\n block.binds.push( this.formatBind( p, attr ) )\n break\n }\n if( attr.name.startsWith('@') ){\n block.binds.push({ t: 'prop', p, name: attr.name.slice( 1 ), e: this.expr( attr.source, attr.loc ) })\n break\n }\n\n const bind: BindIR = { t: 'attr', p, name: attr.name, e: this.expr( attr.source, attr.loc ) }\n if( translatableAttr( attr.name ) ){\n bind.i18n = 1\n const k = attrKey( attr.name )\n if( k ) bind.ik = k\n }\n block.binds.push( bind )\n break\n }\n case 'interp': {\n if( attr.name === '@format' ){\n block.binds.push( this.formatBind( p, attr ) )\n break\n }\n /**\n * `@text=\"Row {i + 1}\"` — an @-prop whose value INTERPOLATES.\n * Without this it fell through to the attribute branch and set a\n * literal `@text` attribute on the element, so the prop it names\n * was never written and nothing rendered.\n */\n if( attr.name.startsWith('@') ){\n block.binds.push({ t: 'prop', p, name: attr.name.slice( 1 ), e: this.concat( attr.parts ) })\n break\n }\n\n const bind: BindIR = { t: 'attr', p, name: attr.name, e: this.concat( attr.parts ) }\n if( translatableAttr( attr.name ) ){\n bind.i18n = 1\n const k = attrKey( attr.name )\n if( k ) bind.ik = k\n }\n block.binds.push( bind )\n break\n }\n case 'event':\n block.binds.push({ t: 'event', p, name: attr.name, e: this.synth( attr.source ) })\n break\n case 'spread':\n block.binds.push({ t: 'spread', p, e: this.expr( attr.source, attr.loc ) })\n break\n case 'fn':\n this.report( 'LIPS-C007', 'warning',\n `Callable attribute '${attr.name}(…)' has no meaning on <${node.tag}>`, attr.loc.offset, attr.loc.length )\n break\n case 'args':\n this.report( 'LIPS-C008', 'warning',\n `Iterator arguments are not applicable to <${node.tag}>`, attr.loc.offset, attr.loc.length )\n break\n }\n }\n\n const kept = Object.keys( attrs ).length\n kept && ( el[ 1 ] = attrs )\n\n if( VOID_ELEMENTS.has( node.tag ) ){\n html.push( open + '>' )\n return\n }\n\n html.push( open + '>' )\n\n /**\n * A key ids ONE FIXED string. Two shapes break that:\n *\n * <h1 i18n=\"k\">Hello {state.name}</h1> — interpolated\n * <h1 i18n=\"k\">a<b>x</b>c</h1> — several text runs\n *\n * In the first the key would resolve the whole entry and silently\n * drop the interpolated value; in the second every run would render\n * the same translation. Both are what `@format` exists for — it\n * takes a reference AND params — so name it and fall back to\n * source-text keying rather than emit something wrong.\n */\n let key = textKey\n const runs = node.children.filter( c => c.t === 'text' || c.t === 'interp' )\n if( key && ( runs.length > 1 || runs.some( c => c.t === 'interp' ) ) ){\n this.report( 'LIPS-C015', 'error',\n `<${node.tag} i18n=\"${key}\"> keys text that is not a single fixed string. `\n + `Use @format=\"${key}, { … }\" for interpolated text.`,\n node.loc.offset, node.loc.length )\n key = undefined\n }\n\n const children: NodeIR[] = []\n node.children.length && emitSiblings( node.children, p, children, i18n, key )\n if( children.length ){\n el[ 1 ] = attrs // `{}` when there are none: children sit at index 2\n el[ 2 ] = children\n }\n html.push( `</${node.tag}>` )\n }\n\n /**\n * `@format=\"reference, { params }\"` → a prop bind carrying the\n * dictionary reference plus a compiled params expression.\n */\n private formatBind( p: Path, attr: AttrNode & { k: 'literal' | 'expr' | 'interp' } ): BindIR {\n /**\n * `@format` carries a reference plus a params OBJECT, so the\n * braces are data — not interpolation. Reconstruct the raw\n * source when the parser split it into interpolation parts.\n */\n const raw = attr.k === 'literal' ? attr.value\n : attr.k === 'expr' ? attr.source\n : attr.parts.map( part => typeof part === 'string' ? part : `{${part.expr}}` ).join('')\n\n const comma = raw.indexOf(',')\n\n if( comma === -1 ){\n this.report( 'LIPS-C012', 'error',\n `@format expects \"reference, { params }\"`, attr.loc.offset, attr.loc.length )\n return { t: 'prop', p, name: 'format', e: this.synth('({})'), ref: raw.trim() }\n }\n\n const\n ref = raw.slice( 0, comma ).trim(),\n params = raw.slice( comma + 1 ).trim()\n\n return { t: 'prop', p, name: 'format', e: this.expr( params, attr.loc ), ref }\n }\n\n // ---- control-flow blocks\n private attrsOf( node: ElementNode ){\n const\n byName = new Map<string, AttrNode>(),\n args: string[] = []\n\n for( const attr of node.attrs ){\n if( attr.k === 'args' ) args.push( ...attr.names )\n else if( 'name' in attr ) byName.set( attr.name, attr )\n }\n return { byName, args }\n }\n\n private controlBlock( node: ElementNode, siblings: TemplateNode[], i: number, p: Path, block: BlockIR, scope: string[] ){\n switch( node.tag ){\n case 'if': {\n const branches: { when: E | null, block: BlockIR }[] = [{\n when: node.head ? this.expr( node.head.expr, node.head.loc ) : this.missingHead( node ),\n block: this.block( node.children, scope )\n }]\n\n for( let j = i + 1; j < siblings.length; j++ ){\n const sib = siblings[ j ]\n if( sib.t !== 'element' ) break\n\n if( sib.tag === 'else-if' )\n branches.push({\n when: sib.head ? this.expr( sib.head.expr, sib.head.loc ) : this.missingHead( sib ),\n block: this.block( sib.children, scope )\n })\n else if( sib.tag === 'else' ){\n branches.push({ when: null, block: this.block( sib.children, scope ) })\n break\n }\n else break\n }\n\n block.blocks.push({ t: 'if', p, branches })\n break\n }\n\n case 'else-if':\n case 'else':\n this.report( 'LIPS-C001', 'error', `<${node.tag}> without a preceding <if>`, node.loc.offset, node.loc.length )\n break\n\n case 'for': {\n const { byName, args } = this.attrsOf( node )\n const\n inAttr = byName.get('in'),\n fromAttr = byName.get('from'),\n toAttr = byName.get('to'),\n byAttr = byName.get('by')\n\n if( !inAttr && !fromAttr ){\n this.report( 'LIPS-C004', 'error', `<for> requires 'in' or 'from'/'to'`, node.loc.offset, node.loc.length )\n break\n }\n\n const child: ChildIR = {\n t: 'for', p, args,\n block: this.block( node.children, [ ...scope, ...args ] )\n }\n if( inAttr && inAttr.k === 'expr' ) child.of = this.expr( inAttr.source, inAttr.loc )\n if( fromAttr ) child.from = this.numInput( fromAttr )\n if( toAttr ) child.to = this.numInput( toAttr )\n if( byAttr && ( byAttr.k === 'literal' || byAttr.k === 'expr' ) )\n child.by = byAttr.k === 'literal' ? { lit: byAttr.value } : { e: this.expr( byAttr.source, byAttr.loc ) }\n\n block.blocks.push( child )\n break\n }\n\n case 'switch': {\n const on = node.head ? this.expr( node.head.expr, node.head.loc ) : this.missingHead( node )\n const cases: { is: CompInput | null, block: BlockIR }[] = []\n\n for( const child of node.children ){\n if( child.t !== 'element' ) continue\n\n if( child.tag === 'case' ){\n const { byName } = this.attrsOf( child )\n const isAttr = byName.get('is')\n\n if( !isAttr || ( isAttr.k !== 'literal' && isAttr.k !== 'expr' ) ){\n this.report( 'LIPS-C004', 'error', `<case> requires an 'is' attribute`, child.loc.offset, child.loc.length )\n continue\n }\n cases.push({\n is: isAttr.k === 'literal' ? { lit: isAttr.value } : { e: this.expr( isAttr.source, isAttr.loc ) },\n block: this.block( child.children, scope )\n })\n }\n else if( child.tag === 'default' )\n cases.push({ is: null, block: this.block( child.children, scope ) })\n else\n this.report( 'LIPS-C003', 'error', `Only <case>/<default> are valid inside <switch>`, child.loc.offset, child.loc.length )\n }\n\n block.blocks.push({ t: 'switch', p, on, cases })\n break\n }\n\n case 'async': {\n const awaitAttr = node.attrs.find( a => a.k === 'fn' && a.name === 'await' ) as ( AttrNode & { k: 'fn' } ) | undefined\n if( !awaitAttr ){\n this.report( 'LIPS-C004', 'error', `<async> requires await(…)`, node.loc.offset, node.loc.length )\n break\n }\n\n const child: ChildIR = { t: 'async', p, awaitE: this.expr( awaitAttr.source, awaitAttr.loc ) }\n\n for( const arm of node.children ){\n if( arm.t !== 'element' ) continue\n const { args } = this.attrsOf( arm )\n\n if( arm.tag === 'then' ) child.then = { args, block: this.block( arm.children, [ ...scope, ...args ] ) }\n else if( arm.tag === 'catch' ) child.catch = { args, block: this.block( arm.children, [ ...scope, ...args ] ) }\n else if( arm.tag === 'loading' ) child.loading = this.block( arm.children, scope )\n else this.report( 'LIPS-C003', 'error', `Only <then>/<catch>/<loading> are valid inside <async>`, arm.loc.offset, arm.loc.length )\n }\n\n block.blocks.push( child )\n break\n }\n\n case 'let':\n case 'const': {\n const vars: Record<string, CompInput> = {}\n\n for( const attr of node.attrs ){\n /**\n * Spread on <let> cannot work with compiled expressions:\n * the spread's keys are unknown at compile time, so binds\n * referencing them as bare identifiers can never resolve.\n * Assign the object to ONE name instead.\n */\n if( attr.k === 'spread' ){\n this.report( 'LIPS-C013', 'error',\n `Spread is not supported on <${node.tag}> — scope names must be known at compile time`,\n attr.loc.offset, attr.loc.length,\n `Assign it to one variable: <${node.tag} obj={ ${attr.source} }/> and read obj.<key>` )\n continue\n }\n\n if( attr.k === 'literal' || attr.k === 'expr' || attr.k === 'interp' || attr.k === 'bool' ){\n vars[ attr.name ] = this.compInput( attr )\n /**\n * RFC decision #1: let/const names are block-scoped\n * (visible to every bind of the enclosing block)\n */\n !block.scope.includes( attr.name ) && block.scope.push( attr.name )\n !scope.includes( attr.name ) && scope.push( attr.name )\n }\n }\n\n block.blocks.push({ t: 'let', p, const: node.tag === 'const', vars })\n break\n }\n\n case 'log':\n /**\n * A log head is an argument LIST (like an event\n * instruction), not a single expression — the\n * runtime resolves it; no single-expr validation.\n */\n block.blocks.push({ t: 'log', p, e: node.head ? this.synth( node.head.expr ) : this.missingHead( node ) })\n break\n\n /**\n * Scoped context (RFC-005 §4):\n *\n * <context selection=state.sel tool=state.tool> … </context>\n *\n * Every attribute becomes a context key visible to the subtree —\n * components included — shadowing the global store for that key\n * only. Unlike `<let>`, the names do NOT enter expression scope:\n * they are read as `context.selection`, which is what makes a\n * child component see them without the parent passing inputs.\n */\n case 'context': {\n const vars: Record<string, CompInput> = {}\n\n for( const attr of node.attrs ){\n /**\n * Same reasoning as <let>: a spread's keys are unknown at\n * compile time. Here they would also silently fail to shadow\n * anything, since lookup is by name at render.\n */\n if( attr.k === 'spread' ){\n this.report( 'LIPS-C016', 'error',\n `Spread is not supported on <context> — provided keys must be known at compile time`,\n attr.loc.offset, attr.loc.length,\n `Provide them one by one: <context a=obj.a b=obj.b>` )\n continue\n }\n\n if( attr.k === 'literal' || attr.k === 'expr' || attr.k === 'interp' || attr.k === 'bool' )\n vars[ attr.name ] = this.compInput( attr )\n }\n\n if( !Object.keys( vars ).length )\n this.report( 'LIPS-C017', 'warning',\n `<context> provides nothing — it renders its children unchanged`,\n node.loc.offset, node.loc.length )\n\n block.blocks.push({ t: 'provide', p, vars, block: this.block( node.children, scope ) })\n break\n }\n\n /**\n * Scoped language (RFC-005 §4):\n *\n * <i18n lang=state.docLang> … </i18n>\n *\n * The subtree's translatable binds resolve against `lang` instead\n * of the global language — a document pane in the content's\n * language while the chrome stays in the reader's.\n */\n case 'i18n': {\n const { byName } = this.attrsOf( node )\n const langAttr = byName.get('lang')\n\n if( !langAttr ){\n this.report( 'LIPS-C018', 'error',\n `<i18n> requires a 'lang' attribute: <i18n lang=state.docLang>`,\n node.loc.offset, node.loc.length )\n break\n }\n\n block.blocks.push({\n t: 'provide', p, vars: {},\n lang: this.compInput( langAttr as AttrNode & { k: 'literal' | 'expr' | 'interp' | 'bool' } ),\n block: this.block( node.children, scope )\n })\n break\n }\n }\n }\n\n private missingHead( node: ElementNode ): E {\n this.report( 'LIPS-C004', 'error', `<${node.tag}> requires a head expression: <${node.tag}( … )>`, node.loc.offset, node.loc.length )\n return this.synth('undefined')\n }\n private numInput( attr: AttrNode ): CompInput {\n if( attr.k === 'literal' ) return { lit: isNumeric( attr.value ) ? Number( attr.value ) : attr.value }\n if( attr.k === 'expr' ) return isNumeric( attr.source ) ? { lit: Number( attr.source ) } : { e: this.expr( attr.source, attr.loc ) }\n return { lit: undefined }\n }\n\n /**\n * Macro call site → inlined block.\n *\n * Every call-site attribute becomes a block-scoped variable\n * (the macro's declared `argv` are the named ones; all of them\n * together also form `arguments` at runtime).\n */\n private macroCall( node: ElementNode, p: Path, scope: string[] ): ChildIR | null {\n const macro = this.macros.get( node.tag )!\n\n if( this.macroStack.includes( macro.name ) ){\n this.report( 'LIPS-C009', 'error',\n `Recursive macro <${macro.name}> (${[ ...this.macroStack, macro.name ].join(' → ')})`,\n node.loc.offset, node.loc.length )\n return null\n }\n\n /**\n * Assignments in SOURCE ORDER — spreads participate like any\n * other set, so `key=k ...each` lets the spread override `key`\n * while `...each key=k` lets the explicit attr win.\n *\n * Undeclared argv default to `undefined` at runtime: falsy in\n * conditions, attribute-removing, renders '' in text (RFC #4).\n */\n const sets: MacroSet[] = []\n for( const attr of node.attrs ){\n if( attr.k === 'literal' || attr.k === 'expr' || attr.k === 'interp' || attr.k === 'bool' )\n sets.push({ name: attr.name, ci: this.compInput( attr ) })\n else if( attr.k === 'spread' )\n sets.push({ spread: this.expr( attr.source, attr.loc ) })\n }\n\n this.macroStack.push( macro.name )\n const block = this.block( macro.children, [ ...scope, ...macro.argv ] )\n this.macroStack.pop()\n\n return { t: 'macro', p, name: macro.name, sets, args: macro.argv, block }\n }\n\n /** Components and dynamic tags share input/event/spread shape */\n /**\n * `on-click=\"…\"` is NOT an event binding. The parser only produces an\n * `event` attribute for the instruction form `on-x( … )`; quoted, it\n * stays an ordinary attribute, so no listener is wired and the source\n * text lands in the DOM as a dead `on-click=\"() => …\"`. Nothing failed\n * loudly, which is exactly the problem — same class as the `@text=\"…\"`\n * and `style={…}` fall-throughs.\n */\n private quotedEvent( tag: string, attr: AttrNode ){\n if( !( 'name' in attr ) || !attr.name.startsWith('on-') ) return false\n\n this.report( 'LIPS-C020', 'error',\n `${attr.name}=\"…\" on <${tag}> wires no listener`,\n attr.loc.offset, attr.loc.length,\n `Handlers use the instruction form: ${attr.name}( … ). `\n + `Quoted, it is an ordinary attribute — the handler never runs and the source is emitted into the DOM.` )\n return true\n }\n\n private compLike( node: ElementNode, p: Path, scope: string[], kind: 'comp' | 'dynamic' ): ChildIR {\n const\n inputs: Record<string, CompInput> = {},\n spreads: E[] = [],\n events: { name: string, e: E }[] = []\n let args: string[] = []\n\n for( const attr of node.attrs ){\n // A quoted handler on a component is the same dead attribute, as an input\n if( attr.k !== 'event' && this.quotedEvent( node.tag, attr ) ) continue\n\n switch( attr.k ){\n case 'literal': case 'bool': case 'expr': case 'interp':\n inputs[ attr.name ] = this.compInput( attr )\n break\n case 'event':\n events.push({ name: attr.name, e: this.synth( attr.source ) })\n break\n case 'spread':\n spreads.push( this.expr( attr.source, attr.loc ) )\n break\n case 'args':\n args = [ ...args, ...attr.names ]\n break\n case 'fn':\n inputs[ attr.name ] = { e: this.expr( attr.source, attr.loc ) }\n break\n }\n }\n\n const contents: ArmIR | undefined = node.children.length\n ? { args, block: this.block( node.children, [ ...scope, ...args ] ) }\n : undefined\n\n return kind === 'comp'\n ? { t: 'comp', p, name: node.tag, inputs, spreads, events, contents }\n : { t: 'dynamic', p, tag: this.expr( node.dynamicTag!.expr, node.dynamicTag!.loc ), inputs, spreads, events, contents }\n }\n}\n\n// -------------------------------------------------------------------- API\n/** Parse `<macro [argv] name=\"X\">…</macro>` blocks into a lookup */\nfunction parseMacros( src: string, diagnostics: TemplateDiagnostic[], check?: CompileOptions['check'] ){\n const macros = new Map<string, MacroDef>()\n if( !src?.trim() ) return macros\n\n const parsed = parseTemplate( src )\n diagnostics.push( ...parsed.diagnostics )\n check?.( parsed.root.children, diagnostics, src )\n\n for( const node of parsed.root.children ){\n if( node.t !== 'element' ) continue\n\n if( node.tag !== 'macro' ){\n diagnostics.push({\n code: 'LIPS-C010', severity: 'warning',\n message: `Only <macro> definitions are allowed in the macros source — ignoring <${node.tag}>`,\n loc: { line: 1, col: 1, offset: node.loc.offset, length: node.loc.length }\n })\n continue\n }\n\n let name = ''\n const argv: string[] = []\n for( const attr of node.attrs ){\n if( attr.k === 'args' ) argv.push( ...attr.names )\n else if( attr.k === 'literal' && attr.name === 'name' ) name = attr.value\n }\n\n if( !name ){\n diagnostics.push({\n code: 'LIPS-C011', severity: 'error',\n message: `<macro> requires a name attribute`,\n loc: { line: 1, col: 1, offset: node.loc.offset, length: node.loc.length }\n })\n continue\n }\n\n // Tag names arrive lowercased — match call sites case-insensitively\n macros.set( name.toLowerCase(), { name, argv, children: node.children })\n }\n\n return macros\n}\n\nexport function compileTemplate( src: string, options?: CompileOptions ): CompileResult {\n const diagnostics: TemplateDiagnostic[] = []\n const macros = parseMacros( options?.macros || '', diagnostics, options?.check )\n\n const parsed = parseTemplate( src )\n options?.check?.( parsed.root.children, diagnostics, src )\n options?.transform?.( parsed.root.children, diagnostics )\n const compiler = new Compiler( src, macros, options?.target === 'tree' )\n const ir = compiler.compile( parsed.root.children )\n\n return { ir, diagnostics: [ ...diagnostics, ...parsed.diagnostics, ...compiler.diagnostics ] }\n}\n",
|
|
47
|
+
"/**\n * Phase 2 — `<router>` for the IR engine.\n *\n * Implemented as an ordinary component (no engine privileges): its\n * template is a dynamic tag holding the matched page's template\n * object, resolved by the host's `resolveTemplate` hook.\n *\n * <router routes=static.routes global\n * on-before(…) on-after(…) on-not-found(…)></router>\n */\n\ntype RouteDef = {\n path: string\n template: any\n default?: boolean\n}\ntype Route = RouteDef & {\n pathVars: string[]\n pathRegex: RegExp\n}\n\nfunction safeDecode( value: string ){\n try { return decodeURIComponent( value ) }\n catch( e ){ return value }\n}\n\n/** URLSearchParams handles percent-decoding, `+`, and values with `=` */\nconst parseQuery = ( str: string ) => Object.fromEntries( new URLSearchParams( str ) )\n\nexport const routerTemplate = {\n state: {\n page: null as any,\n params: {} as Record<string, any>,\n query: {} as Record<string, any>\n },\n\n handler: {\n onCreate( this: any ){\n this.__routes = [] as Route[]\n this.__defaultPath = null as string | null\n this.__currentRoute = null as Route | null\n this.__global = false\n },\n\n onInput( this: any ){ this.processor( this.input ) },\n\n processor( this: any, options: { routes?: RouteDef[], global?: boolean } ){\n if( !options?.routes ) return\n\n if( options.global ) this.__global = true\n\n this.__routes = options.routes.map( ({ path, template, default: _default }: RouteDef ) => {\n if( _default ) this.__defaultPath = path\n\n const\n pathVars = path.match(/:[^\\/]*(\\/|$)/gi ) || [],\n pathRegex = path.replaceAll('/', '\\\\/')\n .replaceAll(/:[^\\/]*(\\/|$)/gi, '([^\\\\\\/]+)(?:\\\\\\/|$)')\n\n return { path, template, default: _default, pathVars, pathRegex: new RegExp(`${pathRegex}$`, 'i') }\n })\n\n if( options.global ){\n const cpathname = window.location.pathname\n\n this.__defaultPath = this.__defaultPath\n && cpathname === '/'\n && cpathname !== this.__defaultPath\n ? this.__defaultPath\n : cpathname\n ? cpathname + window.location.search\n : this.__routes[0]?.path\n }\n },\n\n onAttach( this: any ){\n if( this.input?.global ){\n window.navigate = this.navigate.bind( this )\n window.addEventListener('popstate', ( e: PopStateEvent ) =>\n e.state && this.navigate( e.state.path, true ) )\n }\n\n // Contextual navigation for every component\n typeof this.setContext === 'function' && this.setContext('navigate', this.navigate.bind( this ) )\n\n this.__defaultPath && this.navigate( this.__defaultPath )\n },\n\n navigate( this: any, path: string, back?: boolean ){\n !back && this.__global && history.pushState({ path }, '', path )\n\n const parts = String( path ).split('?')\n path = parts[0]\n\n const query = parts[1] ? parseQuery( parts[1] ) : {}\n\n let fromState: any = null\n if( this.__currentRoute ){\n fromState = { path: this.__currentRoute.path, params: this.state.params }\n this.emit('before', { fromState, toState: { path, query } })\n }\n\n const result = this.match( path )\n if( !result ){\n this.__currentRoute = null\n this.state.params = {}\n this.state.query = {}\n this.state.page = null\n\n this.emit('not-found', path )\n return\n }\n\n const { route, params } = result\n this.emit('after', { fromState, toState: { path: route.path, params, query } })\n\n this.__currentRoute = route\n\n this.state.params = params\n this.state.query = query\n this.state.page = route.template\n },\n\n match( this: any, path: string ){\n const params: Record<string, any> = {}\n\n for( const route of this.__routes as Route[] ){\n const matches = path.match( route.pathRegex )\n if( matches === null || matches.index !== 0 ) continue\n\n for( let x = 0; x + 1 < matches.length && x < route.pathVars.length; x++ )\n params[ route.pathVars[ x ].replaceAll(/[\\/:]/g, '') ] = safeDecode( matches[ x + 1 ] )\n\n return { route, params }\n }\n\n return false\n }\n },\n\n default: `<{state.page} params=state.params query=state.query/>`\n}\n\ndeclare global {\n interface Window {\n navigate: ( path: string, back?: boolean ) => void\n }\n}\n",
|
|
48
|
+
"/**\n * Lips — fast, lightweight, runtime reactive UI framework.\n *\n * Pipeline (no build step required):\n *\n * template string ──parse──▶ AST ──compile──▶ TemplateIR ──render──▶ DOM\n *\n * Updates are fine-grained: a state write notifies only the bindings\n * that read that key. Templates can also be precompiled to IR at build\n * time (see `compileTemplate`) for CSP-safe, parse-free startup.\n */\n\nimport { IRLips, IRFacadeComponent, setCompiler, setStyleCompiler, setMessageFormat, registerBuiltin } from './ir/facade'\nimport { messageFormat } from './i18n/engine'\nimport { compileStyle } from './ir/style'\nimport { compileTemplate } from './ir/compiler'\nimport type { Metavars } from './types'\nimport { routerTemplate } from './ir/router'\n\n/**\n * Full build capabilities. The `./runtime` entry wires none of these, so\n * its bundle tree-shakes the template compiler, the built-in components\n * and the MessageFormat 2 engine out entirely (an app there that\n * translates passes `messageFormat` from `@lipsjs/lips/i18n`).\n *\n * Stylis is deliberately NOT wired here. The scope wrap is ordinary CSS\n * nesting and browsers resolve it natively, so the preprocessor only buys\n * support for engines that predate nesting — worth ~1.9 KB gzipped to\n * those who need it, and nothing to everyone else. Opt in by VALUE:\n * `new Lips({ stylePreprocessor })` with `stylisPreprocessor` from\n * `@lipsjs/lips/stylis` (a side-effect import cannot reach this bundle).\n */\nsetCompiler( compileTemplate )\nsetStyleCompiler( compileStyle )\nsetMessageFormat( messageFormat )\nregisterBuiltin( 'router', routerTemplate )\n\nexport * from './types'\nexport type { TemplatePolicy, Refusal, Verdict, Untrusted } from './ir/policy'\n\nexport {\n parseTemplate,\n parseSFC,\n compileTemplate,\n compileStyle,\n renderIR,\n signal,\n effect,\n untrack,\n reactive,\n batch\n} from './ir'\n\nexport type {\n TemplateIR,\n BlockIR,\n NodeIR,\n CompileOptions,\n Host,\n BindIR,\n ChildIR,\n CompileResult,\n StyleIR,\n StyleBindIR,\n StyleCompileResult,\n TemplateDiagnostic,\n IRInstance,\n IRComponentDef,\n RuntimeOptions,\n RenderSetup,\n SwapReport,\n SwapChange\n} from './ir'\n\n/**\n * A rendered component handle. Generic over the same `Metavars` the\n * template declares, so `component.state` is typed, not `any`:\n *\n * type MT = Metavars<{ tone: string }, { count: number }>\n * const c: Component<MT> = lips.render<MT>('counter', counter)\n * c.state.count++ // number\n *\n * Its event bus runs both ways — `c.on('saved', …)` receives what the\n * component emits, and `c.emit('reset')` reaches listeners the component\n * registered with `this.on(…)`. Inbound events do NOT invoke handler\n * methods by name, so what a component accepts stays explicit.\n */\nexport type Component<MT extends Metavars = Metavars> = IRFacadeComponent<MT>\n\n/** The Lips instance, generic over the shared context shape */\nexport type Lips<Context extends Object = Record<string, any>> = IRLips<Context>\n\nexport default IRLips\n"
|
|
45
49
|
],
|
|
46
|
-
"mappings": "oBAAA,SAAS,EAAE,CAEX,IAAI,EAAM,SACN,EAAM,OACN,EAAS,EAAI,gBACb,EAAgB,EAAI,cAAc,KAAK,CAAG,EAC1C,EAAM,EAAc,KAAK,EACzB,EAAQ,EAAc,OAAO,EAC7B,EAAQ,EAAc,OAAO,EAC7B,EAAK,EAAc,IAAI,EACvB,EAAU,MAAM,QAAS,EAAiB,MAAM,UAChD,EAAS,EAAe,OAAQ,EAAS,EAAe,OAAQ,EAAU,EAAe,QAAS,EAAM,EAAe,IAAK,GAAO,EAAe,KAAM,EAAQ,EAAe,MAAO,GAAO,EAAe,KAAM,EAAS,EAAe,OAC1O,EAAO,iCACP,EAAU,kCACV,EAAS,OACT,EAAQ,QAEZ,SAAS,EAAI,CAAC,EAAU,EAAS,CAC7B,IAAI,EAAa,EAAmB,CAAO,EAC3C,OAAQ,IAAc,IAAe,EAAW,CAAO,IAAM,EAAU,CAAO,EACxE,CAAC,GACA,GAAc,EAAQ,KA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