hyper-html-api 0.9.0 → 0.10.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.
Files changed (55) hide show
  1. package/README.md +18 -5
  2. package/conformance/MANIFEST.json +2 -2
  3. package/conformance/cases/write-query-attribute.after.html +1 -0
  4. package/conformance/cases/write-query-attribute.after.json +3 -0
  5. package/conformance/cases/write-query-attribute.data.json +1 -0
  6. package/conformance/cases/write-query-attribute.html +1 -0
  7. package/conformance/cases/write-query-attribute.meta +4 -0
  8. package/conformance/cases/write-query-attribute.parsed.json +3 -0
  9. package/conformance/cases/write-query-attribute.rules +1 -0
  10. package/conformance/cases/write-query-attribute.write.json +4 -0
  11. package/conformance/cases/write-query-list.after.html +1 -0
  12. package/conformance/cases/write-query-list.after.json +10 -0
  13. package/conformance/cases/write-query-list.data.json +1 -0
  14. package/conformance/cases/write-query-list.html +1 -0
  15. package/conformance/cases/write-query-list.meta +6 -0
  16. package/conformance/cases/write-query-list.parsed.json +8 -0
  17. package/conformance/cases/write-query-list.rules +1 -0
  18. package/conformance/cases/write-query-list.write.json +4 -0
  19. package/conformance/cases/write-query-noop.after.html +1 -0
  20. package/conformance/cases/write-query-noop.after.json +3 -0
  21. package/conformance/cases/write-query-noop.data.json +1 -0
  22. package/conformance/cases/write-query-noop.html +1 -0
  23. package/conformance/cases/write-query-noop.meta +4 -0
  24. package/conformance/cases/write-query-noop.parsed.json +3 -0
  25. package/conformance/cases/write-query-noop.rules +1 -0
  26. package/conformance/cases/write-query-noop.write.json +4 -0
  27. package/conformance/cases/write-query-override.after.html +1 -0
  28. package/conformance/cases/write-query-override.after.json +3 -0
  29. package/conformance/cases/write-query-override.data.json +1 -0
  30. package/conformance/cases/write-query-override.html +1 -0
  31. package/conformance/cases/write-query-override.meta +4 -0
  32. package/conformance/cases/write-query-override.parsed.json +3 -0
  33. package/conformance/cases/write-query-override.rules +1 -0
  34. package/conformance/cases/write-query-override.write.json +4 -0
  35. package/conformance/cases/write-query-refused.data.json +1 -0
  36. package/conformance/cases/write-query-refused.error.json +11 -0
  37. package/conformance/cases/write-query-refused.html +1 -0
  38. package/conformance/cases/write-query-refused.meta +4 -0
  39. package/conformance/cases/write-query-refused.parsed.json +4 -0
  40. package/conformance/cases/write-query-refused.rules +1 -0
  41. package/conformance/cases/write-query-text.after.html +1 -0
  42. package/conformance/cases/write-query-text.after.json +3 -0
  43. package/conformance/cases/write-query-text.data.json +1 -0
  44. package/conformance/cases/write-query-text.html +1 -0
  45. package/conformance/cases/write-query-text.meta +4 -0
  46. package/conformance/cases/write-query-text.parsed.json +3 -0
  47. package/conformance/cases/write-query-text.rules +1 -0
  48. package/conformance/cases/write-query-text.write.json +4 -0
  49. package/dist/hyper-html-api.engine.min.js +1 -1
  50. package/dist/hyper-html-api.min.js +6 -5
  51. package/dist/hyper-html-api.upgrade.min.js +2 -2
  52. package/package.json +2 -2
  53. package/src/dom-api.js +149 -23
  54. package/src/lib/content-dom.js +7 -5
  55. package/src/write.js +20 -10
@@ -1,2 +1,2 @@
1
- var hyperHtmlApiUpgrade=(()=>{var re=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var Ee=(e,t)=>{for(var r in t)re(e,r,{get:t[r],enumerable:!0})},Qe=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ge(t))!Ze.call(e,n)&&n!==r&&re(e,n,{get:()=>t[n],enumerable:!(o=Xe(t,n))||o.enumerable});return e};var et=e=>Qe(re({},"__esModule",{value:!0}),e);var jt={};Ee(jt,{default:()=>Nt,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"],ne=new Set(J),Ae=new Set(["textContent","innerText","innerHTML","value","checked","selected","disabled","readOnly","type","id","className","title"]),oe=new Set(["tagName","nodeName","nodeType","nodeValue","childElementCount","classList","baseURI","documentURI","contentType","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","currentSrc","duration","paused","dataset"]);var X={};Ee(X,{EmptyListInsert:()=>U,MAX_RULE_DEPTH:()=>_,MaxRuleDepthExceeded:()=>I,NoRulesTag:()=>ie,RuleTargetReadOnly:()=>W,RulesParseError:()=>D,ShapeMismatch:()=>H,UnknownRulesVersion:()=>j,WriteRefused:()=>Y,WriteRejected:()=>se});var D=class extends Error{constructor(t,r){super(t),this.name="RulesParseError",this.cause=r}},j=class extends Error{constructor(t){super(`unknown rules version: ${t}. Library supports "1".`),this.name="UnknownRulesVersion",this.version=t}},_=20,I=class extends Error{constructor(t){super(`rule depth exceeded ${_} at path: ${t.join(".")}`),this.name="MaxRuleDepthExceeded",this.path=t}},H=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}},W=class extends Error{constructor(t){super(`cannot write to read-only DOM property "${t}"`),this.name="RuleTargetReadOnly",this.target=t}},Y=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,r){super(`write rejected: ${t.length} unknown key(s), ${r.length} rule(s) with no matching element`),this.name="WriteRejected",this.unknownKeys=t,this.unmatched=r}};function C(e){let t=0,r=null,o=-1;for(let n=0;n<e.length;n++){let i=e[n];i==="\\"?n++:r?i===r&&(r=null):i==='"'||i==="'"?r=i:i==="["||i==="("?t++:i==="]"||i===")"?t>0&&t--:i==="@"&&t===0&&(o=n)}return o}function ce(e){let t=C(e);return t===-1?{selector:e,prop:null}:{selector:e.slice(0,t),prop:e.slice(t+1)||null}}function M(e,t,r,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,r,{depth:0,path:[]},o)}function le(e,t,r,o,n){if(o.depth>_)throw new I(o.path);if(typeof r=="string")return tt(e,t,r,o,n);if(Array.isArray(r)){let[i,l]=r,s=e.find(t,i,n);return be(n,o,s),s.map((c,a)=>le(e,c,l,{depth:o.depth+1,path:[...o.path,a]},n))}if(typeof r=="object"&&r!==null){let i={};for(let[l,s]of Object.entries(r))i[l]=le(e,t,s,{depth:o.depth+1,path:[...o.path,l]},n);return i}return null}function tt(e,t,r,o,n){if(r.endsWith("[]")){let s=r.slice(0,-2),c=e.find(t,s,n);return be(n,o,c),c.map(a=>e.text(a))}if(r.startsWith("@"))return Oe(e,t,r.slice(1));let i=C(r);if(i!==-1){let s=r.slice(0,i),c=r.slice(i+1),a=s?e.find(t,s,n):[t];return a.length===0?null:Oe(e,a[0],c)}if(r===".")return e.text(t);let l=e.find(t,r,n);return l.length===0?null:e.text(l[0])}function be(e,t,r){if(typeof e.onRowsRead=="function")try{e.onRowsRead(t.path.slice(),r)}catch(o){console.warn(`[hyper-html-api] onRowsRead threw at "${t.path.join(".")||"(root)"}"`,o)}}function Oe(e,t,r){if(ne.has(r)){let n=e.prop(t,r);return n==null?null:String(n)}let o=e.attr(t,r);return o||null}function Ce(e,t,r,o){let n=e.length,i=t.length,l=new Array(n).fill(-1);if(o){let u=new Set;for(let p=0;p<n;p++){let g=o[p];!(g>=0&&g<i)||u.has(g)||(l[p]=g,u.add(g))}}if(n===0||i===0)return l;let s=e.map(u=>Se(u,r)),c=t.map(u=>Se(u,r)),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<n;u++)l[u]<0&&d.push(u);let T=[];for(let u=0;u<i;u++)a[u]||T.push(u);if(d.length===0||T.length===0)return l;let h=n*i+1,m=(u,p)=>rt(e[u],t[p],r)*h+Math.abs(u-p);for(let[u,p]of nt(d,T,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 r=Object.keys(t);return JSON.stringify(r.map(o=>{let n=JSON.stringify(e?.[o]);return n===void 0?" undef":n}))}function rt(e,t,r){if(!Me(r))return e===t?0:1;let o=Object.keys(r);if(o.length===0)return 0;let n=0;for(let i of o){let l=JSON.stringify(e?.[i]),s=JSON.stringify(t?.[i]);l!==s&&n++}return n}function nt(e,t,r){return e.length<=t.length?Re(e,t,r,!1):Re(t,e,(o,n)=>r(n,o),!0)}function Re(e,t,r,o){let n=e.length,i=t.length,l=[];for(let y=0;y<=n;y++)l.push(new Float64Array(i+1).fill(1/0));let s=[];for(let y=0;y<=n;y++)s.push(new Uint8Array(i+1));for(let y=0;y<=i;y++)l[n][y]=0;for(let y=n-1;y>=0;y--)for(let d=i-1;d>=0;d--){let T=r(e[y],t[d])+l[y+1][d+1],h=l[y][d+1];T<=h?(l[y][d]=T,s[y][d]=1):l[y][d]=h}let c=[],a=0,f=0;for(;a<n&&f<i;)s[a][f]&&(c.push(o?[t[f],e[a]]:[e[a],t[f]]),a++),f++;return c}function ue(e,t,r,o,n,i,l,s={}){let c=e.find(t,r,s);if(n.length===0){c.forEach(w=>e.remove(w)),fe(s,"onRowsApplied",i.path,[]);return}let a=n.length>c.length,f=c[0]||null;if(a&&!f&&(f=ct(e,t,r,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 T=Ce(n,y,o,ot(e,c,n,i,s)),h=c[0]||f,m=e.parent(h),u=c.length>0?Ne(e,m,h):0,p=lt(e,c),g=new Set,O=[],A=n.map((w,E)=>{let x=T[E];if(x>=0)return g.add(x),O.push(!1),c[x];O.push(!0);let R=e.clone(d);return e.stripIds(R),R});c.forEach((w,E)=>{g.has(E)||e.remove(w)}),p?A.forEach((w,E)=>{let x=u+E;e.children(m).findIndex(Ye=>e.sameNode(Ye,w))!==x&&e.insertAt(m,w,x)}):ft(e,A,O,m,u),it(e,A,o,n,i,l,s),fe(s,"onRowsApplied",i.path,A)}function fe(e,t,r,o){if(typeof e[t]=="function")try{return e[t](r.slice(),o)}catch(n){console.warn(`[hyper-html-api] ${t} threw at "${r.join(".")||"(root)"}"`,n);return}}function ot(e,t,r,o,n){let i=fe(n,"identifyRows",o.path,r);if(!Array.isArray(i))return null;let l=new Array(r.length).fill(-1),s=new Set;for(let c=0;c<r.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,r,o,n,i,l){t.forEach((s,c)=>{if(r===null){let a=o[c],f=a==null?"":String(a);e.text(s)!==f&&e.text(s,f)}else{let a=i(e,s,r,o[c],{depth:n.depth+1,path:[...n.path,c]},l);a&&a!==s&&(t[c]=a)}})}function st(e,t,r,o){return r===null?e.text(t):M(e,t,r,o.onRowsRead?{...o,onRowsRead:void 0}:o)}function Ne(e,t,r){let o=e.children(t);for(let n=0;n<o.length;n++)if(e.sameNode(o[n],r))return n;return-1}function ct(e,t,r,o){if(!o.templateAttr)return null;let n=t;for(;n;){let i=e.find(n,r,{includeRulesTag:!1,templateAttr:null});for(let l of i)if(e.attr(l,o.templateAttr)!=null)return l;n=e.parent(n)}return null}function lt(e,t){if(t.length<=1)return!0;let r=e.parent(t[0]);if(!r)return!1;let o=e.children(r),n=[];for(let i of t){let l=o.findIndex(s=>e.sameNode(s,i));if(l===-1)return!1;n.push(l)}return n.sort((i,l)=>i-l),n[n.length-1]-n[0]===n.length-1}function ft(e,t,r,o,n){let i=null,l=n;for(let s=0;s<t.length;s++){if(!r[s]){i=t[s];continue}let c=i?e.parent(i):o;if(!c)continue;let a=i?Ne(e,c,i)+1:l++;e.insertAt(c,t[s],a),i=t[s]}}var je=new Set(["checked","selected","disabled","readOnly","paused"]);function L(e,t,r,o,n={}){if(Object.prototype.hasOwnProperty.call(n,"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(r,o,[],i),i.length)throw new H(i);G(e,t,r,o,{depth:0,path:[]},n)}function G(e,t,r,o,n,i={}){if(n.depth>_)throw new I(n.path);if(o===void 0)return t;if(typeof r=="string")return ut(e,t,r,o,n,i);if(Array.isArray(r)){let[l,s]=r;return ue(e,t,l,s,o,n,G,i),t}if(typeof r=="object"&&r!==null){for(let[l,s]of Object.entries(r)){let c=G(e,t,s,o==null?o:o[l],{depth:n.depth+1,path:[...n.path,l]},i);c&&c!==t&&(t=c)}return t}return t}function ut(e,t,r,o,n,i){if(r.endsWith("[]")){let c=r.slice(0,-2);return ue(e,t,c,null,o,n,G,i),t}if(r.startsWith("@"))return Le(e,t,r.slice(1),o);let l=C(r);if(l!==-1){let c=r.slice(0,l),a=r.slice(l+1),f=c?e.find(t,c,i):[t];return f.length===0||Le(e,f[0],a,o),t}if(r===".")return Ie(e,t,o),t;let s=e.find(t,r,i);return s.length===0||Ie(e,s[0],o),t}function Ie(e,t,r){let o=r==null?"":String(r);e.text(t)!==o&&e.text(t,o)}function Le(e,t,r,o){if(oe.has(r)){let i=e.prop(t,r);if(i===o||i!=null&&o!=null&&String(i)===String(o))return t;throw new W(r)}if(r==="outerHTML"){let i=o==null?"":String(o);return e.replaceWith(t,i)}if(Ae.has(r)){let i=at(r,o);return e.prop(t,r)!==i&&e.prop(t,r,i),t}let n=o==null?"":String(o);return e.attr(t,r)!==n&&e.attr(t,r,n),t}function at(e,t){return t==null?je.has(e)?!1:"":je.has(e)?t==="false"?!1:!!t:t}function ae(e,t,r,o){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]")){Array.isArray(t)?t.forEach((n,i)=>{typeof n=="object"&&n!==null&&o.push({path:q([...r,i]),expected:"scalar",got:v(n)})}):o.push({path:q(r),expected:"array",got:v(t)});return}t!==null&&typeof t=="object"&&o.push({path:q(r),expected:"scalar",got:v(t)});return}if(Array.isArray(e)){if(!Array.isArray(t)){o.push({path:q(r),expected:"array",got:v(t)});return}let n=e[1];t.forEach((i,l)=>ae(n,i,[...r,l],o));return}if(typeof e=="object"&&e!==null){if(t===null||Array.isArray(t)||typeof t!="object"){o.push({path:q(r),expected:"object",got:v(t)});return}for(let[n,i]of Object.entries(e))ae(i,t[n],[...r,n],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 D(`Invalid strict JSON: ${t.message}`,t)}}function k(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 r(n){let i=[],l=0;for(;l<n.length;){let s=n[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<n.length&&/\s/.test(n[d]);)d++;if(d<n.length&&/[a-zA-Z_]/.test(n[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<n.length&&n[d]!==y;)n[d]==="\\"&&d++,d++;i.push({type:t.STRING,value:n.substring(l+1,d),quoted:!0,sourceQuote:y}),l=d+1;continue}let c=l,a;for(;c<n.length&&!/[{},]/.test(n[c]);)if(n[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 T of y){let h=T.substring(1);if(n.substring(c+1,c+1+h.length)===h){d=!0,c+=h.length;break}}if(!d)break}else if(n[c]==="["){for(c++;c<n.length&&n[c]!=="]";){if(n[c]==='"'||n[c]==="'"){let y=n[c];for(c++;c<n.length&&n[c]!==y;)n[c]==="\\"&&c++,c++}c++}c<n.length&&n[c]==="]"&&c++}else c++;a=n.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(n){let i="";for(let l=0;l<n.length;l++){let s=n[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=n[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 n=r(e),i=o(n);return JSON.parse(i)}catch(n){throw new D("Invalid extraction rules syntax: "+n.message,n)}}var pe="1",ke=/^[a-zA-Z0-9_-]+$/;function B(e,t,r){let o;if(r===void 0)o="script[data-rules-name]";else{if(typeof r!="string"||!ke.test(r))throw new Error(`hyper-html-api: invalid rules token ${JSON.stringify(r)} (must match ${ke})`);o=`script[data-rules-name~="${r}"]`}let n=e.find(t,o,{includeRulesTag:!0});if(n.length===0)return null;r!==void 0&&n.length>1&&console.warn(`hyper-html-api: ${n.length} rules tags match data-rules-name~="${r}"; using the first.`);let i=n[0],l=e.attr(i,"data-rules-version");if(l!==pe)throw new j(l);return{rules:k(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"])}),De=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 r=e.getAttribute?.("clay");return!!(r&&r.split(/\s+/).includes(t)||e.hasAttribute?.(t))}function pt(e,t){if(he(e,t))return!0;for(let[r,o]of Object.entries(dt))if(o.includes(t)&&he(e,r))return!0;return!1}function z(e){let t=Pe[e];if(!t)throw new Error(`Unknown region capability: ${e}`);return[...t.tokens,...t.bundles].flatMap(r=>[`[clay~="${r}"]`,`[${r}]`]).join(", ")}function ht(e,t){let r=e&&e.nodeType===1?e:e?.parentElement;for(;r&&r.nodeType===1;){let o=Pe[t];if(!o)throw new Error(`Unknown region capability: ${t}`);if(o.tokens.some(n=>pt(r,n))||o.bundles.some(n=>he(r,n)))return r;r=r.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 me(e,t,r){if(r&&typeof r=="object")return{rules:r,tagNode:null};if(typeof r=="string"){let o=t&&t.ownerDocument?t.ownerDocument:t;return B(e,o,r)}return null}var gt=/:(?:focus(?:-within|-visible)?|hover|active|visited|defined)\b/i;function $e(e,t){if(!/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(e.tagName||""))return;let r=(e.getAttribute?.("type")||"").toLowerCase();if("value"in e&&"value"in t&&e.tagName!=="OPTION"&&r!=="checkbox"&&r!=="radio"&&(t.value=e.value),"checked"in e&&"checked"in t&&(t.checked=e.checked),"selected"in e&&"selected"in t&&(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 He(e,t,r,o){if(o)return!!e.closest?.(t);let n=e;for(;n?.nodeType===1;){if(n.matches(t))return!0;if(n===r)break;n=n.parentElement}return!1}function Ue(e,t,r,o,n,i,l,s){if(e.nodeType===1&&((l?_e(e,r):He(e,o,i,!1))||n&&He(e,n,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,r,o,n,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:r=null,inherit:o=!0}={}){if(!e)throw new TypeError("createContentView requires a DOM context");let n=e.nodeType===9?e:e.ownerDocument;if(!n?.implementation?.createHTMLDocument)throw new TypeError("createContentView requires an HTML DOM implementation");let i=n.implementation.createHTMLDocument(""),l=new WeakMap,s=new WeakMap,c=e.nodeType===9?e.documentElement:e;r&&i.documentElement.matches(r);let a=z(t),f=Ue(c,i,t,a,r,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(gt.test(d))throw new Error(`Filtered content queries do not support stateful selector: ${d}`)};return{root:f,document:i,capability:t,selector:z(t),cloneToLive:l,liveToClone:s,original(d){return l.get(d)||null},cloneOf(d){return s.get(d)||null},query(d,T=f){return y(d),Array.from(T.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 T=d===f?f:s.get(d);return T?i.importNode(T,!0):null}}}function We(e){return e&&e.nodeType===1&&e.tagName==="SCRIPT"&&e.hasAttribute&&e.hasAttribute("data-rules-name")}function wt(e){return e?(e.nodeType===9||e.nodeType===11,e):null}var b={semanticExclude:!0,find(e,t,r={}){let o=wt(e);if(!o||!o.querySelectorAll)return[];let n=Array.from(o.querySelectorAll(t));r.includeRulesTag||(n=n.filter(s=>!We(s)));let i=[];r.skip&&i.push(r.skip);let l=r.templateAttr===null?null:r.templateAttr||"cms-template";if(l&&i.push("["+l+"]"),i.length){let s=i.join(", ");n=n.filter(c=>!c.closest||!c.closest(s))}return n},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,r){if(r===void 0)return e.hasAttribute&&e.hasAttribute(t)?e.getAttribute(t):null;e.setAttribute(t,r)},removeAttr(e,t){e&&e.removeAttribute&&e.removeAttribute(t)},prop(e,t,r){if(r===void 0){let o=e?e[t]:void 0;return o!==void 0?o:null}e[t]=r},clone(e){return e.cloneNode(!0)},insertAt(e,t,r){let o=e.children[r]||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 n=o.content.firstElementChild;if(!n)throw new Error("dom.replaceWith: html did not parse to an element");return e.parentNode.replaceChild(n,e),n},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 K(e,t={}){if(t.exclude===null)return b;let r=[z("data"),t.exclude].filter(Boolean).join(", "),o=e.nodeType===9?e:e.ownerDocument||e,n=e.nodeType===9?e.documentElement:e;if(!t._write&&!n?.matches?.(r)&&!n?.querySelector?.(r)&&!o?.querySelector?.(r))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(x=>s.cloneOf(x)),A=g[0];for(;A&&g.includes(A);)A=A.nextSibling;for(let x of g)x.remove();if(u==="innerHTML"){let x=l.createElement("template");x.innerHTML=p;for(let R of Array.from(x.content.childNodes))h.insertBefore(R,A||null)}else h.insertBefore(l.createTextNode(p),A||null);let w=F(h,{capability:"data",exclude:t.exclude||null});m.replaceChildren(...Array.from(w.root?.childNodes||[]));let E=x=>{let R=w.original(x);R&&(s.liveToClone.set(R,x),s.cloneToLive.set(x,R));for(let Te of Array.from(x.childNodes||[]))E(Te)};for(let x of Array.from(m.childNodes))E(x)},T={...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=>!We(w)));let O=[];u.skip&&O.push(u.skip);let A=u.templateAttr===null?null:u.templateAttr||"cms-template";if(A&&O.push(`[${A}]`),O.length){let w=O.join(", ");g=g.filter(E=>!E.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?.(r)&&!g?.querySelector?.(r)?b.text(g):(a(h)?.textContent||"").trim()}let u=f(h);if(!u?.matches?.(r)&&!u?.querySelector?.(r)&&!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=T.children(p)[u]||(()=>{for(let E=p.children.length-1;E>=0;E--){let x=p.children[E];if(c().cloneOf(x))return x.nextElementSibling}return p.firstElementChild})(),A=f(m);p.insertBefore(A,O||null);let w=c().cloneOf(p);if(w){let E=c().cloneOf(A);E||(E=l.importNode(A,!0),y(A,E));let x=Array.from(w.children);w.insertBefore(E,x[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 A=w=>{let E=O.original(w);E&&(s.liveToClone.set(E,w),s.cloneToLive.set(w,E));for(let x of Array.from(w.childNodes||[]))A(x)};A(O.root)}}return g}};return T}var S=b;var ye={extract:(e,t,r={})=>M(K(e,r),e,t,r),apply:(e,t,r,o={})=>L(K(e,{...o,_write:!0}),e,t,r,o),findRulesIn:(e,t)=>B(S,e,t),findRules:(e,t)=>me(S,e,t),bind:(e,t,r={})=>{let o=me(S,e,t);if(!o){let n=typeof t=="string"?`data-rules-name~="${t}"`:"the provided rules object";throw new Error(`hyper-html-api: could not resolve rules for ${n}`)}return{...o,get:()=>M(K(e,r),e,o.rules,r),set:n=>L(K(e,{...r,_write:!0}),e,o.rules,n,r)}},parseStrict:de,parseRelaxed:k,ruleAttrIndex:C,splitRule:ce,errors:X,DOM_PROPERTIES:J};var xt="hha:upgrade-check:";function N(e,t){let r=e.querySelector(`meta[name="${t}"]`),o=r?r.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 Tt(e,t){let r=ve(e),o=ve(t);if(!r||!o)return!1;let n=Math.max(r.length,o.length);for(let i=0;i<n;i++){let l=r[i]||0,s=o[i]||0;if(l!==s)return l>s}return!1}function Et(e){try{let t=globalThis.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function At(e,t){try{globalThis.localStorage.setItem(e,JSON.stringify(t))}catch{}}async function qe({force:e=!1,doc:t,loc:r,fetchFn:o,now:n,ttlMs:i=864e5}={}){if(t=t||(typeof document<"u"?document:null),r=r||(typeof location<"u"?location:null),o=o||(d=>fetch(d)),n=n??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,r?r.href:void 0)}catch{return null}if(r&&c.origin===r.origin&&c.pathname===r.pathname)return null;let a=`${xt}${c.href}:${s||"none"}`,f,y=e?null:Et(a);if(y&&typeof y.checkedAt=="number"&&n-y.checkedAt<i)f=y.sourceVersion;else{try{let d=await o(c.href);if(!d.ok)throw new Error(`HTTP ${d.status}`);let T=await d.text(),h=new DOMParser().parseFromString(T,"text/html");f=N(h,"hyper-version")}catch{f=null}At(a,{checkedAt:n,sourceVersion:f})}return f?{available:Tt(f,s||"0.0.0"),currentVersion:s,sourceVersion:f,sourceUrl:c.href}:null}var Ot="script[data-rules-name]";function bt(e){return typeof e=="string"?e.trim().replace(/\s+/g," "):""}function Z(e,t){let r=e.find(t,Ot,{includeRulesTag:!0}),o=new Set,n=[];for(let i of r){let l=bt(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 j(s);o.add(l),n.push({name:l,rules:k(e.text(i))})}return n}function ge(e,t){let r={};for(let{name:o,rules:n}of Z(e,t))r[o]=M(e,t,n);return r}function Be(e){let t=e||document,r=t.nodeType===9?t:t.ownerDocument||t;return{dataByName:ge(S,t),version:N(r,"hyper-version")}}var V=class extends Error{constructor(t,r){super(`could not fetch upgrade source: ${t}`),this.name="UpgradeSourceUnreachable",this.sourceUrl=t,this.cause=r}},Q=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,r){super(t),this.name="UpgradeTransformInvalid",this.cause=r}},ee=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 St="text/hyper-upgrade";function ze(e,t){let r=e.find(t,`script[type="${St}"]`);if(r.length===0)return null;if(r.length>1)throw new ee(r.length);return e.text(r[0])||null}var Rt=new Function("url","return import(url)");async function Fe(e){let t=new Blob([e],{type:"text/javascript"}),r=URL.createObjectURL(t),o;try{o=await Rt(r)}catch(n){throw new P(`transform failed to load: ${n&&n.message?n.message:n}`,n)}finally{URL.revokeObjectURL(r)}if(typeof o.default!="function")throw new P("transform must `export default` a function");return o.default}function te(e,t){let r={carriedOver:0,discarded:0,listItems:0},o=we(t,e,r);return xe(t,e,r),{data:o,summary:r}}function we(e,t,r){if(typeof e=="string")return e.endsWith("[]")?Array.isArray(t)?(r.listItems+=t.length,r.carriedOver+=t.length,t):void 0:t==null||typeof t=="object"?void 0:(r.carriedOver++,t);if(Array.isArray(e)){let[,o]=e;return Array.isArray(t)?(r.listItems+=t.length,t.map(n=>we(o,n,r))):void 0}if(typeof e=="object"&&e!==null){let o={};for(let[n,i]of Object.entries(e)){let l=we(i,t?.[n],r);l!==void 0&&(o[n]=l)}return o}}function xe(e,t,r){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 n of Object.keys(t))o.has(n)?xe(e[n],t[n],r):r.discarded+=$(t[n]);return}if(Array.isArray(e)&&Array.isArray(t)){let o=e[1];t.forEach(n=>xe(o,n,r));return}typeof e=="string"&&!e.endsWith("[]")&&typeof t=="object"&&t!==null&&(r.discarded+=$(t))}}function $(e){return e==null?0:Array.isArray(e)?e.reduce((t,r)=>t+$(r),0):typeof e=="object"?Object.values(e).reduce((t,r)=>t+$(r),0):1}function Ke(e,t,r){let o=Z(e,t),n={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(r,s)){i[s]={carriedOver:0,discarded:0,listItems:0};continue}let{data:a,summary:f}=te(r[s],c);L(e,t,c,a),i[s]=f,n.carriedOver+=f.carriedOver,n.discarded+=f.discarded,n.listItems+=f.listItems}for(let s of Object.keys(r))l.has(s)||(n.discarded+=$(r[s]));return{totals:n,byName:i,rulesTagCount:o.length}}async function Ve({sourceUrl:e,dataByName:t,fromVersion:r,doc:o,loc:n,fetchFn:i}={}){if(o=o||(typeof document<"u"?document:null),n=n||(typeof location<"u"?location:null),i=i||(p=>fetch(p)),!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,n?n.href:void 0);r=r!==void 0?r:N(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=N(a,"hyper-version"),y=t,d=!1,T=ze(S,a);if(T){let g=await(await Fe(T))(y,{fromVersion:r,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}=Ke(S,a,y);if(u===0&&Object.keys(y).length>0)throw new Q(l.href);return{html:Ct(a),fromVersion:r,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:te};var Mt={engine:ye,upgrade:Je},Nt=Mt;return et(jt);})();
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);})();
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "apply",
10
10
  "CMS"
11
11
  ],
12
- "version": "0.9.0",
12
+ "version": "0.10.0",
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.0.0"
66
+ "hyper-morph": "^1.3.0"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@web/test-runner": "^0.20.0",
package/src/dom-api.js CHANGED
@@ -34,43 +34,169 @@ export const engine = {
34
34
 
35
35
  const isNode = (x) => !!x && typeof x.nodeType === 'number'
36
36
 
37
- // Autodetect the page's single rules tag when no `source` is given.
38
- // engine.findRulesIn(root) (no token) silently takes the FIRST of many tags, so
39
- // the sugar counts the tags itself to enforce the one-tag rule with clear,
40
- // distinct errors for "none" vs "multiple".
41
- function autodetect(root) {
42
- const searchRoot = (root && root.ownerDocument) ? root.ownerDocument : root
43
- const tags = domAdapter.find(searchRoot, 'script[data-rules-name]', { includeRulesTag: true })
44
- if (tags.length === 0) {
45
- throw new Error('hyper-html-api: no rules tag found. Add <script type="application/json" data-rules-name="…" data-rules-version="1"> or pass rules.')
37
+ function defaultRules(root) {
38
+ const searchRoot = root && root.ownerDocument ? root.ownerDocument : root
39
+ const found = engineMod.findRulesIn(domAdapter, searchRoot, 'api')
40
+ if (!found) throw new engineMod.errors.NoRulesTag('api')
41
+ return found.rules
42
+ }
43
+
44
+ function containingTree(root) {
45
+ if (root.nodeType === 9) return root
46
+ const documentElement = root.ownerDocument?.documentElement
47
+ if (documentElement?.contains(root)) return documentElement
48
+ let tree = root
49
+ while (tree.parentNode) tree = tree.parentNode
50
+ return tree
51
+ }
52
+
53
+ function cloneContainingTree(tree) {
54
+ if (tree.nodeType !== 11 || !tree.host) return tree.cloneNode(true)
55
+ const clone = tree.ownerDocument.createDocumentFragment()
56
+ for (const child of tree.childNodes) clone.appendChild(child.cloneNode(true))
57
+ return clone
58
+ }
59
+
60
+ function childIndexPath(tree, node) {
61
+ const path = []
62
+ while (node !== tree) {
63
+ const parent = node.parentNode
64
+ path.push(Array.prototype.indexOf.call(parent.childNodes, node))
65
+ node = parent
46
66
  }
47
- if (tags.length > 1) {
48
- throw new Error('hyper-html-api: multiple rules tags found; pass a name, e.g. extractData("api").')
67
+ return path.reverse()
68
+ }
69
+
70
+ function nodeAtPath(tree, path) {
71
+ return path.reduce((node, index) => node.childNodes[index], tree)
72
+ }
73
+
74
+ function matchingNodes(root, selector) {
75
+ const nodes = root.querySelectorAll ? Array.from(root.querySelectorAll(selector)) : []
76
+ if (root.matches?.(selector)) nodes.unshift(root)
77
+ return nodes
78
+ }
79
+
80
+ function copyLiveFormState(source, clone) {
81
+ const sourceOptions = matchingNodes(source, 'option')
82
+ const cloneOptions = matchingNodes(clone, 'option')
83
+ sourceOptions.forEach((node, index) => cloneOptions[index].selected = node.selected)
84
+
85
+ const sourceInputs = matchingNodes(source, 'input')
86
+ const cloneInputs = matchingNodes(clone, 'input')
87
+ sourceInputs.forEach((node, index) => {
88
+ const type = node.type.toLowerCase()
89
+ if (type !== 'file') cloneInputs[index].value = node.value
90
+ if (type === 'checkbox' || type === 'radio') cloneInputs[index].checked = node.checked
91
+ })
92
+
93
+ const sourceTextareas = matchingNodes(source, 'textarea')
94
+ const cloneTextareas = matchingNodes(clone, 'textarea')
95
+ sourceTextareas.forEach((node, index) => cloneTextareas[index].value = node.value)
96
+ }
97
+
98
+ function assertNoReadOnlyTargets(rule, value) {
99
+ if (value === undefined) return
100
+ if (typeof rule === 'string') {
101
+ if (rule.endsWith('[]')) return
102
+ const at = rule.startsWith('@') ? 0 : engineMod.ruleAttrIndex(rule)
103
+ if (at === -1) return
104
+ const name = rule.slice(at + 1)
105
+ if (engineMod.DOM_PROPERTIES_READ_ONLY_SET.has(name)) {
106
+ throw new engineMod.errors.RuleTargetReadOnly(name)
107
+ }
108
+ return
109
+ }
110
+ if (Array.isArray(rule)) {
111
+ if (!Array.isArray(value)) return
112
+ value.forEach(item => assertNoReadOnlyTargets(rule[1], item))
113
+ return
114
+ }
115
+ if (rule && typeof rule === 'object' && value && typeof value === 'object' && !Array.isArray(value)) {
116
+ for (const [key, subrule] of Object.entries(rule)) {
117
+ assertNoReadOnlyTargets(subrule, value[key])
118
+ }
119
+ }
120
+ }
121
+
122
+ function guardedApply(root, rules, data) {
123
+ const opts = { templateAttr: 'cms-template' }
124
+ const liveTree = containingTree(root)
125
+ const rootPath = childIndexPath(liveTree, root)
126
+ const detachedTree = cloneContainingTree(liveTree)
127
+ copyLiveFormState(liveTree, detachedTree)
128
+ const detachedRoot = nodeAtPath(detachedTree, rootPath)
129
+ const detachedAdapter = createDomAdapter(detachedTree, {
130
+ ...opts,
131
+ _write: true,
132
+ })
133
+ const plan = engineMod.planWrite(detachedAdapter, detachedRoot, rules, data, opts)
134
+ if (plan.unknownKeys.length || plan.unmatched.length) {
135
+ throw new engineMod.errors.WriteRejected(plan.unknownKeys, plan.unmatched)
49
136
  }
50
- // findRulesIn (no token) returns the one tag's rules and enforces data-rules-version="1".
51
- return engineMod.findRulesIn(domAdapter, searchRoot).rules
137
+ const guarded = engineMod.guardAdapter(detachedAdapter)
138
+ engineMod.apply(guarded, detachedRoot, rules, data, opts)
139
+ guarded.assertClean()
140
+ assertNoReadOnlyTargets(rules, data)
141
+ const liveGuarded = engineMod.guardAdapter(createDomAdapter(liveTree, { ...opts, _write: true }))
142
+ engineMod.apply(liveGuarded, root, rules, data, opts)
143
+ liveGuarded.assertClean()
52
144
  }
53
145
 
54
- // extractData() → document + autodetect
55
- // extractData(el) → el + autodetect
146
+ function exposeWriteError(error) {
147
+ if (!(error instanceof Error)) return error
148
+ const code = error.name || 'Error'
149
+ try {
150
+ error.code = code
151
+ } catch {
152
+ Object.defineProperty(error, 'code', { value: code, configurable: true, enumerable: true })
153
+ }
154
+ if (error instanceof engineMod.errors.WriteRefused) {
155
+ error.details = error.refusals
156
+ } else if (error instanceof engineMod.errors.WriteRejected) {
157
+ error.details = {
158
+ unknownKeys: error.unknownKeys,
159
+ unmatched: error.unmatched,
160
+ }
161
+ } else if (error instanceof engineMod.errors.ShapeMismatch) {
162
+ error.details = error.mismatches
163
+ } else if (Array.isArray(error.path)) {
164
+ error.details = { path: error.path }
165
+ } else if (typeof error.target === 'string') {
166
+ error.details = { target: error.target }
167
+ } else if (error.token !== undefined) {
168
+ error.details = { token: error.token }
169
+ } else if (error.version !== undefined) {
170
+ error.details = { version: error.version }
171
+ } else {
172
+ error.details = {}
173
+ }
174
+ return error
175
+ }
176
+
177
+ // extractData() → document + api rules tag
178
+ // extractData(el) → el + api rules tag
56
179
  // extractData('api' | {title:'h1'}) → document + named/inline rules
57
180
  // extractData(el, 'api' | {...}) → explicit root + source
58
181
  // One-shot read; returns the extracted data.
59
182
  export function extractData(a, b) {
60
183
  const root = isNode(a) ? a : document
61
184
  const source = isNode(a) ? b : a
62
- if (source === undefined) return engineMod.extract(createDomAdapter(root), root, autodetect(root))
185
+ if (source === undefined) return engineMod.extract(createDomAdapter(root), root, defaultRules(root))
63
186
  return engine.bind(root, source).get()
64
187
  }
65
188
 
66
- // applyData(root, data, source?) — writes `data` INTO the live DOM under `root`,
67
- // using a named/inline `source` or (when omitted) the page's single rules tag.
68
- // MUTATES the DOM and returns `root`.
189
+ // applyData(root, data, source?) validates the complete write on a detached
190
+ // clone, then repeats it against the live nodes so their identities survive.
69
191
  export function applyData(root, data, source) {
70
- if (!isNode(root)) {
71
- throw new Error('hyper-html-api: applyData(root, data, source?) needs a DOM root as the first argument.')
192
+ try {
193
+ if (!isNode(root)) {
194
+ throw new Error('hyper-html-api: applyData(root, data, source?) needs a DOM root as the first argument.')
195
+ }
196
+ const rules = source === undefined ? defaultRules(root) : engine.bind(root, source).rules
197
+ guardedApply(root, rules, data)
198
+ } catch (error) {
199
+ throw exposeWriteError(error)
72
200
  }
73
- if (source === undefined) engineMod.apply(createDomAdapter(root), root, autodetect(root), data)
74
- else engine.bind(root, source).set(data)
75
201
  return root
76
202
  }
@@ -7,9 +7,9 @@ const UNSUPPORTED_SELECTOR = /:(?:focus(?:-within|-visible)?|hover|active|visite
7
7
  function copyControlState(source, copy) {
8
8
  if (!/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(source.tagName || '')) return
9
9
  const type = (source.getAttribute?.('type') || '').toLowerCase()
10
- if ('value' in source && 'value' in copy && source.tagName !== 'OPTION' && type !== 'checkbox' && type !== 'radio') copy.value = source.value
11
- if ('checked' in source && 'checked' in copy) copy.checked = source.checked
12
- if ('selected' in source && 'selected' in copy) copy.selected = source.selected
10
+ if ('value' in source && 'value' in copy && source.tagName !== 'OPTION' && type !== 'checkbox' && type !== 'radio' && type !== 'file') copy.value = source.value
11
+ if (source.tagName === 'INPUT' && (type === 'checkbox' || type === 'radio')) copy.checked = source.checked
12
+ if (source.tagName === 'OPTION') copy.selected = source.selected
13
13
  if (source.tagName === 'SELECT') {
14
14
  for (let i = 0; i < source.options.length; i++) copy.options[i].selected = source.options[i].selected
15
15
  }
@@ -29,8 +29,10 @@ function matchesWithin(node, selector, boundary, inherit) {
29
29
 
30
30
  function importTree(source, targetDocument, capability, capabilityMatch, exclude, boundary, inherit, maps) {
31
31
  if (source.nodeType === 1 && (
32
- (inherit ? hasCapability(source, capability) : matchesWithin(source, capabilityMatch, boundary, false)) ||
33
- (exclude && matchesWithin(source, exclude, boundary, inherit))
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)))
34
36
  )) return null
35
37
  const copy = targetDocument.importNode(source, false)
36
38
  maps.cloneToLive.set(copy, source)
package/src/write.js CHANGED
@@ -4,19 +4,29 @@ import { findRulesIn } from './engine/rules-tag.js'
4
4
  import { guardAdapter } from './engine/write-policy.js'
5
5
  import { planWrite } from './engine/write-plan.js'
6
6
  import { trackAdapter, spliceDocument } from './engine/splice.js'
7
- import { NoRulesTag, WriteRejected } from './engine/errors.js'
7
+ import { NoRulesTag, RulesParseError, WriteRejected } from './engine/errors.js'
8
8
 
9
- // Applies a JSON body to a document's source through the document's own rules
10
- // tag, under the content-only policy. `load` is cheerio.load, passed in so this
11
- // package keeps cheerio out of its browser bundles. Returns the new source and
12
- // whether anything changed. Throws NoRulesTag, WriteRejected, WriteRefused,
13
- // ShapeMismatch or EmptyListInsert, always before producing any output.
14
- export function writeDocument(load, src, data, { token = 'api' } = {}) {
9
+ // Applies a JSON body to a document's source through caller-provided rules
10
+ // (options.rules) or the document's own rules tag, under the content-only
11
+ // policy. `load` is cheerio.load, passed in so this package keeps cheerio out
12
+ // of its browser bundles. Returns the new source and whether anything changed.
13
+ // Throws NoRulesTag, RulesParseError, WriteRejected, WriteRefused, ShapeMismatch
14
+ // or EmptyListInsert, always before producing any output.
15
+ export function writeDocument(load, src, data, options = {}) {
16
+ const { token = 'api' } = options
15
17
  const $ = load(src, { sourceCodeLocationInfo: true })
16
18
  const root = $.root()
17
- const found = findRulesIn(cheerioAdapter, root, token)
18
- if (!found) throw new NoRulesTag(token)
19
- const { rules } = found
19
+ let rules
20
+ if (Object.prototype.hasOwnProperty.call(options, 'rules')) {
21
+ rules = options.rules
22
+ if (rules === null || !['string', 'object'].includes(typeof rules)) {
23
+ throw new RulesParseError('Invalid extraction rules: expected a selector, array, or object.')
24
+ }
25
+ } else {
26
+ const found = findRulesIn(cheerioAdapter, root, token)
27
+ if (!found) throw new NoRulesTag(token)
28
+ rules = found.rules
29
+ }
20
30
  const plan = planWrite(cheerioAdapter, root, rules, data)
21
31
  if (plan.unknownKeys.length || plan.unmatched.length) throw new WriteRejected(plan.unknownKeys, plan.unmatched)
22
32
  const tracker = trackAdapter(cheerioAdapter)