hyper-html-api 0.10.0 → 0.10.1

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.
@@ -1,2 +1,2 @@
1
- var hyperHtmlApiUpgrade=(()=>{var re=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var xe=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:!0})},Qe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Xe(t))!Ze.call(e,r)&&r!==n&&re(e,r,{get:()=>t[r],enumerable:!(o=Ge(t,r))||o.enumerable});return e};var et=e=>Qe(re({},"__esModule",{value:!0}),e);var kt={};xe(kt,{default:()=>jt,engine:()=>ye,upgrade:()=>Je});var J=["textContent","innerText","innerHTML","outerHTML","value","checked","selected","disabled","readOnly","type","tagName","nodeName","nodeType","nodeValue","childElementCount","id","className","classList","baseURI","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","dataset","currentSrc","duration","paused","title","documentURI","contentType"],oe=new Set(J),Ee=new Set(["textContent","innerText","innerHTML","value","checked","selected","disabled","readOnly","type","id","className","title"]),Y=new Set(["tagName","nodeName","nodeType","nodeValue","childElementCount","classList","baseURI","documentURI","contentType","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","currentSrc","duration","paused","dataset"]);var X={};xe(X,{EmptyListInsert:()=>U,MAX_RULE_DEPTH:()=>D,MaxRuleDepthExceeded:()=>j,NoRulesTag:()=>ie,RuleTargetReadOnly:()=>H,RulesParseError:()=>_,ShapeMismatch:()=>W,UnknownRulesVersion:()=>I,WriteRefused:()=>G,WriteRejected:()=>se});var _=class extends Error{constructor(t,n){super(t),this.name="RulesParseError",this.cause=n}},I=class extends Error{constructor(t){super(`unknown rules version: ${t}. Library supports "1".`),this.name="UnknownRulesVersion",this.version=t}},D=20,j=class extends Error{constructor(t){super(`rule depth exceeded ${D} at path: ${t.join(".")}`),this.name="MaxRuleDepthExceeded",this.path=t}},W=class extends Error{constructor(t){super(`shape mismatch: ${t.length} field(s) failed validation`),this.name="ShapeMismatch",this.mismatches=t}},U=class extends Error{constructor(t){super(`cannot add items to empty list at "${t.join(".")}" \u2014 no sibling to clone as template. Seed the list with a hidden item first.`),this.name="EmptyListInsert",this.path=t}},H=class extends Error{constructor(t){super(`cannot write to read-only DOM property "${t}"`),this.name="RuleTargetReadOnly",this.target=t}},G=class extends Error{constructor(t){super(`write refused: ${t.length} write(s) broke the content-only policy`),this.name="WriteRefused",this.refusals=t}},ie=class extends Error{constructor(t){super(`no <script data-rules-name~="${t}"> rules tag in this document`),this.name="NoRulesTag",this.token=t}},se=class extends Error{constructor(t,n){super(`write rejected: ${t.length} unknown key(s), ${n.length} rule(s) with no matching element`),this.name="WriteRejected",this.unknownKeys=t,this.unmatched=n}};function N(e){let t=0,n=null,o=-1;for(let r=0;r<e.length;r++){let i=e[r];i==="\\"?r++:n?i===n&&(n=null):i==='"'||i==="'"?n=i:i==="["||i==="("?t++:i==="]"||i===")"?t>0&&t--:i==="@"&&t===0&&(o=r)}return o}function ce(e){let t=N(e);return t===-1?{selector:e,prop:null}:{selector:e.slice(0,t),prop:e.slice(t+1)||null}}function M(e,t,n,o={}){if(Object.prototype.hasOwnProperty.call(o,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");return le(e,t,n,{depth:0,path:[]},o)}function le(e,t,n,o,r){if(o.depth>D)throw new j(o.path);if(typeof n=="string")return tt(e,t,n,o,r);if(Array.isArray(n)){let[i,l]=n,s=e.find(t,i,r);return be(r,o,s),s.map((c,a)=>le(e,c,l,{depth:o.depth+1,path:[...o.path,a]},r))}if(typeof n=="object"&&n!==null){let i={};for(let[l,s]of Object.entries(n))i[l]=le(e,t,s,{depth:o.depth+1,path:[...o.path,l]},r);return i}return null}function tt(e,t,n,o,r){if(n.endsWith("[]")){let s=n.slice(0,-2),c=e.find(t,s,r);return be(r,o,c),c.map(a=>e.text(a))}if(n.startsWith("@"))return Oe(e,t,n.slice(1));let i=N(n);if(i!==-1){let s=n.slice(0,i),c=n.slice(i+1),a=s?e.find(t,s,r):[t];return a.length===0?null:Oe(e,a[0],c)}if(n===".")return e.text(t);let l=e.find(t,n,r);return l.length===0?null:e.text(l[0])}function be(e,t,n){if(typeof e.onRowsRead=="function")try{e.onRowsRead(t.path.slice(),n)}catch(o){console.warn(`[hyper-html-api] onRowsRead threw at "${t.path.join(".")||"(root)"}"`,o)}}function Oe(e,t,n){if(oe.has(n)){let r=e.prop(t,n);return r==null?null:String(r)}let o=e.attr(t,n);return o||null}function Ne(e,t,n,o){let r=e.length,i=t.length,l=new Array(r).fill(-1);if(o){let u=new Set;for(let p=0;p<r;p++){let g=o[p];!(g>=0&&g<i)||u.has(g)||(l[p]=g,u.add(g))}}if(r===0||i===0)return l;let s=e.map(u=>Se(u,n)),c=t.map(u=>Se(u,n)),a=new Array(i).fill(!1);for(let u of l)u>=0&&(a[u]=!0);let f=new Map;c.forEach((u,p)=>{a[p]||f.set(u,f.has(u)?-1:p)});let y=new Map;s.forEach((u,p)=>{l[p]>=0||y.set(u,(y.get(u)||0)+1)}),s.forEach((u,p)=>{if(l[p]>=0||y.get(u)!==1)return;let g=f.get(u);g===void 0||g===-1||a[g]||(l[p]=g,a[g]=!0)});let d=[];for(let u=0;u<r;u++)l[u]<0&&d.push(u);let A=[];for(let u=0;u<i;u++)a[u]||A.push(u);if(d.length===0||A.length===0)return l;let h=r*i+1,m=(u,p)=>nt(e[u],t[p],n)*h+Math.abs(u-p);for(let[u,p]of rt(d,A,m))l[u]=p;return l}var Me=e=>typeof e=="object"&&e!==null;function Se(e,t){if(!Me(t))return e==null?" null":String(e);let n=Object.keys(t);return JSON.stringify(n.map(o=>{let r=JSON.stringify(e?.[o]);return r===void 0?" undef":r}))}function nt(e,t,n){if(!Me(n))return e===t?0:1;let o=Object.keys(n);if(o.length===0)return 0;let r=0;for(let i of o){let l=JSON.stringify(e?.[i]),s=JSON.stringify(t?.[i]);l!==s&&r++}return r}function rt(e,t,n){return e.length<=t.length?Re(e,t,n,!1):Re(t,e,(o,r)=>n(r,o),!0)}function Re(e,t,n,o){let r=e.length,i=t.length,l=[];for(let y=0;y<=r;y++)l.push(new Float64Array(i+1).fill(1/0));let s=[];for(let y=0;y<=r;y++)s.push(new Uint8Array(i+1));for(let y=0;y<=i;y++)l[r][y]=0;for(let y=r-1;y>=0;y--)for(let d=i-1;d>=0;d--){let A=n(e[y],t[d])+l[y+1][d+1],h=l[y][d+1];A<=h?(l[y][d]=A,s[y][d]=1):l[y][d]=h}let c=[],a=0,f=0;for(;a<r&&f<i;)s[a][f]&&(c.push(o?[t[f],e[a]]:[e[a],t[f]]),a++),f++;return c}function ue(e,t,n,o,r,i,l,s={}){let c=e.find(t,n,s);if(r.length===0){c.forEach(w=>e.remove(w)),fe(s,"onRowsApplied",i.path,[]);return}let a=r.length>c.length,f=c[0]||null;if(a&&!f&&(f=ct(e,t,n,s),!f))throw new U(i.path);let y=c.map(w=>st(e,w,o,s)),d=null;if(a&&f){d=e.clone(f),s.templateAttr&&e.removeAttr(d,s.templateAttr);let w=e.stripIds(d);w>0&&console.warn(`[hyper-html-api] stripped ${w} id attribute(s) from cloned template at "${i.path.join(".")||"(root)"}"`)}let A=Ne(r,y,o,ot(e,c,r,i,s)),h=c[0]||f,m=e.parent(h),u=c.length>0?Ce(e,m,h):0,p=lt(e,c),g=new Set,O=[],E=r.map((w,x)=>{let T=A[x];if(T>=0)return g.add(T),O.push(!1),c[T];O.push(!0);let R=e.clone(d);return e.stripIds(R),R});c.forEach((w,x)=>{g.has(x)||e.remove(w)}),p?E.forEach((w,x)=>{let T=u+x;e.children(m).findIndex(Ye=>e.sameNode(Ye,w))!==T&&e.insertAt(m,w,T)}):ft(e,E,O,m,u),it(e,E,o,r,i,l,s),fe(s,"onRowsApplied",i.path,E)}function fe(e,t,n,o){if(typeof e[t]=="function")try{return e[t](n.slice(),o)}catch(r){console.warn(`[hyper-html-api] ${t} threw at "${n.join(".")||"(root)"}"`,r);return}}function ot(e,t,n,o,r){let i=fe(r,"identifyRows",o.path,n);if(!Array.isArray(i))return null;let l=new Array(n.length).fill(-1),s=new Set;for(let c=0;c<n.length;c++)if(i[c]){for(let a=0;a<t.length;a++)if(!(s.has(a)||!e.sameNode(t[a],i[c]))){l[c]=a,s.add(a);break}}return l}function it(e,t,n,o,r,i,l){t.forEach((s,c)=>{if(n===null){let a=o[c],f=a==null?"":String(a);e.text(s)!==f&&e.text(s,f)}else{let a=i(e,s,n,o[c],{depth:r.depth+1,path:[...r.path,c]},l);a&&a!==s&&(t[c]=a)}})}function st(e,t,n,o){return n===null?e.text(t):M(e,t,n,o.onRowsRead?{...o,onRowsRead:void 0}:o)}function Ce(e,t,n){let o=e.children(t);for(let r=0;r<o.length;r++)if(e.sameNode(o[r],n))return r;return-1}function ct(e,t,n,o){if(!o.templateAttr)return null;let r=t;for(;r;){let i=e.find(r,n,{includeRulesTag:!1,templateAttr:null});for(let l of i)if(e.attr(l,o.templateAttr)!=null)return l;r=e.parent(r)}return null}function lt(e,t){if(t.length<=1)return!0;let n=e.parent(t[0]);if(!n)return!1;let o=e.children(n),r=[];for(let i of t){let l=o.findIndex(s=>e.sameNode(s,i));if(l===-1)return!1;r.push(l)}return r.sort((i,l)=>i-l),r[r.length-1]-r[0]===r.length-1}function ft(e,t,n,o,r){let i=null,l=r;for(let s=0;s<t.length;s++){if(!n[s]){i=t[s];continue}let c=i?e.parent(i):o;if(!c)continue;let a=i?Ce(e,c,i)+1:l++;e.insertAt(c,t[s],a),i=t[s]}}var Ie=new Set(["checked","selected","disabled","readOnly","paused"]);function k(e,t,n,o,r={}){if(Object.prototype.hasOwnProperty.call(r,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");let i=[];if(ae(n,o,[],i),i.length)throw new W(i);Z(e,t,n,o,{depth:0,path:[]},r)}function Z(e,t,n,o,r,i={}){if(r.depth>D)throw new j(r.path);if(o===void 0)return t;if(typeof n=="string")return ut(e,t,n,o,r,i);if(Array.isArray(n)){let[l,s]=n;return ue(e,t,l,s,o,r,Z,i),t}if(typeof n=="object"&&n!==null){for(let[l,s]of Object.entries(n)){let c=Z(e,t,s,o==null?o:o[l],{depth:r.depth+1,path:[...r.path,l]},i);c&&c!==t&&(t=c)}return t}return t}function ut(e,t,n,o,r,i){if(n.endsWith("[]")){let c=n.slice(0,-2);return ue(e,t,c,null,o,r,Z,i),t}if(n.startsWith("@"))return ke(e,t,n.slice(1),o);let l=N(n);if(l!==-1){let c=n.slice(0,l),a=n.slice(l+1),f=c?e.find(t,c,i):[t];return f.length===0||ke(e,f[0],a,o),t}if(n===".")return je(e,t,o),t;let s=e.find(t,n,i);return s.length===0||je(e,s[0],o),t}function je(e,t,n){let o=n==null?"":String(n);e.text(t)!==o&&e.text(t,o)}function ke(e,t,n,o){if(Y.has(n)){let i=e.prop(t,n);if(i===o||i!=null&&o!=null&&String(i)===String(o))return t;throw new H(n)}if(n==="outerHTML"){let i=o==null?"":String(o);return e.replaceWith(t,i)}if(Ee.has(n)){let i=at(n,o);return e.prop(t,n)!==i&&e.prop(t,n,i),t}let r=o==null?"":String(o);return e.attr(t,n)!==r&&e.attr(t,n,r),t}function at(e,t){return t==null?Ie.has(e)?!1:"":Ie.has(e)?t==="false"?!1:!!t:t}function ae(e,t,n,o){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]")){Array.isArray(t)?t.forEach((r,i)=>{typeof r=="object"&&r!==null&&o.push({path:q([...n,i]),expected:"scalar",got:v(r)})}):o.push({path:q(n),expected:"array",got:v(t)});return}t!==null&&typeof t=="object"&&o.push({path:q(n),expected:"scalar",got:v(t)});return}if(Array.isArray(e)){if(!Array.isArray(t)){o.push({path:q(n),expected:"array",got:v(t)});return}let r=e[1];t.forEach((i,l)=>ae(r,i,[...n,l],o));return}if(typeof e=="object"&&e!==null){if(t===null||Array.isArray(t)||typeof t!="object"){o.push({path:q(n),expected:"object",got:v(t)});return}for(let[r,i]of Object.entries(e))ae(i,t[r],[...n,r],o)}}}function v(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function q(e){return e.join(".")}function de(e){try{return JSON.parse(e)}catch(t){throw new _(`Invalid strict JSON: ${t.message}`,t)}}function L(e){try{return JSON.parse(e)}catch{}let t={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function n(r){let i=[],l=0;for(;l<r.length;){let s=r[l];if(/\s/.test(s)){l++;continue}if("{}".includes(s)){i.push({type:s,value:s}),l++;continue}if(s==="["){let y=!1,d=l+1;for(;d<r.length&&/\s/.test(r[d]);)d++;if(d<r.length&&/[a-zA-Z_]/.test(r[d])&&(y=!0),!y){i.push({type:s,value:s}),l++;continue}}if(s==="]"){i.push({type:s,value:s}),l++;continue}if(s===":"){i.push({type:t.COLON,value:s}),l++;continue}if(s===","){i.push({type:t.COMMA,value:s}),l++;continue}if(s==='"'||s==="'"){let y=s,d=l+1;for(;d<r.length&&r[d]!==y;)r[d]==="\\"&&d++,d++;i.push({type:t.STRING,value:r.substring(l+1,d),quoted:!0,sourceQuote:y}),l=d+1;continue}let c=l,a;for(;c<r.length&&!/[{},]/.test(r[c]);)if(r[c]===":"){let y=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],d=!1;for(let A of y){let h=A.substring(1);if(r.substring(c+1,c+1+h.length)===h){d=!0,c+=h.length;break}}if(!d)break}else if(r[c]==="["){for(c++;c<r.length&&r[c]!=="]";){if(r[c]==='"'||r[c]==="'"){let y=r[c];for(c++;c<r.length&&r[c]!==y;)r[c]==="\\"&&c++,c++}c++}c<r.length&&r[c]==="]"&&c++}else c++;a=r.substring(l,c);let f=t.IDENTIFIER;/^-?\d+(\.\d+)?$/.test(a)?f=t.NUMBER:a==="true"||a==="false"||a==="null"?f=t.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test(a)&&(f=t.SELECTOR),i.push({type:f,value:a,quoted:!1}),l=c}return i}function o(r){let i="";for(let l=0;l<r.length;l++){let s=r[l];if("{}".includes(s.type)||"[]".includes(s.type)){i+=s.value;continue}if(s.type===t.COLON){i+=s.value;continue}if(s.type===t.COMMA){let c=r[l+1];if(c&&(c.type==="}"||c.type==="]"))continue;i+=s.value;continue}if(s.type===t.STRING&&s.quoted){let c=s.value;s.sourceQuote==="'"&&(c=c.replace(/\\'/g,"'"),c=c.replace(/(\\*)"/g,(a,f)=>f.length%2===0?f+'\\"':a)),i+=`"${c}"`;continue}if(s.type===t.NUMBER||s.type===t.BOOLEAN){i+=s.value;continue}if(s.type===t.SELECTOR||s.type===t.IDENTIFIER){i+=`"${s.value}"`;continue}i+=`"${s.value}"`}return i}try{let r=n(e),i=o(r);return JSON.parse(i)}catch(r){throw new _("Invalid extraction rules syntax: "+r.message,r)}}var pe="1",Le=/^[a-zA-Z0-9_-]+$/;function B(e,t,n){let o;if(n===void 0)o="script[data-rules-name]";else{if(typeof n!="string"||!Le.test(n))throw new Error(`hyper-html-api: invalid rules token ${JSON.stringify(n)} (must match ${Le})`);o=`script[data-rules-name~="${n}"]`}let r=e.find(t,o,{includeRulesTag:!0});if(r.length===0)return null;n!==void 0&&r.length>1&&console.warn(`hyper-html-api: ${r.length} rules tags match data-rules-name~="${n}"; using the first.`);let i=r[0],l=e.attr(i,"data-rules-version");if(l!==pe)throw new I(l);return{rules:L(e.text(i)),tagNode:i}}var Pe=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),dt=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),_e=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui"]);function he(e,t){if(!e||e.nodeType!==1)return!1;let n=e.getAttribute?.("clay");return!!(n&&n.split(/\s+/).includes(t)||e.hasAttribute?.(t))}function pt(e,t){if(he(e,t))return!0;for(let[n,o]of Object.entries(dt))if(o.includes(t)&&he(e,n))return!0;return!1}function K(e){let t=Pe[e];if(!t)throw new Error(`Unknown region capability: ${e}`);return[...t.tokens,...t.bundles].flatMap(n=>[`[clay~="${n}"]`,`[${n}]`]).join(", ")}function ht(e,t){let n=e&&e.nodeType===1?e:e?.parentElement;for(;n&&n.nodeType===1;){let o=Pe[t];if(!o)throw new Error(`Unknown region capability: ${t}`);if(o.tokens.some(r=>pt(n,r))||o.bundles.some(r=>he(n,r)))return n;n=n.parentElement}return null}function De(e,t){return!!ht(e,t)}var mt=Object.freeze({refusedRuleForms:["innerHTML","outerHTML"],refusedTargets:["script","style","template","noscript","iframe","object","embed","xmp","plaintext","noembed","noframes","meta","link","base","animate","set","animatemotion","animatetransform"],refusedAttributes:["style","srcdoc","is","http-equiv","sandbox","allow","nonce","integrity","charset","htmlclaytoken","htmlclayid","data-rules-name","data-rules-version","clay","contenteditable",..._e],refusedAttributePrefixes:["on"],urlAttributes:["href","src","srcset","action","formaction","poster","cite","data","ping","background","longdesc","usemap","xlink:href","manifest","codebase","icon"],refusedSchemes:["javascript","vbscript","data"]});function me(e,t,n){if(n&&typeof n=="object")return{rules:n,tagNode:null};if(typeof n=="string"){let o=t&&t.ownerDocument?t.ownerDocument:t;return B(e,o,n)}return null}var Tt=/:(?:focus(?:-within|-visible)?|hover|active|visited|defined)\b/i;function $e(e,t){if(!/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(e.tagName||""))return;let n=(e.getAttribute?.("type")||"").toLowerCase();if("value"in e&&"value"in t&&e.tagName!=="OPTION"&&n!=="checkbox"&&n!=="radio"&&n!=="file"&&(t.value=e.value),e.tagName==="INPUT"&&(n==="checkbox"||n==="radio")&&(t.checked=e.checked),e.tagName==="OPTION"&&(t.selected=e.selected),e.tagName==="SELECT")for(let o=0;o<e.options.length;o++)t.options[o].selected=e.options[o].selected;"indeterminate"in e&&"indeterminate"in t&&(t.indeterminate=e.indeterminate)}function We(e,t,n,o){if(o)return!!e.closest?.(t);let r=e;for(;r?.nodeType===1;){if(r.matches(t))return!0;if(r===n)break;r=r.parentElement}return!1}function Ue(e,t,n,o,r,i,l,s){if(e.nodeType===1&&((l?De(e,n):We(e,o,i,!1))||r&&(l&&e!==i?e.matches(r):We(e,r,i,l))))return null;let c=t.importNode(e,!1);s.cloneToLive.set(c,e),s.liveToClone.set(e,c);let a=e.nodeType===1&&e.tagName==="TEMPLATE"?e.content:e,f=c.nodeType===1&&c.tagName==="TEMPLATE"?c.content:c;a!==e&&(s.cloneToLive.set(f,a),s.liveToClone.set(a,f));for(let y of a.childNodes||[]){let d=Ue(y,t,n,o,r,i,l,s);d&&(f.appendChild(d),y.nodeType===1&&$e(y,d))}return e.nodeType===1&&$e(e,c),c}function F(e,{capability:t="data",exclude:n=null,inherit:o=!0}={}){if(!e)throw new TypeError("createContentView requires a DOM context");let r=e.nodeType===9?e:e.ownerDocument;if(!r?.implementation?.createHTMLDocument)throw new TypeError("createContentView requires an HTML DOM implementation");let i=r.implementation.createHTMLDocument(""),l=new WeakMap,s=new WeakMap,c=e.nodeType===9?e.documentElement:e;n&&i.documentElement.matches(n);let a=K(t),f=Ue(c,i,t,a,n,c,o,{cloneToLive:l,liveToClone:s});e.nodeType===9&&f&&(i.replaceChild(f,i.documentElement),s.set(e,i),l.set(i,e));let y=d=>{if(Tt.test(d))throw new Error(`Filtered content queries do not support stateful selector: ${d}`)};return{root:f,document:i,capability:t,selector:K(t),cloneToLive:l,liveToClone:s,original(d){return l.get(d)||null},cloneOf(d){return s.get(d)||null},query(d,A=f){return y(d),Array.from(A.querySelectorAll(d),h=>l.get(h)||h)},text(d=f){return(d===f?f:s.get(d))?.textContent||""},html(d=f){return(d===f?f:s.get(d))?.innerHTML??""},clone(d=f){let A=d===f?f:s.get(d);return A?i.importNode(A,!0):null}}}function He(e){return e&&e.nodeType===1&&e.tagName==="SCRIPT"&&e.hasAttribute&&e.hasAttribute("data-rules-name")}function At(e){return e?(e.nodeType===9||e.nodeType===11,e):null}var b={semanticExclude:!0,find(e,t,n={}){let o=At(e);if(!o||!o.querySelectorAll)return[];let r=Array.from(o.querySelectorAll(t));n.includeRulesTag||(r=r.filter(s=>!He(s)));let i=[];n.skip&&i.push(n.skip);let l=n.templateAttr===null?null:n.templateAttr||"cms-template";if(l&&i.push("["+l+"]"),i.length){let s=i.join(", ");r=r.filter(c=>!c.closest||!c.closest(s))}return r},parent(e){return e?e.parentElement:null},children(e){return e?Array.from(e.children):[]},text(e,t){if(t===void 0)return(e.textContent||"").trim();e.textContent=t},attr(e,t,n){if(n===void 0)return e.hasAttribute&&e.hasAttribute(t)?e.getAttribute(t):null;e.setAttribute(t,n)},removeAttr(e,t){e&&e.removeAttribute&&e.removeAttribute(t)},prop(e,t,n){if(n===void 0){let o=e?e[t]:void 0;return o!==void 0?o:null}e[t]=n},clone(e){return e.cloneNode(!0)},insertAt(e,t,n){let o=e.children[n]||null;e.insertBefore(t,o)},remove(e){e&&e.parentNode&&e.parentNode.removeChild(e)},replaceWith(e,t){if(!e||!e.parentNode)throw new Error("dom.replaceWith: node has no parent");let o=e.ownerDocument.createElement("template");o.innerHTML=t;let r=o.content.firstElementChild;if(!r)throw new Error("dom.replaceWith: html did not parse to an element");return e.parentNode.replaceChild(r,e),r},stripIds(e){let t=0;return e.id&&(e.removeAttribute("id"),t++),(e.querySelectorAll?e.querySelectorAll("[id]"):[]).forEach(o=>{o.removeAttribute("id"),t++}),t},sameNode(e,t){return e===t}};function z(e,t={}){if(t.exclude===null)return b;let n=[K("data"),t.exclude].filter(Boolean).join(", "),o=e.nodeType===9?e:e.ownerDocument||e,r=e.nodeType===9?e.documentElement:e;if(!t._write&&!r?.matches?.(n)&&!r?.querySelector?.(n)&&!o?.querySelector?.(n))return b;let i=e.nodeType===9||!e.isConnected?e:e.ownerDocument,l=e.nodeType===9?e:e.ownerDocument,s=null,c=()=>s||(s=F(i,{capability:"data",exclude:t.exclude||null})),a=h=>{let m=c();return h===e?m.cloneOf(e):m.cloneOf(h)||h},f=h=>s?.original(h)||h,y=(h,m)=>{c().liveToClone.set(h,m),c().cloneToLive.set(m,h);let u=h.childNodes||[],p=m.childNodes||[];for(let g=0;g<Math.min(u.length,p.length);g++)y(u[g],p[g])},d=(h,m,u,p)=>{let g=Array.from(h.childNodes).filter(T=>s.cloneOf(T)),E=g[0];for(;E&&g.includes(E);)E=E.nextSibling;for(let T of g)T.remove();if(u==="innerHTML"){let T=l.createElement("template");T.innerHTML=p;for(let R of Array.from(T.content.childNodes))h.insertBefore(R,E||null)}else h.insertBefore(l.createTextNode(p),E||null);let w=F(h,{capability:"data",exclude:t.exclude||null});m.replaceChildren(...Array.from(w.root?.childNodes||[]));let x=T=>{let R=w.original(T);R&&(s.liveToClone.set(R,T),s.cloneToLive.set(T,R));for(let Ae of Array.from(T.childNodes||[]))x(Ae)};for(let T of Array.from(m.childNodes))x(T)},A={...b,find(h,m,u={}){let p=a(h);if(!p?.querySelectorAll)return[];let g=c().query(m,p);u.includeRulesTag||(g=g.filter(w=>!He(w)));let O=[];u.skip&&O.push(u.skip);let E=u.templateAttr===null?null:u.templateAttr||"cms-template";if(E&&O.push(`[${E}]`),O.length){let w=O.join(", ");g=g.filter(x=>!x.closest?.(w))}return g},parent(h){let m=a(h)?.parentElement;return m?f(m):null},children(h){return Array.from(a(h)?.children||[],f)},text(h,m){if(m===void 0){let g=f(h);return!g?.matches?.(n)&&!g?.querySelector?.(n)?b.text(g):(a(h)?.textContent||"").trim()}let u=f(h);if(!u?.matches?.(n)&&!u?.querySelector?.(n)&&!s){b.text(u,m);return}let p=c().cloneOf(u);p?d(u,p,"textContent",m):b.text(u,m)},attr(h,m,u){let p=f(h);if(u===void 0)return b.attr(p,m);b.attr(p,m,u);let g=s?.cloneOf(p);g&&(b.attr(g,m,u),F(p,{capability:"data",exclude:t.exclude||null}).root===null&&(g.remove(),s.liveToClone.delete(p),s.cloneToLive.delete(g)))},removeAttr(h,m){let u=f(h);b.removeAttr(u,m);let p=s?.cloneOf(u);p&&b.removeAttr(p,m)},prop(h,m,u){let p=f(h);if(u===void 0)return m==="innerHTML"||m==="outerHTML"||m==="textContent"||m==="innerText"?b.prop(a(p),m):b.prop(p,m);let g=m==="innerHTML"||m==="textContent"||m==="innerText",O=g?c().cloneOf(p):s?.cloneOf(p);O&&g?d(p,O,m,u):(b.prop(p,m,u),O&&b.prop(O,m,u))},clone(h){let m=a(h);return m===h?b.clone(h):l.importNode(m,!0)},insertAt(h,m,u){let p=f(h),O=A.children(p)[u]||(()=>{for(let x=p.children.length-1;x>=0;x--){let T=p.children[x];if(c().cloneOf(T))return T.nextElementSibling}return p.firstElementChild})(),E=f(m);p.insertBefore(E,O||null);let w=c().cloneOf(p);if(w){let x=c().cloneOf(E);x||(x=l.importNode(E,!0),y(E,x));let T=Array.from(w.children);w.insertBefore(x,T[u]||null)}},remove(h){let m=f(h),u=c().cloneOf(m);b.remove(m),u&&b.remove(u)},replaceWith(h,m){let u=f(h),p=c().cloneOf(u),g=b.replaceWith(u,m);if(p){let O=F(g,{capability:"data",exclude:t.exclude||null});if(!O.root)p.remove();else{p.replaceWith(O.root);let E=w=>{let x=O.original(w);x&&(s.liveToClone.set(x,w),s.cloneToLive.set(w,x));for(let T of Array.from(w.childNodes||[]))E(T)};E(O.root)}}return g}};return A}var S=b;var ye={extract:(e,t,n={})=>M(z(e,n),e,t,n),apply:(e,t,n,o={})=>k(z(e,{...o,_write:!0}),e,t,n,o),findRulesIn:(e,t)=>B(S,e,t),findRules:(e,t)=>me(S,e,t),bind:(e,t,n={})=>{let o=me(S,e,t);if(!o){let r=typeof t=="string"?`data-rules-name~="${t}"`:"the provided rules object";throw new Error(`hyper-html-api: could not resolve rules for ${r}`)}return{...o,get:()=>M(z(e,n),e,o.rules,n),set:r=>k(z(e,{...n,_write:!0}),e,o.rules,r,n)}},parseStrict:de,parseRelaxed:L,ruleAttrIndex:N,splitRule:ce,errors:X,DOM_PROPERTIES:J};var xt="hha:upgrade-check:";function C(e,t){let n=e.querySelector(`meta[name="${t}"]`),o=n?n.getAttribute("content"):null;return o&&o.trim()?o.trim():null}function ve(e){if(typeof e!="string")return null;let t=e.trim().replace(/^v/,"");return/^\d+(\.\d+)*$/.test(t)?t.split(".").map(Number):null}function Et(e,t){let n=ve(e),o=ve(t);if(!n||!o)return!1;let r=Math.max(n.length,o.length);for(let i=0;i<r;i++){let l=n[i]||0,s=o[i]||0;if(l!==s)return l>s}return!1}function Ot(e){try{let t=globalThis.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function bt(e,t){try{globalThis.localStorage.setItem(e,JSON.stringify(t))}catch{}}async function qe({force:e=!1,doc:t,loc:n,fetchFn:o,now:r,ttlMs:i=864e5}={}){if(t=t||(typeof document<"u"?document:null),n=n||(typeof location<"u"?location:null),o=o||(d=>fetch(d)),r=r??Date.now(),!t)return null;let l=C(t,"hyper-source");if(!l)return null;let s=C(t,"hyper-version"),c;try{c=new URL(l,n?n.href:void 0)}catch{return null}if(n&&c.origin===n.origin&&c.pathname===n.pathname)return null;let a=`${xt}${c.href}:${s||"none"}`,f,y=e?null:Ot(a);if(y&&typeof y.checkedAt=="number"&&r-y.checkedAt<i)f=y.sourceVersion;else{try{let d=await o(c.href);if(!d.ok)throw new Error(`HTTP ${d.status}`);let A=await d.text(),h=new DOMParser().parseFromString(A,"text/html");f=C(h,"hyper-version")}catch{f=null}bt(a,{checkedAt:r,sourceVersion:f})}return f?{available:Et(f,s||"0.0.0"),currentVersion:s,sourceVersion:f,sourceUrl:c.href}:null}var St="script[data-rules-name]";function Rt(e){return typeof e=="string"?e.trim().replace(/\s+/g," "):""}function Q(e,t){let n=e.find(t,St,{includeRulesTag:!0}),o=new Set,r=[];for(let i of n){let l=Rt(e.attr(i,"data-rules-name"));if(!l)continue;if(o.has(l)){console.warn(`hyper-html-api: duplicate rules tag name "${l}"; using the first.`);continue}let s=e.attr(i,"data-rules-version");if(s!==pe)throw new I(s);o.add(l),r.push({name:l,rules:L(e.text(i))})}return r}function ge(e,t){let n={};for(let{name:o,rules:r}of Q(e,t))n[o]=M(e,t,r);return n}function Be(e){let t=e||document,n=t.nodeType===9?t:t.ownerDocument||t;return{dataByName:ge(S,t),version:C(n,"hyper-version")}}var V=class extends Error{constructor(t,n){super(`could not fetch upgrade source: ${t}`),this.name="UpgradeSourceUnreachable",this.sourceUrl=t,this.cause=n}},ee=class extends Error{constructor(t){super(`upgrade source has no rules tags; refusing to drop all existing data: ${t}`),this.name="UpgradeSourceHasNoRules",this.sourceUrl=t}},P=class extends Error{constructor(t,n){super(t),this.name="UpgradeTransformInvalid",this.cause=n}},te=class extends Error{constructor(t){super(`found ${t} script[type="text/hyper-upgrade"] tags; only one is allowed per document.`),this.name="UpgradeMultipleTransforms",this.count=t}};var Nt="text/hyper-upgrade";function Ke(e,t){let n=e.find(t,`script[type="${Nt}"]`);if(n.length===0)return null;if(n.length>1)throw new te(n.length);return e.text(n[0])||null}var Mt=new Function("url","return import(url)");async function Fe(e){let t=new Blob([e],{type:"text/javascript"}),n=URL.createObjectURL(t),o;try{o=await Mt(n)}catch(r){throw new P(`transform failed to load: ${r&&r.message?r.message:r}`,r)}finally{URL.revokeObjectURL(n)}if(typeof o.default!="function")throw new P("transform must `export default` a function");return o.default}function ne(e,t){let n={carriedOver:0,discarded:0,listItems:0},o=we(t,e,n);return Te(t,e,n),{data:o,summary:n}}function we(e,t,n){if(typeof e=="string")return e.endsWith("[]")?Array.isArray(t)?(n.listItems+=t.length,n.carriedOver+=t.length,t):void 0:t==null||typeof t=="object"?void 0:(n.carriedOver++,t);if(Array.isArray(e)){let[,o]=e;return Array.isArray(t)?(n.listItems+=t.length,t.map(r=>we(o,r,n))):void 0}if(typeof e=="object"&&e!==null){let o={};for(let[r,i]of Object.entries(e)){let l=we(i,t?.[r],n);l!==void 0&&(o[r]=l)}return o}}function Te(e,t,n){if(t!=null){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(typeof t!="object"||Array.isArray(t))return;let o=new Set(Object.keys(e));for(let r of Object.keys(t))o.has(r)?Te(e[r],t[r],n):n.discarded+=$(t[r]);return}if(Array.isArray(e)&&Array.isArray(t)){let o=e[1];t.forEach(r=>Te(o,r,n));return}typeof e=="string"&&!e.endsWith("[]")&&typeof t=="object"&&t!==null&&(n.discarded+=$(t))}}function $(e){return e==null?0:Array.isArray(e)?e.reduce((t,n)=>t+$(n),0):typeof e=="object"?Object.values(e).reduce((t,n)=>t+$(n),0):1}function ze(e,t,n){let o=Q(e,t),r={carriedOver:0,discarded:0,listItems:0},i={},l=new Set;for(let{name:s,rules:c}of o){if(l.add(s),!Object.prototype.hasOwnProperty.call(n,s)){i[s]={carriedOver:0,discarded:0,listItems:0};continue}let{data:a,summary:f}=ne(n[s],c);k(e,t,c,a),i[s]=f,r.carriedOver+=f.carriedOver,r.discarded+=f.discarded,r.listItems+=f.listItems}for(let s of Object.keys(n))l.has(s)||(r.discarded+=$(n[s]));return{totals:r,byName:i,rulesTagCount:o.length}}async function Ve({sourceUrl:e,dataByName:t,fromVersion:n,doc:o,loc:r,fetchFn:i}={}){if(o=o||(typeof document<"u"?document:null),r=r||(typeof location<"u"?location:null),i=i||(p=>fetch(p)),!o)throw new Error("upgrade.run requires a document context");if(e=e||C(o,"hyper-source"),!e)throw new Error("upgrade.run: no sourceUrl given and no hyper-source meta tag found");let l=new URL(e,r?r.href:void 0);n=n!==void 0?n:C(o,"hyper-version"),t=t||ge(S,o);let s;try{s=await i(l.href)}catch(p){throw new V(l.href,p)}if(!s.ok)throw new V(l.href,new Error(`HTTP ${s.status}`));let c=await s.text(),a=new DOMParser().parseFromString(c,"text/html"),f=C(a,"hyper-version"),y=t,d=!1,A=Ke(S,a);if(A){let g=await(await Fe(A))(y,{fromVersion:n,toVersion:f});if(!g||typeof g!="object"||Array.isArray(g))throw new P("transform must return a plain object map of { rulesName: data }");y=g,d=!0}let{totals:h,byName:m,rulesTagCount:u}=ze(S,a,y);if(u===0&&Object.keys(y).length>0)throw new ee(l.href);return{html:Ct(a),fromVersion:n,toVersion:f,summary:{transformApplied:d,totals:h,byName:m}}}function Ct(e){return`<!DOCTYPE ${e.doctype&&e.doctype.name?e.doctype.name:"html"}>
2
- `+e.documentElement.outerHTML}var Je={checkForUpdate:qe,run:Ve,extractAll:Be,shapeMatch:ne};var It={engine:ye,upgrade:Je},jt=It;return et(kt);})();
1
+ var hyperHtmlApiUpgrade=(()=>{var ie=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var Ee=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:!0})},Qe=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Xe(t))!Ze.call(e,r)&&r!==n&&ie(e,r,{get:()=>t[r],enumerable:!(o=Ge(t,r))||o.enumerable});return e};var et=e=>Qe(ie({},"__esModule",{value:!0}),e);var Dt={};Ee(Dt,{default:()=>Pt,engine:()=>we,upgrade:()=>Je});var Y=["textContent","innerText","innerHTML","outerHTML","value","checked","selected","disabled","readOnly","type","tagName","nodeName","nodeType","nodeValue","childElementCount","id","className","classList","baseURI","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","dataset","currentSrc","duration","paused","title","documentURI","contentType"],se=new Set(Y),Oe=new Set(["textContent","innerText","innerHTML","value","checked","selected","disabled","readOnly","type","id","className","title"]),G=new Set(["tagName","nodeName","nodeType","nodeValue","childElementCount","classList","baseURI","documentURI","contentType","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","currentSrc","duration","paused","dataset"]);var Z={};Ee(Z,{EmptyListInsert:()=>U,MAX_RULE_DEPTH:()=>_,MaxRuleDepthExceeded:()=>k,NoRulesTag:()=>ce,RuleTargetReadOnly:()=>H,RulesParseError:()=>D,ShapeMismatch:()=>W,UnknownRulesVersion:()=>j,WriteRefused:()=>X,WriteRejected:()=>le});var D=class extends Error{constructor(t,n){super(t),this.name="RulesParseError",this.cause=n}},j=class extends Error{constructor(t){super(`unknown rules version: ${t}. Library supports "1".`),this.name="UnknownRulesVersion",this.version=t}},_=20,k=class extends Error{constructor(t){super(`rule depth exceeded ${_} at path: ${t.join(".")}`),this.name="MaxRuleDepthExceeded",this.path=t}},W=class extends Error{constructor(t){super(`shape mismatch: ${t.length} field(s) failed validation`),this.name="ShapeMismatch",this.mismatches=t}},U=class extends Error{constructor(t){super(`cannot add items to empty list at "${t.join(".")}" \u2014 no sibling to clone as template. Seed the list with a hidden item first.`),this.name="EmptyListInsert",this.path=t}},H=class extends Error{constructor(t){super(`cannot write to read-only DOM property "${t}"`),this.name="RuleTargetReadOnly",this.target=t}},X=class extends Error{constructor(t){super(`write refused: ${t.length} write(s) broke the content-only policy`),this.name="WriteRefused",this.refusals=t}},ce=class extends Error{constructor(t){super(`no <script data-rules-name~="${t}"> rules tag in this document`),this.name="NoRulesTag",this.token=t}},le=class extends Error{constructor(t,n){super(`write rejected: ${t.length} unknown key(s), ${n.length} rule(s) with no matching element`),this.name="WriteRejected",this.unknownKeys=t,this.unmatched=n}};function R(e){let t=0,n=null,o=-1;for(let r=0;r<e.length;r++){let i=e[r];i==="\\"?r++:n?i===n&&(n=null):i==='"'||i==="'"?n=i:i==="["||i==="("?t++:i==="]"||i===")"?t>0&&t--:i==="@"&&t===0&&(o=r)}return o}function fe(e){let t=R(e);return t===-1?{selector:e,prop:null}:{selector:e.slice(0,t),prop:e.slice(t+1)||null}}function C(e,t,n,o={}){if(Object.prototype.hasOwnProperty.call(o,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");return ue(e,t,n,{depth:0,path:[]},o)}function ue(e,t,n,o,r){if(o.depth>_)throw new k(o.path);if(typeof n=="string")return tt(e,t,n,o,r);if(Array.isArray(n)){let[i,l]=n,s=e.find(t,i,r);return Se(r,o,s),s.map((c,d)=>ue(e,c,l,{depth:o.depth+1,path:[...o.path,d]},r))}if(typeof n=="object"&&n!==null){let i={};for(let[l,s]of Object.entries(n))i[l]=ue(e,t,s,{depth:o.depth+1,path:[...o.path,l]},r);return i}return null}function tt(e,t,n,o,r){if(n.endsWith("[]")){let s=n.slice(0,-2),c=e.find(t,s,r);return Se(r,o,c),c.map(d=>e.text(d))}if(n.startsWith("@"))return be(e,t,n.slice(1));let i=R(n);if(i!==-1){let s=n.slice(0,i),c=n.slice(i+1),d=s?e.find(t,s,r):[t];return d.length===0?null:be(e,d[0],c)}if(n===".")return e.text(t);let l=e.find(t,n,r);return l.length===0?null:e.text(l[0])}function Se(e,t,n){if(typeof e.onRowsRead=="function")try{e.onRowsRead(t.path.slice(),n)}catch(o){console.warn(`[hyper-html-api] onRowsRead threw at "${t.path.join(".")||"(root)"}"`,o)}}function be(e,t,n){if(se.has(n)){let r=e.prop(t,n);return r==null?null:String(r)}let o=e.attr(t,n);return o||null}function Ne(e,t,n,o){let r=e.length,i=t.length,l=new Array(r).fill(-1);if(o){let u=new Set;for(let m=0;m<r;m++){let w=o[m];!(w>=0&&w<i)||u.has(w)||(l[m]=w,u.add(w))}}if(r===0||i===0)return l;let s=e.map(u=>Re(u,n)),c=t.map(u=>Re(u,n)),d=new Array(i).fill(!1);for(let u of l)u>=0&&(d[u]=!0);let a=new Map;c.forEach((u,m)=>{d[m]||a.set(u,a.has(u)?-1:m)});let y=new Map;s.forEach((u,m)=>{l[m]>=0||y.set(u,(y.get(u)||0)+1)}),s.forEach((u,m)=>{if(l[m]>=0||y.get(u)!==1)return;let w=a.get(u);w===void 0||w===-1||d[w]||(l[m]=w,d[w]=!0)});let h=[];for(let u=0;u<r;u++)l[u]<0&&h.push(u);let x=[];for(let u=0;u<i;u++)d[u]||x.push(u);if(h.length===0||x.length===0)return l;let f=r*i+1,p=nt(e,t,n),g=(u,m)=>p(u,m)*f+Math.abs(u-m);for(let[u,m]of rt(h,x,g))l[u]=m;return l}var Me=e=>typeof e=="object"&&e!==null;function Re(e,t){if(!Me(t))return e==null?" null":String(e);let n=Object.keys(t);return JSON.stringify(n.map(o=>{let r=JSON.stringify(e?.[o]);return r===void 0?" undef":r}))}function nt(e,t,n){if(!Me(n))return(s,c)=>e[s]===t[c]?0:1;let o=Object.keys(n),r=s=>o.map(c=>JSON.stringify(s?.[c])),i=e.map(r),l=t.map(r);return(s,c)=>{let d=i[s],a=l[c],y=0;for(let h=0;h<o.length;h++)d[h]!==a[h]&&y++;return y}}function rt(e,t,n){return e.length<=t.length?Ce(e,t,n,!1):Ce(t,e,(o,r)=>n(r,o),!0)}function Ce(e,t,n,o){let r=e.length,i=t.length,l=[];for(let y=0;y<=r;y++)l.push(new Float64Array(i+1).fill(1/0));let s=[];for(let y=0;y<=r;y++)s.push(new Uint8Array(i+1));for(let y=0;y<=i;y++)l[r][y]=0;for(let y=r-1;y>=0;y--)for(let h=i-1;h>=0;h--){let x=n(e[y],t[h])+l[y+1][h+1],f=l[y][h+1];x<=f?(l[y][h]=x,s[y][h]=1):l[y][h]=f}let c=[],d=0,a=0;for(;d<r&&a<i;)s[d][a]&&(c.push(o?[t[a],e[d]]:[e[d],t[a]]),d++),a++;return c}function de(e,t,n,o,r,i,l,s={}){let c=e.find(t,n,s);if(r.length===0){c.forEach(T=>e.remove(T)),ae(s,"onRowsApplied",i.path,[]);return}let d=r.length>c.length,a=c[0]||null;if(d&&!a&&(a=ct(e,t,n,s),!a))throw new U(i.path);let y=c.map(T=>st(e,T,o,s)),h=null;if(d&&a){h=e.clone(a),s.templateAttr&&e.removeAttr(h,s.templateAttr);let T=e.stripIds(h);T>0&&console.warn(`[hyper-html-api] stripped ${T} id attribute(s) from cloned template at "${i.path.join(".")||"(root)"}"`)}let x=Ne(r,y,o,ot(e,c,r,i,s)),f=c[0]||a,p=e.parent(f),g=c.length>0?je(e,p,f):0,u=ft(e,c),m=new Set,w=[],A=r.map((T,O)=>{let E=x[O];if(E>=0)return m.add(E),w.push(!1),c[E];w.push(!0);let M=e.clone(h);return e.stripIds(M),M});c.forEach((T,O)=>{m.has(O)||e.remove(T)}),u?lt(e,p,g,A,w):ut(e,A,w,p,g),it(e,A,o,r,i,l,s),ae(s,"onRowsApplied",i.path,A)}function ae(e,t,n,o){if(typeof e[t]=="function")try{return e[t](n.slice(),o)}catch(r){console.warn(`[hyper-html-api] ${t} threw at "${n.join(".")||"(root)"}"`,r);return}}function ot(e,t,n,o,r){let i=ae(r,"identifyRows",o.path,n);if(!Array.isArray(i))return null;let l=new Array(n.length).fill(-1),s=new Set,c=new Map(t.map((d,a)=>[e.identity(d),a]));for(let d=0;d<n.length;d++){if(!i[d])continue;let a=c.get(e.identity(i[d]));a===void 0||s.has(a)||(l[d]=a,s.add(a))}return l}function it(e,t,n,o,r,i,l){t.forEach((s,c)=>{if(n===null){let d=o[c],a=d==null?"":String(d);e.text(s)!==a&&e.text(s,a)}else{let d=i(e,s,n,o[c],{depth:r.depth+1,path:[...r.path,c]},l);d&&d!==s&&(t[c]=d)}})}function st(e,t,n,o){return n===null?e.text(t):C(e,t,n,o.onRowsRead?{...o,onRowsRead:void 0}:o)}function je(e,t,n){let o=e.children(t);for(let r=0;r<o.length;r++)if(e.sameNode(o[r],n))return r;return-1}function ct(e,t,n,o){if(!o.templateAttr)return null;let r=t;for(;r;){let i=e.find(r,n,{includeRulesTag:!1,templateAttr:null});for(let l of i)if(e.attr(l,o.templateAttr)!=null)return l;r=e.parent(r)}return null}function lt(e,t,n,o,r){let i=e.children(t),l=i.map(c=>e.identity(c)),s=!1;o.forEach((c,d)=>{let a=e.identity(c),y=n+d;if(l[y]===a)return;if(!r[d]){let x=l.indexOf(a);x!==-1&&(l.splice(x,1),i.splice(x,1))}let h=Math.min(y,i.length);h<i.length?e.insertBefore(i[h],c):i.length?s?e.insertAfter(i[i.length-1],c):(e.insertAt(t,c,y),s=!0):e.insertAt(t,c,0),l.splice(h,0,a),i.splice(h,0,c)})}function ft(e,t){if(t.length<=1)return!0;let n=e.parent(t[0]);if(!n)return!1;let o=new Map(e.children(n).map((i,l)=>[e.identity(i),l])),r=[];for(let i of t){let l=o.get(e.identity(i));if(l===void 0)return!1;r.push(l)}return r.sort((i,l)=>i-l),r[r.length-1]-r[0]===r.length-1}function ut(e,t,n,o,r){let i=null,l=r;for(let s=0;s<t.length;s++){if(!n[s]){i=t[s];continue}let c=i?e.parent(i):o;if(!c)continue;let d=i?je(e,c,i)+1:l++;e.insertAt(c,t[s],d),i=t[s]}}var ke=new Set(["checked","selected","disabled","readOnly","paused"]);function I(e,t,n,o,r={}){if(Object.prototype.hasOwnProperty.call(r,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");let i=[];if(pe(n,o,[],i),i.length)throw new W(i);Q(e,t,n,o,{depth:0,path:[]},r)}function Q(e,t,n,o,r,i={}){if(r.depth>_)throw new k(r.path);if(o===void 0)return t;if(typeof n=="string")return at(e,t,n,o,r,i);if(Array.isArray(n)){let[l,s]=n;return de(e,t,l,s,o,r,Q,i),t}if(typeof n=="object"&&n!==null){for(let[l,s]of Object.entries(n)){let c=Q(e,t,s,o==null?o:o[l],{depth:r.depth+1,path:[...r.path,l]},i);c&&c!==t&&(t=c)}return t}return t}function at(e,t,n,o,r,i){if(n.endsWith("[]")){let c=n.slice(0,-2);return de(e,t,c,null,o,r,Q,i),t}if(n.startsWith("@"))return Le(e,t,n.slice(1),o);let l=R(n);if(l!==-1){let c=n.slice(0,l),d=n.slice(l+1),a=c?e.find(t,c,i):[t];return a.length===0||Le(e,a[0],d,o),t}if(n===".")return Ie(e,t,o),t;let s=e.find(t,n,i);return s.length===0||Ie(e,s[0],o),t}function Ie(e,t,n){let o=n==null?"":String(n);e.text(t)!==o&&e.text(t,o)}function Le(e,t,n,o){if(G.has(n)){let i=e.prop(t,n);if(i===o||i!=null&&o!=null&&String(i)===String(o))return t;throw new H(n)}if(n==="outerHTML"){let i=o==null?"":String(o);return e.replaceWith(t,i)}if(Oe.has(n)){let i=dt(n,o);return e.prop(t,n)!==i&&e.prop(t,n,i),t}let r=o==null?"":String(o);return e.attr(t,n)!==r&&e.attr(t,n,r),t}function dt(e,t){return t==null?ke.has(e)?!1:"":ke.has(e)?t==="false"?!1:!!t:t}function pe(e,t,n,o){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]")){Array.isArray(t)?t.forEach((r,i)=>{typeof r=="object"&&r!==null&&o.push({path:B([...n,i]),expected:"scalar",got:v(r)})}):o.push({path:B(n),expected:"array",got:v(t)});return}t!==null&&typeof t=="object"&&o.push({path:B(n),expected:"scalar",got:v(t)});return}if(Array.isArray(e)){if(!Array.isArray(t)){o.push({path:B(n),expected:"array",got:v(t)});return}let r=e[1];t.forEach((i,l)=>pe(r,i,[...n,l],o));return}if(typeof e=="object"&&e!==null){if(t===null||Array.isArray(t)||typeof t!="object"){o.push({path:B(n),expected:"object",got:v(t)});return}for(let[r,i]of Object.entries(e))pe(i,t[r],[...n,r],o)}}}function v(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function B(e){return e.join(".")}function he(e){try{return JSON.parse(e)}catch(t){throw new D(`Invalid strict JSON: ${t.message}`,t)}}function L(e){try{return JSON.parse(e)}catch{}let t={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function n(r){let i=[],l=0;for(;l<r.length;){let s=r[l];if(/\s/.test(s)){l++;continue}if("{}".includes(s)){i.push({type:s,value:s}),l++;continue}if(s==="["){let y=!1,h=l+1;for(;h<r.length&&/\s/.test(r[h]);)h++;if(h<r.length&&/[a-zA-Z_]/.test(r[h])&&(y=!0),!y){i.push({type:s,value:s}),l++;continue}}if(s==="]"){i.push({type:s,value:s}),l++;continue}if(s===":"){i.push({type:t.COLON,value:s}),l++;continue}if(s===","){i.push({type:t.COMMA,value:s}),l++;continue}if(s==='"'||s==="'"){let y=s,h=l+1;for(;h<r.length&&r[h]!==y;)r[h]==="\\"&&h++,h++;i.push({type:t.STRING,value:r.substring(l+1,h),quoted:!0,sourceQuote:y}),l=h+1;continue}let c=l,d;for(;c<r.length&&!/[{},]/.test(r[c]);)if(r[c]===":"){let y=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],h=!1;for(let x of y){let f=x.substring(1);if(r.substring(c+1,c+1+f.length)===f){h=!0,c+=f.length;break}}if(!h)break}else if(r[c]==="["){for(c++;c<r.length&&r[c]!=="]";){if(r[c]==='"'||r[c]==="'"){let y=r[c];for(c++;c<r.length&&r[c]!==y;)r[c]==="\\"&&c++,c++}c++}c<r.length&&r[c]==="]"&&c++}else c++;d=r.substring(l,c);let a=t.IDENTIFIER;/^-?\d+(\.\d+)?$/.test(d)?a=t.NUMBER:d==="true"||d==="false"||d==="null"?a=t.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test(d)&&(a=t.SELECTOR),i.push({type:a,value:d,quoted:!1}),l=c}return i}function o(r){let i="";for(let l=0;l<r.length;l++){let s=r[l];if("{}".includes(s.type)||"[]".includes(s.type)){i+=s.value;continue}if(s.type===t.COLON){i+=s.value;continue}if(s.type===t.COMMA){let c=r[l+1];if(c&&(c.type==="}"||c.type==="]"))continue;i+=s.value;continue}if(s.type===t.STRING&&s.quoted){let c=s.value;s.sourceQuote==="'"&&(c=c.replace(/\\'/g,"'"),c=c.replace(/(\\*)"/g,(d,a)=>a.length%2===0?a+'\\"':d)),i+=`"${c}"`;continue}if(s.type===t.NUMBER||s.type===t.BOOLEAN){i+=s.value;continue}if(s.type===t.SELECTOR||s.type===t.IDENTIFIER){i+=`"${s.value}"`;continue}i+=`"${s.value}"`}return i}try{let r=n(e),i=o(r);return JSON.parse(i)}catch(r){throw new D("Invalid extraction rules syntax: "+r.message,r)}}var me="1",Pe=/^[a-zA-Z0-9_-]+$/;function q(e,t,n){let o;if(n===void 0)o="script[data-rules-name]";else{if(typeof n!="string"||!Pe.test(n))throw new Error(`hyper-html-api: invalid rules token ${JSON.stringify(n)} (must match ${Pe})`);o=`script[data-rules-name~="${n}"]`}let r=e.find(t,o,{includeRulesTag:!0});if(r.length===0)return null;n!==void 0&&r.length>1&&console.warn(`hyper-html-api: ${r.length} rules tags match data-rules-name~="${n}"; using the first.`);let i=r[0],l=e.attr(i,"data-rules-version");if(l!==me)throw new j(l);return{rules:L(e.text(i)),tagNode:i}}var ee=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),pt=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),De=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui","live"]);function K(e,t){if(!e||e.nodeType!==1)return!1;let n=e.getAttribute?.("clay");return!!(n&&n.split(/\s+/).includes(t)||e.hasAttribute?.(t))}function ye(e,t){if(K(e,t))return!0;for(let[n,o]of Object.entries(pt))if(o.includes(t)&&K(e,n))return!0;return!1}function z(e){let t=ee[e];if(!t)throw new Error(`Unknown region capability: ${e}`);return[...t.tokens,...t.bundles].flatMap(n=>[`[clay~="${n}"]`,`[${n}]`]).join(", ")}function ht(e,t){let n=e&&e.nodeType===1?e:e?.parentElement;for(;n&&n.nodeType===1;){let o=ee[t];if(!o)throw new Error(`Unknown region capability: ${t}`);if(o.tokens.some(r=>ye(n,r))||o.bundles.some(r=>K(n,r)))return n;n=n.parentElement}return null}function _e(e,t){return!!ht(e,t)}var mt=Object.freeze({refusedRuleForms:["innerHTML","outerHTML"],refusedTargets:["script","style","template","noscript","iframe","object","embed","xmp","plaintext","noembed","noframes","meta","link","base","animate","set","animatemotion","animatetransform"],refusedAttributes:["style","srcdoc","is","http-equiv","sandbox","allow","nonce","integrity","charset","htmlclaytoken","htmlclayid","data-rules-name","data-rules-version","clay","contenteditable",...De],refusedAttributePrefixes:["on"],urlAttributes:["href","src","srcset","action","formaction","poster","cite","data","ping","background","longdesc","usemap","xlink:href","manifest","codebase","icon"],refusedSchemes:["javascript","vbscript","data"]});function ge(e,t,n){if(n&&typeof n=="object")return{rules:n,tagNode:null};if(typeof n=="string"){let o=t&&t.ownerDocument?t.ownerDocument:t;return q(e,o,n)}return null}var At=/:(?:focus(?:-within|-visible)?|hover|active|visited|defined)\b/i;function Tt(e,t){if(!/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(e.tagName||""))return;let n=(e.getAttribute?.("type")||"").toLowerCase();"value"in e&&"value"in t&&e.tagName!=="OPTION"&&n!=="checkbox"&&n!=="radio"&&n!=="file"&&(t.value=e.value),e.tagName==="INPUT"&&(n==="checkbox"||n==="radio")&&(t.checked=e.checked),e.tagName==="OPTION"&&(t.selected=e.selected),"indeterminate"in e&&"indeterminate"in t&&(t.indeterminate=e.indeterminate)}function $e(e,t,n,o){if(o)return!!e.closest?.(t);let r=e;for(;r?.nodeType===1;){if(r.matches(t))return!0;if(r===n)break;r=r.parentElement}return!1}function We(e,t,n,o,r,i){return(i?_e(e,t):$e(e,n,r,!1))||!!(o&&(i&&e!==r?e.matches(o):$e(e,o,r,i)))}function xt(e,t){let n=ee[t];return n.tokens.some(o=>ye(e,o))||n.bundles.some(o=>K(e,o))}var Et=new Set(["INPUT","TEXTAREA","SELECT","OPTION"]);function Ue(e,t,n,o){if(e.nodeType===1&&o(e)){n.dropped.push(t);return}n.cloneToLive.set(t,e),n.liveToClone.set(e,t);let r=e,i=t;if(e.nodeType===1){if(Et.has(e.tagName)&&n.controls.push(e,t),e.tagName==="TEMPLATE"){for(;t.firstChild;)t.removeChild(t.firstChild);r=e.content,i=t.content,n.cloneToLive.set(i,r),n.liveToClone.set(r,i)}}else if(e.nodeType!==11)return;let l=i.firstChild;for(let s=r.firstChild;s&&l;s=s.nextSibling)Ue(s,l,n,o),l=l.nextSibling}function F(e,{capability:t="data",exclude:n=null,inherit:o=!0,provenance:r=null}={}){if(!e)throw new TypeError("createContentView requires a DOM context");let i=e.nodeType===9?e:e.ownerDocument;if(!i?.implementation?.createHTMLDocument)throw new TypeError("createContentView requires an HTML DOM implementation");let l=i.implementation.createHTMLDocument(""),s=r||new WeakMap,c=new WeakMap,d=e.nodeType===9?e.documentElement:e;n&&l.documentElement.matches(n);let a=z(t),y=o?f=>xt(f,t)||!!(n&&f.matches(n)):f=>We(f,t,a,n,d,!1),h=null;if(d.nodeType!==1||!We(d,t,a,n,d,o)){h=l.importNode(d,!0);let f={cloneToLive:s,liveToClone:c,dropped:[],controls:[]};Ue(d,h,f,y);for(let p of f.dropped)p.remove();for(let p=0;p<f.controls.length;p+=2)Tt(f.controls[p],f.controls[p+1])}e.nodeType===9&&h&&(l.replaceChild(h,l.documentElement),c.set(e,l),s.set(l,e));let x=f=>{if(At.test(f))throw new Error(`Filtered content queries do not support stateful selector: ${f}`)};return{root:h,document:l,capability:t,selector:z(t),cloneToLive:s,liveToClone:c,original(f){return s.get(f)||null},cloneOf(f){return c.get(f)||null},query(f,p=h){return x(f),Array.from(p.querySelectorAll(f),g=>s.get(g)||g)},text(f=h){return(f===h?h:c.get(f))?.textContent||""},html(f=h){return(f===h?h:c.get(f))?.innerHTML??""},clone(f=h){let p=f===h?h:c.get(f);return p?l.importNode(p,!0):null}}}function He(e){return e&&e.nodeType===1&&e.tagName==="SCRIPT"&&e.hasAttribute&&e.hasAttribute("data-rules-name")}function Ot(e){return e?(e.nodeType===9||e.nodeType===11,e):null}var b={semanticExclude:!0,find(e,t,n={}){let o=Ot(e);if(!o||!o.querySelectorAll)return[];let r=Array.from(o.querySelectorAll(t));n.includeRulesTag||(r=r.filter(s=>!He(s)));let i=[];n.skip&&i.push(n.skip);let l=n.templateAttr===null?null:n.templateAttr||"cms-template";if(l&&i.push("["+l+"]"),i.length){let s=i.join(", ");r=r.filter(c=>!c.closest||!c.closest(s))}return r},parent(e){return e?e.parentElement:null},children(e){return e?Array.from(e.children):[]},text(e,t){if(t===void 0)return(e.textContent||"").trim();e.textContent=t},attr(e,t,n){if(n===void 0)return e.hasAttribute&&e.hasAttribute(t)?e.getAttribute(t):null;e.setAttribute(t,n)},removeAttr(e,t){e&&e.removeAttribute&&e.removeAttribute(t)},prop(e,t,n){if(n===void 0){let o=e?e[t]:void 0;return o!==void 0?o:null}e[t]=n},clone(e){return e.cloneNode(!0)},insertAt(e,t,n){let o=e.children[n]||null;e.insertBefore(t,o)},insertBefore(e,t){e.parentNode.insertBefore(t,e)},insertAfter(e,t){e.parentNode.insertBefore(t,e.nextSibling)},identity(e){return e||null},remove(e){e&&e.parentNode&&e.parentNode.removeChild(e)},replaceWith(e,t){if(!e||!e.parentNode)throw new Error("dom.replaceWith: node has no parent");let o=e.ownerDocument.createElement("template");o.innerHTML=t;let r=o.content.firstElementChild;if(!r)throw new Error("dom.replaceWith: html did not parse to an element");return e.parentNode.replaceChild(r,e),r},stripIds(e){let t=0;return e.id&&(e.removeAttribute("id"),t++),(e.querySelectorAll?e.querySelectorAll("[id]"):[]).forEach(o=>{o.removeAttribute("id"),t++}),t},sameNode(e,t){return e===t}};function V(e,t={}){if(t.exclude===null)return b;let n=[z("data"),t.exclude].filter(Boolean).join(", "),o=e.nodeType===9?e:e.ownerDocument||e,r=e.nodeType===9?e.documentElement:e;if(!t._write&&!r?.matches?.(n)&&!r?.querySelector?.(n)&&!o?.querySelector?.(n))return b;let i=e.nodeType===9||!e.isConnected?e:e.ownerDocument,l=e.nodeType===9?e:e.ownerDocument,s=null,c=()=>s||(s=F(i,{capability:"data",exclude:t.exclude||null})),d=f=>{let p=c();return f===e?p.cloneOf(e):p.cloneOf(f)||f},a=f=>s?.original(f)||f,y=(f,p)=>{c().liveToClone.set(f,p),c().cloneToLive.set(p,f);let g=f.childNodes||[],u=p.childNodes||[];for(let m=0;m<Math.min(g.length,u.length);m++)y(g[m],u[m])},h=(f,p,g,u)=>{let m=Array.from(f.childNodes).filter(E=>s.cloneOf(E)),A=m[0];for(;A&&m.includes(A);)A=A.nextSibling;for(let E of m)E.remove();if(g==="innerHTML"){let E=l.createElement("template");E.innerHTML=u;for(let M of Array.from(E.content.childNodes))f.insertBefore(M,A||null)}else f.insertBefore(l.createTextNode(u),A||null);let T=F(f,{capability:"data",exclude:t.exclude||null});p.replaceChildren(...Array.from(T.root?.childNodes||[]));let O=E=>{let M=T.original(E);M&&(s.liveToClone.set(M,E),s.cloneToLive.set(E,M));for(let Ye of Array.from(E.childNodes||[]))O(Ye)};for(let E of Array.from(p.childNodes))O(E)},x={...b,find(f,p,g={}){let u=d(f);if(!u?.querySelectorAll)return[];let m=c().query(p,u);g.includeRulesTag||(m=m.filter(T=>!He(T)));let w=[];g.skip&&w.push(g.skip);let A=g.templateAttr===null?null:g.templateAttr||"cms-template";if(A&&w.push(`[${A}]`),w.length){let T=w.join(", ");m=m.filter(O=>!O.closest?.(T))}return m},parent(f){let p=d(f)?.parentElement;return p?a(p):null},children(f){return Array.from(d(f)?.children||[],a)},text(f,p){if(p===void 0){let m=a(f);return!m?.matches?.(n)&&!m?.querySelector?.(n)?b.text(m):(d(f)?.textContent||"").trim()}let g=a(f);if(!g?.matches?.(n)&&!g?.querySelector?.(n)&&!s){b.text(g,p);return}let u=c().cloneOf(g);u?h(g,u,"textContent",p):b.text(g,p)},attr(f,p,g){let u=a(f);if(g===void 0)return b.attr(u,p);b.attr(u,p,g);let m=s?.cloneOf(u);m&&(b.attr(m,p,g),F(u,{capability:"data",exclude:t.exclude||null}).root===null&&(m.remove(),s.liveToClone.delete(u),s.cloneToLive.delete(m)))},removeAttr(f,p){let g=a(f);b.removeAttr(g,p);let u=s?.cloneOf(g);u&&b.removeAttr(u,p)},prop(f,p,g){let u=a(f);if(g===void 0)return p==="innerHTML"||p==="outerHTML"||p==="textContent"||p==="innerText"?b.prop(d(u),p):b.prop(u,p);let m=p==="innerHTML"||p==="textContent"||p==="innerText",w=m?c().cloneOf(u):s?.cloneOf(u);w&&m?h(u,w,p,g):(b.prop(u,p,g),w&&b.prop(w,p,g))},clone(f){let p=d(f);return p===f?b.clone(f):l.importNode(p,!0)},insertAt(f,p,g){let u=a(f),w=x.children(u)[g]||(()=>{for(let O=u.children.length-1;O>=0;O--){let E=u.children[O];if(c().cloneOf(E))return E.nextElementSibling}return u.firstElementChild})(),A=a(p);u.insertBefore(A,w||null);let T=c().cloneOf(u);if(T){let O=c().cloneOf(A);O||(O=l.importNode(A,!0),y(A,O));let E=Array.from(T.children);T.insertBefore(O,E[g]||null)}},insertBefore(f,p){let g=a(f),u=a(p);g.parentNode.insertBefore(u,g);let m=c().cloneOf(g.parentNode);if(m){let w=c().cloneOf(u);w||(w=l.importNode(u,!0),y(u,w));let A=c().cloneOf(g);A?A.before(w):m.appendChild(w)}},insertAfter(f,p){let g=a(f),u=a(p);g.parentNode.insertBefore(u,g.nextSibling);let m=c().cloneOf(g.parentNode);if(m){let w=c().cloneOf(u);w||(w=l.importNode(u,!0),y(u,w));let A=c().cloneOf(g);A?A.after(w):m.appendChild(w)}},identity(f){return a(f)||null},remove(f){let p=a(f),g=c().cloneOf(p);b.remove(p),g&&b.remove(g)},replaceWith(f,p){let g=a(f),u=c().cloneOf(g),m=b.replaceWith(g,p);if(u){let w=F(m,{capability:"data",exclude:t.exclude||null});if(!w.root)u.remove();else{u.replaceWith(w.root);let A=T=>{let O=w.original(T);O&&(s.liveToClone.set(O,T),s.cloneToLive.set(T,O));for(let E of Array.from(T.childNodes||[]))A(E)};A(w.root)}}return m}};return x}var S=b;var we={extract:(e,t,n={})=>C(V(e,n),e,t,n),apply:(e,t,n,o={})=>I(V(e,{...o,_write:!0}),e,t,n,o),findRulesIn:(e,t)=>q(S,e,t),findRules:(e,t)=>ge(S,e,t),bind:(e,t,n={})=>{let o=ge(S,e,t);if(!o){let r=typeof t=="string"?`data-rules-name~="${t}"`:"the provided rules object";throw new Error(`hyper-html-api: could not resolve rules for ${r}`)}return{...o,get:()=>C(V(e,n),e,o.rules,n),set:r=>I(V(e,{...n,_write:!0}),e,o.rules,r,n)}},parseStrict:he,parseRelaxed:L,ruleAttrIndex:R,splitRule:fe,errors:Z,DOM_PROPERTIES:Y};var bt="hha:upgrade-check:";function N(e,t){let n=e.querySelector(`meta[name="${t}"]`),o=n?n.getAttribute("content"):null;return o&&o.trim()?o.trim():null}function ve(e){if(typeof e!="string")return null;let t=e.trim().replace(/^v/,"");return/^\d+(\.\d+)*$/.test(t)?t.split(".").map(Number):null}function St(e,t){let n=ve(e),o=ve(t);if(!n||!o)return!1;let r=Math.max(n.length,o.length);for(let i=0;i<r;i++){let l=n[i]||0,s=o[i]||0;if(l!==s)return l>s}return!1}function Rt(e){try{let t=globalThis.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Ct(e,t){try{globalThis.localStorage.setItem(e,JSON.stringify(t))}catch{}}async function Be({force:e=!1,doc:t,loc:n,fetchFn:o,now:r,ttlMs:i=864e5}={}){if(t=t||(typeof document<"u"?document:null),n=n||(typeof location<"u"?location:null),o=o||(h=>fetch(h)),r=r??Date.now(),!t)return null;let l=N(t,"hyper-source");if(!l)return null;let s=N(t,"hyper-version"),c;try{c=new URL(l,n?n.href:void 0)}catch{return null}if(n&&c.origin===n.origin&&c.pathname===n.pathname)return null;let d=`${bt}${c.href}:${s||"none"}`,a,y=e?null:Rt(d);if(y&&typeof y.checkedAt=="number"&&r-y.checkedAt<i)a=y.sourceVersion;else{try{let h=await o(c.href);if(!h.ok)throw new Error(`HTTP ${h.status}`);let x=await h.text(),f=new DOMParser().parseFromString(x,"text/html");a=N(f,"hyper-version")}catch{a=null}Ct(d,{checkedAt:r,sourceVersion:a})}return a?{available:St(a,s||"0.0.0"),currentVersion:s,sourceVersion:a,sourceUrl:c.href}:null}var Nt="script[data-rules-name]";function Mt(e){return typeof e=="string"?e.trim().replace(/\s+/g," "):""}function te(e,t){let n=e.find(t,Nt,{includeRulesTag:!0}),o=new Set,r=[];for(let i of n){let l=Mt(e.attr(i,"data-rules-name"));if(!l)continue;if(o.has(l)){console.warn(`hyper-html-api: duplicate rules tag name "${l}"; using the first.`);continue}let s=e.attr(i,"data-rules-version");if(s!==me)throw new j(s);o.add(l),r.push({name:l,rules:L(e.text(i))})}return r}function Ae(e,t){let n={};for(let{name:o,rules:r}of te(e,t))n[o]=C(e,t,r);return n}function qe(e){let t=e||document,n=t.nodeType===9?t:t.ownerDocument||t;return{dataByName:Ae(S,t),version:N(n,"hyper-version")}}var J=class extends Error{constructor(t,n){super(`could not fetch upgrade source: ${t}`),this.name="UpgradeSourceUnreachable",this.sourceUrl=t,this.cause=n}},ne=class extends Error{constructor(t){super(`upgrade source has no rules tags; refusing to drop all existing data: ${t}`),this.name="UpgradeSourceHasNoRules",this.sourceUrl=t}},P=class extends Error{constructor(t,n){super(t),this.name="UpgradeTransformInvalid",this.cause=n}},re=class extends Error{constructor(t){super(`found ${t} script[type="text/hyper-upgrade"] tags; only one is allowed per document.`),this.name="UpgradeMultipleTransforms",this.count=t}};var jt="text/hyper-upgrade";function Ke(e,t){let n=e.find(t,`script[type="${jt}"]`);if(n.length===0)return null;if(n.length>1)throw new re(n.length);return e.text(n[0])||null}var kt=new Function("url","return import(url)");async function ze(e){let t=new Blob([e],{type:"text/javascript"}),n=URL.createObjectURL(t),o;try{o=await kt(n)}catch(r){throw new P(`transform failed to load: ${r&&r.message?r.message:r}`,r)}finally{URL.revokeObjectURL(n)}if(typeof o.default!="function")throw new P("transform must `export default` a function");return o.default}function oe(e,t){let n={carriedOver:0,discarded:0,listItems:0},o=Te(t,e,n);return xe(t,e,n),{data:o,summary:n}}function Te(e,t,n){if(typeof e=="string")return e.endsWith("[]")?Array.isArray(t)?(n.listItems+=t.length,n.carriedOver+=t.length,t):void 0:t==null||typeof t=="object"?void 0:(n.carriedOver++,t);if(Array.isArray(e)){let[,o]=e;return Array.isArray(t)?(n.listItems+=t.length,t.map(r=>Te(o,r,n))):void 0}if(typeof e=="object"&&e!==null){let o={};for(let[r,i]of Object.entries(e)){let l=Te(i,t?.[r],n);l!==void 0&&(o[r]=l)}return o}}function xe(e,t,n){if(t!=null){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(typeof t!="object"||Array.isArray(t))return;let o=new Set(Object.keys(e));for(let r of Object.keys(t))o.has(r)?xe(e[r],t[r],n):n.discarded+=$(t[r]);return}if(Array.isArray(e)&&Array.isArray(t)){let o=e[1];t.forEach(r=>xe(o,r,n));return}typeof e=="string"&&!e.endsWith("[]")&&typeof t=="object"&&t!==null&&(n.discarded+=$(t))}}function $(e){return e==null?0:Array.isArray(e)?e.reduce((t,n)=>t+$(n),0):typeof e=="object"?Object.values(e).reduce((t,n)=>t+$(n),0):1}function Fe(e,t,n){let o=te(e,t),r={carriedOver:0,discarded:0,listItems:0},i={},l=new Set;for(let{name:s,rules:c}of o){if(l.add(s),!Object.prototype.hasOwnProperty.call(n,s)){i[s]={carriedOver:0,discarded:0,listItems:0};continue}let{data:d,summary:a}=oe(n[s],c);I(e,t,c,d),i[s]=a,r.carriedOver+=a.carriedOver,r.discarded+=a.discarded,r.listItems+=a.listItems}for(let s of Object.keys(n))l.has(s)||(r.discarded+=$(n[s]));return{totals:r,byName:i,rulesTagCount:o.length}}async function Ve({sourceUrl:e,dataByName:t,fromVersion:n,doc:o,loc:r,fetchFn:i}={}){if(o=o||(typeof document<"u"?document:null),r=r||(typeof location<"u"?location:null),i=i||(u=>fetch(u)),!o)throw new Error("upgrade.run requires a document context");if(e=e||N(o,"hyper-source"),!e)throw new Error("upgrade.run: no sourceUrl given and no hyper-source meta tag found");let l=new URL(e,r?r.href:void 0);n=n!==void 0?n:N(o,"hyper-version"),t=t||Ae(S,o);let s;try{s=await i(l.href)}catch(u){throw new J(l.href,u)}if(!s.ok)throw new J(l.href,new Error(`HTTP ${s.status}`));let c=await s.text(),d=new DOMParser().parseFromString(c,"text/html"),a=N(d,"hyper-version"),y=t,h=!1,x=Ke(S,d);if(x){let m=await(await ze(x))(y,{fromVersion:n,toVersion:a});if(!m||typeof m!="object"||Array.isArray(m))throw new P("transform must return a plain object map of { rulesName: data }");y=m,h=!0}let{totals:f,byName:p,rulesTagCount:g}=Fe(S,d,y);if(g===0&&Object.keys(y).length>0)throw new ne(l.href);return{html:It(d),fromVersion:n,toVersion:a,summary:{transformApplied:h,totals:f,byName:p}}}function It(e){return`<!DOCTYPE ${e.doctype&&e.doctype.name?e.doctype.name:"html"}>
2
+ `+e.documentElement.outerHTML}var Je={checkForUpdate:Be,run:Ve,extractAll:qe,shapeMatch:oe};var Lt={engine:we,upgrade:Je},Pt=Lt;return et(Dt);})();
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "apply",
10
10
  "CMS"
11
11
  ],
12
- "version": "0.10.0",
12
+ "version": "0.10.1",
13
13
  "homepage": "https://github.com/panphora/hyper-html-api",
14
14
  "bugs": {
15
15
  "url": "https://github.com/panphora/hyper-html-api/issues"
@@ -63,7 +63,7 @@
63
63
  "url": "git+https://github.com/panphora/hyper-html-api.git"
64
64
  },
65
65
  "dependencies": {
66
- "hyper-morph": "^1.3.0"
66
+ "hyper-morph": "^1.6.2"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@web/test-runner": "^0.20.0",
@@ -207,6 +207,18 @@ const cheerioAdapter = {
207
207
  else parent.append(node)
208
208
  },
209
209
 
210
+ insertBefore(ref, node) {
211
+ ref.before(node)
212
+ },
213
+
214
+ insertAfter(ref, node) {
215
+ ref.after(node)
216
+ },
217
+
218
+ identity(node) {
219
+ return node && node[0] ? node[0] : null
220
+ },
221
+
210
222
  remove(node) {
211
223
  if (node) node.remove()
212
224
  },
@@ -76,6 +76,18 @@ const dom = {
76
76
  parent.insertBefore(node, ref)
77
77
  },
78
78
 
79
+ insertBefore(ref, node) {
80
+ ref.parentNode.insertBefore(node, ref)
81
+ },
82
+
83
+ insertAfter(ref, node) {
84
+ ref.parentNode.insertBefore(node, ref.nextSibling)
85
+ },
86
+
87
+ identity(node) {
88
+ return node || null
89
+ },
90
+
79
91
  remove(node) {
80
92
  if (node && node.parentNode) node.parentNode.removeChild(node)
81
93
  },
@@ -268,6 +280,41 @@ export function createDomAdapter(operationRoot, opts = {}) {
268
280
  parentCopy.insertBefore(nodeCopy, copyContentChildren[index] || null)
269
281
  }
270
282
  },
283
+ insertBefore(ref, node) {
284
+ const targetRef = live(ref)
285
+ const targetNode = live(node)
286
+ targetRef.parentNode.insertBefore(targetNode, targetRef)
287
+ const parentCopy = contentView().cloneOf(targetRef.parentNode)
288
+ if (parentCopy) {
289
+ let nodeCopy = contentView().cloneOf(targetNode)
290
+ if (!nodeCopy) {
291
+ nodeCopy = outputDocument.importNode(targetNode, true)
292
+ mapParallel(targetNode, nodeCopy)
293
+ }
294
+ const refCopy = contentView().cloneOf(targetRef)
295
+ if (refCopy) refCopy.before(nodeCopy)
296
+ else parentCopy.appendChild(nodeCopy)
297
+ }
298
+ },
299
+ insertAfter(ref, node) {
300
+ const targetRef = live(ref)
301
+ const targetNode = live(node)
302
+ targetRef.parentNode.insertBefore(targetNode, targetRef.nextSibling)
303
+ const parentCopy = contentView().cloneOf(targetRef.parentNode)
304
+ if (parentCopy) {
305
+ let nodeCopy = contentView().cloneOf(targetNode)
306
+ if (!nodeCopy) {
307
+ nodeCopy = outputDocument.importNode(targetNode, true)
308
+ mapParallel(targetNode, nodeCopy)
309
+ }
310
+ const refCopy = contentView().cloneOf(targetRef)
311
+ if (refCopy) refCopy.after(nodeCopy)
312
+ else parentCopy.appendChild(nodeCopy)
313
+ }
314
+ },
315
+ identity(node) {
316
+ return live(node) || null
317
+ },
271
318
  remove(node) {
272
319
  const target = live(node)
273
320
  const copy = contentView().cloneOf(target)
@@ -76,17 +76,7 @@ export function listDiff(adapter, parentCtx, selector, shape, newItems, trace, a
76
76
  })
77
77
 
78
78
  if (contiguous) {
79
- // Place each final node at its target index. If the node is already
80
- // there, do nothing (no-op apply on unchanged data drops zero state).
81
- // Otherwise insertAt moves an attached node (DOM/cheerio both treat
82
- // insertBefore on an attached node as "move to here").
83
- finalNodes.forEach((node, i) => {
84
- const targetIdx = anchorIdx + i
85
- const siblings = adapter.children(parent)
86
- const currentIdx = siblings.findIndex((s) => adapter.sameNode(s, node))
87
- if (currentIdx === targetIdx) return
88
- adapter.insertAt(parent, node, targetIdx)
89
- })
79
+ placeContiguous(adapter, parent, anchorIdx, finalNodes, fresh)
90
80
  } else {
91
81
  // The matched nodes are not a contiguous run of siblings, so this list has
92
82
  // no DOM order to restore: any repositioning would move elements the list
@@ -132,14 +122,13 @@ function lockSuppliedRows(adapter, oldNodes, newItems, trace, opts) {
132
122
  if (!Array.isArray(supplied)) return null
133
123
  const locked = new Array(newItems.length).fill(-1)
134
124
  const taken = new Set()
125
+ const position = new Map(oldNodes.map((n, j) => [adapter.identity(n), j]))
135
126
  for (let i = 0; i < newItems.length; i++) {
136
127
  if (!supplied[i]) continue
137
- for (let j = 0; j < oldNodes.length; j++) {
138
- if (taken.has(j) || !adapter.sameNode(oldNodes[j], supplied[i])) continue
139
- locked[i] = j
140
- taken.add(j)
141
- break
142
- }
128
+ const j = position.get(adapter.identity(supplied[i]))
129
+ if (j === undefined || taken.has(j)) continue
130
+ locked[i] = j
131
+ taken.add(j)
143
132
  }
144
133
  return locked
145
134
  }
@@ -201,6 +190,49 @@ function findFallbackTemplate(adapter, parentCtx, selector, opts) {
201
190
  return null
202
191
  }
203
192
 
193
+ // Puts finalNodes at anchorIdx onward among the parent's content children and leaves every other
194
+ // child in its order. A node already in place is not touched, so an unchanged apply moves nothing.
195
+ // The children are read once and each move is mirrored in a local copy: reading them per row, as
196
+ // this used to, made a list write cost the square of its length.
197
+ //
198
+ // Every surviving node sits at or after its target when its turn comes, because the run started at
199
+ // anchorIdx and the earlier targets are already filled. So removing a node from the copy never
200
+ // shifts the target it is moving to.
201
+ function placeContiguous(adapter, parent, anchorIdx, finalNodes, fresh) {
202
+ const siblings = adapter.children(parent)
203
+ const order = siblings.map((s) => adapter.identity(s))
204
+ // Past the end of the content children, insertAt appends to the very end of the
205
+ // parent when the parent has no no-data child, which is past any trailing text:
206
+ // "after the last content child" is NOT what it does there, and the document
207
+ // has to come out byte-identical. So the first row that lands past the end still
208
+ // goes through insertAt, and the rows after it follow that node, which is now
209
+ // the parent's last child. Only one row ever pays for the index insert, because
210
+ // the targets only move forward and the local copy grows with them.
211
+ let appended = false
212
+ finalNodes.forEach((node, i) => {
213
+ const id = adapter.identity(node)
214
+ const target = anchorIdx + i
215
+ if (order[target] === id) return
216
+ if (!fresh[i]) {
217
+ const current = order.indexOf(id)
218
+ if (current !== -1) {
219
+ order.splice(current, 1)
220
+ siblings.splice(current, 1)
221
+ }
222
+ }
223
+ const at = Math.min(target, siblings.length)
224
+ if (at < siblings.length) adapter.insertBefore(siblings[at], node)
225
+ else if (!siblings.length) adapter.insertAt(parent, node, 0)
226
+ else if (appended) adapter.insertAfter(siblings[siblings.length - 1], node)
227
+ else {
228
+ adapter.insertAt(parent, node, target)
229
+ appended = true
230
+ }
231
+ order.splice(at, 0, id)
232
+ siblings.splice(at, 0, node)
233
+ })
234
+ }
235
+
204
236
  // Repositioning only means something when the list occupies a contiguous run of
205
237
  // element siblings under one parent. Two containers, or an unowned sibling
206
238
  // sitting between two owned nodes, has no list order to restore.
@@ -208,11 +240,11 @@ function isContiguousRun(adapter, nodes) {
208
240
  if (nodes.length <= 1) return true
209
241
  const parent = adapter.parent(nodes[0])
210
242
  if (!parent) return false
211
- const siblings = adapter.children(parent)
243
+ const position = new Map(adapter.children(parent).map((s, i) => [adapter.identity(s), i]))
212
244
  const indices = []
213
245
  for (const node of nodes) {
214
- const i = siblings.findIndex((s) => adapter.sameNode(s, node))
215
- if (i === -1) return false
246
+ const i = position.get(adapter.identity(node))
247
+ if (i === undefined) return false
216
248
  indices.push(i)
217
249
  }
218
250
  indices.sort((a, b) => a - b)
@@ -76,7 +76,8 @@ export function matchRows(newItems, oldValues, shape, locked) {
76
76
  // Changed content outranks displacement: the scale is larger than any total
77
77
  // displacement this list can produce, so position only ever breaks a tie.
78
78
  const scale = n * m + 1
79
- const cost = (i, j) => differingFields(newItems[i], oldValues[j], shape) * scale + Math.abs(i - j)
79
+ const differing = fieldDistance(newItems, oldValues, shape)
80
+ const cost = (i, j) => differing(i, j) * scale + Math.abs(i - j)
80
81
  for (const [i, j] of alignInOrder(leftNew, leftOld, cost)) matches[i] = j
81
82
  return matches
82
83
  }
@@ -97,17 +98,22 @@ function itemKey(item, shape) {
97
98
  )
98
99
  }
99
100
 
100
- function differingFields(a, b, shape) {
101
- if (!isObjectShape(shape)) return a === b ? 0 : 1
101
+ // How many fields differ between new item i and old item j. Each item's fields are encoded once
102
+ // here: the alignment table asks this for every pair, and encoding per pair made it the dominant
103
+ // cost of a large list.
104
+ function fieldDistance(newItems, oldValues, shape) {
105
+ if (!isObjectShape(shape)) return (i, j) => (newItems[i] === oldValues[j] ? 0 : 1)
102
106
  const fields = Object.keys(shape)
103
- if (fields.length === 0) return 0
104
- let differing = 0
105
- for (const f of fields) {
106
- const av = JSON.stringify(a == null ? undefined : a[f])
107
- const bv = JSON.stringify(b == null ? undefined : b[f])
108
- if (av !== bv) differing++
107
+ const encode = (item) => fields.map((f) => JSON.stringify(item == null ? undefined : item[f]))
108
+ const newCodes = newItems.map(encode)
109
+ const oldCodes = oldValues.map(encode)
110
+ return (i, j) => {
111
+ const a = newCodes[i]
112
+ const b = oldCodes[j]
113
+ let differing = 0
114
+ for (let k = 0; k < fields.length; k++) if (a[k] !== b[k]) differing++
115
+ return differing
109
116
  }
110
- return differing
111
117
  }
112
118
 
113
119
  // Pair every entry of the shorter list with one of the longer, keeping both in
@@ -54,6 +54,20 @@ export function trackAdapter(adapter) {
54
54
  if (from) mark(from)
55
55
  return adapter.insertAt(parent, node, index)
56
56
  },
57
+ insertBefore(ref, node) {
58
+ const p = adapter.parent(ref)
59
+ if (p) mark(p)
60
+ const from = adapter.parent(node)
61
+ if (from) mark(from)
62
+ return adapter.insertBefore(ref, node)
63
+ },
64
+ insertAfter(ref, node) {
65
+ const p = adapter.parent(ref)
66
+ if (p) mark(p)
67
+ const from = adapter.parent(node)
68
+ if (from) mark(from)
69
+ return adapter.insertAfter(ref, node)
70
+ },
57
71
  remove(node) {
58
72
  const p = adapter.parent(node)
59
73
  if (p) mark(p)
@@ -1,6 +1,6 @@
1
1
  // GENERATED from clayjs/src/lib/content-dom.js. Edit ClayJS and run `npm run propagate:foundation`.
2
2
 
3
- import { capabilitySelector, hasCapability } from './region-capabilities.js'
3
+ import { capabilitySelector, hasCapability, CAPABILITIES, expandsTo, hasPolicyToken } from './region-capabilities.js'
4
4
 
5
5
  const UNSUPPORTED_SELECTOR = /:(?:focus(?:-within|-visible)?|hover|active|visited|defined)\b/i
6
6
 
@@ -9,10 +9,9 @@ function copyControlState(source, copy) {
9
9
  const type = (source.getAttribute?.('type') || '').toLowerCase()
10
10
  if ('value' in source && 'value' in copy && source.tagName !== 'OPTION' && type !== 'checkbox' && type !== 'radio' && type !== 'file') copy.value = source.value
11
11
  if (source.tagName === 'INPUT' && (type === 'checkbox' || type === 'radio')) copy.checked = source.checked
12
+ // Each surviving option carries its own selection, so a <select> whose excluded
13
+ // options were removed from the copy keeps the rest in step with the page.
12
14
  if (source.tagName === 'OPTION') copy.selected = source.selected
13
- if (source.tagName === 'SELECT') {
14
- for (let i = 0; i < source.options.length; i++) copy.options[i].selected = source.options[i].selected
15
- }
16
15
  if ('indeterminate' in source && 'indeterminate' in copy) copy.indeterminate = source.indeterminate
17
16
  }
18
17
 
@@ -27,46 +26,77 @@ function matchesWithin(node, selector, boundary, inherit) {
27
26
  return false
28
27
  }
29
28
 
30
- function importTree(source, targetDocument, capability, capabilityMatch, exclude, boundary, inherit, maps) {
31
- if (source.nodeType === 1 && (
32
- (inherit
33
- ? hasCapability(source, capability)
34
- : matchesWithin(source, capabilityMatch, boundary, false)) ||
35
- (exclude && (inherit && source !== boundary ? source.matches(exclude) : matchesWithin(source, exclude, boundary, inherit)))
36
- )) return null
37
- const copy = targetDocument.importNode(source, false)
29
+ // One native deep clone, then a lockstep walk of the two isomorphic trees that
30
+ // records provenance, collects controls, and marks excluded subtrees for removal.
31
+ // The browser's clone is far cheaper than importing node by node. The root answers
32
+ // for its ancestors once; below it the walk is top-down, so with inheritance each
33
+ // element answers only for its own markers: an excluded ancestor is never entered.
34
+ function excluded(source, capability, capabilityMatch, exclude, boundary, inherit) {
35
+ return (inherit
36
+ ? hasCapability(source, capability)
37
+ : matchesWithin(source, capabilityMatch, boundary, false)) ||
38
+ !!(exclude && (inherit && source !== boundary ? source.matches(exclude) : matchesWithin(source, exclude, boundary, inherit)))
39
+ }
40
+
41
+ // The test closestWithCapability makes at each level, for this element alone.
42
+ function hasOwnCapability(element, capability) {
43
+ const definition = CAPABILITIES[capability]
44
+ return definition.tokens.some(token => expandsTo(element, token)) ||
45
+ definition.bundles.some(bundle => hasPolicyToken(element, bundle))
46
+ }
47
+
48
+ const CONTROL_TAGS = new Set(['INPUT', 'TEXTAREA', 'SELECT', 'OPTION'])
49
+
50
+ function pairTree(source, copy, maps, drop) {
51
+ if (source.nodeType === 1 && drop(source)) { maps.dropped.push(copy); return }
38
52
  maps.cloneToLive.set(copy, source)
39
53
  maps.liveToClone.set(source, copy)
40
- const sourceChildren = source.nodeType === 1 && source.tagName === 'TEMPLATE' ? source.content : source
41
- const copyChildren = copy.nodeType === 1 && copy.tagName === 'TEMPLATE' ? copy.content : copy
42
- if (sourceChildren !== source) {
43
- maps.cloneToLive.set(copyChildren, sourceChildren)
44
- maps.liveToClone.set(sourceChildren, copyChildren)
45
- }
46
- for (const child of sourceChildren.childNodes || []) {
47
- const childCopy = importTree(child, targetDocument, capability, capabilityMatch, exclude, boundary, inherit, maps)
48
- if (childCopy) {
49
- copyChildren.appendChild(childCopy)
50
- if (child.nodeType === 1) copyControlState(child, childCopy)
54
+ let sourceChildren = source
55
+ let copyChildren = copy
56
+ if (source.nodeType === 1) {
57
+ if (CONTROL_TAGS.has(source.tagName)) maps.controls.push(source, copy)
58
+ if (source.tagName === 'TEMPLATE') {
59
+ // The deep clone also copied the template's own child nodes, which are not its
60
+ // content and were never part of the view.
61
+ while (copy.firstChild) copy.removeChild(copy.firstChild)
62
+ sourceChildren = source.content
63
+ copyChildren = copy.content
64
+ maps.cloneToLive.set(copyChildren, sourceChildren)
65
+ maps.liveToClone.set(sourceChildren, copyChildren)
51
66
  }
67
+ } else if (source.nodeType !== 11) return
68
+ let c = copyChildren.firstChild
69
+ for (let s = sourceChildren.firstChild; s && c; s = s.nextSibling) {
70
+ pairTree(s, c, maps, drop)
71
+ c = c.nextSibling
52
72
  }
53
- if (source.nodeType === 1) copyControlState(source, copy)
54
- return copy
55
73
  }
56
74
 
57
- export function createContentView(context, { capability = 'data', exclude = null, inherit = true } = {}) {
75
+ export function createContentView(context, { capability = 'data', exclude = null, inherit = true, provenance = null } = {}) {
58
76
  if (!context) throw new TypeError('createContentView requires a DOM context')
59
77
  const sourceDocument = context.nodeType === 9 ? context : context.ownerDocument
60
78
  if (!sourceDocument?.implementation?.createHTMLDocument) {
61
79
  throw new TypeError('createContentView requires an HTML DOM implementation')
62
80
  }
63
81
  const inertDocument = sourceDocument.implementation.createHTMLDocument('')
64
- const cloneToLive = new WeakMap()
82
+ const cloneToLive = provenance || new WeakMap()
65
83
  const liveToClone = new WeakMap()
66
84
  const sourceRoot = context.nodeType === 9 ? context.documentElement : context
67
85
  if (exclude) inertDocument.documentElement.matches(exclude)
68
86
  const capabilityMatch = capabilitySelector(capability)
69
- const root = importTree(sourceRoot, inertDocument, capability, capabilityMatch, exclude, sourceRoot, inherit, { cloneToLive, liveToClone })
87
+ const drop = inherit
88
+ ? (el) => hasOwnCapability(el, capability) || !!(exclude && el.matches(exclude))
89
+ : (el) => excluded(el, capability, capabilityMatch, exclude, sourceRoot, false)
90
+ let root = null
91
+ if (sourceRoot.nodeType !== 1 || !excluded(sourceRoot, capability, capabilityMatch, exclude, sourceRoot, inherit)) {
92
+ root = inertDocument.importNode(sourceRoot, true)
93
+ const maps = { cloneToLive, liveToClone, dropped: [], controls: [] }
94
+ pairTree(sourceRoot, root, maps, drop)
95
+ for (const node of maps.dropped) node.remove()
96
+ // Control state is copied once the copy holds only what the view keeps, so a
97
+ // <select> sees exactly the options the old node-by-node import gave it.
98
+ for (let i = 0; i < maps.controls.length; i += 2) copyControlState(maps.controls[i], maps.controls[i + 1])
99
+ }
70
100
  if (context.nodeType === 9 && root) {
71
101
  inertDocument.replaceChild(root, inertDocument.documentElement)
72
102
  liveToClone.set(context, inertDocument)
@@ -23,6 +23,7 @@ export const POLICY_TOKENS = Object.freeze([
23
23
  'no-data',
24
24
  'freeze',
25
25
  'editor-ui',
26
+ 'live',
26
27
  ])
27
28
 
28
29
  export function hasPolicyToken(element, token) {