@gramlot/gramlot 0.3.35 → 0.3.36

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.
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @module
8
8
  */
9
- var tp=Object.defineProperty;var ee=(o,e)=>{for(var t in e)tp(o,t,{get:e[t],enumerable:!0})};var ai=new WeakMap,Iu=`
9
+ var tp=Object.defineProperty;var ee=(o,e)=>{for(var t in e)tp(o,t,{get:e[t],enumerable:!0})};var li=new WeakMap,Iu=`
10
10
  --gramlot-toolbar-thickness:56px; --gramlot-toolbar-control-size:44px; --gramlot-toolbar-padding:6px;
11
11
  `,Cu=`
12
12
  box-sizing:border-box; height:100dvh; min-height:0; overflow:auto;
@@ -22,17 +22,17 @@ var tp=Object.defineProperty;var ee=(o,e)=>{for(var t in e)tp(o,t,{get:e[t],enum
22
22
  :root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"]{${Cu}}
23
23
  :root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"] > *{max-height:100%;}
24
24
  }
25
- `,Cn=class o{static install({document:e,root:t}){return ai.has(t)||ai.set(t,new o(e,t)),ai.get(t)}constructor(e,t){this.document=e,this.root=t,this.releases=[],this.closed=!1,t.setAttribute("data-gramlot-viewport",e.defaultView.parent===e.defaultView?"root":"child");let r=e.querySelector('meta[name="viewport"]');r||(r=e.createElement("meta"),r.name="viewport",r.content="width=device-width,initial-scale=1",e.head.append(r));let n=r.content.split(",").map(i=>i.trim()).filter(i=>!i.startsWith("viewport-fit="));r.content=[...n,"viewport-fit=cover"].join(","),this.style=e.createElement("style"),this.style.textContent=rp,e.head.append(this.style)}subscribeAppearance(e){let t=this.document.defaultView,r=t.matchMedia("(prefers-color-scheme: dark)"),n=()=>{let a=t.getComputedStyle(this.document.documentElement).colorScheme;e({dark:a==="dark"||!["light","dark"].includes(a)&&r.matches})},i=new t.MutationObserver(n);i.observe(this.document.documentElement,{attributes:!0,attributeFilter:["data-theme","style","class"]}),r.addEventListener("change",n),n();let s=()=>{i.disconnect(),r.removeEventListener("change",n)};return this.releases.push(s),s}dispose(){if(!this.closed){this.closed=!0;for(let e of this.releases)e();this.style.remove(),this.root.removeAttribute("data-gramlot-viewport"),ai.delete(this.root)}}};var Dn=class{#e=new Map;registerGroup(e,t={}){if(typeof e!="string"||!e||e.includes(":"))throw new TypeError("Extension command namespace must be nonempty and unqualified");if(this.#e.has(e))throw new Error(`Duplicate command namespace: ${e}`);if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["author","description"].includes(n))||Object.values(t).some(n=>typeof n!="string"))throw new TypeError(`Invalid command group metadata: ${e}`);let r=new Map;return this.#e.set(e,{metadata:{...t},commands:r}),Object.freeze({register(n,i){if(typeof n!="string"||!n||n.includes(":"))throw new TypeError("Invalid command name");if(r.has(n))throw new Error(`Duplicate command: ${e}:${n}`);if(!i||typeof i!="object"||Array.isArray(i)||!Object.hasOwn(i,"label")||!Object.hasOwn(i,"publish")||Object.keys(i).some(s=>!["label","publish","icon","iconSrc","tooltip"].includes(s))||Object.values(i).some(s=>typeof s!="string"))throw new TypeError(`Invalid command definition: ${e}:${n}`);r.set(n,Object.freeze({...i}))}})}get(e){let t=e.indexOf(":");return this.#e.get(e.slice(0,t))?.commands.get(e.slice(t+1))}toDocument(){return{document_format:{name:"gramlot_commands",version:"1.0"},groups:Object.fromEntries([...this.#e].map(([e,{metadata:t,commands:r}])=>[e,{...t,commands:Object.fromEntries(r)}]))}}};var Nn=class{constructor(e,{fetcher:t=globalThis.fetch?.bind(globalThis),closeUrl:r="/gramlot/close",navigator:n=globalThis.navigator,XMLHttpRequest:i=globalThis.XMLHttpRequest}={}){this.rpcUrl=e,this.fetcher=t,this.closeUrl=r,this.navigator=n,this.XMLHttpRequest=i}get supportsCallSync(){return!0}async call(e,t){let r=await this.fetcher(this.rpcUrl,{method:"POST",credentials:"same-origin",signal:t,headers:{"Content-Type":"application/json"},body:e});if(r.status!==200)throw new Error(`rpc failed: HTTP ${r.status}`);return r.text()}callSync(e){let t=new this.XMLHttpRequest;if(t.open("POST",this.rpcUrl,!1),t.setRequestHeader("Content-Type","application/json"),t.send(e),t.status!==200)throw new Error(`rpc failed: HTTP ${t.status}`);return t.responseText}close(e){if(typeof this.closeUrl!="string"||!this.closeUrl.trim())throw new TypeError("HttpTransport.closeUrl must be nonempty text");if(typeof this.navigator?.sendBeacon!="function")throw new TypeError("HttpTransport requires navigator.sendBeacon");let t=new Blob([JSON.stringify({pageId:e})],{type:"application/json"});try{this.navigator.sendBeacon(this.closeUrl,t)}catch(r){if(r.name==="TypeError")throw r}}dispose(){}};var li=class{constructor(e,t){this.channel=e,this.closeTransport=t}get supportsCallSync(){return!1}call(e,t){return this.channel.call(e,t)}close(e,t){this.closeTransport.close(e,t)}dispose(){this.closeTransport.dispose()}};var Rt=class{createTransport({rpcUrl:e,closeUrl:t,document:r,channel:n=null}){let i=r.defaultView,s=new Nn(e,{closeUrl:t,navigator:i.navigator,XMLHttpRequest:i.XMLHttpRequest});return n===null?s:new li(n,s)}};var Ua={};ee(Ua,{CONTENT_TYPES:()=>za,__version__:()=>Um,createDecimal:()=>Ye,fetchTytx:()=>Ai,fromTytx:()=>j,fromTytxIter:()=>La,getDateType:()=>bt,getDecimalLibrary:()=>Zr,getRegisteredType:()=>Kr,getSubtypeDict:()=>Pe,getTransport:()=>qa,isDecimal:()=>U,registerClass:()=>yd,registerSubtype:()=>vd,registerType:()=>Vn,setDecimalLibrary:()=>_d,setSubtypeDict:()=>wt,toTytx:()=>R,toTytxIter:()=>dd});var xa={};ee(xa,{Decimal:()=>Wr,default:()=>va});var Ur=9e15,Mt=1e9,ga="0123456789abcdef",di="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",fi="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",ba={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Ur,maxE:Ur,crypto:!1},$u,gt,q=!0,pi="[DecimalError] ",Bt=pi+"Invalid argument: ",Ru=pi+"Precision limit exceeded",ju=pi+"crypto unavailable",Pu="[object Decimal]",Ee=Math.floor,pe=Math.pow,np=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,op=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,ip=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Bu=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Ge=1e7,M=7,sp=9007199254740991,ap=di.length-1,wa=fi.length-1,A={toStringTag:Pu};A.absoluteValue=A.abs=function(){var o=new this.constructor(this);return o.s<0&&(o.s=1),B(o)};A.ceil=function(){return B(new this.constructor(this),this.e+1,2)};A.clampedTo=A.clamp=function(o,e){var t,r=this,n=r.constructor;if(o=new n(o),e=new n(e),!o.s||!e.s)return new n(NaN);if(o.gt(e))throw Error(Bt+e);return t=r.cmp(o),t<0?o:r.cmp(e)>0?e:new n(r)};A.comparedTo=A.cmp=function(o){var e,t,r,n,i=this,s=i.d,a=(o=new i.constructor(o)).d,l=i.s,c=o.s;if(!s||!a)return!l||!c?NaN:l!==c?l:s===a?0:!s^l<0?1:-1;if(!s[0]||!a[0])return s[0]?l:a[0]?-c:0;if(l!==c)return l;if(i.e!==o.e)return i.e>o.e^l<0?1:-1;for(r=s.length,n=a.length,e=0,t=r<n?r:n;e<t;++e)if(s[e]!==a[e])return s[e]>a[e]^l<0?1:-1;return r===n?0:r>n^l<0?1:-1};A.cosine=A.cos=function(){var o,e,t=this,r=t.constructor;return t.d?t.d[0]?(o=r.precision,e=r.rounding,r.precision=o+Math.max(t.e,t.sd())+M,r.rounding=1,t=lp(r,qu(r,t)),r.precision=o,r.rounding=e,B(gt==2||gt==3?t.neg():t,o,e,!0)):new r(1):new r(NaN)};A.cubeRoot=A.cbrt=function(){var o,e,t,r,n,i,s,a,l,c,u=this,d=u.constructor;if(!u.isFinite()||u.isZero())return new d(u);for(q=!1,i=u.s*pe(u.s*u,1/3),!i||Math.abs(i)==1/0?(t=ye(u.d),o=u.e,(i=(o-t.length+1)%3)&&(t+=i==1||i==-2?"0":"00"),i=pe(t,1/3),o=Ee((o+1)/3)-(o%3==(o<0?-1:2)),i==1/0?t="5e"+o:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+o),r=new d(t),r.s=u.s):r=new d(i.toString()),s=(o=d.precision)+3;;)if(a=r,l=a.times(a).times(a),c=l.plus(u),r=re(c.plus(u).times(a),c.plus(l),s+2,1),ye(a.d).slice(0,s)===(t=ye(r.d)).slice(0,s))if(t=t.slice(s-3,s+1),t=="9999"||!n&&t=="4999"){if(!n&&(B(a,o+1,0),a.times(a).times(a).eq(u))){r=a;break}s+=4,n=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(B(r,o+1,1),e=!r.times(r).times(r).eq(u));break}return q=!0,B(r,o,d.rounding,e)};A.decimalPlaces=A.dp=function(){var o,e=this.d,t=NaN;if(e){if(o=e.length-1,t=(o-Ee(this.e/M))*M,o=e[o],o)for(;o%10==0;o/=10)t--;t<0&&(t=0)}return t};A.dividedBy=A.div=function(o){return re(this,new this.constructor(o))};A.dividedToIntegerBy=A.divToInt=function(o){var e=this,t=e.constructor;return B(re(e,new t(o),0,1,1),t.precision,t.rounding)};A.equals=A.eq=function(o){return this.cmp(o)===0};A.floor=function(){return B(new this.constructor(this),this.e+1,3)};A.greaterThan=A.gt=function(o){return this.cmp(o)>0};A.greaterThanOrEqualTo=A.gte=function(o){var e=this.cmp(o);return e==1||e===0};A.hyperbolicCosine=A.cosh=function(){var o,e,t,r,n,i=this,s=i.constructor,a=new s(1);if(!i.isFinite())return new s(i.s?1/0:NaN);if(i.isZero())return a;t=s.precision,r=s.rounding,s.precision=t+Math.max(i.e,i.sd())+4,s.rounding=1,n=i.d.length,n<32?(o=Math.ceil(n/3),e=(1/gi(4,o)).toString()):(o=16,e="2.3283064365386962890625e-10"),i=Vr(s,1,i.times(e),new s(1),!0);for(var l,c=o,u=new s(8);c--;)l=i.times(i),i=a.minus(l.times(u.minus(l.times(u))));return B(i,s.precision=t,s.rounding=r,!0)};A.hyperbolicSine=A.sinh=function(){var o,e,t,r,n=this,i=n.constructor;if(!n.isFinite()||n.isZero())return new i(n);if(e=i.precision,t=i.rounding,i.precision=e+Math.max(n.e,n.sd())+4,i.rounding=1,r=n.d.length,r<3)n=Vr(i,2,n,n,!0);else{o=1.4*Math.sqrt(r),o=o>16?16:o|0,n=n.times(1/gi(5,o)),n=Vr(i,2,n,n,!0);for(var s,a=new i(5),l=new i(16),c=new i(20);o--;)s=n.times(n),n=n.times(a.plus(s.times(l.times(s).plus(c))))}return i.precision=e,i.rounding=t,B(n,e,t,!0)};A.hyperbolicTangent=A.tanh=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+7,r.rounding=1,re(t.sinh(),t.cosh(),r.precision=o,r.rounding=e)):new r(t.s)};A.inverseCosine=A.acos=function(){var o=this,e=o.constructor,t=o.abs().cmp(1),r=e.precision,n=e.rounding;return t!==-1?t===0?o.isNeg()?it(e,r,n):new e(0):new e(NaN):o.isZero()?it(e,r+4,n).times(.5):(e.precision=r+6,e.rounding=1,o=new e(1).minus(o).div(o.plus(1)).sqrt().atan(),e.precision=r,e.rounding=n,o.times(2))};A.inverseHyperbolicCosine=A.acosh=function(){var o,e,t=this,r=t.constructor;return t.lte(1)?new r(t.eq(1)?0:NaN):t.isFinite()?(o=r.precision,e=r.rounding,r.precision=o+Math.max(Math.abs(t.e),t.sd())+4,r.rounding=1,q=!1,t=t.times(t).minus(1).sqrt().plus(t),q=!0,r.precision=o,r.rounding=e,t.ln()):new r(t)};A.inverseHyperbolicSine=A.asinh=function(){var o,e,t=this,r=t.constructor;return!t.isFinite()||t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+2*Math.max(Math.abs(t.e),t.sd())+6,r.rounding=1,q=!1,t=t.times(t).plus(1).sqrt().plus(t),q=!0,r.precision=o,r.rounding=e,t.ln())};A.inverseHyperbolicTangent=A.atanh=function(){var o,e,t,r,n=this,i=n.constructor;return n.isFinite()?n.e>=0?new i(n.abs().eq(1)?n.s/0:n.isZero()?n:NaN):(o=i.precision,e=i.rounding,r=n.sd(),Math.max(r,o)<2*-n.e-1?B(new i(n),o,e,!0):(i.precision=t=r-n.e,n=re(n.plus(1),new i(1).minus(n),t+o,1),i.precision=o+4,i.rounding=1,n=n.ln(),i.precision=o,i.rounding=e,n.times(.5))):new i(NaN)};A.inverseSine=A.asin=function(){var o,e,t,r,n=this,i=n.constructor;return n.isZero()?new i(n):(e=n.abs().cmp(1),t=i.precision,r=i.rounding,e!==-1?e===0?(o=it(i,t+4,r).times(.5),o.s=n.s,o):new i(NaN):(i.precision=t+6,i.rounding=1,n=n.div(new i(1).minus(n.times(n)).sqrt().plus(1)).atan(),i.precision=t,i.rounding=r,n.times(2)))};A.inverseTangent=A.atan=function(){var o,e,t,r,n,i,s,a,l,c=this,u=c.constructor,d=u.precision,f=u.rounding;if(c.isFinite()){if(c.isZero())return new u(c);if(c.abs().eq(1)&&d+4<=wa)return s=it(u,d+4,f).times(.25),s.s=c.s,s}else{if(!c.s)return new u(NaN);if(d+4<=wa)return s=it(u,d+4,f).times(.5),s.s=c.s,s}for(u.precision=a=d+10,u.rounding=1,t=Math.min(28,a/M+2|0),o=t;o;--o)c=c.div(c.times(c).plus(1).sqrt().plus(1));for(q=!1,e=Math.ceil(a/M),r=1,l=c.times(c),s=new u(c),n=c;o!==-1;)if(n=n.times(l),i=s.minus(n.div(r+=2)),n=n.times(l),s=i.plus(n.div(r+=2)),s.d[e]!==void 0)for(o=e;s.d[o]===i.d[o]&&o--;);return t&&(s=s.times(2<<t-1)),q=!0,B(s,u.precision=d,u.rounding=f,!0)};A.isFinite=function(){return!!this.d};A.isInteger=A.isInt=function(){return!!this.d&&Ee(this.e/M)>this.d.length-2};A.isNaN=function(){return!this.s};A.isNegative=A.isNeg=function(){return this.s<0};A.isPositive=A.isPos=function(){return this.s>0};A.isZero=function(){return!!this.d&&this.d[0]===0};A.lessThan=A.lt=function(o){return this.cmp(o)<0};A.lessThanOrEqualTo=A.lte=function(o){return this.cmp(o)<1};A.logarithm=A.log=function(o){var e,t,r,n,i,s,a,l,c=this,u=c.constructor,d=u.precision,f=u.rounding,h=5;if(o==null)o=new u(10),e=!0;else{if(o=new u(o),t=o.d,o.s<0||!t||!t[0]||o.eq(1))return new u(NaN);e=o.eq(10)}if(t=c.d,c.s<0||!t||!t[0]||c.eq(1))return new u(t&&!t[0]?-1/0:c.s!=1?NaN:t?0:1/0);if(e)if(t.length>1)i=!0;else{for(n=t[0];n%10===0;)n/=10;i=n!==1}if(q=!1,a=d+h,s=Pt(c,a),r=e?hi(u,a+10):Pt(o,a),l=re(s,r,a,1),On(l.d,n=d,f))do if(a+=10,s=Pt(c,a),r=e?hi(u,a+10):Pt(o,a),l=re(s,r,a,1),!i){+ye(l.d).slice(n+1,n+15)+1==1e14&&(l=B(l,d+1,0));break}while(On(l.d,n+=10,f));return q=!0,B(l,d,f)};A.minus=A.sub=function(o){var e,t,r,n,i,s,a,l,c,u,d,f,h=this,p=h.constructor;if(o=new p(o),!h.d||!o.d)return!h.s||!o.s?o=new p(NaN):h.d?o.s=-o.s:o=new p(o.d||h.s!==o.s?h:NaN),o;if(h.s!=o.s)return o.s=-o.s,h.plus(o);if(c=h.d,f=o.d,a=p.precision,l=p.rounding,!c[0]||!f[0]){if(f[0])o.s=-o.s;else if(c[0])o=new p(h);else return new p(l===3?-0:0);return q?B(o,a,l):o}if(t=Ee(o.e/M),u=Ee(h.e/M),c=c.slice(),i=u-t,i){for(d=i<0,d?(e=c,i=-i,s=f.length):(e=f,t=u,s=c.length),r=Math.max(Math.ceil(a/M),s)+2,i>r&&(i=r,e.length=1),e.reverse(),r=i;r--;)e.push(0);e.reverse()}else{for(r=c.length,s=f.length,d=r<s,d&&(s=r),r=0;r<s;r++)if(c[r]!=f[r]){d=c[r]<f[r];break}i=0}for(d&&(e=c,c=f,f=e,o.s=-o.s),s=c.length,r=f.length-s;r>0;--r)c[s++]=0;for(r=f.length;r>i;){if(c[--r]<f[r]){for(n=r;n&&c[--n]===0;)c[n]=Ge-1;--c[n],c[r]+=Ge}c[r]-=f[r]}for(;c[--s]===0;)c.pop();for(;c[0]===0;c.shift())--t;return c[0]?(o.d=c,o.e=mi(c,t),q?B(o,a,l):o):new p(l===3?-0:0)};A.modulo=A.mod=function(o){var e,t=this,r=t.constructor;return o=new r(o),!t.d||!o.s||o.d&&!o.d[0]?new r(NaN):!o.d||t.d&&!t.d[0]?B(new r(t),r.precision,r.rounding):(q=!1,r.modulo==9?(e=re(t,o.abs(),0,3,1),e.s*=o.s):e=re(t,o,0,r.modulo,1),e=e.times(o),q=!0,t.minus(e))};A.naturalExponential=A.exp=function(){return _a(this)};A.naturalLogarithm=A.ln=function(){return Pt(this)};A.negated=A.neg=function(){var o=new this.constructor(this);return o.s=-o.s,B(o)};A.plus=A.add=function(o){var e,t,r,n,i,s,a,l,c,u,d=this,f=d.constructor;if(o=new f(o),!d.d||!o.d)return!d.s||!o.s?o=new f(NaN):d.d||(o=new f(o.d||d.s===o.s?d:NaN)),o;if(d.s!=o.s)return o.s=-o.s,d.minus(o);if(c=d.d,u=o.d,a=f.precision,l=f.rounding,!c[0]||!u[0])return u[0]||(o=new f(d)),q?B(o,a,l):o;if(i=Ee(d.e/M),r=Ee(o.e/M),c=c.slice(),n=i-r,n){for(n<0?(t=c,n=-n,s=u.length):(t=u,r=i,s=c.length),i=Math.ceil(a/M),s=i>s?i+1:s+1,n>s&&(n=s,t.length=1),t.reverse();n--;)t.push(0);t.reverse()}for(s=c.length,n=u.length,s-n<0&&(n=s,t=u,u=c,c=t),e=0;n;)e=(c[--n]=c[n]+u[n]+e)/Ge|0,c[n]%=Ge;for(e&&(c.unshift(e),++r),s=c.length;c[--s]==0;)c.pop();return o.d=c,o.e=mi(c,r),q?B(o,a,l):o};A.precision=A.sd=function(o){var e,t=this;if(o!==void 0&&o!==!!o&&o!==1&&o!==0)throw Error(Bt+o);return t.d?(e=Mu(t.d),o&&t.e+1>e&&(e=t.e+1)):e=NaN,e};A.round=function(){var o=this,e=o.constructor;return B(new e(o),o.e+1,e.rounding)};A.sine=A.sin=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+Math.max(t.e,t.sd())+M,r.rounding=1,t=up(r,qu(r,t)),r.precision=o,r.rounding=e,B(gt>2?t.neg():t,o,e,!0)):new r(NaN)};A.squareRoot=A.sqrt=function(){var o,e,t,r,n,i,s=this,a=s.d,l=s.e,c=s.s,u=s.constructor;if(c!==1||!a||!a[0])return new u(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);for(q=!1,c=Math.sqrt(+s),c==0||c==1/0?(e=ye(a),(e.length+l)%2==0&&(e+="0"),c=Math.sqrt(e),l=Ee((l+1)/2)-(l<0||l%2),c==1/0?e="5e"+l:(e=c.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),r=new u(e)):r=new u(c.toString()),t=(l=u.precision)+3;;)if(i=r,r=i.plus(re(s,i,t+2,1)).times(.5),ye(i.d).slice(0,t)===(e=ye(r.d)).slice(0,t))if(e=e.slice(t-3,t+1),e=="9999"||!n&&e=="4999"){if(!n&&(B(i,l+1,0),i.times(i).eq(s))){r=i;break}t+=4,n=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(B(r,l+1,1),o=!r.times(r).eq(s));break}return q=!0,B(r,l,u.rounding,o)};A.tangent=A.tan=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+10,r.rounding=1,t=t.sin(),t.s=1,t=re(t,new r(1).minus(t.times(t)).sqrt(),o+10,0),r.precision=o,r.rounding=e,B(gt==2||gt==4?t.neg():t,o,e,!0)):new r(NaN)};A.times=A.mul=function(o){var e,t,r,n,i,s,a,l,c,u=this,d=u.constructor,f=u.d,h=(o=new d(o)).d;if(o.s*=u.s,!f||!f[0]||!h||!h[0])return new d(!o.s||f&&!f[0]&&!h||h&&!h[0]&&!f?NaN:!f||!h?o.s/0:o.s*0);for(t=Ee(u.e/M)+Ee(o.e/M),l=f.length,c=h.length,l<c&&(i=f,f=h,h=i,s=l,l=c,c=s),i=[],s=l+c,r=s;r--;)i.push(0);for(r=c;--r>=0;){for(e=0,n=l+r;n>r;)a=i[n]+h[r]*f[n-r-1]+e,i[n--]=a%Ge|0,e=a/Ge|0;i[n]=(i[n]+e)%Ge|0}for(;!i[--s];)i.pop();return e?++t:i.shift(),o.d=i,o.e=mi(i,t),q?B(o,d.precision,d.rounding):o};A.toBinary=function(o,e){return ya(this,2,o,e)};A.toDecimalPlaces=A.toDP=function(o,e){var t=this,r=t.constructor;return t=new r(t),o===void 0?t:(je(o,0,Mt),e===void 0?e=r.rounding:je(e,0,8),B(t,o+t.e+1,e))};A.toExponential=function(o,e){var t,r=this,n=r.constructor;return o===void 0?t=st(r,!0):(je(o,0,Mt),e===void 0?e=n.rounding:je(e,0,8),r=B(new n(r),o+1,e),t=st(r,!0,o+1)),r.isNeg()&&!r.isZero()?"-"+t:t};A.toFixed=function(o,e){var t,r,n=this,i=n.constructor;return o===void 0?t=st(n):(je(o,0,Mt),e===void 0?e=i.rounding:je(e,0,8),r=B(new i(n),o+n.e+1,e),t=st(r,!1,o+r.e+1)),n.isNeg()&&!n.isZero()?"-"+t:t};A.toFraction=function(o){var e,t,r,n,i,s,a,l,c,u,d,f,h=this,p=h.d,m=h.constructor;if(!p)return new m(h);if(c=t=new m(1),r=l=new m(0),e=new m(r),i=e.e=Mu(p)-h.e-1,s=i%M,e.d[0]=pe(10,s<0?M+s:s),o==null)o=i>0?e:c;else{if(a=new m(o),!a.isInt()||a.lt(c))throw Error(Bt+a);o=a.gt(e)?i>0?e:c:a}for(q=!1,a=new m(ye(p)),u=m.precision,m.precision=i=p.length*M*2;d=re(a,e,0,1,1),n=t.plus(d.times(r)),n.cmp(o)!=1;)t=r,r=n,n=c,c=l.plus(d.times(n)),l=n,n=e,e=a.minus(d.times(n)),a=n;return n=re(o.minus(t),r,0,1,1),l=l.plus(n.times(c)),t=t.plus(n.times(r)),l.s=c.s=h.s,f=re(c,r,i,1).minus(h).abs().cmp(re(l,t,i,1).minus(h).abs())<1?[c,r]:[l,t],m.precision=u,q=!0,f};A.toHexadecimal=A.toHex=function(o,e){return ya(this,16,o,e)};A.toNearest=function(o,e){var t=this,r=t.constructor;if(t=new r(t),o==null){if(!t.d)return t;o=new r(1),e=r.rounding}else{if(o=new r(o),e===void 0?e=r.rounding:je(e,0,8),!t.d)return o.s?t:o;if(!o.d)return o.s&&(o.s=t.s),o}return o.d[0]?(q=!1,t=re(t,o,0,e,1).times(o),q=!0,B(t)):(o.s=t.s,t=o),t};A.toNumber=function(){return+this};A.toOctal=function(o,e){return ya(this,8,o,e)};A.toPower=A.pow=function(o){var e,t,r,n,i,s,a=this,l=a.constructor,c=+(o=new l(o));if(!a.d||!o.d||!a.d[0]||!o.d[0])return new l(pe(+a,c));if(a=new l(a),a.eq(1))return a;if(r=l.precision,i=l.rounding,o.eq(1))return B(a,r,i);if(e=Ee(o.e/M),e>=o.d.length-1&&(t=c<0?-c:c)<=sp)return n=Lu(l,a,t,r),o.s<0?new l(1).div(n):B(n,r,i);if(s=a.s,s<0){if(e<o.d.length-1)return new l(NaN);if((o.d[e]&1)==0&&(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return t=pe(+a,c),e=t==0||!isFinite(t)?Ee(c*(Math.log("0."+ye(a.d))/Math.LN10+a.e+1)):new l(t+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?s/0:0):(q=!1,l.rounding=a.s=1,t=Math.min(12,(e+"").length),n=_a(o.times(Pt(a,r+t)),r),n.d&&(n=B(n,r+5,1),On(n.d,r,i)&&(e=r+10,n=B(_a(o.times(Pt(a,e+t)),e),e+5,1),+ye(n.d).slice(r+1,r+15)+1==1e14&&(n=B(n,r+1,0)))),n.s=s,q=!0,l.rounding=i,B(n,r,i))};A.toPrecision=function(o,e){var t,r=this,n=r.constructor;return o===void 0?t=st(r,r.e<=n.toExpNeg||r.e>=n.toExpPos):(je(o,1,Mt),e===void 0?e=n.rounding:je(e,0,8),r=B(new n(r),o,e),t=st(r,o<=r.e||r.e<=n.toExpNeg,o)),r.isNeg()&&!r.isZero()?"-"+t:t};A.toSignificantDigits=A.toSD=function(o,e){var t=this,r=t.constructor;return o===void 0?(o=r.precision,e=r.rounding):(je(o,1,Mt),e===void 0?e=r.rounding:je(e,0,8)),B(new r(t),o,e)};A.toString=function(){var o=this,e=o.constructor,t=st(o,o.e<=e.toExpNeg||o.e>=e.toExpPos);return o.isNeg()&&!o.isZero()?"-"+t:t};A.truncated=A.trunc=function(){return B(new this.constructor(this),this.e+1,1)};A.valueOf=A.toJSON=function(){var o=this,e=o.constructor,t=st(o,o.e<=e.toExpNeg||o.e>=e.toExpPos);return o.isNeg()?"-"+t:t};function ye(o){var e,t,r,n=o.length-1,i="",s=o[0];if(n>0){for(i+=s,e=1;e<n;e++)r=o[e]+"",t=M-r.length,t&&(i+=jt(t)),i+=r;s=o[e],r=s+"",t=M-r.length,t&&(i+=jt(t))}else if(s===0)return"0";for(;s%10===0;)s/=10;return i+s}function je(o,e,t){if(o!==~~o||o<e||o>t)throw Error(Bt+o)}function On(o,e,t,r){var n,i,s,a;for(i=o[0];i>=10;i/=10)--e;return--e<0?(e+=M,n=0):(n=Math.ceil((e+1)/M),e%=M),i=pe(10,M-e),a=o[n]%i|0,r==null?e<3?(e==0?a=a/100|0:e==1&&(a=a/10|0),s=t<4&&a==99999||t>3&&a==49999||a==5e4||a==0):s=(t<4&&a+1==i||t>3&&a+1==i/2)&&(o[n+1]/i/100|0)==pe(10,e-2)-1||(a==i/2||a==0)&&(o[n+1]/i/100|0)==0:e<4?(e==0?a=a/1e3|0:e==1?a=a/100|0:e==2&&(a=a/10|0),s=(r||t<4)&&a==9999||!r&&t>3&&a==4999):s=((r||t<4)&&a+1==i||!r&&t>3&&a+1==i/2)&&(o[n+1]/i/1e3|0)==pe(10,e-3)-1,s}function ci(o,e,t){for(var r,n=[0],i,s=0,a=o.length;s<a;){for(i=n.length;i--;)n[i]*=e;for(n[0]+=ga.indexOf(o.charAt(s++)),r=0;r<n.length;r++)n[r]>t-1&&(n[r+1]===void 0&&(n[r+1]=0),n[r+1]+=n[r]/t|0,n[r]%=t)}return n.reverse()}function lp(o,e){var t,r,n;if(e.isZero())return e;r=e.d.length,r<32?(t=Math.ceil(r/3),n=(1/gi(4,t)).toString()):(t=16,n="2.3283064365386962890625e-10"),o.precision+=t,e=Vr(o,1,e.times(n),new o(1));for(var i=t;i--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return o.precision-=t,e}var re=(function(){function o(r,n,i){var s,a=0,l=r.length;for(r=r.slice();l--;)s=r[l]*n+a,r[l]=s%i|0,a=s/i|0;return a&&r.unshift(a),r}function e(r,n,i,s){var a,l;if(i!=s)l=i>s?1:-1;else for(a=l=0;a<i;a++)if(r[a]!=n[a]){l=r[a]>n[a]?1:-1;break}return l}function t(r,n,i,s){for(var a=0;i--;)r[i]-=a,a=r[i]<n[i]?1:0,r[i]=a*s+r[i]-n[i];for(;!r[0]&&r.length>1;)r.shift()}return function(r,n,i,s,a,l){var c,u,d,f,h,p,m,b,w,_,v,E,D,k,C,O,L,z,V,le,_e=r.constructor,ht=r.s==n.s?1:-1,ne=r.d,X=n.d;if(!ne||!ne[0]||!X||!X[0])return new _e(!r.s||!n.s||(ne?X&&ne[0]==X[0]:!X)?NaN:ne&&ne[0]==0||!X?ht*0:ht/0);for(l?(h=1,u=r.e-n.e):(l=Ge,h=M,u=Ee(r.e/h)-Ee(n.e/h)),V=X.length,L=ne.length,w=new _e(ht),_=w.d=[],d=0;X[d]==(ne[d]||0);d++);if(X[d]>(ne[d]||0)&&u--,i==null?(k=i=_e.precision,s=_e.rounding):a?k=i+(r.e-n.e)+1:k=i,k<0)_.push(1),p=!0;else{if(k=k/h+2|0,d=0,V==1){for(f=0,X=X[0],k++;(d<L||f)&&k--;d++)C=f*l+(ne[d]||0),_[d]=C/X|0,f=C%X|0;p=f||d<L}else{for(f=l/(X[0]+1)|0,f>1&&(X=o(X,f,l),ne=o(ne,f,l),V=X.length,L=ne.length),O=V,v=ne.slice(0,V),E=v.length;E<V;)v[E++]=0;le=X.slice(),le.unshift(0),z=X[0],X[1]>=l/2&&++z;do f=0,c=e(X,v,V,E),c<0?(D=v[0],V!=E&&(D=D*l+(v[1]||0)),f=D/z|0,f>1?(f>=l&&(f=l-1),m=o(X,f,l),b=m.length,E=v.length,c=e(m,v,b,E),c==1&&(f--,t(m,V<b?le:X,b,l))):(f==0&&(c=f=1),m=X.slice()),b=m.length,b<E&&m.unshift(0),t(v,m,E,l),c==-1&&(E=v.length,c=e(X,v,V,E),c<1&&(f++,t(v,V<E?le:X,E,l))),E=v.length):c===0&&(f++,v=[0]),_[d++]=f,c&&v[0]?v[E++]=ne[O]||0:(v=[ne[O]],E=1);while((O++<L||v[0]!==void 0)&&k--);p=v[0]!==void 0}_[0]||_.shift()}if(h==1)w.e=u,$u=p;else{for(d=1,f=_[0];f>=10;f/=10)d++;w.e=d+u*h-1,B(w,a?i+w.e+1:i,s,p)}return w}})();function B(o,e,t,r){var n,i,s,a,l,c,u,d,f,h=o.constructor;e:if(e!=null){if(d=o.d,!d)return o;for(n=1,a=d[0];a>=10;a/=10)n++;if(i=e-n,i<0)i+=M,s=e,u=d[f=0],l=u/pe(10,n-s-1)%10|0;else if(f=Math.ceil((i+1)/M),a=d.length,f>=a)if(r){for(;a++<=f;)d.push(0);u=l=0,n=1,i%=M,s=i-M+1}else break e;else{for(u=a=d[f],n=1;a>=10;a/=10)n++;i%=M,s=i-M+n,l=s<0?0:u/pe(10,n-s-1)%10|0}if(r=r||e<0||d[f+1]!==void 0||(s<0?u:u%pe(10,n-s-1)),c=t<4?(l||r)&&(t==0||t==(o.s<0?3:2)):l>5||l==5&&(t==4||r||t==6&&(i>0?s>0?u/pe(10,n-s):0:d[f-1])%10&1||t==(o.s<0?8:7)),e<1||!d[0])return d.length=0,c?(e-=o.e+1,d[0]=pe(10,(M-e%M)%M),o.e=-e||0):d[0]=o.e=0,o;if(i==0?(d.length=f,a=1,f--):(d.length=f+1,a=pe(10,M-i),d[f]=s>0?(u/pe(10,n-s)%pe(10,s)|0)*a:0),c)for(;;)if(f==0){for(i=1,s=d[0];s>=10;s/=10)i++;for(s=d[0]+=a,a=1;s>=10;s/=10)a++;i!=a&&(o.e++,d[0]==Ge&&(d[0]=1));break}else{if(d[f]+=a,d[f]!=Ge)break;d[f--]=0,a=1}for(i=d.length;d[--i]===0;)d.pop()}return q&&(o.e>h.maxE?(o.d=null,o.e=NaN):o.e<h.minE&&(o.e=0,o.d=[0])),o}function st(o,e,t){if(!o.isFinite())return zu(o);var r,n=o.e,i=ye(o.d),s=i.length;return e?(t&&(r=t-s)>0?i=i.charAt(0)+"."+i.slice(1)+jt(r):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(o.e<0?"e":"e+")+o.e):n<0?(i="0."+jt(-n-1)+i,t&&(r=t-s)>0&&(i+=jt(r))):n>=s?(i+=jt(n+1-s),t&&(r=t-n-1)>0&&(i=i+"."+jt(r))):((r=n+1)<s&&(i=i.slice(0,r)+"."+i.slice(r)),t&&(r=t-s)>0&&(n+1===s&&(i+="."),i+=jt(r))),i}function mi(o,e){var t=o[0];for(e*=M;t>=10;t/=10)e++;return e}function hi(o,e,t){if(e>ap)throw q=!0,t&&(o.precision=t),Error(Ru);return B(new o(di),e,1,!0)}function it(o,e,t){if(e>wa)throw Error(Ru);return B(new o(fi),e,t,!0)}function Mu(o){var e=o.length-1,t=e*M+1;if(e=o[e],e){for(;e%10==0;e/=10)t--;for(e=o[0];e>=10;e/=10)t++}return t}function jt(o){for(var e="";o--;)e+="0";return e}function Lu(o,e,t,r){var n,i=new o(1),s=Math.ceil(r/M+4);for(q=!1;;){if(t%2&&(i=i.times(e),Nu(i.d,s)&&(n=!0)),t=Ee(t/2),t===0){t=i.d.length-1,n&&i.d[t]===0&&++i.d[t];break}e=e.times(e),Nu(e.d,s)}return q=!0,i}function Du(o){return o.d[o.d.length-1]&1}function Fu(o,e,t){for(var r,n,i=new o(e[0]),s=0;++s<e.length;){if(n=new o(e[s]),!n.s){i=n;break}r=i.cmp(n),(r===t||r===0&&i.s===t)&&(i=n)}return i}function _a(o,e){var t,r,n,i,s,a,l,c=0,u=0,d=0,f=o.constructor,h=f.rounding,p=f.precision;if(!o.d||!o.d[0]||o.e>17)return new f(o.d?o.d[0]?o.s<0?0:1/0:1:o.s?o.s<0?0:o:NaN);for(e==null?(q=!1,l=p):l=e,a=new f(.03125);o.e>-2;)o=o.times(a),d+=5;for(r=Math.log(pe(2,d))/Math.LN10*2+5|0,l+=r,t=i=s=new f(1),f.precision=l;;){if(i=B(i.times(o),l,1),t=t.times(++u),a=s.plus(re(i,t,l,1)),ye(a.d).slice(0,l)===ye(s.d).slice(0,l)){for(n=d;n--;)s=B(s.times(s),l,1);if(e==null)if(c<3&&On(s.d,l-r,h,c))f.precision=l+=10,t=i=a=new f(1),u=0,c++;else return B(s,f.precision=p,h,q=!0);else return f.precision=p,s}s=a}}function Pt(o,e){var t,r,n,i,s,a,l,c,u,d,f,h=1,p=10,m=o,b=m.d,w=m.constructor,_=w.rounding,v=w.precision;if(m.s<0||!b||!b[0]||!m.e&&b[0]==1&&b.length==1)return new w(b&&!b[0]?-1/0:m.s!=1?NaN:b?0:m);if(e==null?(q=!1,u=v):u=e,w.precision=u+=p,t=ye(b),r=t.charAt(0),Math.abs(i=m.e)<15e14){for(;r<7&&r!=1||r==1&&t.charAt(1)>3;)m=m.times(o),t=ye(m.d),r=t.charAt(0),h++;i=m.e,r>1?(m=new w("0."+t),i++):m=new w(r+"."+t.slice(1))}else return c=hi(w,u+2,v).times(i+""),m=Pt(new w(r+"."+t.slice(1)),u-p).plus(c),w.precision=v,e==null?B(m,v,_,q=!0):m;for(d=m,l=s=m=re(m.minus(1),m.plus(1),u,1),f=B(m.times(m),u,1),n=3;;){if(s=B(s.times(f),u,1),c=l.plus(re(s,new w(n),u,1)),ye(c.d).slice(0,u)===ye(l.d).slice(0,u))if(l=l.times(2),i!==0&&(l=l.plus(hi(w,u+2,v).times(i+""))),l=re(l,new w(h),u,1),e==null)if(On(l.d,u-p,_,a))w.precision=u+=p,c=s=m=re(d.minus(1),d.plus(1),u,1),f=B(m.times(m),u,1),n=a=1;else return B(l,w.precision=v,_,q=!0);else return w.precision=v,l;l=c,n+=2}}function zu(o){return String(o.s*o.s/0)}function ui(o,e){var t,r,n;for((t=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(t<0&&(t=r),t+=+e.slice(r+1),e=e.substring(0,r)):t<0&&(t=e.length),r=0;e.charCodeAt(r)===48;r++);for(n=e.length;e.charCodeAt(n-1)===48;--n);if(e=e.slice(r,n),e){if(n-=r,o.e=t=t-r-1,o.d=[],r=(t+1)%M,t<0&&(r+=M),r<n){for(r&&o.d.push(+e.slice(0,r)),n-=M;r<n;)o.d.push(+e.slice(r,r+=M));e=e.slice(r),r=M-e.length}else r-=n;for(;r--;)e+="0";o.d.push(+e),q&&(o.e>o.constructor.maxE?(o.d=null,o.e=NaN):o.e<o.constructor.minE&&(o.e=0,o.d=[0]))}else o.e=0,o.d=[0];return o}function cp(o,e){var t,r,n,i,s,a,l,c,u;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Bu.test(e))return ui(o,e)}else if(e==="Infinity"||e==="NaN")return+e||(o.s=NaN),o.e=NaN,o.d=null,o;if(op.test(e))t=16,e=e.toLowerCase();else if(np.test(e))t=2;else if(ip.test(e))t=8;else throw Error(Bt+e);for(i=e.search(/p/i),i>0?(l=+e.slice(i+1),e=e.substring(2,i)):e=e.slice(2),i=e.indexOf("."),s=i>=0,r=o.constructor,s&&(e=e.replace(".",""),a=e.length,i=a-i,n=Lu(r,new r(t),i,i*2)),c=ci(e,t,Ge),u=c.length-1,i=u;c[i]===0;--i)c.pop();return i<0?new r(o.s*0):(o.e=mi(c,u),o.d=c,q=!1,s&&(o=re(o,n,a*4)),l&&(o=o.times(Math.abs(l)<54?pe(2,l):Wr.pow(2,l))),q=!0,o)}function up(o,e){var t,r=e.d.length;if(r<3)return e.isZero()?e:Vr(o,2,e,e);t=1.4*Math.sqrt(r),t=t>16?16:t|0,e=e.times(1/gi(5,t)),e=Vr(o,2,e,e);for(var n,i=new o(5),s=new o(16),a=new o(20);t--;)n=e.times(e),e=e.times(i.plus(n.times(s.times(n).minus(a))));return e}function Vr(o,e,t,r,n){var i,s,a,l,c=1,u=o.precision,d=Math.ceil(u/M);for(q=!1,l=t.times(t),a=new o(r);;){if(s=re(a.times(l),new o(e++*e++),u,1),a=n?r.plus(s):r.minus(s),r=re(s.times(l),new o(e++*e++),u,1),s=a.plus(r),s.d[d]!==void 0){for(i=d;s.d[i]===a.d[i]&&i--;);if(i==-1)break}i=a,a=r,r=s,s=i,c++}return q=!0,s.d.length=d+1,s}function gi(o,e){for(var t=o;--e;)t*=o;return t}function qu(o,e){var t,r=e.s<0,n=it(o,o.precision,1),i=n.times(.5);if(e=e.abs(),e.lte(i))return gt=r?4:1,e;if(t=e.divToInt(n),t.isZero())gt=r?3:2;else{if(e=e.minus(t.times(n)),e.lte(i))return gt=Du(t)?r?2:3:r?4:1,e;gt=Du(t)?r?1:4:r?3:2}return e.minus(n).abs()}function ya(o,e,t,r){var n,i,s,a,l,c,u,d,f,h=o.constructor,p=t!==void 0;if(p?(je(t,1,Mt),r===void 0?r=h.rounding:je(r,0,8)):(t=h.precision,r=h.rounding),!o.isFinite())u=zu(o);else{for(u=st(o),s=u.indexOf("."),p?(n=2,e==16?t=t*4-3:e==8&&(t=t*3-2)):n=e,s>=0&&(u=u.replace(".",""),f=new h(1),f.e=u.length-s,f.d=ci(st(f),10,n),f.e=f.d.length),d=ci(u,10,n),i=l=d.length;d[--l]==0;)d.pop();if(!d[0])u=p?"0p+0":"0";else{if(s<0?i--:(o=new h(o),o.d=d,o.e=i,o=re(o,f,t,r,0,n),d=o.d,i=o.e,c=$u),s=d[t],a=n/2,c=c||d[t+1]!==void 0,c=r<4?(s!==void 0||c)&&(r===0||r===(o.s<0?3:2)):s>a||s===a&&(r===4||c||r===6&&d[t-1]&1||r===(o.s<0?8:7)),d.length=t,c)for(;++d[--t]>n-1;)d[t]=0,t||(++i,d.unshift(1));for(l=d.length;!d[l-1];--l);for(s=0,u="";s<l;s++)u+=ga.charAt(d[s]);if(p){if(l>1)if(e==16||e==8){for(s=e==16?4:3,--l;l%s;l++)u+="0";for(d=ci(u,n,e),l=d.length;!d[l-1];--l);for(s=1,u="1.";s<l;s++)u+=ga.charAt(d[s])}else u=u.charAt(0)+"."+u.slice(1);u=u+(i<0?"p":"p+")+i}else if(i<0){for(;++i;)u="0"+u;u="0."+u}else if(++i>l)for(i-=l;i--;)u+="0";else i<l&&(u=u.slice(0,i)+"."+u.slice(i))}u=(e==16?"0x":e==2?"0b":e==8?"0o":"")+u}return o.s<0?"-"+u:u}function Nu(o,e){if(o.length>e)return o.length=e,!0}function dp(o){return new this(o).abs()}function fp(o){return new this(o).acos()}function hp(o){return new this(o).acosh()}function pp(o,e){return new this(o).plus(e)}function mp(o){return new this(o).asin()}function gp(o){return new this(o).asinh()}function bp(o){return new this(o).atan()}function wp(o){return new this(o).atanh()}function _p(o,e){o=new this(o),e=new this(e);var t,r=this.precision,n=this.rounding,i=r+4;return!o.s||!e.s?t=new this(NaN):!o.d&&!e.d?(t=it(this,i,1).times(e.s>0?.25:.75),t.s=o.s):!e.d||o.isZero()?(t=e.s<0?it(this,r,n):new this(0),t.s=o.s):!o.d||e.isZero()?(t=it(this,i,1).times(.5),t.s=o.s):e.s<0?(this.precision=i,this.rounding=1,t=this.atan(re(o,e,i,1)),e=it(this,i,1),this.precision=r,this.rounding=n,t=o.s<0?t.minus(e):t.plus(e)):t=this.atan(re(o,e,i,1)),t}function yp(o){return new this(o).cbrt()}function vp(o){return B(o=new this(o),o.e+1,2)}function xp(o,e,t){return new this(o).clamp(e,t)}function kp(o){if(!o||typeof o!="object")throw Error(pi+"Object expected");var e,t,r,n=o.defaults===!0,i=["precision",1,Mt,"rounding",0,8,"toExpNeg",-Ur,0,"toExpPos",0,Ur,"maxE",0,Ur,"minE",-Ur,0,"modulo",0,9];for(e=0;e<i.length;e+=3)if(t=i[e],n&&(this[t]=ba[t]),(r=o[t])!==void 0)if(Ee(r)===r&&r>=i[e+1]&&r<=i[e+2])this[t]=r;else throw Error(Bt+t+": "+r);if(t="crypto",n&&(this[t]=ba[t]),(r=o[t])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[t]=!0;else throw Error(ju);else this[t]=!1;else throw Error(Bt+t+": "+r);return this}function Ep(o){return new this(o).cos()}function Tp(o){return new this(o).cosh()}function Uu(o){var e,t,r;function n(i){var s,a,l,c=this;if(!(c instanceof n))return new n(i);if(c.constructor=n,Ou(i)){c.s=i.s,q?!i.d||i.e>n.maxE?(c.e=NaN,c.d=null):i.e<n.minE?(c.e=0,c.d=[0]):(c.e=i.e,c.d=i.d.slice()):(c.e=i.e,c.d=i.d?i.d.slice():i.d);return}if(l=typeof i,l==="number"){if(i===0){c.s=1/i<0?-1:1,c.e=0,c.d=[0];return}if(i<0?(i=-i,c.s=-1):c.s=1,i===~~i&&i<1e7){for(s=0,a=i;a>=10;a/=10)s++;q?s>n.maxE?(c.e=NaN,c.d=null):s<n.minE?(c.e=0,c.d=[0]):(c.e=s,c.d=[i]):(c.e=s,c.d=[i]);return}if(i*0!==0){i||(c.s=NaN),c.e=NaN,c.d=null;return}return ui(c,i.toString())}if(l==="string")return(a=i.charCodeAt(0))===45?(i=i.slice(1),c.s=-1):(a===43&&(i=i.slice(1)),c.s=1),Bu.test(i)?ui(c,i):cp(c,i);if(l==="bigint")return i<0?(i=-i,c.s=-1):c.s=1,ui(c,i.toString());throw Error(Bt+i)}if(n.prototype=A,n.ROUND_UP=0,n.ROUND_DOWN=1,n.ROUND_CEIL=2,n.ROUND_FLOOR=3,n.ROUND_HALF_UP=4,n.ROUND_HALF_DOWN=5,n.ROUND_HALF_EVEN=6,n.ROUND_HALF_CEIL=7,n.ROUND_HALF_FLOOR=8,n.EUCLID=9,n.config=n.set=kp,n.clone=Uu,n.isDecimal=Ou,n.abs=dp,n.acos=fp,n.acosh=hp,n.add=pp,n.asin=mp,n.asinh=gp,n.atan=bp,n.atanh=wp,n.atan2=_p,n.cbrt=yp,n.ceil=vp,n.clamp=xp,n.cos=Ep,n.cosh=Tp,n.div=Sp,n.exp=Ap,n.floor=Ip,n.hypot=Cp,n.ln=Dp,n.log=Np,n.log10=$p,n.log2=Op,n.max=Rp,n.min=jp,n.mod=Pp,n.mul=Bp,n.pow=Mp,n.random=Lp,n.round=Fp,n.sign=zp,n.sin=qp,n.sinh=Up,n.sqrt=Vp,n.sub=Wp,n.sum=Gp,n.tan=Hp,n.tanh=Xp,n.trunc=Yp,o===void 0&&(o={}),o&&o.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<r.length;)o.hasOwnProperty(t=r[e++])||(o[t]=this[t]);return n.config(o),n}function Sp(o,e){return new this(o).div(e)}function Ap(o){return new this(o).exp()}function Ip(o){return B(o=new this(o),o.e+1,3)}function Cp(){var o,e,t=new this(0);for(q=!1,o=0;o<arguments.length;)if(e=new this(arguments[o++]),e.d)t.d&&(t=t.plus(e.times(e)));else{if(e.s)return q=!0,new this(1/0);t=e}return q=!0,t.sqrt()}function Ou(o){return o instanceof Wr||o&&o.toStringTag===Pu||!1}function Dp(o){return new this(o).ln()}function Np(o,e){return new this(o).log(e)}function Op(o){return new this(o).log(2)}function $p(o){return new this(o).log(10)}function Rp(){return Fu(this,arguments,-1)}function jp(){return Fu(this,arguments,1)}function Pp(o,e){return new this(o).mod(e)}function Bp(o,e){return new this(o).mul(e)}function Mp(o,e){return new this(o).pow(e)}function Lp(o){var e,t,r,n,i=0,s=new this(1),a=[];if(o===void 0?o=this.precision:je(o,1,Mt),r=Math.ceil(o/M),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(r));i<r;)n=e[i],n>=429e7?e[i]=crypto.getRandomValues(new Uint32Array(1))[0]:a[i++]=n%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(r*=4);i<r;)n=e[i]+(e[i+1]<<8)+(e[i+2]<<16)+((e[i+3]&127)<<24),n>=214e7?crypto.randomBytes(4).copy(e,i):(a.push(n%1e7),i+=4);i=r/4}else throw Error(ju);else for(;i<r;)a[i++]=Math.random()*1e7|0;for(r=a[--i],o%=M,r&&o&&(n=pe(10,M-o),a[i]=(r/n|0)*n);a[i]===0;i--)a.pop();if(i<0)t=0,a=[0];else{for(t=-1;a[0]===0;t-=M)a.shift();for(r=1,n=a[0];n>=10;n/=10)r++;r<M&&(t-=M-r)}return s.e=t,s.d=a,s}function Fp(o){return B(o=new this(o),o.e+1,this.rounding)}function zp(o){return o=new this(o),o.d?o.d[0]?o.s:0*o.s:o.s||NaN}function qp(o){return new this(o).sin()}function Up(o){return new this(o).sinh()}function Vp(o){return new this(o).sqrt()}function Wp(o,e){return new this(o).sub(e)}function Gp(){var o=0,e=arguments,t=new this(e[o]);for(q=!1;t.s&&++o<e.length;)t=t.plus(e[o]);return q=!0,B(t,this.precision,this.rounding)}function Hp(o){return new this(o).tan()}function Xp(o){return new this(o).tanh()}function Yp(o){return B(o=new this(o),o.e+1,1)}A[Symbol.for("nodejs.util.inspect.custom")]=A.toString;A[Symbol.toStringTag]="Decimal";var Wr=A.constructor=Uu(ba);di=new Wr(di);fi=new Wr(fi);var va=Wr;var $n=class{constructor(){throw new Error("The Gramlot browser runtime has no big.js: decimals use decimal.js")}};var Mn={};ee(Mn,{DecodeError:()=>Te,Decoder:()=>Xe,EXT_TIMESTAMP:()=>Ea,Encoder:()=>Gr,ExtData:()=>He,ExtensionCodec:()=>Lt,decode:()=>Ju,decodeArrayStream:()=>td,decodeAsync:()=>ed,decodeMulti:()=>Qu,decodeMultiStream:()=>rd,decodeTimestampExtension:()=>Ca,decodeTimestampToTimeSpec:()=>Ia,encode:()=>_i,encodeDateToTimeSpec:()=>Sa,encodeTimeSpecToTimestamp:()=>Ta,encodeTimestampExtension:()=>Aa});function Vu(o){let e=o.length,t=0,r=0;for(;r<e;){let n=o.charCodeAt(r++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&r<e){let i=o.charCodeAt(r);(i&64512)===56320&&(++r,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function Zp(o,e,t){let r=o.length,n=t,i=0;for(;i<r;){let s=o.charCodeAt(i++);if((s&4294967168)===0){e[n++]=s;continue}else if((s&4294965248)===0)e[n++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&i<r){let a=o.charCodeAt(i);(a&64512)===56320&&(++i,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[n++]=s>>12&15|224,e[n++]=s>>6&63|128):(e[n++]=s>>18&7|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128)}e[n++]=s&63|128}}var Kp=new TextEncoder,Jp=50;function Qp(o,e,t){Kp.encodeInto(o,e.subarray(t))}function Wu(o,e,t){o.length>Jp?Qp(o,e,t):Zp(o,e,t)}var em=4096;function ka(o,e,t){let r=e,n=r+t,i=[],s="";for(;r<n;){let a=o[r++];if((a&128)===0)i.push(a);else if((a&224)===192){let l=o[r++]&63;i.push((a&31)<<6|l)}else if((a&240)===224){let l=o[r++]&63,c=o[r++]&63;i.push((a&31)<<12|l<<6|c)}else if((a&248)===240){let l=o[r++]&63,c=o[r++]&63,u=o[r++]&63,d=(a&7)<<18|l<<12|c<<6|u;d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(a);i.length>=em&&(s+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(s+=String.fromCharCode(...i)),s}var tm=new TextDecoder,rm=200;function nm(o,e,t){let r=o.subarray(e,e+t);return tm.decode(r)}function Gu(o,e,t){return t>rm?nm(o,e,t):ka(o,e,t)}var He=class{type;data;constructor(e,t){this.type=e,this.data=t}};var Te=class o extends Error{constructor(e){super(e);let t=Object.create(o.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:o.name})}};function Hu(o,e,t){let r=t/4294967296,n=t;o.setUint32(e,r),o.setUint32(e+4,n)}function bi(o,e,t){let r=Math.floor(t/4294967296),n=t;o.setUint32(e,r),o.setUint32(e+4,n)}function wi(o,e){let t=o.getInt32(e),r=o.getUint32(e+4);return t*4294967296+r}function Xu(o,e){let t=o.getUint32(e),r=o.getUint32(e+4);return t*4294967296+r}var Ea=-1,om=4294967296-1,im=17179869184-1;function Ta({sec:o,nsec:e}){if(o>=0&&e>=0&&o<=im)if(e===0&&o<=om){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,o),t}else{let t=o/4294967296,r=o&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|t&3),i.setUint32(4,r),n}else{let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setUint32(0,e),bi(r,4,o),t}}function Sa(o){let e=o.getTime(),t=Math.floor(e/1e3),r=(e-t*1e3)*1e6,n=Math.floor(r/1e9);return{sec:t+n,nsec:r-n*1e9}}function Aa(o){if(o instanceof Date){let e=Sa(o);return Ta(e)}else return null}function Ia(o){let e=new DataView(o.buffer,o.byteOffset,o.byteLength);switch(o.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),r=e.getUint32(4),n=(t&3)*4294967296+r,i=t>>>2;return{sec:n,nsec:i}}case 12:{let t=wi(e,4),r=e.getUint32(0);return{sec:t,nsec:r}}default:throw new Te(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${o.length}`)}}function Ca(o){let e=Ia(o);return new Date(e.sec*1e3+e.nsec/1e6)}var Yu={type:Ea,encode:Aa,decode:Ca};var Lt=class o{static defaultCodec=new o;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Yu)}register({type:e,encode:t,decode:r}){if(e>=0)this.encoders[e]=t,this.decoders[e]=r;else{let n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=r}}tryToEncode(e,t){for(let r=0;r<this.builtInEncoders.length;r++){let n=this.builtInEncoders[r];if(n!=null){let i=n(e,t);if(i!=null){let s=-1-r;return new He(s,i)}}}for(let r=0;r<this.encoders.length;r++){let n=this.encoders[r];if(n!=null){let i=n(e,t);if(i!=null){let s=r;return new He(s,i)}}}return e instanceof He?e:null}decode(e,t,r){let n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,r):new He(t,e)}};function sm(o){return o instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&o instanceof SharedArrayBuffer}function Rn(o){return o instanceof Uint8Array?o:ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):sm(o)?new Uint8Array(o):Uint8Array.from(o)}var am=100,lm=2048,Gr=class o{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Lt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??am,this.initialBufferSize=e?.initialBufferSize??lm,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),r=new Uint8Array(t),n=new DataView(t);r.set(this.bytes),this.view=n,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=Vu(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Wu(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,t){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let r=Rn(e);this.writeU8a(r)}encodeArray(e,t){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let r=0;for(let n of t)e[n]!==void 0&&r++;return r}encodeMap(e,t){let r=Object.keys(e);this.sortKeys&&r.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of r){let s=e[i];this.ignoreUndefined&&s===void 0||(this.encodeString(i),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),n=r.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(r);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Hu(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),bi(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function _i(o,e){return new Gr(e).encodeSharedRef(o)}function yi(o){return`${o<0?"-":""}0x${Math.abs(o).toString(16).padStart(2,"0")}`}var cm=16,um=16,vi=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=cm,t=um){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,r){let n=this.caches[r-1];e:for(let i of n){let s=i.bytes;for(let a=0;a<r;a++)if(s[a]!==e[t+a])continue e;return i.str}return null}store(e,t){let r=this.caches[e.length-1],n={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)}decode(e,t,r){let n=this.find(e,t,r);if(n!=null)return this.hit++,n;this.miss++;let i=ka(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,i),i}};var Da="array",Bn="map_key",Ku="map_value",dm=o=>{if(typeof o=="string"||typeof o=="number")return o;throw new Te("The type of key must be string or number but "+typeof o)},Na=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Da,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=Bn,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Da){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===Bn||e.type===Ku){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Pn=-1,Oa=new DataView(new ArrayBuffer(0)),fm=new Uint8Array(Oa.buffer);try{Oa.getInt8(0)}catch(o){if(!(o instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var Zu=new RangeError("Insufficient data"),hm=new vi,Xe=class o{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Oa;bytes=fm;headByte=Pn;stack=new Na;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Lt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:hm,this.mapKeyConverter=e?.mapKeyConverter??dm}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Pn,this.stack.reset()}setBuffer(e){let t=Rn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Pn&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),r=Rn(e),n=new Uint8Array(t.length+r.length);n.set(t),n.set(r,t.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:r}=this;return new RangeError(`Extra ${t.byteLength-r} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,r;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),t=!0}catch(l){if(!(l instanceof RangeError))throw l}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:n,pos:i,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${yi(n)} at ${s} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let r=t,n=-1;for await(let i of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(n=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){let n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();t=this.decodeExtension(n,4)}else throw new Te(`Unrecognized type byte: ${yi(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let n=r.top();if(n.type===Da)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,r.release(n);else continue e;else if(n.type===Bn){if(t==="__proto__")throw new Te("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=Ku;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,r.release(n);else{n.key=null,n.type=Bn;continue e}}return t}}readHeadByte(){return this.headByte===Pn&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Pn}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Te(`Unrecognized array type byte: ${yi(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Te(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Te(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new Te(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Zu;let r=this.pos+t,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,r,e):n=Gu(this.bytes,r,e),this.pos+=t+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Bn:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new Te(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Zu;let r=this.pos+t,n=this.bytes.subarray(r,r+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new Te(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=Xu(this.view,this.pos);return this.pos+=8,e}readI64(){let e=wi(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Ju(o,e){return new Xe(e).decode(o)}function Qu(o,e){return new Xe(e).decodeMulti(o)}function pm(o){return o[Symbol.asyncIterator]!=null}async function*mm(o){let e=o.getReader();try{for(;;){let{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}function xi(o){return pm(o)?o:mm(o)}async function ed(o,e){let t=xi(o);return new Xe(e).decodeAsync(t)}function td(o,e){let t=xi(o);return new Xe(e).decodeArrayStream(t)}function rd(o,e){let t=xi(o);return new Xe(e).decodeStream(t)}var nd=()=>{throw new Error("The Gramlot browser runtime has no @xmldom/xmldom: XML uses the native DOMParser")},Hr=class{constructor(){nd()}},ki=class{constructor(){nd()}};var Ln=va,Fn=$n,at=Mn,od=Hr,id=ki;var sd=at!==null;function ad(){if(!sd)throw new Error("@msgpack/msgpack is required for MessagePack support. Install with: npm install @msgpack/msgpack")}var ld=gm();function gm(){if(!sd)return null;let o=new TextEncoder,e=new TextDecoder,t=new at.ExtensionCodec;return t.register({type:-1,encode:r=>{if(r instanceof Date){let n=bt(r);if(n==="D"||n==="H")return null}return at.encodeTimestampExtension(r)},decode:r=>at.decodeTimestampExtension(r)}),t.register({type:1,encode:r=>U(r)?o.encode(r.toString()):null,decode:r=>Ye(e.decode(r))}),t.register({type:2,encode:r=>{if(r instanceof Date&&bt(r)==="D"){let n=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),s=String(r.getUTCDate()).padStart(2,"0");return o.encode(`${n}-${i}-${s}`)}return null},decode:r=>new Date(e.decode(r)+"T00:00:00.000Z")}),t.register({type:3,encode:r=>{if(r instanceof Date&&bt(r)==="H"){let n=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=String(r.getUTCMilliseconds()).padStart(3,"0");return o.encode(`${n}:${i}:${s}.${a}`)}return null},decode:r=>{let n=e.decode(r),i=n.indexOf("."),s=i>=0?n.substring(0,i):n,a=i>=0?n.substring(i+1):"0",[l,c,u]=s.split(":"),d=Math.round(+a.substring(0,3));return new Date(Date.UTC(1970,0,1,+l,+c,+u,d))}}),t.register({type:4,encode:r=>{let n=$a(r);if(n!==null){let[i,s]=n;return o.encode(`${i}:${s(r)}`)}return null},decode:r=>{let n=e.decode(r),i=n.indexOf(":"),s=n.slice(0,i),a=n.slice(i+1),l=Ft[s];if(l!==void 0){let[,c]=l;return c(a)}return`${a}::${s}`}}),t}function cd(o){return ad(),at.encode(o,{extensionCodec:ld})}function ud(o){return ad(),at.decode(o,{extensionCodec:ld})}function Ei(o,e=!1){let t=Ti(o);if(t===null)return[!1,String(o)];let[r,n,i]=t;return i&&!e?[!1,String(o)]:[!0,`${n(o)}::${r}`]}function Ra(o){if(!o.includes("::"))return[!1,o];let e=o.lastIndexOf("::"),t=o.slice(0,e),r=o.slice(e+2),n=Ft[r];if(n===void 0)return[!1,o];let[,i]=n;return[!0,i(t)]}function Xr(o,e,t){if(o!==null&&typeof o=="object"&&!Array.isArray(o)){let r={};for(let[n,i]of Object.entries(o))r[n]=Xr(i,e,t);return r}return Array.isArray(o)?o.map(r=>Xr(r,e,t)):t(o)?e(o):o}function zn(o){let e=Ti(o);if(e!==null){let[t,r,n]=e;return n?[o,!1]:[`${r(o)}::${t}`,!0]}if(Array.isArray(o)){let t=!1;return[o.map(n=>{let[i,s]=zn(n);return s&&(t=!0),i}),t]}if(o!==null&&typeof o=="object"){let t=!1,r={};for(let[n,i]of Object.entries(o)){let[s,a]=zn(i);a&&(t=!0),r[n]=s}return[r,t]}return[o,!1]}function bm(o,e=!1){let[t,r]=Ei(o,e);if(t)return r;let[n,i]=zn(o),s=JSON.stringify(n);return i?`${s}::JS`:s}function wm(o){return JSON.stringify(o)}function _m(o){if(!at)throw new Error("@msgpack/msgpack is required for MessagePack support");return at.encode(o)}function R(o,e=null,{raw:t=!1,qs:r=!1,_forceSuffix:n=!1}={}){if(r)return`${hd(o)}::QS`;if(t){if(e===null||e==="json")return wm(o);if(e==="msgpack")return _m(o);throw e==="xml"?new Error("raw=true is not supported for XML transport"):new Error(`Unknown transport: ${e}`)}if(e===null||e==="json"){let i=bm(o,n);return e==="json"?`"${i}"`:i}else{if(e==="xml")return`<?xml version="1.0" ?><tytx_root>${fd(o)}</tytx_root>`;if(e==="msgpack")return cd(o);throw new Error(`Unknown transport: ${e}`)}}function dd(o){return Symbol.asyncIterator in o?(async function*(){for await(let t of o)yield zn(t)[0]})():(function*(){for(let t of o)yield zn(t)[0]})()}var Yr,ja;typeof window<"u"&&window.DOMParser?(Yr=window.DOMParser,ja=window.XMLSerializer):(Yr=od,ja=id);function pd(o){if(o===null||typeof o!="object"||Array.isArray(o))return!1;let e=Object.keys(o);if(e.length!==1)return!1;let t=o[e[0]];return t!==null&&typeof t=="object"&&"value"in t}function md(o,e,t){let r=o.createElement(e),n=t.attrs||{},i=t.value;for(let[s,a]of Object.entries(n))r.setAttribute(s,R(a,null,{_forceSuffix:!0}));if(Array.isArray(i))for(let s of i)if(pd(s)){let[a]=Object.keys(s),l=s[a],c=md(o,a,l);r.appendChild(c)}else{r.textContent=R(i);break}else r.textContent=R(i);return r}function fd(o){if(!Yr)throw new Error("XML support requires @xmldom/xmldom package in Node.js");if(pd(o)){let[e]=Object.keys(o),t=o[e],r=new Yr().parseFromString("<root/>","text/xml"),n=md(r,e,t);return new ja().serializeToString(n)}else return R(o)}function Pa(o){let e={};for(let r=0;r<o.attributes.length;r++){let n=o.attributes[r];e[n.name]=j(n.value)}let t=[];for(let r=0;r<o.childNodes.length;r++){let n=o.childNodes[r];n.nodeType===1&&t.push(n)}if(t.length>0)if(t.length===1){let r=t[0],n=Pa(r);return{attrs:e,value:{[r.tagName]:n}}}else{let r=[];for(let n of t){let i=Pa(n);r.push({[n.tagName]:i})}return{attrs:e,value:r}}return{attrs:e,value:j(o.textContent)}}function gd(o){if(!Yr)throw new Error("XML support requires @xmldom/xmldom package in Node.js");let r=new Yr().parseFromString(o,"text/xml").documentElement;if(r.tagName==="tytx_root"){let i=null;for(let s=0;s<r.childNodes.length;s++)if(r.childNodes[s].nodeType===1){i=r.childNodes[s];break}if(!i)return j(r.textContent);r=i}let n=Pa(r);return{[r.tagName]:n}}function Ba(o){return typeof o=="string"}function ym(o){let[e,t]=Ra(o);if(e)return t;let r=o;r.endsWith("::JS")&&(r=r.slice(0,-4));let n;try{n=JSON.parse(r)}catch{return o}return Xr(n,Ma,Ba)}function Ma(o){return o.includes("::")?Ra(o)[1]:o}function vm(o){let e=gd(o);return typeof e=="string"?j(e):e}function xm(o){return ud(o)}function j(o,e=null){if(o===null)return null;if(e===null||e==="json"){let t=o;return e==="json"&&o.startsWith('"')&&o.endsWith('"')&&(t=o.slice(1,-1)),ym(t)}else{if(e==="xml")return vm(o);if(e==="msgpack")return xm(o);throw new Error(`Unknown transport: ${e}`)}}function La(o){return Symbol.asyncIterator in o?(async function*(){for await(let t of o)yield Xr(t,Ma,Ba)})():(function*(){for(let t of o)yield Xr(t,Ma,Ba)})()}function hd(o){if(Array.isArray(o))return o.map(e=>String(e)).join("&");if(o!==null&&typeof o=="object"){let e=[];for(let[t,r]of Object.entries(o)){let[n,i]=Ei(r,!0);n?e.push(`${t}=${i}`):e.push(`${t}=${r}`)}return e.join("&")}throw new TypeError(`toQs expects object or array, got ${typeof o}`)}function bd(o){if(!o)return[];let e=o.split("&"),t=e.map(s=>s.includes("=")),r=t.every(Boolean),n=!t.some(Boolean);if(!r&&!n)throw new Error("QS format error: mixed items with and without '='");if(n)return e.map(s=>j(s));let i={};for(let s of e){let a=s.indexOf("="),l=s.slice(0,a),c=s.slice(a+1);i[l]=j(c)}return i}var qn=Ln||Fn||Number,Un=Ln?"decimal.js":Fn?"big.js":"number";function _d(o){o==="decimal.js"&&Ln?(qn=Ln,Un="decimal.js"):o==="big.js"&&Fn?(qn=Fn,Un="big.js"):(qn=Number,Un="number")}function Zr(){return Un}function Ye(o){return new qn(o)}function U(o){return Un==="number"?!1:o instanceof qn}function bt(o){let e=o.getUTCFullYear()===1970&&o.getUTCMonth()===0&&o.getUTCDate()===1,t=o.getUTCHours()===0&&o.getUTCMinutes()===0&&o.getUTCSeconds()===0&&o.getUTCMilliseconds()===0;return e&&!t?"H":t&&!e?"D":"DHZ"}function km(o){return o.toString()}function Em(o){let e=o.getUTCFullYear(),t=String(o.getUTCMonth()+1).padStart(2,"0"),r=String(o.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function Tm(o){return o.toISOString()}function Sm(o){let e=String(o.getUTCHours()).padStart(2,"0"),t=String(o.getUTCMinutes()).padStart(2,"0"),r=String(o.getUTCSeconds()).padStart(2,"0"),n=String(o.getUTCMilliseconds()).padStart(3,"0");return`${e}:${t}:${r}.${n}`}function Am(o){return o?"true":"false"}function Im(o){return o.toString()}function Cm(o){return o.toString()}function Dm(o){let e="";for(let t=0;t<o.length;t+=32768)e+=String.fromCharCode.apply(null,o.subarray(t,t+32768));return btoa(e)}var Si=[],Fa=new Map;function $a(o){if(o===null||typeof o!="object")return null;for(let e=Object.getPrototypeOf(o);e!==null;e=Object.getPrototypeOf(e))for(let[t,r,n,i]of Si)if(t.prototype===e)return[r,n,i];return null}function Ti(o){if(o===null)return["NN",()=>"",!0];if(U(o))return["N",km,!1];if(o instanceof Uint8Array)return["RAW",Dm,!1];if(o instanceof Date){let e=bt(o);return e==="D"?["D",Em,!1]:e==="H"?["H",Sm,!1]:["DHZ",Tm,!1]}return typeof o=="boolean"?["B",Am,!0]:typeof o=="number"?Number.isInteger(o)?["L",Im,!0]:["R",Cm,!0]:$a(o)}function Nm(o){return Ye(o)}function Om(o){let[e,t,r]=o.split("-").map(Number);return new Date(Date.UTC(e,t-1,r,0,0,0,0))}function wd(o){return new Date(o)}function $m(o){let[e,t,r]=o.split(":"),[n,i]=r.split(".");return new Date(Date.UTC(1970,0,1,Number(e),Number(t),Number(n),Number(i||0)))}function Rm(o){return o.toLowerCase()==="true"}function jm(o){return parseInt(o,10)}function Pm(o){return parseFloat(o)}function Bm(o){return o}function Mm(o){return null}var Lm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Fm(o){if(!Lm.test(o))throw new Error(`RAW payload is not standard padded base64: '${o}'`);let e=atob(o),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function zm(o){return bd(o)}var qm=/^[A-Z]+$/,Ft={N:[Object,Nm],D:[Date,Om],DH:[Date,wd],DHZ:[Date,wd],H:[Date,$m],L:[Number,jm],R:[Number,Pm],T:[String,Bm],B:[Boolean,Rm],QS:[Object,zm],NN:[null,Mm],RAW:[Uint8Array,Fm]};function Kr(o){return Object.hasOwn(Ft,o)?Ft[o][0]:null}function Vn(o,e,t,r,n=!1){if(typeof e!="string"||!qm.test(e))throw new Error(`TYTX suffix '${e}' is invalid: expected uppercase ASCII letters only`);let i=Ft[e];if(i!==void 0&&i[0]!==o){let s=i[0]===null?"null":i[0].name;throw new Error(`TYTX suffix '${e}' is already registered for ${s}`)}Si=Si.filter(([s])=>s!==o),Si.push([o,e,t,n]),Ft[e]=[o,r]}function yd(o){if(!o.tytxSuffix)throw new Error(`registerClass: ${o.name} is missing a static tytxSuffix`);if(typeof o.prototype?.toTytx!="function")throw new Error(`registerClass: ${o.name} is missing a toTytx method`);if(typeof o.fromTytx!="function")throw new Error(`registerClass: ${o.name} is missing a static fromTytx method`);return Vn(o,o.tytxSuffix,e=>e.toTytx(),e=>o.fromTytx(e),o.tytxJsonNative||!1),o}function wt(o,e){Fa.set(o,e)}function Pe(o){return Fa.has(o)?Fa.get(o):{}}function vd(o,e,t=e.name){let r=Pe(o);if((r[t]??e)!==e)throw new Error(`TYTX subtype name '${t}' is already registered for suffix '${o}' by ${r[t].name}`);wt(o,{...r,[t]:e})}var za={json:"application/json",xml:"application/xml",msgpack:"application/msgpack"};function qa(o){if(!o)return null;let e=o.toLowerCase();return e.includes("jsonl")?"jsonl":e.includes("json")?"json":e.includes("xml")?"xml":e.includes("msgpack")?"msgpack":null}async function Ai(o,e={}){let{body:t,transport:r="json",method:n=t!==void 0?"POST":"GET",headers:i={},...s}=e,a={"X-TYTX-Transport":r,...i},l;if(t!==void 0){a["Content-Type"]=za[r];let h=R(t,r);l=h}let c=await fetch(o,{method:n,headers:a,body:l,...s});if(!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);let u=c.headers.get("Content-Type")||"",d=qa(u)||r,f;if(d==="msgpack"){let h=await c.arrayBuffer();f=j(Buffer.from(h),d)}else{let h=await c.text();f=j(h,d)}return f}var Um="0.16.4";var rl={};ee(rl,{BuilderBase:()=>Ae,Collection:()=>ut,CustomTypes:()=>hr,DATA_ELEMENT_FIELDS:()=>tl,DATA_ROOT:()=>an,HtmlBuilder:()=>Je,HtmlRenderer:()=>Wt,META_ATTRS:()=>lt,RendererBase:()=>Ut,SOURCE_ROOT:()=>sn,SourceBag:()=>N,SourceBagNode:()=>Se,SvgBuilder:()=>vt,SvgRenderer:()=>Gt,VALUE:()=>cr,XmlRenderer:()=>Vt,pointerDependencies:()=>Ze,pointerExpression:()=>Jr,pointerTemplate:()=>zt,pointerTransform:()=>H,resolveRenderTag:()=>nn,sourceAttributeItems:()=>ge,sourceBagFromTytx:()=>Ri,sourceBagToTytx:()=>Rd,sourceTarget:()=>Z,svgAttributes:()=>Kn,wrapSource:()=>on});function H(o){if(typeof o!="string"||!["^","="].includes(o[0])||o.startsWith("=="))return null;let e=o.indexOf(":");if(e<0)return null;let t=o[e+1]==="=";return{pointer:o.slice(0,e),expression:t,body:o.slice(e+(t?2:1))}}var xd=/^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;function zt(o,e){let t="",r=!1;for(let n=0;n<o.length;){if(o[n]!=="{"&&o[n]!=="}"){t+=o[n++];continue}let i=o.slice(n).match(xd);if(!i)throw new SyntaxError("Invalid pointer template placeholder");let s=i[1]??"",a=s.startsWith("?"),l=e(a?s.slice(1):s);l==null||l===""&&!a?r=!0:t+=String(l),n+=i[0].length}return r?null:t}function Jr(o){let e=[],t=new Set,r="",n=!0;for(let i=0;i<o.length;){let s=i,a=o[i];if(a==='"'||a==="'"||a==="`"){for(i++;i<o.length;){if(o[i]==="\\"){i+=2;continue}if(o[i++]===a)break}r+=o.slice(s,i),n=!1;continue}if(o.startsWith("//",i)){i=o.indexOf(`
26
- `,i),i<0&&(i=o.length),r+=o.slice(s,i);continue}if(o.startsWith("/*",i)){let u=o.indexOf("*/",i+2);i=u<0?o.length:u+2,r+=o.slice(s,i);continue}if(a==="/"&&n){let u=!1;for(i++;i<o.length;){let d=o[i++];if(d==="\\"){i++;continue}if(d==="[")u=!0;else if(d==="]")u=!1;else if(d==="/"&&!u)break}for(;/[a-z]/i.test(o[i]??"")&&i<o.length;)i++;r+=o.slice(s,i),n=!1;continue}let l=a==="{"?o.slice(i).match(xd):null;if(l){let u=l[1]??"";if(u.startsWith("?"))throw new SyntaxError("Optional slots are supported in pointer templates only");r+=`_pointerValues[${e.length}]`,e.push(u),i+=l[0].length,n=!1;continue}let c=o.slice(i).match(/^[A-Za-z_$][\w$]*/);if(c){t.add(c[0]),r+=c[0],i+=c[0].length,n=["return","typeof","void","delete","new","in","instanceof","yield","await"].includes(c[0]);continue}r+=a,i++,/\s/.test(a)||(n=/[([{,:;=!?&|+*%~<>\/-]/.test(a))}return{text:r,slots:e,identifiers:t}}function kd(o,e,t=()=>null){let r=new Map,n=[],i=s=>{if(r.has(s))return r.get(s);if(!o.has(s))throw new Error(`Referenced Source attribute '${s}' does not exist`);if(n.includes(s))throw new Error(`Cyclic attribute dependency: ${[...n,s].join(" -> ")}`);n.push(s);try{let a=o.get(s),l=typeof s=="string"?H(a):null,c=e.get(s);if(l){let u=d=>d?i(d):e.get(s);if(l.expression){let d=Jr(l.body);c=t(s,a,d,d.slots.map(u))}else c=zt(l.body,u),e.get(s)==null&&(c=null)}return r.set(s,c),c}finally{n.pop()}};return new Map([...o.keys()].map(s=>[s,i(s)]))}function Ze(o,e){let t=new Map([...Object.entries(o.getAttr()),...o.fixedAttrItems()]),r=new Set,n=[],i=s=>{let a=H(s);if(!a)return;let l=[];a.expression?l.push(...Jr(a.body).slots):zt(a.body,c=>(l.push(c),""));for(let c of l.filter(Boolean)){if(!t.has(c))throw new Error(`Referenced Source attribute '${c}' does not exist`);if(n.includes(c))throw new Error(`Cyclic attribute dependency: ${[...n,c].join(" -> ")}`);r.has(c)||(n.push(c),i(t.get(c)),n.pop(),r.add(c))}};return i(e),r}var Za={};ee(Za,{Bag:()=>x,BagCbResolver:()=>_t,BagException:()=>rn,BagNode:()=>qe,BagNodeContainer:()=>Qr,BagResolver:()=>Y,BagSerializationError:()=>ce,OpaqueResolver:()=>lr,RETRY_POLICIES:()=>Va,StorageResolver:()=>Xn,UrlResolver:()=>Gn,UuidResolver:()=>Hn,registerResolver:()=>Ni});var Va={network:{maxAttempts:3,delay:1,backoff:2,jitter:!0,on:["TypeError","NetworkError","AbortError"]},aggressive:{maxAttempts:5,delay:.5,backoff:2,jitter:!0,on:["Error"]},gentle:{maxAttempts:2,delay:2,backoff:1.5,jitter:!1,on:["TypeError","NetworkError"]}};function Vm(o){let e=o._retryPolicy;return e==null?null:typeof e=="string"?Va[e]||null:e}function Wm(o,e){return e.some(t=>t==="Error"?!0:o.name===t||o.constructor.name===t)}function Gm(o){return new Promise(e=>setTimeout(e,o))}async function Hm(o,e){if(!e)return o();let t=e.maxAttempts||3,r=e.delay||1,n=e.backoff||2,i=e.jitter!==!1,s=e.on||["Error"],a=null,l=r*1e3;for(let c=0;c<t;c++)try{let u=o();return u instanceof Promise?await u:u}catch(u){if(a=u,c<t-1&&Wm(u,s)){let d=l;i&&(d*=1+Math.random()*.1),await Gm(d),l*=n}else throw u}throw a}var Y=class o{static classKwargs={cacheTime:0,readOnly:!1,asBag:null,retryPolicy:null};static classArgs=[];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy"]);constructor(e={}){let r={...this.constructor.classKwargs,...e};for(let i of["interval","reactive"])if(Object.hasOwn(r,i))throw new TypeError(`Removed resolver option: ${i}. Schedule updates in the application; use reset() and read explicitly.`);this.cacheTime=r.cacheTime,this._readOnly=r.readOnly,this._asBag=r.asBag,this._retryPolicy=r.retryPolicy,this._kw={};let n=this.constructor.internalParams;for(let[i,s]of Object.entries(r))n.has(i)||(this._kw[i]=s);this._lastUpdate=null,this._node=null,this._lastEffectiveFingerprint=null,this._cachedValue=null,this.init()}init(){}setNode(e){e!==this._node&&!this.readOnly&&this._lastUpdate!==null&&this.reset(),this._node=e,this.onSetResolver(e)}onSetResolver(e){}get node(){return this._node}get cacheTime(){return this._cacheTime}set cacheTime(e){if(typeof e=="boolean")throw new TypeError("cacheTime must be numeric; use a negative value for infinite caching");this._cacheTime=e}get readOnly(){return this._readOnly}get expired(){return this._cacheTime<0?this._lastUpdate===null:this._cacheTime===0||this._lastUpdate===null?!0:(Date.now()-this._lastUpdate)/1e3>this._cacheTime}reset(...e){if(e.length)throw new TypeError("reset() takes no arguments. It invalidates the cache for the next explicit read.");this._lastUpdate=null,this._lastEffectiveFingerprint=null}get cachedValue(){return!this.readOnly&&this._node?this._node._value:this._cachedValue}set cachedValue(e){!this.readOnly&&this._node?this._node.setValue(e,!1):this._cachedValue=e}_computeEffectiveFingerprint(e){return JSON.stringify(Object.entries(e).sort())}_buildEffectiveKw(){let e={...this._kw};if(this._node&&this._node.attr)for(let t of Object.keys(this._kw))Object.hasOwn(this._node.attr,t)&&(e[t]=this._node.attr[t]);return e}resolve(e={}){let{static:t=!1,...r}=e;if(t)return this._node?this._node._value:this.cachedValue;let n=this._buildEffectiveKw();if(Object.keys(r).length>0)return this._load({...n,...r},s=>this._prepareValue(s));let i=this._computeEffectiveFingerprint(n);return i===this._lastEffectiveFingerprint&&!this.expired?this.cachedValue:(this._lastEffectiveFingerprint=i,this._load(n,s=>this._finalize(s)))}_load(e,t){let r=Vm(this),n=()=>this.load(e);if(r)return Hm(n,r).then(t);let i=n();return i&&typeof i.then=="function"?i.then(t):t(i)}_finalize(e){return e=this._prepareValue(e),this._lastUpdate=Date.now(),(!this.readOnly||this.cacheTime!==0)&&(this.cachedValue=e),e}_prepareValue(e){let t;return this._asBag===!0?t=!0:this._asBag===!1?t=!1:t=!this._readOnly,t&&e!==null&&e!==void 0&&(e=this._convertToBag(e)),e}_convertToBag(e){let t=o._BagClass;if(!t||e&&typeof e._htraverse=="function")return e;if(typeof e=="string"){if(e=e.trim(),e.startsWith("<")&&t.fromXml)return t.fromXml(e);if((e.startsWith("{")||e.startsWith("["))&&t.fromTytx)return t.fromTytx(e)}return e}static registerBagClass(e){o._BagClass=e}load(e){return null}};Y._BagClass=null;var _t=class extends Y{static classKwargs={cacheTime:0,readOnly:!1,asBag:!1,retryPolicy:null,callback:null};static classArgs=["callback"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy","callback"]);constructor(e={}){typeof e=="function"&&(e={callback:e}),super(e),this._callback=e.callback||null}load(e){return this._callback?this._callback.call(this,e):null}};var qe=class o{constructor(e,t,r=null,n=null,i=null,s=null,a=null,l=!0){this.label=t,this._value=null,this._attr={},this._parentBag=null,this._resolver=null,this._nodeSubscribers={},this._onChangedValue=null,this.nodeTag=s,this.xmlTag=a,this._compiled=null,this.parentBag=e,n&&this.setAttr(n,!1,!0,l),r!==null&&this.setValue(r,!1),i&&(this.resolver=i)}get parentBag(){return this._parentBag}set parentBag(e){e===null&&this._value?.parentNode===this&&this._value.setBackref(),this._parentBag=e,e?.backref&&this._value&&typeof this._value._htraverse=="function"&&this._value.setBackref(this,e)}get value(){return this.getValue()}set value(e){this.setValue(e)}getValue(e=!1,t=null,r={}){if(t!==null){let n=j(`${t}::QS`);if(Array.isArray(n)){let i=n.length?n:Object.keys(this._attr),s=i.map(l=>{let c=this.getAttr(l);return!e&&c instanceof Y?c.resolve():c}),a=l=>n.length===0?Object.fromEntries(i.map((c,u)=>[c,l[u]])):l.length===1?l[0]:l;return s.some(l=>l&&typeof l.then=="function")?Promise.all(s).then(a):a(s)}else{if(!this._resolver)throw new Error("Cannot use kwargs syntax without resolver");r={...r,...n}}}return this._resolver!==null?this._resolver.resolve({static:e,...r}):this._value}setValue(e,t=!0,r=null,n=null,i=!0,s=null,a=!1){e instanceof Y?(this.resolver=e,e=null):e instanceof o&&(r=r||{},Object.assign(r,e._attr),e.resolver&&(this.resolver=e.resolver),e=e._value);let l=this._value;l!==e&&l?.parentNode===this&&l.setBackref(),this._value=e;let c=l!==this._value,u=t??!0,d=null;if(r!==null){let h={...this._attr};this.setAttr(r,!1,n,i);let p=this._buildAttrDiff(h,this._attr);d=Object.keys(p).length>0?p:null}t=u&&(c||d!==null);let f=d?c?"upd_value_attr":"upd_attrs":"upd_value";if(this._onChangedValue&&this._onChangedValue(this,e,l,u),t){let h=d!==null?{oldvalue:l,attrs_diff:d}:{oldvalue:l};for(let p of Object.values(this._nodeSubscribers))p({node:this,info:h,evt:f})}this._parentBag!==null&&this._parentBag.backref&&(e&&typeof e._htraverse=="function"&&e.setBackref(this,this._parentBag),t&&this._parentBag._onNodeChanged(this,[this.label],f,l,d,s,a))}replace(e){if(!(e instanceof o))throw new TypeError("BagNode.replace expects a BagNode");if(e===this)return this;let t=e.staticValue;t&&typeof t._htraverse=="function"&&(t=t.createChildBag().replace(t));let r=null;e.resolver&&(r=Object.create(Object.getPrototypeOf(e.resolver),Object.getOwnPropertyDescriptors(e.resolver)),r._node=null,r._kw={...e.resolver._kw});let n=this._value,i={...this._attr},s=this.resolver;s&&s._node===this&&(s._node=null),this.resolver=r,this.setValue(t,!1,{...e.attr},!1,!1,null);let a=this._buildAttrDiff(i,this._attr),l=Object.keys(a).length?a:null,c=n!==t||s!==r;if(c||l){let u=l?c?"upd_value_attr":"upd_attrs":"upd_value",d=l?{oldvalue:n,attrs_diff:l}:{oldvalue:n};for(let f of Object.values(this._nodeSubscribers))f({node:this,info:d,evt:u});this._parentBag!==null&&this._parentBag.backref&&this._parentBag._onNodeChanged(this,[this.label],u,n,l)}return this}get staticValue(){return this._value}set staticValue(e){this._value=e}get resolver(){return this._resolver}set resolver(e){this._resolver=e,e&&e.setNode&&e.setNode(this)}resetResolver(){if(!this._resolver)throw new Error("Cannot reset resolver: node has no resolver");this._resolver.reset(),this.setValue(null)}get attr(){return this._attr}getAttr(e=null,t=null){return e?e in this._attr?this._attr[e]:t:this._attr}_buildAttrDiff(e,t){let r={},n=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of n){let s=i in e?e[i]:null,a=i in t?t[i]:null;s!==a&&(r[i]={old:s,new:a})}return r}setAttr(e=null,t=!0,r=!0,n=!0){let i=e||{},s=Object.keys(this._nodeSubscribers).length>0,l=t&&(s||this._parentBag!==null&&this._parentBag.backref)?{...this._attr}:null;if(r?Object.assign(this._attr,i):this._attr={...i},n)for(let c of Object.keys(this._attr))this._attr[c]===null&&delete this._attr[c];if(t&&l!==null){let c=this._buildAttrDiff(l,this._attr);if(Object.keys(c).length>0&&s)for(let u of Object.values(this._nodeSubscribers))u({node:this,info:{attrs_diff:c},evt:"upd_attrs"});if(Object.keys(c).length>0&&this._parentBag!==null&&this._parentBag.backref){let u=t===!0?"true":String(t);this._parentBag._onNodeChanged(this,[this.label],"upd_attrs",null,c,u)}}}delAttr(...e){for(let t of e)if(typeof t=="string"&&t.includes(","))for(let r of t.split(","))delete this._attr[r.trim()];else delete this._attr[t]}hasAttr(e,t=null){return e in this._attr?t!==null?this._attr[e]===t:!0:!1}getInheritedAttributes(){let e={};return this._parentBag&&this._parentBag.parentNode&&(e=this._parentBag.parentNode.getInheritedAttributes()),{...e,...this._attr}}subscribe(e,t){this._nodeSubscribers[e]=t}unsubscribe(e){delete this._nodeSubscribers[e]}get compiled(){return this._compiled||(this._compiled={}),this._compiled}get isBranch(){return this._value!=null&&typeof this._value._htraverse=="function"}get position(){return this._parentBag===null?null:this._parentBag._nodes.index(this.label)}get fullpath(){if(this._parentBag!==null){let e=this._parentBag.fullpath;return e?`${e}.${this.label}`:this.label}return null}get parentNode(){return this._parentBag?this._parentBag.parentNode:null}attributeOwnerNode(e,t=null){let r=this;if(t===null)for(;r&&!(e in r._attr);)r=r.parentNode;else for(;r&&r._attr[e]!==t;)r=r.parentNode;return r}asTuple(){return[this.label,this.value,this._attr,this._resolver||null]}isEqual(e){if(!(e instanceof o)||this.label!==e.label)return!1;let t=Object.keys(this._attr),r=Object.keys(e._attr);if(t.length!==r.length)return!1;for(let n of t)if(this._attr[n]!==e._attr[n])return!1;return this._resolver!==null?this._resolver===e._resolver:this._value&&typeof this._value.equalTo=="function"?this._value.equalTo(e._value):this._value&&typeof this._value.isEqual=="function"?this._value.isEqual(e._value):this._value===e._value}diff(e){if(this.label!==e.label)return`Other label: ${e.label}`;let t=Object.keys(this._attr),r=Object.keys(e._attr);return t.length!==r.length||t.some(n=>this._attr[n]!==e._attr[n])?`attributes self:${JSON.stringify(this._attr)} --- other:${JSON.stringify(e._attr)}`:this._value!==e._value?`value self:${this._value} --- other:${e._value}`:null}toJson(e=!0){let t=this.value;return t&&typeof t.toJson=="function"&&(t=t.toJson(e,!0)),{label:this.label,value:t,attr:this._attr}}toString(){return`BagNode : ${this.label}`}};var Qr=class o{constructor(){this._dict=Object.create(null),this._list=[],this._parentBag=null}index(e){if(e in this._dict)return this._list.findIndex(r=>r.label===e);let t=e.match(/^#(\d+)$/);if(t){let r=parseInt(t[1],10);return r<this._list.length?r:-1}if(t=e.match(/^#(\w*)=(.*)$/),t){let[,r,n]=t,i=n.includes("::")?j(n):n;return r?this._list.findIndex(s=>s.getAttr(r)===i):this._list.findIndex(s=>s._value===i)}return-1}_parsePosition(e){let t=this._list.length;if(e==null||e===">")return t;if(typeof e=="number")return e<0&&(e=t+e),Math.max(0,Math.min(e,t));if(e==="<")return 0;if(e.startsWith("#")){let r=this._parseSharpIndex(e.slice(1),e);return Math.min(r,t)}if(e.startsWith("<")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i,t)}let n=this.index(r);if(n<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return n}if(e.startsWith(">")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i+1,t)}let n=this.index(r);if(n<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return n+1}throw new Error(`Invalid node_position '${e}': unrecognized syntax`)}_parseSharpIndex(e,t){if(!/^-?\d+$/.test(e))throw new Error(`Invalid node_position '${t}': '${e}' is not an integer`);let r=parseInt(e,10);if(r<0)throw new Error(`Invalid node_position '${t}': negative index not allowed in '#n' syntax`);return r}get(e){if(typeof e=="number")return e>=0&&e<this._list.length?this._list[e]:null;if(e.startsWith("#")){let t=this.index(e);return t>=0?this._list[t]:null}return this._dict[e]||null}set(e,t,r=">",n=null,i=null,s=null,a=!1,l=!0,c=null,u=!0,d=!1,f=null){let h=null;if(e.includes("?")&&([e,h]=e.split("?",2)),e==null||e.startsWith("#"))throw new Error("Cannot create new node with #n syntax");if(h){let m=h.split("&");if(m.length===1)n={[m[0]]:t};else{if(!Array.isArray(t)||t.length!==m.length)throw new Error("Wrong attributes assignment");n={};for(let b=0;b<m.length;b++)n[m[b]]=t[b]}t=null}let p=this._dict[e];if(p)f&&(p.nodeTag=f),s!==null&&(s===!1?p.resolver=null:p.resolver=s),h?p.setAttr(n,u,!0,l):p.setValue(t,u,n,a,l,c,d);else{let m=i&&i.nodeClass?i.nodeClass:qe;p=new m(i,e,h?null:t,n,s,f,null,l);let b=this._parsePosition(r);this._dict[e]=p,this._list.splice(b,0,p),u&&i&&i.backref&&i._onNodeInserted(p,b,null,c,d)}return d&&p.setValue(null,!1),p}pop(e){let t=this.get(e);if(t){delete this._dict[t.label];let r=this._list.indexOf(t);return r>=0&&this._list.splice(r,1),t}return null}has(e){return e in this._dict}get length(){return this._list.length}clear(){this._dict=Object.create(null),this._list=[]}keys(){return this._list.map(e=>e.label)}values(){return this._list.map(e=>e.getValue())}items(){return this._list.map(e=>[e.label,e.getValue()])}[Symbol.iterator](){return this._list[Symbol.iterator]()}move(e,t,r=!0){if(t<0)return;let n=Array.isArray(e)?e:[e];if(n.length===0||t>=this._list.length)return;let i=this._list[t].label;if(n.length>1){let s=[...n].sort((u,d)=>u-d),a=s[0]<t?1:0,l=[];for(let u=s.length-1;u>=0;u--){let d=s[u];if(d>=0&&d<this._list.length){let f=this._list[d];this._list.splice(d,1),l.push(f),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(f,d)}}let c=this.index(i);c<0&&(c=this._list.length),c+=a;for(let u of l)this._list.splice(c,0,u),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(u,c)}else{let s=n[0];if(s===t||s<0||s>=this._list.length)return;let a=this._list[s];this._list.splice(s,1),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(a,s),this._list.splice(t,0,a),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(a,t)}}isEqual(e){if(!(e instanceof o)||this._list.length!==e._list.length)return!1;for(let t=0;t<this._list.length;t++){let r=this._list[t],n=e._list[t];if(!r.isEqual(n))return!1}return!0}};var Wa="::RSLV:",Ii=new Map,Ci=new Map,Di=new WeakMap,ce=class extends Error{constructor(e){super(e),this.name="BagSerializationError"}},lr=class extends Y{constructor(e){super({asBag:!1}),Di.set(this,e)}get payload(){return Di.get(this)}load(){throw new ce("This resolver is opaque; local execution is unavailable")}};function Ni(o,{module:e,name:t,encode:r,decode:n}){if(!(o.prototype instanceof Y)||o===lr||typeof e!="string"||!e||typeof t!="string"||!t||typeof r!="function"||typeof n!="function")throw new TypeError("registerResolver requires a BagResolver subclass, module, name and adapters");let i=JSON.stringify([e,t]);if(Ii.has(i)&&Ii.get(i).cls!==o)throw new TypeError(`Resolver ${e}.${t} is already registered`);if(Ci.has(o)&&Ci.get(o).key!==i)throw new TypeError("A resolver class cannot own two wire identities");let s={cls:o,module:e,name:t,encode:r,decode:n,key:i};Ii.set(i,s),Ci.set(o,s)}function Ed(o){if(!o||typeof o!="object"||Array.isArray(o)||typeof o.resolver_module!="string"||typeof o.resolver_class!="string"||!Array.isArray(o.args??[])||!o.kwargs||typeof o.kwargs!="object"||Array.isArray(o.kwargs))throw new ce("Invalid resolver description")}function Td(o,e=new Set){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(typeof o!="object"||e.has(o)||!Array.isArray(o)&&Object.getPrototypeOf(o)!==Object.prototype&&Object.getPrototypeOf(o)!==null)throw new ce("Resolver parameters must be JSON data; callbacks cannot travel");e.add(o);for(let t of Object.values(o))Td(t,e);e.delete(o)}}function Wn(o){if(Di.has(o))return Di.get(o);let e=Ci.get(o.constructor);if(!e)throw new ce(`Unregistered resolver: ${o.constructor.name}`);let t=e.encode(o),r={resolver_module:e.module,resolver_class:e.name,args:t.args??[],kwargs:t.kwargs??{}};return Ed(r),Td(r),Wa+JSON.stringify(r)}function Oi(o){if(typeof o!="string"||!o.startsWith(Wa))return null;let e=o.slice(Wa.length);if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+$/.test(e))return new lr(o);let t;try{t=JSON.parse(e)}catch{throw new ce("Invalid resolver JSON or signed token")}Ed(t);let r=Ii.get(JSON.stringify([t.resolver_module,t.resolver_class]));if(!r)return new lr(o);let n=r.decode({args:t.args??[],kwargs:t.kwargs});if(!(n instanceof r.cls))throw new ce("Resolver decoder returned an incompatible instance");return n}function $i(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[e,t instanceof Y?Wn(t):t]))}function Ga(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[e,Oi(t)??t]))}var Ke="__cls";function en(o,e){return o!==null&&o.tytxSuffix===e?o:Kr(e)}function Xm(o){let e=o.tytxSuffix,t=Object.entries(Pe(e)).filter(([,r])=>r===o).map(([r])=>r);if(t.length===0)throw new ce(`${o.name} is not in the TYTX subtype dictionary of '${e}'`);if(t.length>1)throw new ce(`${o.name} is in the TYTX subtype dictionary of '${e}' under several names: ${t.sort().join(", ")}`);return t[0]}function Ha(o,e){let t=Pe(o);if(!Object.hasOwn(t,e))throw new ce(`Unknown Bag class '${e}' for TYTX type '${o}'`);return t[e]}function Xa(o,e){return o===e?null:Xm(o)}function*Ad(o,e=[]){for(let t of o){let r=[...e,t.label];yield[r,t];let n=t.getValue(!0);!t.resolver&&n instanceof x&&(yield*Ad(n,r))}}function Ym(o){let e=o.toISOString(),t=o.getUTCFullYear()===1970&&o.getUTCMonth()===0&&o.getUTCDate()===1,r=o.getUTCHours()===0&&o.getUTCMinutes()===0&&o.getUTCSeconds()===0&&o.getUTCMilliseconds()===0;if(r&&!t)return e.slice(0,e.indexOf("T"));let n=e.replace(/\.000Z$/,"Z");return t&&!r?n.slice(n.indexOf("T")+1):n}function tn(o){if(o===null||typeof o!="object")return!1;let e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function qt(o){return typeof o=="string"?o.includes("::")?`${o}::T`:o:Array.isArray(o)?o.map(qt):tn(o)?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,qt(t)])):o}function Ya(o){if(!tn(o))throw new TypeError("Bag options must be an object");let{recursive:e=!0}=o;if(typeof e!="boolean")throw new TypeError("recursive must be a boolean");return e}var Sd=!1,x=class o{static tytxSuffix="X";constructor(e=null,t={}){this._nodes=new Qr,this._backref=!1,this._parent=null,this._parentNode=null,this._rootAttributes=null,this._updSubscribers={},this._insSubscribers={},this._delSubscribers={},Ya(t),e!=null&&this.fillFrom(e,t)}get parent(){return this._parent}set parent(e){this._parent=e}get parentNode(){return this._parentNode}set parentNode(e){this._parentNode=e}get backref(){return!!this._backref}get nodeClass(){return qe}createChildBag(){return new this.constructor}get fullpath(){if(this._parent!==null&&this._parentNode!==null){let e=this._parent.fullpath;return e?`${e}.${this._parentNode.label}`:this._parentNode.label}return null}relativePath(e){let t=[],r=e;for(;r!==null;){if(r.parentBag===this)return t.push(r.label),t.reverse(),t.join(".");t.push(r.label),r=r.parentNode}return null}get length(){return this._nodes.length}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}get attributes(){return this._parentNode!==null?this._parentNode.getAttr():{}}get rootAttributes(){return this._rootAttributes}set rootAttributes(e){this._rootAttributes=e!==null?{...e}:null}_htraverseBefore(e){let t=this,r;for(typeof e=="string"?(e=e.replace(/\.\.\//g,"#parent."),r=e.split(".").filter(n=>n)):r=[...e];r.length&&r[0]==="#parent"&&t!==null;)r.shift(),t=t.parent;return[t,r]}_htraverse(e,t=!1,r=!0){let[n,i]=this._htraverseBefore(e);if(n===null)return[null,null];if(i.length===0)return[n,""];for(;i.length>1&&n instanceof o;){let s=i[0];if(s==="#parent"){if(n.parent===null||n.parent===void 0)break;i.shift(),n=n.parent;continue}let a=n._nodes.get(s);if(!a)break;let l=a.getValue(r);if(l instanceof o)i.shift(),n=l;else if(t){let c=n.createChildBag();a.setValue(c,!0,null,!0,!0,"autocreate"),i.shift(),n=c}else break}if(!t)return i.length>1?[null,null]:[n,i[0]];for(;i.length>1;){let s=i.shift();if(s.startsWith("#"))throw new rn("Not existing index in #n syntax");let a=n.createChildBag();n._nodes.set(s,a,">",null,n,null,!1,!0,"autocreate"),n=a}return[n,i[0]]}get(e,t=null,r=!0,n={}){if(!e)return this;if(e==="#parent")return this.parent;let i=null;e.includes("?")&&([e,i]=e.split("?",2));let s=this._nodes.get(e);return s?s.getValue(r,i,n):t}getItem(e,t=null,r=!1,n={}){if(!e)return this;let[i,s]=this._htraverse(e,!1,r);return i instanceof o?i.get(s,t,r,n):t}setItem(e,t,r=null,n=">",i=!1,s=!0,a=null,l=!1,c=!0,u=null,d=null){if(e==="")throw new RangeError("setItem requires a non-empty path");let[f,h]=this._htraverse(e,!0);return f._nodes.set(h,t,n,r,f,u,i,s,a,c,l,d)}_pop(e,t=null){let r=this._nodes.index(e);if(r>=0){let n=this._nodes.pop(r);return this.backref&&this._onNodeDeleted(n,r,null,t),n}return null}pop(e,t=null,r=null){let n=this.popNode(e,r);return n?n.value:t}delItem(e,t=null,r=null){return this.pop(e,t,r)}popNode(e,t=null){let[r,n]=this._htraverse(e,!1,!0);if(!r||!n)return null;let i=r._nodes.get(n);if(!i)return null;try{return r._pop(n,t)}finally{i.parentBag===r&&r._nodes._dict[i.label]!==i&&(i.parentBag=null)}}clear(){let e=[...this._nodes];this._nodes.clear(),this.backref&&this._onNodeDeleted(e,-1);for(let t of e)t.parentBag=null}getNode(e,t=!0,r=!1,n=null){if(e==null||e==="")return this.parentNode;if(typeof e=="number")return this._nodes.get(e);typeof e=="string"&&(e=e.split("?",1)[0]);let[i,s]=this._htraverse(e,r,t);if(i instanceof o&&s){let a=i._nodes.get(s);if(a)return a;if(r)return i._nodes.set(s,n,">",null,i,null,!1,!0,"autocreate"),i._nodes.get(s)}return null}setBackref(e=null,t=null){let r=this._backref;if(this._backref=!0,this._parent=t,this._parentNode=e,!r){this._nodes._parentBag=this;for(let n of this)n.parentBag=this}}delParentRef(){this._parent=null,this._parentNode=null,this._backref=!1}clearBackref(){if(this._backref){this._backref=!1,this._parent=null,this._parentNode=null,this._nodes._parentBag=null;for(let e of this){e.parentBag=null;let t=e.getValue(!0);t instanceof o&&t.clearBackref()}}}_onNodeChanged(e,t,r,n=null,i=null,s=null,a=!1){for(let l of Object.values(this._updSubscribers))l({node:e,pathlist:t,oldvalue:n,attrs_diff:i,evt:r,reason:s,fired:a});this._parent&&this._parentNode&&this._parent._onNodeChanged(e,[this._parentNode.label,...t],r,n,i,s,a)}_onNodeInserted(e,t,r=null,n=null,i=!1){let s=e.parentBag,a=e.getValue(!0);s!==null&&s.backref&&a instanceof o&&a.setBackref(e,s),r===null&&(r=[]);for(let l of Object.values(this._insSubscribers))l({node:e,pathlist:r,ind:t,evt:"ins",reason:n,fired:i});this._parent&&this._parentNode&&this._parent._onNodeInserted(e,t,[this._parentNode.label,...r],n,i)}_onNodeDeleted(e,t,r=null,n=null){for(let i of Object.values(this._delSubscribers))i({node:e,pathlist:r,ind:t,evt:"del",reason:n});this._parent&&this._parentNode&&(r===null&&(r=[]),this._parent._onNodeDeleted(e,t,[this._parentNode.label,...r],n))}_subscribe(e,t,r){r!=null&&(t[e]=r)}subscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=null,insert:n=null,delete:i=null,any:s=null}=t;this.backref||this.setBackref(),this._subscribe(e,this._updSubscribers,r||s),this._subscribe(e,this._insSubscribers,n||s),this._subscribe(e,this._delSubscribers,i||s)}unsubscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=!1,insert:n=!1,delete:i=!1,any:s=!1}=t;(r||s)&&delete this._updSubscribers[e],(n||s)&&delete this._insSubscribers[e],(i||s)&&delete this._delSubscribers[e]}[Symbol.iterator](){return this._nodes[Symbol.iterator]()}keys(){return this._nodes.keys()}values(){return this._nodes.values()}items(){return[...this._nodes].map(e=>({key:e.label,value:e.getValue()}))}get nodes(){return this.getNodes()}node(e){return this._nodes.get(e)}setAttr(e=null,t=null,r=!0){let n=o.prototype.getNode.call(this,e,!0,!0);n&&n.setAttr(t,!0,!0,r)}getAttr(e=null,t=null,r=null){let n=this.getNode(e);return n?n.getAttr(t,r):r}delAttr(e=null,...t){let r=this.getNode(e);r&&r.delAttr(...t)}getInheritedAttributes(){return this._parentNode?this._parentNode.getInheritedAttributes():{}}getNodes(e=null){return e?[...this._nodes].filter(t=>e(t)):[...this._nodes]}getNodeByValue(e,t){for(let r of this._nodes){let n=r.value;if(n instanceof o){if(n.getItem(e)===t)return r}else if(n&&n.get&&n.get(e)===t)return r}return null}getNodeByAttr(e,t,r=!1,n=!1){let i=t===void 0,s=r&&typeof t=="string"?t.toLowerCase():t,a=l=>{let c=[];for(let u of l._nodes){if(e in u.attr){let d=r&&typeof u.attr[e]=="string"?u.attr[e].toLowerCase():u.attr[e];if(i||d==s)return u}if(u._value instanceof o)if(n){let d=a(u._value);if(d)return d}else c.push(u._value)}for(let u of c){let d=a(u);if(d)return d}return null};return a(this)}isEmpty(e=!1,t=!1){if(this._nodes.length===0)return!0;for(let r of this._nodes){if(r._resolver!==null)return!1;let n=r.getValue(!0);if(n!=null&&!(e&&n===0)&&!(t&&n===""))return!1}return!0}query(e=null,t=null,r=!1,n=!1,i=!0,s=!0,a=null,l=!0){e||(e="#k,#v,#a");let c=this,u;if(typeof e=="string"){if(e.includes(":")){let[h,p]=e.split(":");c=this.getItem(h),e=p}u=e.split(",").map(h=>h.trim())}else u=e;let d=(h,p,m,b,w)=>{if(p==="#k")return h.label;if(p==="#p")return m;if(p==="#n")return h;if(typeof p=="function")return p(h);if(p==="#v"){let _=w();return b&&_ instanceof o?null:_}else if(p.startsWith("#v.")){let _=p.split(".").slice(1).join("."),v=w();return v&&v.getItem?v.getItem(_):null}else{if(p==="#__v")return h.getValue(!0);if(p.startsWith("#a")){let _=p.includes(".")?p.split(".").slice(1).join("."):null;return h.getAttr(_)}else{let _=w();return _&&_.getItem?_.getItem(p):null}}};function*f(){let h=0;function*p(m,b){for(let w of m._nodes){let _=b?`${b}.${w.label}`:w.label,v=!1,E,D=()=>(v||(E=w.getValue(l),v=!0),E);if((i&&s||(D()instanceof o?s:i))&&(t===null||t(w))&&(yield u.length===1?d(w,u[0],_,n,D):u.map(C=>d(w,C,_,n,D)),h++,a!==null&&h>=a))return;if(n){let C=D();if(C instanceof o&&(yield*p(C,_),a!==null&&h>=a))return}}}yield*p(c,"")}return r?f():[...f()]}getLeaves(){let e=[],t=(r,n)=>{for(let i of r._nodes){let s=n?`${n}.${i.label}`:i.label,a=i.getValue(!1);a instanceof o?t(a,s):e.push([s,a])}};return t(this,""),e}digest(e=null,t=null,r=!1){typeof t=="boolean"&&(console.warn("Bag.digest(what, asColumns) is deprecated; use digest(what, null, asColumns)."),r=t,t=null);let n=this.query(e,t,!1,!1,!0,!0,null,!1);if(r){if(!n||n.length===0)return(typeof e=="string"?e:"#k,#v,#a").split(",").map(l=>l.trim()).map(()=>[]);let i=[...n];if(i.length&&Array.isArray(i[0])){let s=i[0].length,a=[];for(let l=0;l<s;l++)a.push(i.map(c=>c[l]));return a}return[i]}return[...n]}columns(e,t=!1){typeof e=="string"&&(e=e.split(","));let r=t?"#a.":"",n=e.map(i=>`${r}${i}`).join(",");return this.digest(n,null,!0)}sum(e="#v",t=!1,r=null){if(t!=null&&typeof t!="boolean")throw new TypeError("sum strict must be a boolean; pass condition as the third argument");if(r!=null&&typeof r!="function")throw new TypeError("sum condition must be callable; deep is no longer supported");let n=i=>{let s=0,a=!1;for(let l of this.query(i,r)){if(l==null||l===""){a=!0;continue}if(typeof l!="number"&&typeof l!="boolean"){if(t)throw new TypeError(`sum encountered non-numeric value: ${typeof l}`);continue}s+=l}return t&&a?null:s};return e.includes(",")?e.split(",").map(i=>n(i.trim())):n(e)}sort(e="#k:a"){let t=(n,i)=>n==null?[-1,""]:i&&typeof n=="string"?[0,n.toLowerCase()]:[0,n],r=(n,i)=>n[0]!==i[0]?n[0]-i[0]:n[1]<i[1]?-1:n[1]>i[1]?1:0;if(typeof e=="function")this._nodes._list.sort((n,i)=>{let s=e(n),a=e(i);return s<a?-1:s>a?1:0});else{let n=e.split(",");n.reverse();for(let i of n){let s,a;i.includes(":")?[s,a]=i.split(":",2):(s=i,a="a"),s=s.trim(),a=a.trim();let l=a==="d"||a==="D",c=a==="a"||a==="d",u;if(s.toLowerCase()==="#k")u=d=>t(d.label,c);else if(s.toLowerCase()==="#v")u=d=>t(d.value,c);else if(s.toLowerCase().startsWith("#a.")){let d=s.slice(3);u=f=>t(f.getAttr(d),c)}else u=d=>{let f=d.value,h=f instanceof o?f.getItem(s):f?f[s]:null;return t(h,c)};this._nodes._list.sort((d,f)=>{let h=r(u(d),u(f));return l?-h:h})}}return this}equalTo(e){return e instanceof o?this._nodes.isEqual(e._nodes):!1}has(e){if(typeof e=="string"){let t=null;e.includes("?")&&([e,t]=e.split("?",2));let r=this.getNode(e);return r===null?!1:t===null?!0:t.split("&").every(n=>n in r.attr)}else if(e&&e.label!==void 0)return[...this._nodes].includes(e);return!1}getResolver(e){let t=this.getNode(e);return t?t.resolver:null}setResolver(e,t){let r=this.getNode(e);r||(this.setItem(e,null),r=this.getNode(e)),r.resolver=t}setCallbackItem(e,t,r={}){let n=new _t({callback:t,...r});this.setResolver(e,n)}move(e,t,r=!0){this._nodes.move(e,t,r)}asDict(e=!1,t=!1,r=!1,n=!1){let i={};for(let s of this._nodes){let a=s.value;if(n&&a==null)continue;let l=s.label;e&&(l=String(l)),t&&(l=l.toLowerCase()),r&&a instanceof o&&(a=o.prototype.asDict.call(a,e,t,r,n)),Object.defineProperty(i,l,{value:a,enumerable:!0,writable:!0,configurable:!0})}return i}setdefault(e,t=null){let r=this.getNode(e);return r?r.value:(this.setItem(e,t),t)}deepcopy(e=!1){let t=this.createChildBag();for(let r of this._nodes){let n=r.getValue(!e);n instanceof o&&(n=n.deepcopy(e));let i=new t.nodeClass(t,r.label,n);i.setAttr({...r.attr},!1,!1,!1),i.nodeTag=r.nodeTag,i.xmlTag=r.xmlTag,t._nodes._list.push(i),t._nodes._dict[i.label]=i}return t}update(e,t=null,r=null,n=!1){if(!(e instanceof o)){for(let i in e){let s=e[i];(!n||s!==null||!this._nodes.has(i))&&this.setItem(i,s,null,">",!1,!1,r,!1,r!==!1)}return}for(let i of[...e]){let s=i.label,a=t==="static"?i.resolver:null,l=a?null:i.getValue(),c=i.attr.__replace;delete i.attr.__replace;let u=this._nodes.get(s);if(u)if(u.setAttr(i.attr,r===null?!0:r,!0,!1),i.nodeTag!=null&&(u.nodeTag=i.nodeTag),i.xmlTag!=null&&(u.xmlTag=i.xmlTag),a)u.resolver=a,u.setValue(null,r===null?!0:r,null,null,!1,r);else{i.resolver&&(u.resolver=null);let d=u.getValue();l instanceof o&&d instanceof o&&!c?d.update(l,t,r,n):(!n||l!==null)&&u.setValue(l,r===null?!0:r,null,null,!1,r)}else{let d=this.setItem(s,a||l,i.attr,">",!1,!1,r,!1,r!==!1);d.nodeTag=i.nodeTag,d.xmlTag=i.xmlTag}}}_fillFromBag(e){this.clear();for(let t of e){let r=new this.nodeClass(this,t.label);r.replace(t),r.nodeTag=t.nodeTag,r.xmlTag=t.xmlTag,this._nodes._list.push(r),this._nodes._dict[r.label]=r}}_appendLiteral(e,t,r=null,n=null,i=null){if(typeof e!="string")throw new TypeError("Bag labels must be strings");let s=new this.nodeClass(this,e,null,r,n,i,null,!1);return t instanceof Y?s.resolver=t:s._value=t,this._nodes._dict[e]=s,this._nodes._list.push(s),s}fillFrom(e=null,t={}){let r=Ya(t);if(e!=null&&!tn(e)&&!Array.isArray(e))throw new TypeError("Bag source must be a dictionary, array or null");let n=this.createChildBag(),i=new Set,s=(a,l,c)=>{if(i.has(l))throw new TypeError(`Cyclic Bag source at ${c}`);i.add(l);try{let u=Array.isArray(l)?String(l.length).length+1:0,d=Array.isArray(l)?Array.from(l,(f,h)=>[`r_${String(h).padStart(u,"0")}`,f]):Object.entries(l);if(!Array.isArray(l)&&Object.getOwnPropertySymbols(l).some(f=>Object.prototype.propertyIsEnumerable.call(l,f)))throw new TypeError(`Bag labels must be strings at ${c}`);for(let[f,h]of d){let p=h;r&&(tn(p)||Array.isArray(p))&&(p=this.createChildBag(),s(p,h,`${c}[${JSON.stringify(f)}]`)),a._appendLiteral(f,p)}}finally{i.delete(l)}};return e!=null&&s(n,e,"$"),this._replacePrepared(n)}_loadSource(e,t={}){return this.fillFrom(e,t)}replace(e){if(!(e instanceof o))throw new TypeError("Bag.replace expects a Bag");if(e===this)return this;let t=this.createChildBag();return t._fillFromBag(e),this._replacePrepared(t)}_replacePrepared(e){for(let r of this._nodes){r.parentBag=null;let n=r.getValue(!0);n instanceof o&&n.clearBackref()}let t=this._nodes;this._nodes=e._nodes,e._nodes=t,this._nodes._parentBag=this.backref?this:null,e._nodes._parentBag=null;for(let r of this._nodes)r.parentBag=this;for(let r of e._nodes)r._parentBag=e;return this.backref&&this.parent&&this.parentNode&&this.parent._onNodeChanged(this.parentNode,[this.parentNode.label],"upd_value",e),this}forEach(e,{static:t=!0,deep:r=!1,kwargs:n={}}={}){if(typeof e!="function")throw new TypeError("forEach requires a callback");let i=(s,a)=>{for(let l=0;l<s._nodes.length;l++){let c=s._nodes._list[l],u={...a};"_pathlist"in a&&(u._pathlist=[...a._pathlist,c.label]),"_indexlist"in a&&(u._indexlist=[...a._indexlist,l]);let d=e(c,u,l);if(d)return d;if(d==null&&r){let f=c.getValue(t);if(f instanceof o){let h=i(f,u);if(h)return h}}}return null};return i(this,n)}*traverse(){for(let e of this._nodes){yield e;let t=e.getValue(!0);t instanceof o&&(yield*t.traverse())}}*_iterNodesWithPaths(e=!0,t=""){for(let r of this._nodes){let n=t?`${t}.${r.label}`:r.label;yield[n,r];let i=r.getValue(e);i instanceof o&&(yield*i._iterNodesWithPaths(e,n))}}*_nodeFlattener(e=null){let t=e!==null,r=t?Object.create(null):null,n=0,i=new Map([["[]",this.constructor]]);for(let[s,a]of Ad(this)){let l=s.slice(0,-1),c=JSON.stringify(s),u=JSON.stringify(l),d=a.getValue(!0),f,h=null;if(a.resolver)f=Wn(a.resolver);else if(d instanceof o){let b=d.constructor,w=b.tytxSuffix;i.set(c,b),h=Xa(b,en(i.get(u),w)),f=`::${w}`}else d===null?f="::NN":f=qt(d);if(a.attr&&Object.hasOwn(a.attr,Ke))throw new ce(`node '${s}': the attribute '${Ke}' is reserved for the Bag class name`);let p=$i(qt(a.attr));h!==null&&(p[Ke]=h);let m=a.nodeTag;t?(yield[l.length?r[u]:null,a.label,m,f,p],d instanceof o&&(r[c]=n,e[n]=s,n++)):yield[l,a.label,m,f,p]}}toTytx(e="json",t=!1){let r=this._toTytxPayload(t),n=this.constructor.tytxSuffix;if(e==="json")return`${r}::${n}`;if(e==="msgpack")return _i(new He(4,new TextEncoder().encode(`${n}:${r}`)));throw new TypeError(`Unsupported transport: ${e}`)}_toTytxPayload(e=!1){let t;if(e){let i={};t={rows:[...this._nodeFlattener(i)],paths:i}}else t={rows:[...this._nodeFlattener(null)]};let r=this.constructor,n=Xa(r,en(null,r.tytxSuffix));return n!==null&&(t[Ke]=n),t.rows=t.rows.map(([i,s,a,l,c])=>[qt(i),qt(s),qt(a),l,c]),t.paths&&(t.paths=qt(t.paths)),R(t)}static fromTytx(e,t="json",r={}){if(tn(t)&&(r=t,t="json"),Ya(r),typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("fromTytx requires serialized text or bytes");if(t!=="json"&&t!=="msgpack")throw new TypeError(`Unsupported transport: ${t}`);t==="json"&&e instanceof Uint8Array&&(e=new TextDecoder().decode(e));let n=j(e,t==="json"?null:t);if(n instanceof o)return n;if(!tn(n)&&!Array.isArray(n))throw new TypeError("fromTytx requires a dictionary, array or typed Bag root");return new this(n,r)}static _fromTytxPayload(e){let t=this.tytxSuffix;if(e==="")return new(en(null,t));let r=j(e);if(!r||!Array.isArray(r.rows))throw new ce("Invalid TYTX Bag: expected rows");let n=r.paths,i=n!=null,s=Object.hasOwn(r,Ke)?Ha(t,r[Ke]):en(null,t),a=new s,l=new Map([["[]",a]]);for(let c of r.rows){if(!Array.isArray(c)||c.length!==5)throw new ce("Invalid TYTX Bag row");let[u,d,f,h,p]=c,m=u??"";if(i){if(u!==null&&!Object.hasOwn(n,u))throw new ce(`Unknown TYTX parent reference: ${u}`);m=u===null?"":n[u]}if(typeof m=="string"&&(m=m?m.split("."):[]),!Array.isArray(m))throw new ce("Invalid TYTX parent path");let b=JSON.stringify(m);if(!l.has(b))throw new ce(`Missing or undecodable TYTX parent branch: ${m}`);let w=l.get(b),_=JSON.stringify([...m,d]),v=h,E=Oi(v),D=Ga(p),k=Object.hasOwn(D,Ke)?D[Ke]:null;if(delete D[Ke],v instanceof o){let O=v.constructor.tytxSuffix,L=k!==null?Ha(O,k):en(w.constructor,O);v=new L,l.set(_,v)}else if(k!==null)throw new ce(`node '${_}': the attribute '${Ke}' is reserved for the Bag class name of a branch`);let C=w._appendLiteral(d,E?null:v,D,E);C.nodeTag=f??null}return a}toXml(e={}){let{pretty:t=!1,encoding:r="UTF-8",docHeader:n=null,selfClosedTags:i=null}=e,s=this._bagToXml(i,t);return n===!0?s=`<?xml version='1.0' encoding='${r}'?>
25
+ `,Dn=class o{static install({document:e,root:t}){return li.has(t)||li.set(t,new o(e,t)),li.get(t)}constructor(e,t){this.document=e,this.root=t,this.releases=[],this.closed=!1,t.setAttribute("data-gramlot-viewport",e.defaultView.parent===e.defaultView?"root":"child");let r=e.querySelector('meta[name="viewport"]');r||(r=e.createElement("meta"),r.name="viewport",r.content="width=device-width,initial-scale=1",e.head.append(r));let n=r.content.split(",").map(i=>i.trim()).filter(i=>!i.startsWith("viewport-fit="));r.content=[...n,"viewport-fit=cover"].join(","),this.style=e.createElement("style"),this.style.textContent=rp,e.head.append(this.style)}subscribeAppearance(e){let t=this.document.defaultView,r=t.matchMedia("(prefers-color-scheme: dark)"),n=()=>{let a=t.getComputedStyle(this.document.documentElement).colorScheme;e({dark:a==="dark"||!["light","dark"].includes(a)&&r.matches})},i=new t.MutationObserver(n);i.observe(this.document.documentElement,{attributes:!0,attributeFilter:["data-theme","style","class"]}),r.addEventListener("change",n),n();let s=()=>{i.disconnect(),r.removeEventListener("change",n)};return this.releases.push(s),s}dispose(){if(!this.closed){this.closed=!0;for(let e of this.releases)e();this.style.remove(),this.root.removeAttribute("data-gramlot-viewport"),li.delete(this.root)}}};var Nn=class{#e=new Map;registerGroup(e,t={}){if(typeof e!="string"||!e||e.includes(":"))throw new TypeError("Extension command namespace must be nonempty and unqualified");if(this.#e.has(e))throw new Error(`Duplicate command namespace: ${e}`);if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["author","description"].includes(n))||Object.values(t).some(n=>typeof n!="string"))throw new TypeError(`Invalid command group metadata: ${e}`);let r=new Map;return this.#e.set(e,{metadata:{...t},commands:r}),Object.freeze({register(n,i){if(typeof n!="string"||!n||n.includes(":"))throw new TypeError("Invalid command name");if(r.has(n))throw new Error(`Duplicate command: ${e}:${n}`);if(!i||typeof i!="object"||Array.isArray(i)||!Object.hasOwn(i,"label")||!Object.hasOwn(i,"publish")||Object.keys(i).some(s=>!["label","publish","icon","iconSrc","tooltip"].includes(s))||Object.values(i).some(s=>typeof s!="string"))throw new TypeError(`Invalid command definition: ${e}:${n}`);r.set(n,Object.freeze({...i}))}})}get(e){let t=e.indexOf(":");return this.#e.get(e.slice(0,t))?.commands.get(e.slice(t+1))}toDocument(){return{document_format:{name:"gramlot_commands",version:"1.0"},groups:Object.fromEntries([...this.#e].map(([e,{metadata:t,commands:r}])=>[e,{...t,commands:Object.fromEntries(r)}]))}}};var On=class{constructor(e,{fetcher:t=globalThis.fetch?.bind(globalThis),closeUrl:r="/gramlot/close",navigator:n=globalThis.navigator,XMLHttpRequest:i=globalThis.XMLHttpRequest}={}){this.rpcUrl=e,this.fetcher=t,this.closeUrl=r,this.navigator=n,this.XMLHttpRequest=i}get supportsCallSync(){return!0}async call(e,t){let r=await this.fetcher(this.rpcUrl,{method:"POST",credentials:"same-origin",signal:t,headers:{"Content-Type":"application/json"},body:e});if(r.status!==200)throw new Error(`rpc failed: HTTP ${r.status}`);return r.text()}callSync(e){let t=new this.XMLHttpRequest;if(t.open("POST",this.rpcUrl,!1),t.setRequestHeader("Content-Type","application/json"),t.send(e),t.status!==200)throw new Error(`rpc failed: HTTP ${t.status}`);return t.responseText}close(e){if(typeof this.closeUrl!="string"||!this.closeUrl.trim())throw new TypeError("HttpTransport.closeUrl must be nonempty text");if(typeof this.navigator?.sendBeacon!="function")throw new TypeError("HttpTransport requires navigator.sendBeacon");let t=new Blob([JSON.stringify({pageId:e})],{type:"application/json"});try{this.navigator.sendBeacon(this.closeUrl,t)}catch(r){if(r.name==="TypeError")throw r}}dispose(){}};var ci=class{constructor(e,t){this.channel=e,this.closeTransport=t}get supportsCallSync(){return!1}call(e,t){return this.channel.call(e,t)}close(e,t){this.closeTransport.close(e,t)}dispose(){this.closeTransport.dispose()}};var Rt=class{createTransport({rpcUrl:e,closeUrl:t,document:r,channel:n=null}){let i=r.defaultView,s=new On(e,{closeUrl:t,navigator:i.navigator,XMLHttpRequest:i.XMLHttpRequest});return n===null?s:new ci(n,s)}};var Va={};ee(Va,{CONTENT_TYPES:()=>Ua,__version__:()=>qm,createDecimal:()=>Ye,fetchTytx:()=>Ii,fromTytx:()=>j,fromTytxIter:()=>Fa,getDateType:()=>bt,getDecimalLibrary:()=>Zr,getRegisteredType:()=>Kr,getSubtypeDict:()=>Pe,getTransport:()=>qa,isDecimal:()=>q,registerClass:()=>yd,registerSubtype:()=>vd,registerType:()=>Wn,setDecimalLibrary:()=>_d,setSubtypeDict:()=>wt,toTytx:()=>R,toTytxIter:()=>dd});var ka={};ee(ka,{Decimal:()=>Wr,default:()=>xa});var qr=9e15,Mt=1e9,ba="0123456789abcdef",fi="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",hi="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",wa={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-qr,maxE:qr,crypto:!1},$u,gt,U=!0,mi="[DecimalError] ",Bt=mi+"Invalid argument: ",Ru=mi+"Precision limit exceeded",ju=mi+"crypto unavailable",Pu="[object Decimal]",Ee=Math.floor,pe=Math.pow,np=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,op=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,ip=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Bu=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Ge=1e7,M=7,sp=9007199254740991,ap=fi.length-1,_a=hi.length-1,A={toStringTag:Pu};A.absoluteValue=A.abs=function(){var o=new this.constructor(this);return o.s<0&&(o.s=1),B(o)};A.ceil=function(){return B(new this.constructor(this),this.e+1,2)};A.clampedTo=A.clamp=function(o,e){var t,r=this,n=r.constructor;if(o=new n(o),e=new n(e),!o.s||!e.s)return new n(NaN);if(o.gt(e))throw Error(Bt+e);return t=r.cmp(o),t<0?o:r.cmp(e)>0?e:new n(r)};A.comparedTo=A.cmp=function(o){var e,t,r,n,i=this,s=i.d,a=(o=new i.constructor(o)).d,l=i.s,c=o.s;if(!s||!a)return!l||!c?NaN:l!==c?l:s===a?0:!s^l<0?1:-1;if(!s[0]||!a[0])return s[0]?l:a[0]?-c:0;if(l!==c)return l;if(i.e!==o.e)return i.e>o.e^l<0?1:-1;for(r=s.length,n=a.length,e=0,t=r<n?r:n;e<t;++e)if(s[e]!==a[e])return s[e]>a[e]^l<0?1:-1;return r===n?0:r>n^l<0?1:-1};A.cosine=A.cos=function(){var o,e,t=this,r=t.constructor;return t.d?t.d[0]?(o=r.precision,e=r.rounding,r.precision=o+Math.max(t.e,t.sd())+M,r.rounding=1,t=lp(r,Uu(r,t)),r.precision=o,r.rounding=e,B(gt==2||gt==3?t.neg():t,o,e,!0)):new r(1):new r(NaN)};A.cubeRoot=A.cbrt=function(){var o,e,t,r,n,i,s,a,l,c,u=this,d=u.constructor;if(!u.isFinite()||u.isZero())return new d(u);for(U=!1,i=u.s*pe(u.s*u,1/3),!i||Math.abs(i)==1/0?(t=ye(u.d),o=u.e,(i=(o-t.length+1)%3)&&(t+=i==1||i==-2?"0":"00"),i=pe(t,1/3),o=Ee((o+1)/3)-(o%3==(o<0?-1:2)),i==1/0?t="5e"+o:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+o),r=new d(t),r.s=u.s):r=new d(i.toString()),s=(o=d.precision)+3;;)if(a=r,l=a.times(a).times(a),c=l.plus(u),r=re(c.plus(u).times(a),c.plus(l),s+2,1),ye(a.d).slice(0,s)===(t=ye(r.d)).slice(0,s))if(t=t.slice(s-3,s+1),t=="9999"||!n&&t=="4999"){if(!n&&(B(a,o+1,0),a.times(a).times(a).eq(u))){r=a;break}s+=4,n=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(B(r,o+1,1),e=!r.times(r).times(r).eq(u));break}return U=!0,B(r,o,d.rounding,e)};A.decimalPlaces=A.dp=function(){var o,e=this.d,t=NaN;if(e){if(o=e.length-1,t=(o-Ee(this.e/M))*M,o=e[o],o)for(;o%10==0;o/=10)t--;t<0&&(t=0)}return t};A.dividedBy=A.div=function(o){return re(this,new this.constructor(o))};A.dividedToIntegerBy=A.divToInt=function(o){var e=this,t=e.constructor;return B(re(e,new t(o),0,1,1),t.precision,t.rounding)};A.equals=A.eq=function(o){return this.cmp(o)===0};A.floor=function(){return B(new this.constructor(this),this.e+1,3)};A.greaterThan=A.gt=function(o){return this.cmp(o)>0};A.greaterThanOrEqualTo=A.gte=function(o){var e=this.cmp(o);return e==1||e===0};A.hyperbolicCosine=A.cosh=function(){var o,e,t,r,n,i=this,s=i.constructor,a=new s(1);if(!i.isFinite())return new s(i.s?1/0:NaN);if(i.isZero())return a;t=s.precision,r=s.rounding,s.precision=t+Math.max(i.e,i.sd())+4,s.rounding=1,n=i.d.length,n<32?(o=Math.ceil(n/3),e=(1/bi(4,o)).toString()):(o=16,e="2.3283064365386962890625e-10"),i=Vr(s,1,i.times(e),new s(1),!0);for(var l,c=o,u=new s(8);c--;)l=i.times(i),i=a.minus(l.times(u.minus(l.times(u))));return B(i,s.precision=t,s.rounding=r,!0)};A.hyperbolicSine=A.sinh=function(){var o,e,t,r,n=this,i=n.constructor;if(!n.isFinite()||n.isZero())return new i(n);if(e=i.precision,t=i.rounding,i.precision=e+Math.max(n.e,n.sd())+4,i.rounding=1,r=n.d.length,r<3)n=Vr(i,2,n,n,!0);else{o=1.4*Math.sqrt(r),o=o>16?16:o|0,n=n.times(1/bi(5,o)),n=Vr(i,2,n,n,!0);for(var s,a=new i(5),l=new i(16),c=new i(20);o--;)s=n.times(n),n=n.times(a.plus(s.times(l.times(s).plus(c))))}return i.precision=e,i.rounding=t,B(n,e,t,!0)};A.hyperbolicTangent=A.tanh=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+7,r.rounding=1,re(t.sinh(),t.cosh(),r.precision=o,r.rounding=e)):new r(t.s)};A.inverseCosine=A.acos=function(){var o=this,e=o.constructor,t=o.abs().cmp(1),r=e.precision,n=e.rounding;return t!==-1?t===0?o.isNeg()?it(e,r,n):new e(0):new e(NaN):o.isZero()?it(e,r+4,n).times(.5):(e.precision=r+6,e.rounding=1,o=new e(1).minus(o).div(o.plus(1)).sqrt().atan(),e.precision=r,e.rounding=n,o.times(2))};A.inverseHyperbolicCosine=A.acosh=function(){var o,e,t=this,r=t.constructor;return t.lte(1)?new r(t.eq(1)?0:NaN):t.isFinite()?(o=r.precision,e=r.rounding,r.precision=o+Math.max(Math.abs(t.e),t.sd())+4,r.rounding=1,U=!1,t=t.times(t).minus(1).sqrt().plus(t),U=!0,r.precision=o,r.rounding=e,t.ln()):new r(t)};A.inverseHyperbolicSine=A.asinh=function(){var o,e,t=this,r=t.constructor;return!t.isFinite()||t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+2*Math.max(Math.abs(t.e),t.sd())+6,r.rounding=1,U=!1,t=t.times(t).plus(1).sqrt().plus(t),U=!0,r.precision=o,r.rounding=e,t.ln())};A.inverseHyperbolicTangent=A.atanh=function(){var o,e,t,r,n=this,i=n.constructor;return n.isFinite()?n.e>=0?new i(n.abs().eq(1)?n.s/0:n.isZero()?n:NaN):(o=i.precision,e=i.rounding,r=n.sd(),Math.max(r,o)<2*-n.e-1?B(new i(n),o,e,!0):(i.precision=t=r-n.e,n=re(n.plus(1),new i(1).minus(n),t+o,1),i.precision=o+4,i.rounding=1,n=n.ln(),i.precision=o,i.rounding=e,n.times(.5))):new i(NaN)};A.inverseSine=A.asin=function(){var o,e,t,r,n=this,i=n.constructor;return n.isZero()?new i(n):(e=n.abs().cmp(1),t=i.precision,r=i.rounding,e!==-1?e===0?(o=it(i,t+4,r).times(.5),o.s=n.s,o):new i(NaN):(i.precision=t+6,i.rounding=1,n=n.div(new i(1).minus(n.times(n)).sqrt().plus(1)).atan(),i.precision=t,i.rounding=r,n.times(2)))};A.inverseTangent=A.atan=function(){var o,e,t,r,n,i,s,a,l,c=this,u=c.constructor,d=u.precision,f=u.rounding;if(c.isFinite()){if(c.isZero())return new u(c);if(c.abs().eq(1)&&d+4<=_a)return s=it(u,d+4,f).times(.25),s.s=c.s,s}else{if(!c.s)return new u(NaN);if(d+4<=_a)return s=it(u,d+4,f).times(.5),s.s=c.s,s}for(u.precision=a=d+10,u.rounding=1,t=Math.min(28,a/M+2|0),o=t;o;--o)c=c.div(c.times(c).plus(1).sqrt().plus(1));for(U=!1,e=Math.ceil(a/M),r=1,l=c.times(c),s=new u(c),n=c;o!==-1;)if(n=n.times(l),i=s.minus(n.div(r+=2)),n=n.times(l),s=i.plus(n.div(r+=2)),s.d[e]!==void 0)for(o=e;s.d[o]===i.d[o]&&o--;);return t&&(s=s.times(2<<t-1)),U=!0,B(s,u.precision=d,u.rounding=f,!0)};A.isFinite=function(){return!!this.d};A.isInteger=A.isInt=function(){return!!this.d&&Ee(this.e/M)>this.d.length-2};A.isNaN=function(){return!this.s};A.isNegative=A.isNeg=function(){return this.s<0};A.isPositive=A.isPos=function(){return this.s>0};A.isZero=function(){return!!this.d&&this.d[0]===0};A.lessThan=A.lt=function(o){return this.cmp(o)<0};A.lessThanOrEqualTo=A.lte=function(o){return this.cmp(o)<1};A.logarithm=A.log=function(o){var e,t,r,n,i,s,a,l,c=this,u=c.constructor,d=u.precision,f=u.rounding,h=5;if(o==null)o=new u(10),e=!0;else{if(o=new u(o),t=o.d,o.s<0||!t||!t[0]||o.eq(1))return new u(NaN);e=o.eq(10)}if(t=c.d,c.s<0||!t||!t[0]||c.eq(1))return new u(t&&!t[0]?-1/0:c.s!=1?NaN:t?0:1/0);if(e)if(t.length>1)i=!0;else{for(n=t[0];n%10===0;)n/=10;i=n!==1}if(U=!1,a=d+h,s=Pt(c,a),r=e?pi(u,a+10):Pt(o,a),l=re(s,r,a,1),$n(l.d,n=d,f))do if(a+=10,s=Pt(c,a),r=e?pi(u,a+10):Pt(o,a),l=re(s,r,a,1),!i){+ye(l.d).slice(n+1,n+15)+1==1e14&&(l=B(l,d+1,0));break}while($n(l.d,n+=10,f));return U=!0,B(l,d,f)};A.minus=A.sub=function(o){var e,t,r,n,i,s,a,l,c,u,d,f,h=this,p=h.constructor;if(o=new p(o),!h.d||!o.d)return!h.s||!o.s?o=new p(NaN):h.d?o.s=-o.s:o=new p(o.d||h.s!==o.s?h:NaN),o;if(h.s!=o.s)return o.s=-o.s,h.plus(o);if(c=h.d,f=o.d,a=p.precision,l=p.rounding,!c[0]||!f[0]){if(f[0])o.s=-o.s;else if(c[0])o=new p(h);else return new p(l===3?-0:0);return U?B(o,a,l):o}if(t=Ee(o.e/M),u=Ee(h.e/M),c=c.slice(),i=u-t,i){for(d=i<0,d?(e=c,i=-i,s=f.length):(e=f,t=u,s=c.length),r=Math.max(Math.ceil(a/M),s)+2,i>r&&(i=r,e.length=1),e.reverse(),r=i;r--;)e.push(0);e.reverse()}else{for(r=c.length,s=f.length,d=r<s,d&&(s=r),r=0;r<s;r++)if(c[r]!=f[r]){d=c[r]<f[r];break}i=0}for(d&&(e=c,c=f,f=e,o.s=-o.s),s=c.length,r=f.length-s;r>0;--r)c[s++]=0;for(r=f.length;r>i;){if(c[--r]<f[r]){for(n=r;n&&c[--n]===0;)c[n]=Ge-1;--c[n],c[r]+=Ge}c[r]-=f[r]}for(;c[--s]===0;)c.pop();for(;c[0]===0;c.shift())--t;return c[0]?(o.d=c,o.e=gi(c,t),U?B(o,a,l):o):new p(l===3?-0:0)};A.modulo=A.mod=function(o){var e,t=this,r=t.constructor;return o=new r(o),!t.d||!o.s||o.d&&!o.d[0]?new r(NaN):!o.d||t.d&&!t.d[0]?B(new r(t),r.precision,r.rounding):(U=!1,r.modulo==9?(e=re(t,o.abs(),0,3,1),e.s*=o.s):e=re(t,o,0,r.modulo,1),e=e.times(o),U=!0,t.minus(e))};A.naturalExponential=A.exp=function(){return ya(this)};A.naturalLogarithm=A.ln=function(){return Pt(this)};A.negated=A.neg=function(){var o=new this.constructor(this);return o.s=-o.s,B(o)};A.plus=A.add=function(o){var e,t,r,n,i,s,a,l,c,u,d=this,f=d.constructor;if(o=new f(o),!d.d||!o.d)return!d.s||!o.s?o=new f(NaN):d.d||(o=new f(o.d||d.s===o.s?d:NaN)),o;if(d.s!=o.s)return o.s=-o.s,d.minus(o);if(c=d.d,u=o.d,a=f.precision,l=f.rounding,!c[0]||!u[0])return u[0]||(o=new f(d)),U?B(o,a,l):o;if(i=Ee(d.e/M),r=Ee(o.e/M),c=c.slice(),n=i-r,n){for(n<0?(t=c,n=-n,s=u.length):(t=u,r=i,s=c.length),i=Math.ceil(a/M),s=i>s?i+1:s+1,n>s&&(n=s,t.length=1),t.reverse();n--;)t.push(0);t.reverse()}for(s=c.length,n=u.length,s-n<0&&(n=s,t=u,u=c,c=t),e=0;n;)e=(c[--n]=c[n]+u[n]+e)/Ge|0,c[n]%=Ge;for(e&&(c.unshift(e),++r),s=c.length;c[--s]==0;)c.pop();return o.d=c,o.e=gi(c,r),U?B(o,a,l):o};A.precision=A.sd=function(o){var e,t=this;if(o!==void 0&&o!==!!o&&o!==1&&o!==0)throw Error(Bt+o);return t.d?(e=Mu(t.d),o&&t.e+1>e&&(e=t.e+1)):e=NaN,e};A.round=function(){var o=this,e=o.constructor;return B(new e(o),o.e+1,e.rounding)};A.sine=A.sin=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+Math.max(t.e,t.sd())+M,r.rounding=1,t=up(r,Uu(r,t)),r.precision=o,r.rounding=e,B(gt>2?t.neg():t,o,e,!0)):new r(NaN)};A.squareRoot=A.sqrt=function(){var o,e,t,r,n,i,s=this,a=s.d,l=s.e,c=s.s,u=s.constructor;if(c!==1||!a||!a[0])return new u(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);for(U=!1,c=Math.sqrt(+s),c==0||c==1/0?(e=ye(a),(e.length+l)%2==0&&(e+="0"),c=Math.sqrt(e),l=Ee((l+1)/2)-(l<0||l%2),c==1/0?e="5e"+l:(e=c.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),r=new u(e)):r=new u(c.toString()),t=(l=u.precision)+3;;)if(i=r,r=i.plus(re(s,i,t+2,1)).times(.5),ye(i.d).slice(0,t)===(e=ye(r.d)).slice(0,t))if(e=e.slice(t-3,t+1),e=="9999"||!n&&e=="4999"){if(!n&&(B(i,l+1,0),i.times(i).eq(s))){r=i;break}t+=4,n=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(B(r,l+1,1),o=!r.times(r).eq(s));break}return U=!0,B(r,l,u.rounding,o)};A.tangent=A.tan=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+10,r.rounding=1,t=t.sin(),t.s=1,t=re(t,new r(1).minus(t.times(t)).sqrt(),o+10,0),r.precision=o,r.rounding=e,B(gt==2||gt==4?t.neg():t,o,e,!0)):new r(NaN)};A.times=A.mul=function(o){var e,t,r,n,i,s,a,l,c,u=this,d=u.constructor,f=u.d,h=(o=new d(o)).d;if(o.s*=u.s,!f||!f[0]||!h||!h[0])return new d(!o.s||f&&!f[0]&&!h||h&&!h[0]&&!f?NaN:!f||!h?o.s/0:o.s*0);for(t=Ee(u.e/M)+Ee(o.e/M),l=f.length,c=h.length,l<c&&(i=f,f=h,h=i,s=l,l=c,c=s),i=[],s=l+c,r=s;r--;)i.push(0);for(r=c;--r>=0;){for(e=0,n=l+r;n>r;)a=i[n]+h[r]*f[n-r-1]+e,i[n--]=a%Ge|0,e=a/Ge|0;i[n]=(i[n]+e)%Ge|0}for(;!i[--s];)i.pop();return e?++t:i.shift(),o.d=i,o.e=gi(i,t),U?B(o,d.precision,d.rounding):o};A.toBinary=function(o,e){return va(this,2,o,e)};A.toDecimalPlaces=A.toDP=function(o,e){var t=this,r=t.constructor;return t=new r(t),o===void 0?t:(je(o,0,Mt),e===void 0?e=r.rounding:je(e,0,8),B(t,o+t.e+1,e))};A.toExponential=function(o,e){var t,r=this,n=r.constructor;return o===void 0?t=st(r,!0):(je(o,0,Mt),e===void 0?e=n.rounding:je(e,0,8),r=B(new n(r),o+1,e),t=st(r,!0,o+1)),r.isNeg()&&!r.isZero()?"-"+t:t};A.toFixed=function(o,e){var t,r,n=this,i=n.constructor;return o===void 0?t=st(n):(je(o,0,Mt),e===void 0?e=i.rounding:je(e,0,8),r=B(new i(n),o+n.e+1,e),t=st(r,!1,o+r.e+1)),n.isNeg()&&!n.isZero()?"-"+t:t};A.toFraction=function(o){var e,t,r,n,i,s,a,l,c,u,d,f,h=this,p=h.d,m=h.constructor;if(!p)return new m(h);if(c=t=new m(1),r=l=new m(0),e=new m(r),i=e.e=Mu(p)-h.e-1,s=i%M,e.d[0]=pe(10,s<0?M+s:s),o==null)o=i>0?e:c;else{if(a=new m(o),!a.isInt()||a.lt(c))throw Error(Bt+a);o=a.gt(e)?i>0?e:c:a}for(U=!1,a=new m(ye(p)),u=m.precision,m.precision=i=p.length*M*2;d=re(a,e,0,1,1),n=t.plus(d.times(r)),n.cmp(o)!=1;)t=r,r=n,n=c,c=l.plus(d.times(n)),l=n,n=e,e=a.minus(d.times(n)),a=n;return n=re(o.minus(t),r,0,1,1),l=l.plus(n.times(c)),t=t.plus(n.times(r)),l.s=c.s=h.s,f=re(c,r,i,1).minus(h).abs().cmp(re(l,t,i,1).minus(h).abs())<1?[c,r]:[l,t],m.precision=u,U=!0,f};A.toHexadecimal=A.toHex=function(o,e){return va(this,16,o,e)};A.toNearest=function(o,e){var t=this,r=t.constructor;if(t=new r(t),o==null){if(!t.d)return t;o=new r(1),e=r.rounding}else{if(o=new r(o),e===void 0?e=r.rounding:je(e,0,8),!t.d)return o.s?t:o;if(!o.d)return o.s&&(o.s=t.s),o}return o.d[0]?(U=!1,t=re(t,o,0,e,1).times(o),U=!0,B(t)):(o.s=t.s,t=o),t};A.toNumber=function(){return+this};A.toOctal=function(o,e){return va(this,8,o,e)};A.toPower=A.pow=function(o){var e,t,r,n,i,s,a=this,l=a.constructor,c=+(o=new l(o));if(!a.d||!o.d||!a.d[0]||!o.d[0])return new l(pe(+a,c));if(a=new l(a),a.eq(1))return a;if(r=l.precision,i=l.rounding,o.eq(1))return B(a,r,i);if(e=Ee(o.e/M),e>=o.d.length-1&&(t=c<0?-c:c)<=sp)return n=Lu(l,a,t,r),o.s<0?new l(1).div(n):B(n,r,i);if(s=a.s,s<0){if(e<o.d.length-1)return new l(NaN);if((o.d[e]&1)==0&&(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return t=pe(+a,c),e=t==0||!isFinite(t)?Ee(c*(Math.log("0."+ye(a.d))/Math.LN10+a.e+1)):new l(t+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?s/0:0):(U=!1,l.rounding=a.s=1,t=Math.min(12,(e+"").length),n=ya(o.times(Pt(a,r+t)),r),n.d&&(n=B(n,r+5,1),$n(n.d,r,i)&&(e=r+10,n=B(ya(o.times(Pt(a,e+t)),e),e+5,1),+ye(n.d).slice(r+1,r+15)+1==1e14&&(n=B(n,r+1,0)))),n.s=s,U=!0,l.rounding=i,B(n,r,i))};A.toPrecision=function(o,e){var t,r=this,n=r.constructor;return o===void 0?t=st(r,r.e<=n.toExpNeg||r.e>=n.toExpPos):(je(o,1,Mt),e===void 0?e=n.rounding:je(e,0,8),r=B(new n(r),o,e),t=st(r,o<=r.e||r.e<=n.toExpNeg,o)),r.isNeg()&&!r.isZero()?"-"+t:t};A.toSignificantDigits=A.toSD=function(o,e){var t=this,r=t.constructor;return o===void 0?(o=r.precision,e=r.rounding):(je(o,1,Mt),e===void 0?e=r.rounding:je(e,0,8)),B(new r(t),o,e)};A.toString=function(){var o=this,e=o.constructor,t=st(o,o.e<=e.toExpNeg||o.e>=e.toExpPos);return o.isNeg()&&!o.isZero()?"-"+t:t};A.truncated=A.trunc=function(){return B(new this.constructor(this),this.e+1,1)};A.valueOf=A.toJSON=function(){var o=this,e=o.constructor,t=st(o,o.e<=e.toExpNeg||o.e>=e.toExpPos);return o.isNeg()?"-"+t:t};function ye(o){var e,t,r,n=o.length-1,i="",s=o[0];if(n>0){for(i+=s,e=1;e<n;e++)r=o[e]+"",t=M-r.length,t&&(i+=jt(t)),i+=r;s=o[e],r=s+"",t=M-r.length,t&&(i+=jt(t))}else if(s===0)return"0";for(;s%10===0;)s/=10;return i+s}function je(o,e,t){if(o!==~~o||o<e||o>t)throw Error(Bt+o)}function $n(o,e,t,r){var n,i,s,a;for(i=o[0];i>=10;i/=10)--e;return--e<0?(e+=M,n=0):(n=Math.ceil((e+1)/M),e%=M),i=pe(10,M-e),a=o[n]%i|0,r==null?e<3?(e==0?a=a/100|0:e==1&&(a=a/10|0),s=t<4&&a==99999||t>3&&a==49999||a==5e4||a==0):s=(t<4&&a+1==i||t>3&&a+1==i/2)&&(o[n+1]/i/100|0)==pe(10,e-2)-1||(a==i/2||a==0)&&(o[n+1]/i/100|0)==0:e<4?(e==0?a=a/1e3|0:e==1?a=a/100|0:e==2&&(a=a/10|0),s=(r||t<4)&&a==9999||!r&&t>3&&a==4999):s=((r||t<4)&&a+1==i||!r&&t>3&&a+1==i/2)&&(o[n+1]/i/1e3|0)==pe(10,e-3)-1,s}function ui(o,e,t){for(var r,n=[0],i,s=0,a=o.length;s<a;){for(i=n.length;i--;)n[i]*=e;for(n[0]+=ba.indexOf(o.charAt(s++)),r=0;r<n.length;r++)n[r]>t-1&&(n[r+1]===void 0&&(n[r+1]=0),n[r+1]+=n[r]/t|0,n[r]%=t)}return n.reverse()}function lp(o,e){var t,r,n;if(e.isZero())return e;r=e.d.length,r<32?(t=Math.ceil(r/3),n=(1/bi(4,t)).toString()):(t=16,n="2.3283064365386962890625e-10"),o.precision+=t,e=Vr(o,1,e.times(n),new o(1));for(var i=t;i--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return o.precision-=t,e}var re=(function(){function o(r,n,i){var s,a=0,l=r.length;for(r=r.slice();l--;)s=r[l]*n+a,r[l]=s%i|0,a=s/i|0;return a&&r.unshift(a),r}function e(r,n,i,s){var a,l;if(i!=s)l=i>s?1:-1;else for(a=l=0;a<i;a++)if(r[a]!=n[a]){l=r[a]>n[a]?1:-1;break}return l}function t(r,n,i,s){for(var a=0;i--;)r[i]-=a,a=r[i]<n[i]?1:0,r[i]=a*s+r[i]-n[i];for(;!r[0]&&r.length>1;)r.shift()}return function(r,n,i,s,a,l){var c,u,d,f,h,p,m,b,w,_,v,E,D,k,C,O,L,z,V,le,_e=r.constructor,ht=r.s==n.s?1:-1,ne=r.d,X=n.d;if(!ne||!ne[0]||!X||!X[0])return new _e(!r.s||!n.s||(ne?X&&ne[0]==X[0]:!X)?NaN:ne&&ne[0]==0||!X?ht*0:ht/0);for(l?(h=1,u=r.e-n.e):(l=Ge,h=M,u=Ee(r.e/h)-Ee(n.e/h)),V=X.length,L=ne.length,w=new _e(ht),_=w.d=[],d=0;X[d]==(ne[d]||0);d++);if(X[d]>(ne[d]||0)&&u--,i==null?(k=i=_e.precision,s=_e.rounding):a?k=i+(r.e-n.e)+1:k=i,k<0)_.push(1),p=!0;else{if(k=k/h+2|0,d=0,V==1){for(f=0,X=X[0],k++;(d<L||f)&&k--;d++)C=f*l+(ne[d]||0),_[d]=C/X|0,f=C%X|0;p=f||d<L}else{for(f=l/(X[0]+1)|0,f>1&&(X=o(X,f,l),ne=o(ne,f,l),V=X.length,L=ne.length),O=V,v=ne.slice(0,V),E=v.length;E<V;)v[E++]=0;le=X.slice(),le.unshift(0),z=X[0],X[1]>=l/2&&++z;do f=0,c=e(X,v,V,E),c<0?(D=v[0],V!=E&&(D=D*l+(v[1]||0)),f=D/z|0,f>1?(f>=l&&(f=l-1),m=o(X,f,l),b=m.length,E=v.length,c=e(m,v,b,E),c==1&&(f--,t(m,V<b?le:X,b,l))):(f==0&&(c=f=1),m=X.slice()),b=m.length,b<E&&m.unshift(0),t(v,m,E,l),c==-1&&(E=v.length,c=e(X,v,V,E),c<1&&(f++,t(v,V<E?le:X,E,l))),E=v.length):c===0&&(f++,v=[0]),_[d++]=f,c&&v[0]?v[E++]=ne[O]||0:(v=[ne[O]],E=1);while((O++<L||v[0]!==void 0)&&k--);p=v[0]!==void 0}_[0]||_.shift()}if(h==1)w.e=u,$u=p;else{for(d=1,f=_[0];f>=10;f/=10)d++;w.e=d+u*h-1,B(w,a?i+w.e+1:i,s,p)}return w}})();function B(o,e,t,r){var n,i,s,a,l,c,u,d,f,h=o.constructor;e:if(e!=null){if(d=o.d,!d)return o;for(n=1,a=d[0];a>=10;a/=10)n++;if(i=e-n,i<0)i+=M,s=e,u=d[f=0],l=u/pe(10,n-s-1)%10|0;else if(f=Math.ceil((i+1)/M),a=d.length,f>=a)if(r){for(;a++<=f;)d.push(0);u=l=0,n=1,i%=M,s=i-M+1}else break e;else{for(u=a=d[f],n=1;a>=10;a/=10)n++;i%=M,s=i-M+n,l=s<0?0:u/pe(10,n-s-1)%10|0}if(r=r||e<0||d[f+1]!==void 0||(s<0?u:u%pe(10,n-s-1)),c=t<4?(l||r)&&(t==0||t==(o.s<0?3:2)):l>5||l==5&&(t==4||r||t==6&&(i>0?s>0?u/pe(10,n-s):0:d[f-1])%10&1||t==(o.s<0?8:7)),e<1||!d[0])return d.length=0,c?(e-=o.e+1,d[0]=pe(10,(M-e%M)%M),o.e=-e||0):d[0]=o.e=0,o;if(i==0?(d.length=f,a=1,f--):(d.length=f+1,a=pe(10,M-i),d[f]=s>0?(u/pe(10,n-s)%pe(10,s)|0)*a:0),c)for(;;)if(f==0){for(i=1,s=d[0];s>=10;s/=10)i++;for(s=d[0]+=a,a=1;s>=10;s/=10)a++;i!=a&&(o.e++,d[0]==Ge&&(d[0]=1));break}else{if(d[f]+=a,d[f]!=Ge)break;d[f--]=0,a=1}for(i=d.length;d[--i]===0;)d.pop()}return U&&(o.e>h.maxE?(o.d=null,o.e=NaN):o.e<h.minE&&(o.e=0,o.d=[0])),o}function st(o,e,t){if(!o.isFinite())return zu(o);var r,n=o.e,i=ye(o.d),s=i.length;return e?(t&&(r=t-s)>0?i=i.charAt(0)+"."+i.slice(1)+jt(r):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(o.e<0?"e":"e+")+o.e):n<0?(i="0."+jt(-n-1)+i,t&&(r=t-s)>0&&(i+=jt(r))):n>=s?(i+=jt(n+1-s),t&&(r=t-n-1)>0&&(i=i+"."+jt(r))):((r=n+1)<s&&(i=i.slice(0,r)+"."+i.slice(r)),t&&(r=t-s)>0&&(n+1===s&&(i+="."),i+=jt(r))),i}function gi(o,e){var t=o[0];for(e*=M;t>=10;t/=10)e++;return e}function pi(o,e,t){if(e>ap)throw U=!0,t&&(o.precision=t),Error(Ru);return B(new o(fi),e,1,!0)}function it(o,e,t){if(e>_a)throw Error(Ru);return B(new o(hi),e,t,!0)}function Mu(o){var e=o.length-1,t=e*M+1;if(e=o[e],e){for(;e%10==0;e/=10)t--;for(e=o[0];e>=10;e/=10)t++}return t}function jt(o){for(var e="";o--;)e+="0";return e}function Lu(o,e,t,r){var n,i=new o(1),s=Math.ceil(r/M+4);for(U=!1;;){if(t%2&&(i=i.times(e),Nu(i.d,s)&&(n=!0)),t=Ee(t/2),t===0){t=i.d.length-1,n&&i.d[t]===0&&++i.d[t];break}e=e.times(e),Nu(e.d,s)}return U=!0,i}function Du(o){return o.d[o.d.length-1]&1}function Fu(o,e,t){for(var r,n,i=new o(e[0]),s=0;++s<e.length;){if(n=new o(e[s]),!n.s){i=n;break}r=i.cmp(n),(r===t||r===0&&i.s===t)&&(i=n)}return i}function ya(o,e){var t,r,n,i,s,a,l,c=0,u=0,d=0,f=o.constructor,h=f.rounding,p=f.precision;if(!o.d||!o.d[0]||o.e>17)return new f(o.d?o.d[0]?o.s<0?0:1/0:1:o.s?o.s<0?0:o:NaN);for(e==null?(U=!1,l=p):l=e,a=new f(.03125);o.e>-2;)o=o.times(a),d+=5;for(r=Math.log(pe(2,d))/Math.LN10*2+5|0,l+=r,t=i=s=new f(1),f.precision=l;;){if(i=B(i.times(o),l,1),t=t.times(++u),a=s.plus(re(i,t,l,1)),ye(a.d).slice(0,l)===ye(s.d).slice(0,l)){for(n=d;n--;)s=B(s.times(s),l,1);if(e==null)if(c<3&&$n(s.d,l-r,h,c))f.precision=l+=10,t=i=a=new f(1),u=0,c++;else return B(s,f.precision=p,h,U=!0);else return f.precision=p,s}s=a}}function Pt(o,e){var t,r,n,i,s,a,l,c,u,d,f,h=1,p=10,m=o,b=m.d,w=m.constructor,_=w.rounding,v=w.precision;if(m.s<0||!b||!b[0]||!m.e&&b[0]==1&&b.length==1)return new w(b&&!b[0]?-1/0:m.s!=1?NaN:b?0:m);if(e==null?(U=!1,u=v):u=e,w.precision=u+=p,t=ye(b),r=t.charAt(0),Math.abs(i=m.e)<15e14){for(;r<7&&r!=1||r==1&&t.charAt(1)>3;)m=m.times(o),t=ye(m.d),r=t.charAt(0),h++;i=m.e,r>1?(m=new w("0."+t),i++):m=new w(r+"."+t.slice(1))}else return c=pi(w,u+2,v).times(i+""),m=Pt(new w(r+"."+t.slice(1)),u-p).plus(c),w.precision=v,e==null?B(m,v,_,U=!0):m;for(d=m,l=s=m=re(m.minus(1),m.plus(1),u,1),f=B(m.times(m),u,1),n=3;;){if(s=B(s.times(f),u,1),c=l.plus(re(s,new w(n),u,1)),ye(c.d).slice(0,u)===ye(l.d).slice(0,u))if(l=l.times(2),i!==0&&(l=l.plus(pi(w,u+2,v).times(i+""))),l=re(l,new w(h),u,1),e==null)if($n(l.d,u-p,_,a))w.precision=u+=p,c=s=m=re(d.minus(1),d.plus(1),u,1),f=B(m.times(m),u,1),n=a=1;else return B(l,w.precision=v,_,U=!0);else return w.precision=v,l;l=c,n+=2}}function zu(o){return String(o.s*o.s/0)}function di(o,e){var t,r,n;for((t=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(t<0&&(t=r),t+=+e.slice(r+1),e=e.substring(0,r)):t<0&&(t=e.length),r=0;e.charCodeAt(r)===48;r++);for(n=e.length;e.charCodeAt(n-1)===48;--n);if(e=e.slice(r,n),e){if(n-=r,o.e=t=t-r-1,o.d=[],r=(t+1)%M,t<0&&(r+=M),r<n){for(r&&o.d.push(+e.slice(0,r)),n-=M;r<n;)o.d.push(+e.slice(r,r+=M));e=e.slice(r),r=M-e.length}else r-=n;for(;r--;)e+="0";o.d.push(+e),U&&(o.e>o.constructor.maxE?(o.d=null,o.e=NaN):o.e<o.constructor.minE&&(o.e=0,o.d=[0]))}else o.e=0,o.d=[0];return o}function cp(o,e){var t,r,n,i,s,a,l,c,u;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Bu.test(e))return di(o,e)}else if(e==="Infinity"||e==="NaN")return+e||(o.s=NaN),o.e=NaN,o.d=null,o;if(op.test(e))t=16,e=e.toLowerCase();else if(np.test(e))t=2;else if(ip.test(e))t=8;else throw Error(Bt+e);for(i=e.search(/p/i),i>0?(l=+e.slice(i+1),e=e.substring(2,i)):e=e.slice(2),i=e.indexOf("."),s=i>=0,r=o.constructor,s&&(e=e.replace(".",""),a=e.length,i=a-i,n=Lu(r,new r(t),i,i*2)),c=ui(e,t,Ge),u=c.length-1,i=u;c[i]===0;--i)c.pop();return i<0?new r(o.s*0):(o.e=gi(c,u),o.d=c,U=!1,s&&(o=re(o,n,a*4)),l&&(o=o.times(Math.abs(l)<54?pe(2,l):Wr.pow(2,l))),U=!0,o)}function up(o,e){var t,r=e.d.length;if(r<3)return e.isZero()?e:Vr(o,2,e,e);t=1.4*Math.sqrt(r),t=t>16?16:t|0,e=e.times(1/bi(5,t)),e=Vr(o,2,e,e);for(var n,i=new o(5),s=new o(16),a=new o(20);t--;)n=e.times(e),e=e.times(i.plus(n.times(s.times(n).minus(a))));return e}function Vr(o,e,t,r,n){var i,s,a,l,c=1,u=o.precision,d=Math.ceil(u/M);for(U=!1,l=t.times(t),a=new o(r);;){if(s=re(a.times(l),new o(e++*e++),u,1),a=n?r.plus(s):r.minus(s),r=re(s.times(l),new o(e++*e++),u,1),s=a.plus(r),s.d[d]!==void 0){for(i=d;s.d[i]===a.d[i]&&i--;);if(i==-1)break}i=a,a=r,r=s,s=i,c++}return U=!0,s.d.length=d+1,s}function bi(o,e){for(var t=o;--e;)t*=o;return t}function Uu(o,e){var t,r=e.s<0,n=it(o,o.precision,1),i=n.times(.5);if(e=e.abs(),e.lte(i))return gt=r?4:1,e;if(t=e.divToInt(n),t.isZero())gt=r?3:2;else{if(e=e.minus(t.times(n)),e.lte(i))return gt=Du(t)?r?2:3:r?4:1,e;gt=Du(t)?r?1:4:r?3:2}return e.minus(n).abs()}function va(o,e,t,r){var n,i,s,a,l,c,u,d,f,h=o.constructor,p=t!==void 0;if(p?(je(t,1,Mt),r===void 0?r=h.rounding:je(r,0,8)):(t=h.precision,r=h.rounding),!o.isFinite())u=zu(o);else{for(u=st(o),s=u.indexOf("."),p?(n=2,e==16?t=t*4-3:e==8&&(t=t*3-2)):n=e,s>=0&&(u=u.replace(".",""),f=new h(1),f.e=u.length-s,f.d=ui(st(f),10,n),f.e=f.d.length),d=ui(u,10,n),i=l=d.length;d[--l]==0;)d.pop();if(!d[0])u=p?"0p+0":"0";else{if(s<0?i--:(o=new h(o),o.d=d,o.e=i,o=re(o,f,t,r,0,n),d=o.d,i=o.e,c=$u),s=d[t],a=n/2,c=c||d[t+1]!==void 0,c=r<4?(s!==void 0||c)&&(r===0||r===(o.s<0?3:2)):s>a||s===a&&(r===4||c||r===6&&d[t-1]&1||r===(o.s<0?8:7)),d.length=t,c)for(;++d[--t]>n-1;)d[t]=0,t||(++i,d.unshift(1));for(l=d.length;!d[l-1];--l);for(s=0,u="";s<l;s++)u+=ba.charAt(d[s]);if(p){if(l>1)if(e==16||e==8){for(s=e==16?4:3,--l;l%s;l++)u+="0";for(d=ui(u,n,e),l=d.length;!d[l-1];--l);for(s=1,u="1.";s<l;s++)u+=ba.charAt(d[s])}else u=u.charAt(0)+"."+u.slice(1);u=u+(i<0?"p":"p+")+i}else if(i<0){for(;++i;)u="0"+u;u="0."+u}else if(++i>l)for(i-=l;i--;)u+="0";else i<l&&(u=u.slice(0,i)+"."+u.slice(i))}u=(e==16?"0x":e==2?"0b":e==8?"0o":"")+u}return o.s<0?"-"+u:u}function Nu(o,e){if(o.length>e)return o.length=e,!0}function dp(o){return new this(o).abs()}function fp(o){return new this(o).acos()}function hp(o){return new this(o).acosh()}function pp(o,e){return new this(o).plus(e)}function mp(o){return new this(o).asin()}function gp(o){return new this(o).asinh()}function bp(o){return new this(o).atan()}function wp(o){return new this(o).atanh()}function _p(o,e){o=new this(o),e=new this(e);var t,r=this.precision,n=this.rounding,i=r+4;return!o.s||!e.s?t=new this(NaN):!o.d&&!e.d?(t=it(this,i,1).times(e.s>0?.25:.75),t.s=o.s):!e.d||o.isZero()?(t=e.s<0?it(this,r,n):new this(0),t.s=o.s):!o.d||e.isZero()?(t=it(this,i,1).times(.5),t.s=o.s):e.s<0?(this.precision=i,this.rounding=1,t=this.atan(re(o,e,i,1)),e=it(this,i,1),this.precision=r,this.rounding=n,t=o.s<0?t.minus(e):t.plus(e)):t=this.atan(re(o,e,i,1)),t}function yp(o){return new this(o).cbrt()}function vp(o){return B(o=new this(o),o.e+1,2)}function xp(o,e,t){return new this(o).clamp(e,t)}function kp(o){if(!o||typeof o!="object")throw Error(mi+"Object expected");var e,t,r,n=o.defaults===!0,i=["precision",1,Mt,"rounding",0,8,"toExpNeg",-qr,0,"toExpPos",0,qr,"maxE",0,qr,"minE",-qr,0,"modulo",0,9];for(e=0;e<i.length;e+=3)if(t=i[e],n&&(this[t]=wa[t]),(r=o[t])!==void 0)if(Ee(r)===r&&r>=i[e+1]&&r<=i[e+2])this[t]=r;else throw Error(Bt+t+": "+r);if(t="crypto",n&&(this[t]=wa[t]),(r=o[t])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[t]=!0;else throw Error(ju);else this[t]=!1;else throw Error(Bt+t+": "+r);return this}function Ep(o){return new this(o).cos()}function Tp(o){return new this(o).cosh()}function qu(o){var e,t,r;function n(i){var s,a,l,c=this;if(!(c instanceof n))return new n(i);if(c.constructor=n,Ou(i)){c.s=i.s,U?!i.d||i.e>n.maxE?(c.e=NaN,c.d=null):i.e<n.minE?(c.e=0,c.d=[0]):(c.e=i.e,c.d=i.d.slice()):(c.e=i.e,c.d=i.d?i.d.slice():i.d);return}if(l=typeof i,l==="number"){if(i===0){c.s=1/i<0?-1:1,c.e=0,c.d=[0];return}if(i<0?(i=-i,c.s=-1):c.s=1,i===~~i&&i<1e7){for(s=0,a=i;a>=10;a/=10)s++;U?s>n.maxE?(c.e=NaN,c.d=null):s<n.minE?(c.e=0,c.d=[0]):(c.e=s,c.d=[i]):(c.e=s,c.d=[i]);return}if(i*0!==0){i||(c.s=NaN),c.e=NaN,c.d=null;return}return di(c,i.toString())}if(l==="string")return(a=i.charCodeAt(0))===45?(i=i.slice(1),c.s=-1):(a===43&&(i=i.slice(1)),c.s=1),Bu.test(i)?di(c,i):cp(c,i);if(l==="bigint")return i<0?(i=-i,c.s=-1):c.s=1,di(c,i.toString());throw Error(Bt+i)}if(n.prototype=A,n.ROUND_UP=0,n.ROUND_DOWN=1,n.ROUND_CEIL=2,n.ROUND_FLOOR=3,n.ROUND_HALF_UP=4,n.ROUND_HALF_DOWN=5,n.ROUND_HALF_EVEN=6,n.ROUND_HALF_CEIL=7,n.ROUND_HALF_FLOOR=8,n.EUCLID=9,n.config=n.set=kp,n.clone=qu,n.isDecimal=Ou,n.abs=dp,n.acos=fp,n.acosh=hp,n.add=pp,n.asin=mp,n.asinh=gp,n.atan=bp,n.atanh=wp,n.atan2=_p,n.cbrt=yp,n.ceil=vp,n.clamp=xp,n.cos=Ep,n.cosh=Tp,n.div=Sp,n.exp=Ap,n.floor=Ip,n.hypot=Cp,n.ln=Dp,n.log=Np,n.log10=$p,n.log2=Op,n.max=Rp,n.min=jp,n.mod=Pp,n.mul=Bp,n.pow=Mp,n.random=Lp,n.round=Fp,n.sign=zp,n.sin=Up,n.sinh=qp,n.sqrt=Vp,n.sub=Wp,n.sum=Gp,n.tan=Hp,n.tanh=Xp,n.trunc=Yp,o===void 0&&(o={}),o&&o.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<r.length;)o.hasOwnProperty(t=r[e++])||(o[t]=this[t]);return n.config(o),n}function Sp(o,e){return new this(o).div(e)}function Ap(o){return new this(o).exp()}function Ip(o){return B(o=new this(o),o.e+1,3)}function Cp(){var o,e,t=new this(0);for(U=!1,o=0;o<arguments.length;)if(e=new this(arguments[o++]),e.d)t.d&&(t=t.plus(e.times(e)));else{if(e.s)return U=!0,new this(1/0);t=e}return U=!0,t.sqrt()}function Ou(o){return o instanceof Wr||o&&o.toStringTag===Pu||!1}function Dp(o){return new this(o).ln()}function Np(o,e){return new this(o).log(e)}function Op(o){return new this(o).log(2)}function $p(o){return new this(o).log(10)}function Rp(){return Fu(this,arguments,-1)}function jp(){return Fu(this,arguments,1)}function Pp(o,e){return new this(o).mod(e)}function Bp(o,e){return new this(o).mul(e)}function Mp(o,e){return new this(o).pow(e)}function Lp(o){var e,t,r,n,i=0,s=new this(1),a=[];if(o===void 0?o=this.precision:je(o,1,Mt),r=Math.ceil(o/M),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(r));i<r;)n=e[i],n>=429e7?e[i]=crypto.getRandomValues(new Uint32Array(1))[0]:a[i++]=n%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(r*=4);i<r;)n=e[i]+(e[i+1]<<8)+(e[i+2]<<16)+((e[i+3]&127)<<24),n>=214e7?crypto.randomBytes(4).copy(e,i):(a.push(n%1e7),i+=4);i=r/4}else throw Error(ju);else for(;i<r;)a[i++]=Math.random()*1e7|0;for(r=a[--i],o%=M,r&&o&&(n=pe(10,M-o),a[i]=(r/n|0)*n);a[i]===0;i--)a.pop();if(i<0)t=0,a=[0];else{for(t=-1;a[0]===0;t-=M)a.shift();for(r=1,n=a[0];n>=10;n/=10)r++;r<M&&(t-=M-r)}return s.e=t,s.d=a,s}function Fp(o){return B(o=new this(o),o.e+1,this.rounding)}function zp(o){return o=new this(o),o.d?o.d[0]?o.s:0*o.s:o.s||NaN}function Up(o){return new this(o).sin()}function qp(o){return new this(o).sinh()}function Vp(o){return new this(o).sqrt()}function Wp(o,e){return new this(o).sub(e)}function Gp(){var o=0,e=arguments,t=new this(e[o]);for(U=!1;t.s&&++o<e.length;)t=t.plus(e[o]);return U=!0,B(t,this.precision,this.rounding)}function Hp(o){return new this(o).tan()}function Xp(o){return new this(o).tanh()}function Yp(o){return B(o=new this(o),o.e+1,1)}A[Symbol.for("nodejs.util.inspect.custom")]=A.toString;A[Symbol.toStringTag]="Decimal";var Wr=A.constructor=qu(wa);fi=new Wr(fi);hi=new Wr(hi);var xa=Wr;var Rn=class{constructor(){throw new Error("The Gramlot browser runtime has no big.js: decimals use decimal.js")}};var Ln={};ee(Ln,{DecodeError:()=>Te,Decoder:()=>Xe,EXT_TIMESTAMP:()=>Ta,Encoder:()=>Gr,ExtData:()=>He,ExtensionCodec:()=>Lt,decode:()=>Ju,decodeArrayStream:()=>td,decodeAsync:()=>ed,decodeMulti:()=>Qu,decodeMultiStream:()=>rd,decodeTimestampExtension:()=>Da,decodeTimestampToTimeSpec:()=>Ca,encode:()=>yi,encodeDateToTimeSpec:()=>Aa,encodeTimeSpecToTimestamp:()=>Sa,encodeTimestampExtension:()=>Ia});function Vu(o){let e=o.length,t=0,r=0;for(;r<e;){let n=o.charCodeAt(r++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&r<e){let i=o.charCodeAt(r);(i&64512)===56320&&(++r,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function Zp(o,e,t){let r=o.length,n=t,i=0;for(;i<r;){let s=o.charCodeAt(i++);if((s&4294967168)===0){e[n++]=s;continue}else if((s&4294965248)===0)e[n++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&i<r){let a=o.charCodeAt(i);(a&64512)===56320&&(++i,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[n++]=s>>12&15|224,e[n++]=s>>6&63|128):(e[n++]=s>>18&7|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128)}e[n++]=s&63|128}}var Kp=new TextEncoder,Jp=50;function Qp(o,e,t){Kp.encodeInto(o,e.subarray(t))}function Wu(o,e,t){o.length>Jp?Qp(o,e,t):Zp(o,e,t)}var em=4096;function Ea(o,e,t){let r=e,n=r+t,i=[],s="";for(;r<n;){let a=o[r++];if((a&128)===0)i.push(a);else if((a&224)===192){let l=o[r++]&63;i.push((a&31)<<6|l)}else if((a&240)===224){let l=o[r++]&63,c=o[r++]&63;i.push((a&31)<<12|l<<6|c)}else if((a&248)===240){let l=o[r++]&63,c=o[r++]&63,u=o[r++]&63,d=(a&7)<<18|l<<12|c<<6|u;d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(a);i.length>=em&&(s+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(s+=String.fromCharCode(...i)),s}var tm=new TextDecoder,rm=200;function nm(o,e,t){let r=o.subarray(e,e+t);return tm.decode(r)}function Gu(o,e,t){return t>rm?nm(o,e,t):Ea(o,e,t)}var He=class{type;data;constructor(e,t){this.type=e,this.data=t}};var Te=class o extends Error{constructor(e){super(e);let t=Object.create(o.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:o.name})}};function Hu(o,e,t){let r=t/4294967296,n=t;o.setUint32(e,r),o.setUint32(e+4,n)}function wi(o,e,t){let r=Math.floor(t/4294967296),n=t;o.setUint32(e,r),o.setUint32(e+4,n)}function _i(o,e){let t=o.getInt32(e),r=o.getUint32(e+4);return t*4294967296+r}function Xu(o,e){let t=o.getUint32(e),r=o.getUint32(e+4);return t*4294967296+r}var Ta=-1,om=4294967296-1,im=17179869184-1;function Sa({sec:o,nsec:e}){if(o>=0&&e>=0&&o<=im)if(e===0&&o<=om){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,o),t}else{let t=o/4294967296,r=o&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|t&3),i.setUint32(4,r),n}else{let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setUint32(0,e),wi(r,4,o),t}}function Aa(o){let e=o.getTime(),t=Math.floor(e/1e3),r=(e-t*1e3)*1e6,n=Math.floor(r/1e9);return{sec:t+n,nsec:r-n*1e9}}function Ia(o){if(o instanceof Date){let e=Aa(o);return Sa(e)}else return null}function Ca(o){let e=new DataView(o.buffer,o.byteOffset,o.byteLength);switch(o.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),r=e.getUint32(4),n=(t&3)*4294967296+r,i=t>>>2;return{sec:n,nsec:i}}case 12:{let t=_i(e,4),r=e.getUint32(0);return{sec:t,nsec:r}}default:throw new Te(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${o.length}`)}}function Da(o){let e=Ca(o);return new Date(e.sec*1e3+e.nsec/1e6)}var Yu={type:Ta,encode:Ia,decode:Da};var Lt=class o{static defaultCodec=new o;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Yu)}register({type:e,encode:t,decode:r}){if(e>=0)this.encoders[e]=t,this.decoders[e]=r;else{let n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=r}}tryToEncode(e,t){for(let r=0;r<this.builtInEncoders.length;r++){let n=this.builtInEncoders[r];if(n!=null){let i=n(e,t);if(i!=null){let s=-1-r;return new He(s,i)}}}for(let r=0;r<this.encoders.length;r++){let n=this.encoders[r];if(n!=null){let i=n(e,t);if(i!=null){let s=r;return new He(s,i)}}}return e instanceof He?e:null}decode(e,t,r){let n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,r):new He(t,e)}};function sm(o){return o instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&o instanceof SharedArrayBuffer}function jn(o){return o instanceof Uint8Array?o:ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):sm(o)?new Uint8Array(o):Uint8Array.from(o)}var am=100,lm=2048,Gr=class o{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Lt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??am,this.initialBufferSize=e?.initialBufferSize??lm,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),r=new Uint8Array(t),n=new DataView(t);r.set(this.bytes),this.view=n,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=Vu(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Wu(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,t){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let r=jn(e);this.writeU8a(r)}encodeArray(e,t){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let r=0;for(let n of t)e[n]!==void 0&&r++;return r}encodeMap(e,t){let r=Object.keys(e);this.sortKeys&&r.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of r){let s=e[i];this.ignoreUndefined&&s===void 0||(this.encodeString(i),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),n=r.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(r);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Hu(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),wi(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function yi(o,e){return new Gr(e).encodeSharedRef(o)}function vi(o){return`${o<0?"-":""}0x${Math.abs(o).toString(16).padStart(2,"0")}`}var cm=16,um=16,xi=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=cm,t=um){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,r){let n=this.caches[r-1];e:for(let i of n){let s=i.bytes;for(let a=0;a<r;a++)if(s[a]!==e[t+a])continue e;return i.str}return null}store(e,t){let r=this.caches[e.length-1],n={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)}decode(e,t,r){let n=this.find(e,t,r);if(n!=null)return this.hit++,n;this.miss++;let i=Ea(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,i),i}};var Na="array",Mn="map_key",Ku="map_value",dm=o=>{if(typeof o=="string"||typeof o=="number")return o;throw new Te("The type of key must be string or number but "+typeof o)},Oa=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Na,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=Mn,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Na){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===Mn||e.type===Ku){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Bn=-1,$a=new DataView(new ArrayBuffer(0)),fm=new Uint8Array($a.buffer);try{$a.getInt8(0)}catch(o){if(!(o instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var Zu=new RangeError("Insufficient data"),hm=new xi,Xe=class o{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=$a;bytes=fm;headByte=Bn;stack=new Oa;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Lt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:hm,this.mapKeyConverter=e?.mapKeyConverter??dm}clone(){return new o({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Bn,this.stack.reset()}setBuffer(e){let t=jn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Bn&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),r=jn(e),n=new Uint8Array(t.length+r.length);n.set(t),n.set(r,t.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:r}=this;return new RangeError(`Extra ${t.byteLength-r} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,r;for await(let a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),t=!0}catch(l){if(!(l instanceof RangeError))throw l}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:n,pos:i,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${vi(n)} at ${s} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let r=t,n=-1;for await(let i of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(n=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{let n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){let n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();t=this.decodeExtension(n,4)}else throw new Te(`Unrecognized type byte: ${vi(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let n=r.top();if(n.type===Na)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,r.release(n);else continue e;else if(n.type===Mn){if(t==="__proto__")throw new Te("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=Ku;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,r.release(n);else{n.key=null,n.type=Mn;continue e}}return t}}readHeadByte(){return this.headByte===Bn&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Bn}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Te(`Unrecognized array type byte: ${vi(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Te(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Te(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new Te(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Zu;let r=this.pos+t,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,r,e):n=Gu(this.bytes,r,e),this.pos+=t+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Mn:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new Te(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Zu;let r=this.pos+t,n=this.bytes.subarray(r,r+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new Te(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=Xu(this.view,this.pos);return this.pos+=8,e}readI64(){let e=_i(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Ju(o,e){return new Xe(e).decode(o)}function Qu(o,e){return new Xe(e).decodeMulti(o)}function pm(o){return o[Symbol.asyncIterator]!=null}async function*mm(o){let e=o.getReader();try{for(;;){let{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}function ki(o){return pm(o)?o:mm(o)}async function ed(o,e){let t=ki(o);return new Xe(e).decodeAsync(t)}function td(o,e){let t=ki(o);return new Xe(e).decodeArrayStream(t)}function rd(o,e){let t=ki(o);return new Xe(e).decodeStream(t)}var nd=()=>{throw new Error("The Gramlot browser runtime has no @xmldom/xmldom: XML uses the native DOMParser")},Hr=class{constructor(){nd()}},Ei=class{constructor(){nd()}};var Fn=xa,zn=Rn,at=Ln,od=Hr,id=Ei;var sd=at!==null;function ad(){if(!sd)throw new Error("@msgpack/msgpack is required for MessagePack support. Install with: npm install @msgpack/msgpack")}var ld=gm();function gm(){if(!sd)return null;let o=new TextEncoder,e=new TextDecoder,t=new at.ExtensionCodec;return t.register({type:-1,encode:r=>{if(r instanceof Date){let n=bt(r);if(n==="D"||n==="H")return null}return at.encodeTimestampExtension(r)},decode:r=>at.decodeTimestampExtension(r)}),t.register({type:1,encode:r=>q(r)?o.encode(r.toString()):null,decode:r=>Ye(e.decode(r))}),t.register({type:2,encode:r=>{if(r instanceof Date&&bt(r)==="D"){let n=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),s=String(r.getUTCDate()).padStart(2,"0");return o.encode(`${n}-${i}-${s}`)}return null},decode:r=>new Date(e.decode(r)+"T00:00:00.000Z")}),t.register({type:3,encode:r=>{if(r instanceof Date&&bt(r)==="H"){let n=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=String(r.getUTCMilliseconds()).padStart(3,"0");return o.encode(`${n}:${i}:${s}.${a}`)}return null},decode:r=>{let n=e.decode(r),i=n.indexOf("."),s=i>=0?n.substring(0,i):n,a=i>=0?n.substring(i+1):"0",[l,c,u]=s.split(":"),d=Math.round(+a.substring(0,3));return new Date(Date.UTC(1970,0,1,+l,+c,+u,d))}}),t.register({type:4,encode:r=>{let n=Ra(r);if(n!==null){let[i,s]=n;return o.encode(`${i}:${s(r)}`)}return null},decode:r=>{let n=e.decode(r),i=n.indexOf(":"),s=n.slice(0,i),a=n.slice(i+1),l=Ft[s];if(l!==void 0){let[,c]=l;return c(a)}return`${a}::${s}`}}),t}function cd(o){return ad(),at.encode(o,{extensionCodec:ld})}function ud(o){return ad(),at.decode(o,{extensionCodec:ld})}function Ti(o,e=!1){let t=Si(o);if(t===null)return[!1,String(o)];let[r,n,i]=t;return i&&!e?[!1,String(o)]:[!0,`${n(o)}::${r}`]}function ja(o){if(!o.includes("::"))return[!1,o];let e=o.lastIndexOf("::"),t=o.slice(0,e),r=o.slice(e+2),n=Ft[r];if(n===void 0)return[!1,o];let[,i]=n;return[!0,i(t)]}function Xr(o,e,t){if(o!==null&&typeof o=="object"&&!Array.isArray(o)){let r={};for(let[n,i]of Object.entries(o))r[n]=Xr(i,e,t);return r}return Array.isArray(o)?o.map(r=>Xr(r,e,t)):t(o)?e(o):o}function Un(o){let e=Si(o);if(e!==null){let[t,r,n]=e;return n?[o,!1]:[`${r(o)}::${t}`,!0]}if(Array.isArray(o)){let t=!1;return[o.map(n=>{let[i,s]=Un(n);return s&&(t=!0),i}),t]}if(o!==null&&typeof o=="object"){let t=!1,r={};for(let[n,i]of Object.entries(o)){let[s,a]=Un(i);a&&(t=!0),r[n]=s}return[r,t]}return[o,!1]}function bm(o,e=!1){let[t,r]=Ti(o,e);if(t)return r;let[n,i]=Un(o),s=JSON.stringify(n);return i?`${s}::JS`:s}function wm(o){return JSON.stringify(o)}function _m(o){if(!at)throw new Error("@msgpack/msgpack is required for MessagePack support");return at.encode(o)}function R(o,e=null,{raw:t=!1,qs:r=!1,_forceSuffix:n=!1}={}){if(r)return`${hd(o)}::QS`;if(t){if(e===null||e==="json")return wm(o);if(e==="msgpack")return _m(o);throw e==="xml"?new Error("raw=true is not supported for XML transport"):new Error(`Unknown transport: ${e}`)}if(e===null||e==="json"){let i=bm(o,n);return e==="json"?`"${i}"`:i}else{if(e==="xml")return`<?xml version="1.0" ?><tytx_root>${fd(o)}</tytx_root>`;if(e==="msgpack")return cd(o);throw new Error(`Unknown transport: ${e}`)}}function dd(o){return Symbol.asyncIterator in o?(async function*(){for await(let t of o)yield Un(t)[0]})():(function*(){for(let t of o)yield Un(t)[0]})()}var Yr,Pa;typeof window<"u"&&window.DOMParser?(Yr=window.DOMParser,Pa=window.XMLSerializer):(Yr=od,Pa=id);function pd(o){if(o===null||typeof o!="object"||Array.isArray(o))return!1;let e=Object.keys(o);if(e.length!==1)return!1;let t=o[e[0]];return t!==null&&typeof t=="object"&&"value"in t}function md(o,e,t){let r=o.createElement(e),n=t.attrs||{},i=t.value;for(let[s,a]of Object.entries(n))r.setAttribute(s,R(a,null,{_forceSuffix:!0}));if(Array.isArray(i))for(let s of i)if(pd(s)){let[a]=Object.keys(s),l=s[a],c=md(o,a,l);r.appendChild(c)}else{r.textContent=R(i);break}else r.textContent=R(i);return r}function fd(o){if(!Yr)throw new Error("XML support requires @xmldom/xmldom package in Node.js");if(pd(o)){let[e]=Object.keys(o),t=o[e],r=new Yr().parseFromString("<root/>","text/xml"),n=md(r,e,t);return new Pa().serializeToString(n)}else return R(o)}function Ba(o){let e={};for(let r=0;r<o.attributes.length;r++){let n=o.attributes[r];e[n.name]=j(n.value)}let t=[];for(let r=0;r<o.childNodes.length;r++){let n=o.childNodes[r];n.nodeType===1&&t.push(n)}if(t.length>0)if(t.length===1){let r=t[0],n=Ba(r);return{attrs:e,value:{[r.tagName]:n}}}else{let r=[];for(let n of t){let i=Ba(n);r.push({[n.tagName]:i})}return{attrs:e,value:r}}return{attrs:e,value:j(o.textContent)}}function gd(o){if(!Yr)throw new Error("XML support requires @xmldom/xmldom package in Node.js");let r=new Yr().parseFromString(o,"text/xml").documentElement;if(r.tagName==="tytx_root"){let i=null;for(let s=0;s<r.childNodes.length;s++)if(r.childNodes[s].nodeType===1){i=r.childNodes[s];break}if(!i)return j(r.textContent);r=i}let n=Ba(r);return{[r.tagName]:n}}function Ma(o){return typeof o=="string"}function ym(o){let[e,t]=ja(o);if(e)return t;let r=o;r.endsWith("::JS")&&(r=r.slice(0,-4));let n;try{n=JSON.parse(r)}catch{return o}return Xr(n,La,Ma)}function La(o){return o.includes("::")?ja(o)[1]:o}function vm(o){let e=gd(o);return typeof e=="string"?j(e):e}function xm(o){return ud(o)}function j(o,e=null){if(o===null)return null;if(e===null||e==="json"){let t=o;return e==="json"&&o.startsWith('"')&&o.endsWith('"')&&(t=o.slice(1,-1)),ym(t)}else{if(e==="xml")return vm(o);if(e==="msgpack")return xm(o);throw new Error(`Unknown transport: ${e}`)}}function Fa(o){return Symbol.asyncIterator in o?(async function*(){for await(let t of o)yield Xr(t,La,Ma)})():(function*(){for(let t of o)yield Xr(t,La,Ma)})()}function hd(o){if(Array.isArray(o))return o.map(e=>String(e)).join("&");if(o!==null&&typeof o=="object"){let e=[];for(let[t,r]of Object.entries(o)){let[n,i]=Ti(r,!0);n?e.push(`${t}=${i}`):e.push(`${t}=${r}`)}return e.join("&")}throw new TypeError(`toQs expects object or array, got ${typeof o}`)}function bd(o){if(!o)return[];let e=o.split("&"),t=e.map(s=>s.includes("=")),r=t.every(Boolean),n=!t.some(Boolean);if(!r&&!n)throw new Error("QS format error: mixed items with and without '='");if(n)return e.map(s=>j(s));let i={};for(let s of e){let a=s.indexOf("="),l=s.slice(0,a),c=s.slice(a+1);i[l]=j(c)}return i}var qn=Fn||zn||Number,Vn=Fn?"decimal.js":zn?"big.js":"number";function _d(o){o==="decimal.js"&&Fn?(qn=Fn,Vn="decimal.js"):o==="big.js"&&zn?(qn=zn,Vn="big.js"):(qn=Number,Vn="number")}function Zr(){return Vn}function Ye(o){return new qn(o)}function q(o){return Vn==="number"?!1:o instanceof qn}function bt(o){let e=o.getUTCFullYear()===1970&&o.getUTCMonth()===0&&o.getUTCDate()===1,t=o.getUTCHours()===0&&o.getUTCMinutes()===0&&o.getUTCSeconds()===0&&o.getUTCMilliseconds()===0;return e&&!t?"H":t&&!e?"D":"DHZ"}function km(o){return o.toString()}function Em(o){let e=o.getUTCFullYear(),t=String(o.getUTCMonth()+1).padStart(2,"0"),r=String(o.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function Tm(o){return o.toISOString()}function Sm(o){let e=String(o.getUTCHours()).padStart(2,"0"),t=String(o.getUTCMinutes()).padStart(2,"0"),r=String(o.getUTCSeconds()).padStart(2,"0"),n=String(o.getUTCMilliseconds()).padStart(3,"0");return`${e}:${t}:${r}.${n}`}function Am(o){return o?"true":"false"}function Im(o){return o.toString()}function Cm(o){return o.toString()}function Dm(o){let e="";for(let t=0;t<o.length;t+=32768)e+=String.fromCharCode.apply(null,o.subarray(t,t+32768));return btoa(e)}var Ai=[],za=new Map;function Ra(o){if(o===null||typeof o!="object")return null;for(let e=Object.getPrototypeOf(o);e!==null;e=Object.getPrototypeOf(e))for(let[t,r,n,i]of Ai)if(t.prototype===e)return[r,n,i];return null}function Si(o){if(o===null)return["NN",()=>"",!0];if(q(o))return["N",km,!1];if(o instanceof Uint8Array)return["RAW",Dm,!1];if(o instanceof Date){let e=bt(o);return e==="D"?["D",Em,!1]:e==="H"?["H",Sm,!1]:["DHZ",Tm,!1]}return typeof o=="boolean"?["B",Am,!0]:typeof o=="number"?Number.isInteger(o)?["L",Im,!0]:["R",Cm,!0]:Ra(o)}function Nm(o){return Ye(o)}function Om(o){let[e,t,r]=o.split("-").map(Number);return new Date(Date.UTC(e,t-1,r,0,0,0,0))}function wd(o){return new Date(o)}function $m(o){let[e,t,r]=o.split(":"),[n,i]=r.split(".");return new Date(Date.UTC(1970,0,1,Number(e),Number(t),Number(n),Number(i||0)))}function Rm(o){return o.toLowerCase()==="true"}function jm(o){return parseInt(o,10)}function Pm(o){return parseFloat(o)}function Bm(o){return o}function Mm(o){return null}var Lm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Fm(o){if(!Lm.test(o))throw new Error(`RAW payload is not standard padded base64: '${o}'`);let e=atob(o),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function zm(o){return bd(o)}var Um=/^[A-Z]+$/,Ft={N:[Object,Nm],D:[Date,Om],DH:[Date,wd],DHZ:[Date,wd],H:[Date,$m],L:[Number,jm],R:[Number,Pm],T:[String,Bm],B:[Boolean,Rm],QS:[Object,zm],NN:[null,Mm],RAW:[Uint8Array,Fm]};function Kr(o){return Object.hasOwn(Ft,o)?Ft[o][0]:null}function Wn(o,e,t,r,n=!1){if(typeof e!="string"||!Um.test(e))throw new Error(`TYTX suffix '${e}' is invalid: expected uppercase ASCII letters only`);let i=Ft[e];if(i!==void 0&&i[0]!==o){let s=i[0]===null?"null":i[0].name;throw new Error(`TYTX suffix '${e}' is already registered for ${s}`)}Ai=Ai.filter(([s])=>s!==o),Ai.push([o,e,t,n]),Ft[e]=[o,r]}function yd(o){if(!o.tytxSuffix)throw new Error(`registerClass: ${o.name} is missing a static tytxSuffix`);if(typeof o.prototype?.toTytx!="function")throw new Error(`registerClass: ${o.name} is missing a toTytx method`);if(typeof o.fromTytx!="function")throw new Error(`registerClass: ${o.name} is missing a static fromTytx method`);return Wn(o,o.tytxSuffix,e=>e.toTytx(),e=>o.fromTytx(e),o.tytxJsonNative||!1),o}function wt(o,e){za.set(o,e)}function Pe(o){return za.has(o)?za.get(o):{}}function vd(o,e,t=e.name){let r=Pe(o);if((r[t]??e)!==e)throw new Error(`TYTX subtype name '${t}' is already registered for suffix '${o}' by ${r[t].name}`);wt(o,{...r,[t]:e})}var Ua={json:"application/json",xml:"application/xml",msgpack:"application/msgpack"};function qa(o){if(!o)return null;let e=o.toLowerCase();return e.includes("jsonl")?"jsonl":e.includes("json")?"json":e.includes("xml")?"xml":e.includes("msgpack")?"msgpack":null}async function Ii(o,e={}){let{body:t,transport:r="json",method:n=t!==void 0?"POST":"GET",headers:i={},...s}=e,a={"X-TYTX-Transport":r,...i},l;if(t!==void 0){a["Content-Type"]=Ua[r];let h=R(t,r);l=h}let c=await fetch(o,{method:n,headers:a,body:l,...s});if(!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);let u=c.headers.get("Content-Type")||"",d=qa(u)||r,f;if(d==="msgpack"){let h=await c.arrayBuffer();f=j(Buffer.from(h),d)}else{let h=await c.text();f=j(h,d)}return f}var qm="0.16.4";var nl={};ee(nl,{BuilderBase:()=>Ae,Collection:()=>ut,CustomTypes:()=>hr,DATA_ELEMENT_FIELDS:()=>rl,DATA_ROOT:()=>an,HtmlBuilder:()=>Je,HtmlRenderer:()=>Wt,META_ATTRS:()=>lt,RendererBase:()=>qt,SOURCE_ROOT:()=>sn,SourceBag:()=>N,SourceBagNode:()=>Se,SvgBuilder:()=>vt,SvgRenderer:()=>Gt,VALUE:()=>cr,XmlRenderer:()=>Vt,pointerDependencies:()=>Ze,pointerExpression:()=>Jr,pointerTemplate:()=>zt,pointerTransform:()=>H,resolveRenderTag:()=>nn,sourceAttributeItems:()=>ge,sourceBagFromTytx:()=>ji,sourceBagToTytx:()=>Rd,sourceTarget:()=>Z,svgAttributes:()=>Jn,wrapSource:()=>on});function H(o){if(typeof o!="string"||!["^","="].includes(o[0])||o.startsWith("=="))return null;let e=o.indexOf(":");if(e<0)return null;let t=o[e+1]==="=";return{pointer:o.slice(0,e),expression:t,body:o.slice(e+(t?2:1))}}var xd=/^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;function zt(o,e){let t="",r=!1;for(let n=0;n<o.length;){if(o[n]!=="{"&&o[n]!=="}"){t+=o[n++];continue}let i=o.slice(n).match(xd);if(!i)throw new SyntaxError("Invalid pointer template placeholder");let s=i[1]??"",a=s.startsWith("?"),l=e(a?s.slice(1):s);l==null||l===""&&!a?r=!0:t+=String(l),n+=i[0].length}return r?null:t}function Jr(o){let e=[],t=new Set,r="",n=!0;for(let i=0;i<o.length;){let s=i,a=o[i];if(a==='"'||a==="'"||a==="`"){for(i++;i<o.length;){if(o[i]==="\\"){i+=2;continue}if(o[i++]===a)break}r+=o.slice(s,i),n=!1;continue}if(o.startsWith("//",i)){i=o.indexOf(`
26
+ `,i),i<0&&(i=o.length),r+=o.slice(s,i);continue}if(o.startsWith("/*",i)){let u=o.indexOf("*/",i+2);i=u<0?o.length:u+2,r+=o.slice(s,i);continue}if(a==="/"&&n){let u=!1;for(i++;i<o.length;){let d=o[i++];if(d==="\\"){i++;continue}if(d==="[")u=!0;else if(d==="]")u=!1;else if(d==="/"&&!u)break}for(;/[a-z]/i.test(o[i]??"")&&i<o.length;)i++;r+=o.slice(s,i),n=!1;continue}let l=a==="{"?o.slice(i).match(xd):null;if(l){let u=l[1]??"";if(u.startsWith("?"))throw new SyntaxError("Optional slots are supported in pointer templates only");r+=`_pointerValues[${e.length}]`,e.push(u),i+=l[0].length,n=!1;continue}let c=o.slice(i).match(/^[A-Za-z_$][\w$]*/);if(c){t.add(c[0]),r+=c[0],i+=c[0].length,n=["return","typeof","void","delete","new","in","instanceof","yield","await"].includes(c[0]);continue}r+=a,i++,/\s/.test(a)||(n=/[([{,:;=!?&|+*%~<>\/-]/.test(a))}return{text:r,slots:e,identifiers:t}}function kd(o,e,t=()=>null){let r=new Map,n=[],i=s=>{if(r.has(s))return r.get(s);if(!o.has(s))throw new Error(`Referenced Source attribute '${s}' does not exist`);if(n.includes(s))throw new Error(`Cyclic attribute dependency: ${[...n,s].join(" -> ")}`);n.push(s);try{let a=o.get(s),l=typeof s=="string"?H(a):null,c=e.get(s);if(l){let u=d=>d?i(d):e.get(s);if(l.expression){let d=Jr(l.body);c=t(s,a,d,d.slots.map(u))}else c=zt(l.body,u),e.get(s)==null&&(c=null)}return r.set(s,c),c}finally{n.pop()}};return new Map([...o.keys()].map(s=>[s,i(s)]))}function Ze(o,e){let t=new Map([...Object.entries(o.getAttr()),...o.fixedAttrItems()]),r=new Set,n=[],i=s=>{let a=H(s);if(!a)return;let l=[];a.expression?l.push(...Jr(a.body).slots):zt(a.body,c=>(l.push(c),""));for(let c of l.filter(Boolean)){if(!t.has(c))throw new Error(`Referenced Source attribute '${c}' does not exist`);if(n.includes(c))throw new Error(`Cyclic attribute dependency: ${[...n,c].join(" -> ")}`);r.has(c)||(n.push(c),i(t.get(c)),n.pop(),r.add(c))}};return i(e),r}var Ka={};ee(Ka,{Bag:()=>x,BagCbResolver:()=>_t,BagException:()=>rn,BagNode:()=>Ue,BagNodeContainer:()=>Qr,BagResolver:()=>Y,BagSerializationError:()=>ce,OpaqueResolver:()=>lr,RETRY_POLICIES:()=>Wa,StorageResolver:()=>Yn,UrlResolver:()=>Hn,UuidResolver:()=>Xn,registerResolver:()=>Oi});var Wa={network:{maxAttempts:3,delay:1,backoff:2,jitter:!0,on:["TypeError","NetworkError","AbortError"]},aggressive:{maxAttempts:5,delay:.5,backoff:2,jitter:!0,on:["Error"]},gentle:{maxAttempts:2,delay:2,backoff:1.5,jitter:!1,on:["TypeError","NetworkError"]}};function Vm(o){let e=o._retryPolicy;return e==null?null:typeof e=="string"?Wa[e]||null:e}function Wm(o,e){return e.some(t=>t==="Error"?!0:o.name===t||o.constructor.name===t)}function Gm(o){return new Promise(e=>setTimeout(e,o))}async function Hm(o,e){if(!e)return o();let t=e.maxAttempts||3,r=e.delay||1,n=e.backoff||2,i=e.jitter!==!1,s=e.on||["Error"],a=null,l=r*1e3;for(let c=0;c<t;c++)try{let u=o();return u instanceof Promise?await u:u}catch(u){if(a=u,c<t-1&&Wm(u,s)){let d=l;i&&(d*=1+Math.random()*.1),await Gm(d),l*=n}else throw u}throw a}var Y=class o{static classKwargs={cacheTime:0,readOnly:!1,asBag:null,retryPolicy:null};static classArgs=[];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy"]);constructor(e={}){let r={...this.constructor.classKwargs,...e};for(let i of["interval","reactive"])if(Object.hasOwn(r,i))throw new TypeError(`Removed resolver option: ${i}. Schedule updates in the application; use reset() and read explicitly.`);this.cacheTime=r.cacheTime,this._readOnly=r.readOnly,this._asBag=r.asBag,this._retryPolicy=r.retryPolicy,this._kw={};let n=this.constructor.internalParams;for(let[i,s]of Object.entries(r))n.has(i)||(this._kw[i]=s);this._lastUpdate=null,this._node=null,this._lastEffectiveFingerprint=null,this._cachedValue=null,this.init()}init(){}setNode(e){e!==this._node&&!this.readOnly&&this._lastUpdate!==null&&this.reset(),this._node=e,this.onSetResolver(e)}onSetResolver(e){}get node(){return this._node}get cacheTime(){return this._cacheTime}set cacheTime(e){if(typeof e=="boolean")throw new TypeError("cacheTime must be numeric; use a negative value for infinite caching");this._cacheTime=e}get readOnly(){return this._readOnly}get expired(){return this._cacheTime<0?this._lastUpdate===null:this._cacheTime===0||this._lastUpdate===null?!0:(Date.now()-this._lastUpdate)/1e3>this._cacheTime}reset(...e){if(e.length)throw new TypeError("reset() takes no arguments. It invalidates the cache for the next explicit read.");this._lastUpdate=null,this._lastEffectiveFingerprint=null}get cachedValue(){return!this.readOnly&&this._node?this._node._value:this._cachedValue}set cachedValue(e){!this.readOnly&&this._node?this._node.setValue(e,!1):this._cachedValue=e}_computeEffectiveFingerprint(e){return JSON.stringify(Object.entries(e).sort())}_buildEffectiveKw(){let e={...this._kw};if(this._node&&this._node.attr)for(let t of Object.keys(this._kw))Object.hasOwn(this._node.attr,t)&&(e[t]=this._node.attr[t]);return e}resolve(e={}){let{static:t=!1,...r}=e;if(t)return this._node?this._node._value:this.cachedValue;let n=this._buildEffectiveKw();if(Object.keys(r).length>0)return this._load({...n,...r},s=>this._prepareValue(s));let i=this._computeEffectiveFingerprint(n);return i===this._lastEffectiveFingerprint&&!this.expired?this.cachedValue:(this._lastEffectiveFingerprint=i,this._load(n,s=>this._finalize(s)))}_load(e,t){let r=Vm(this),n=()=>this.load(e);if(r)return Hm(n,r).then(t);let i=n();return i&&typeof i.then=="function"?i.then(t):t(i)}_finalize(e){return e=this._prepareValue(e),this._lastUpdate=Date.now(),(!this.readOnly||this.cacheTime!==0)&&(this.cachedValue=e),e}_prepareValue(e){let t;return this._asBag===!0?t=!0:this._asBag===!1?t=!1:t=!this._readOnly,t&&e!==null&&e!==void 0&&(e=this._convertToBag(e)),e}_convertToBag(e){let t=o._BagClass;if(!t||e&&typeof e._htraverse=="function")return e;if(typeof e=="string"){if(e=e.trim(),e.startsWith("<")&&t.fromXml)return t.fromXml(e);if((e.startsWith("{")||e.startsWith("["))&&t.fromTytx)return t.fromTytx(e)}return e}static registerBagClass(e){o._BagClass=e}load(e){return null}};Y._BagClass=null;var _t=class extends Y{static classKwargs={cacheTime:0,readOnly:!1,asBag:!1,retryPolicy:null,callback:null};static classArgs=["callback"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy","callback"]);constructor(e={}){typeof e=="function"&&(e={callback:e}),super(e),this._callback=e.callback||null}load(e){return this._callback?this._callback.call(this,e):null}};var Ue=class o{constructor(e,t,r=null,n=null,i=null,s=null,a=null,l=!0){this.label=t,this._value=null,this._attr={},this._parentBag=null,this._resolver=null,this._nodeSubscribers={},this._onChangedValue=null,this.nodeTag=s,this.xmlTag=a,this._compiled=null,this.parentBag=e,n&&this.setAttr(n,!1,!0,l),r!==null&&this.setValue(r,!1),i&&(this.resolver=i)}get parentBag(){return this._parentBag}set parentBag(e){e===null&&this._value?.parentNode===this&&this._value.setBackref(),this._parentBag=e,e?.backref&&this._value&&typeof this._value._htraverse=="function"&&this._value.setBackref(this,e)}get value(){return this.getValue()}set value(e){this.setValue(e)}getValue(e=!1,t=null,r={}){if(t!==null){let n=j(`${t}::QS`);if(Array.isArray(n)){let i=n.length?n:Object.keys(this._attr),s=i.map(l=>{let c=this.getAttr(l);return!e&&c instanceof Y?c.resolve():c}),a=l=>n.length===0?Object.fromEntries(i.map((c,u)=>[c,l[u]])):l.length===1?l[0]:l;return s.some(l=>l&&typeof l.then=="function")?Promise.all(s).then(a):a(s)}else{if(!this._resolver)throw new Error("Cannot use kwargs syntax without resolver");r={...r,...n}}}return this._resolver!==null?this._resolver.resolve({static:e,...r}):this._value}setValue(e,t=!0,r=null,n=null,i=!0,s=null,a=!1){e instanceof Y?(this.resolver=e,e=null):e instanceof o&&(r=r||{},Object.assign(r,e._attr),e.resolver&&(this.resolver=e.resolver),e=e._value);let l=this._value;l!==e&&l?.parentNode===this&&l.setBackref(),this._value=e;let c=l!==this._value,u=t??!0,d=null;if(r!==null){let h={...this._attr};this.setAttr(r,!1,n,i);let p=this._buildAttrDiff(h,this._attr);d=Object.keys(p).length>0?p:null}t=u&&(c||d!==null);let f=d?c?"upd_value_attr":"upd_attrs":"upd_value";if(this._onChangedValue&&this._onChangedValue(this,e,l,u),t){let h=d!==null?{oldvalue:l,attrs_diff:d}:{oldvalue:l};for(let p of Object.values(this._nodeSubscribers))p({node:this,info:h,evt:f})}this._parentBag!==null&&this._parentBag.backref&&(e&&typeof e._htraverse=="function"&&e.setBackref(this,this._parentBag),t&&this._parentBag._onNodeChanged(this,[this.label],f,l,d,s,a))}replace(e){if(!(e instanceof o))throw new TypeError("BagNode.replace expects a BagNode");if(e===this)return this;let t=e.staticValue;t&&typeof t._htraverse=="function"&&(t=t.createChildBag().replace(t));let r=null;e.resolver&&(r=Object.create(Object.getPrototypeOf(e.resolver),Object.getOwnPropertyDescriptors(e.resolver)),r._node=null,r._kw={...e.resolver._kw});let n=this._value,i={...this._attr},s=this.resolver;s&&s._node===this&&(s._node=null),this.resolver=r,this.setValue(t,!1,{...e.attr},!1,!1,null);let a=this._buildAttrDiff(i,this._attr),l=Object.keys(a).length?a:null,c=n!==t||s!==r;if(c||l){let u=l?c?"upd_value_attr":"upd_attrs":"upd_value",d=l?{oldvalue:n,attrs_diff:l}:{oldvalue:n};for(let f of Object.values(this._nodeSubscribers))f({node:this,info:d,evt:u});this._parentBag!==null&&this._parentBag.backref&&this._parentBag._onNodeChanged(this,[this.label],u,n,l)}return this}get staticValue(){return this._value}set staticValue(e){this._value=e}get resolver(){return this._resolver}set resolver(e){this._resolver=e,e&&e.setNode&&e.setNode(this)}resetResolver(){if(!this._resolver)throw new Error("Cannot reset resolver: node has no resolver");this._resolver.reset(),this.setValue(null)}get attr(){return this._attr}getAttr(e=null,t=null){return e?e in this._attr?this._attr[e]:t:this._attr}_buildAttrDiff(e,t){let r={},n=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of n){let s=i in e?e[i]:null,a=i in t?t[i]:null;s!==a&&(r[i]={old:s,new:a})}return r}setAttr(e=null,t=!0,r=!0,n=!0){let i=e||{},s=Object.keys(this._nodeSubscribers).length>0,l=t&&(s||this._parentBag!==null&&this._parentBag.backref)?{...this._attr}:null;if(r?Object.assign(this._attr,i):this._attr={...i},n)for(let c of Object.keys(this._attr))this._attr[c]===null&&delete this._attr[c];if(t&&l!==null){let c=this._buildAttrDiff(l,this._attr);if(Object.keys(c).length>0&&s)for(let u of Object.values(this._nodeSubscribers))u({node:this,info:{attrs_diff:c},evt:"upd_attrs"});if(Object.keys(c).length>0&&this._parentBag!==null&&this._parentBag.backref){let u=t===!0?"true":String(t);this._parentBag._onNodeChanged(this,[this.label],"upd_attrs",null,c,u)}}}delAttr(...e){for(let t of e)if(typeof t=="string"&&t.includes(","))for(let r of t.split(","))delete this._attr[r.trim()];else delete this._attr[t]}hasAttr(e,t=null){return e in this._attr?t!==null?this._attr[e]===t:!0:!1}getInheritedAttributes(){let e={};return this._parentBag&&this._parentBag.parentNode&&(e=this._parentBag.parentNode.getInheritedAttributes()),{...e,...this._attr}}subscribe(e,t){this._nodeSubscribers[e]=t}unsubscribe(e){delete this._nodeSubscribers[e]}get compiled(){return this._compiled||(this._compiled={}),this._compiled}get isBranch(){return this._value!=null&&typeof this._value._htraverse=="function"}get position(){return this._parentBag===null?null:this._parentBag._nodes.index(this.label)}get fullpath(){if(this._parentBag!==null){let e=this._parentBag.fullpath;return e?`${e}.${this.label}`:this.label}return null}get parentNode(){return this._parentBag?this._parentBag.parentNode:null}attributeOwnerNode(e,t=null){let r=this;if(t===null)for(;r&&!(e in r._attr);)r=r.parentNode;else for(;r&&r._attr[e]!==t;)r=r.parentNode;return r}asTuple(){return[this.label,this.value,this._attr,this._resolver||null]}isEqual(e){if(!(e instanceof o)||this.label!==e.label)return!1;let t=Object.keys(this._attr),r=Object.keys(e._attr);if(t.length!==r.length)return!1;for(let n of t)if(this._attr[n]!==e._attr[n])return!1;return this._resolver!==null?this._resolver===e._resolver:this._value&&typeof this._value.equalTo=="function"?this._value.equalTo(e._value):this._value&&typeof this._value.isEqual=="function"?this._value.isEqual(e._value):this._value===e._value}diff(e){if(this.label!==e.label)return`Other label: ${e.label}`;let t=Object.keys(this._attr),r=Object.keys(e._attr);return t.length!==r.length||t.some(n=>this._attr[n]!==e._attr[n])?`attributes self:${JSON.stringify(this._attr)} --- other:${JSON.stringify(e._attr)}`:this._value!==e._value?`value self:${this._value} --- other:${e._value}`:null}toJson(e=!0){let t=this.value;return t&&typeof t.toJson=="function"&&(t=t.toJson(e,!0)),{label:this.label,value:t,attr:this._attr}}toString(){return`BagNode : ${this.label}`}};var Qr=class o{constructor(){this._dict=Object.create(null),this._list=[],this._parentBag=null}index(e){if(e in this._dict)return this._list.findIndex(r=>r.label===e);let t=e.match(/^#(\d+)$/);if(t){let r=parseInt(t[1],10);return r<this._list.length?r:-1}if(t=e.match(/^#(\w*)=(.*)$/),t){let[,r,n]=t,i=n.includes("::")?j(n):n;return r?this._list.findIndex(s=>s.getAttr(r)===i):this._list.findIndex(s=>s._value===i)}return-1}_parsePosition(e){let t=this._list.length;if(e==null||e===">")return t;if(typeof e=="number")return e<0&&(e=t+e),Math.max(0,Math.min(e,t));if(e==="<")return 0;if(e.startsWith("#")){let r=this._parseSharpIndex(e.slice(1),e);return Math.min(r,t)}if(e.startsWith("<")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i,t)}let n=this.index(r);if(n<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return n}if(e.startsWith(">")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i+1,t)}let n=this.index(r);if(n<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return n+1}throw new Error(`Invalid node_position '${e}': unrecognized syntax`)}_parseSharpIndex(e,t){if(!/^-?\d+$/.test(e))throw new Error(`Invalid node_position '${t}': '${e}' is not an integer`);let r=parseInt(e,10);if(r<0)throw new Error(`Invalid node_position '${t}': negative index not allowed in '#n' syntax`);return r}get(e){if(typeof e=="number")return e>=0&&e<this._list.length?this._list[e]:null;if(e.startsWith("#")){let t=this.index(e);return t>=0?this._list[t]:null}return this._dict[e]||null}set(e,t,r=">",n=null,i=null,s=null,a=!1,l=!0,c=null,u=!0,d=!1,f=null){let h=null;if(e.includes("?")&&([e,h]=e.split("?",2)),e==null||e.startsWith("#"))throw new Error("Cannot create new node with #n syntax");if(h){let m=h.split("&");if(m.length===1)n={[m[0]]:t};else{if(!Array.isArray(t)||t.length!==m.length)throw new Error("Wrong attributes assignment");n={};for(let b=0;b<m.length;b++)n[m[b]]=t[b]}t=null}let p=this._dict[e];if(p)f&&(p.nodeTag=f),s!==null&&(s===!1?p.resolver=null:p.resolver=s),h?p.setAttr(n,u,!0,l):p.setValue(t,u,n,a,l,c,d);else{let m=i&&i.nodeClass?i.nodeClass:Ue;p=new m(i,e,h?null:t,n,s,f,null,l);let b=this._parsePosition(r);this._dict[e]=p,this._list.splice(b,0,p),u&&i&&i.backref&&i._onNodeInserted(p,b,null,c,d)}return d&&p.setValue(null,!1),p}pop(e){let t=this.get(e);if(t){delete this._dict[t.label];let r=this._list.indexOf(t);return r>=0&&this._list.splice(r,1),t}return null}has(e){return e in this._dict}get length(){return this._list.length}clear(){this._dict=Object.create(null),this._list=[]}keys(){return this._list.map(e=>e.label)}values(){return this._list.map(e=>e.getValue())}items(){return this._list.map(e=>[e.label,e.getValue()])}[Symbol.iterator](){return this._list[Symbol.iterator]()}move(e,t,r=!0){if(t<0)return;let n=Array.isArray(e)?e:[e];if(n.length===0||t>=this._list.length)return;let i=this._list[t].label;if(n.length>1){let s=[...n].sort((u,d)=>u-d),a=s[0]<t?1:0,l=[];for(let u=s.length-1;u>=0;u--){let d=s[u];if(d>=0&&d<this._list.length){let f=this._list[d];this._list.splice(d,1),l.push(f),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(f,d)}}let c=this.index(i);c<0&&(c=this._list.length),c+=a;for(let u of l)this._list.splice(c,0,u),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(u,c)}else{let s=n[0];if(s===t||s<0||s>=this._list.length)return;let a=this._list[s];this._list.splice(s,1),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(a,s),this._list.splice(t,0,a),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(a,t)}}isEqual(e){if(!(e instanceof o)||this._list.length!==e._list.length)return!1;for(let t=0;t<this._list.length;t++){let r=this._list[t],n=e._list[t];if(!r.isEqual(n))return!1}return!0}};var Ga="::RSLV:",Ci=new Map,Di=new Map,Ni=new WeakMap,ce=class extends Error{constructor(e){super(e),this.name="BagSerializationError"}},lr=class extends Y{constructor(e){super({asBag:!1}),Ni.set(this,e)}get payload(){return Ni.get(this)}load(){throw new ce("This resolver is opaque; local execution is unavailable")}};function Oi(o,{module:e,name:t,encode:r,decode:n}){if(!(o.prototype instanceof Y)||o===lr||typeof e!="string"||!e||typeof t!="string"||!t||typeof r!="function"||typeof n!="function")throw new TypeError("registerResolver requires a BagResolver subclass, module, name and adapters");let i=JSON.stringify([e,t]);if(Ci.has(i)&&Ci.get(i).cls!==o)throw new TypeError(`Resolver ${e}.${t} is already registered`);if(Di.has(o)&&Di.get(o).key!==i)throw new TypeError("A resolver class cannot own two wire identities");let s={cls:o,module:e,name:t,encode:r,decode:n,key:i};Ci.set(i,s),Di.set(o,s)}function Ed(o){if(!o||typeof o!="object"||Array.isArray(o)||typeof o.resolver_module!="string"||typeof o.resolver_class!="string"||!Array.isArray(o.args??[])||!o.kwargs||typeof o.kwargs!="object"||Array.isArray(o.kwargs))throw new ce("Invalid resolver description")}function Td(o,e=new Set){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(typeof o!="object"||e.has(o)||!Array.isArray(o)&&Object.getPrototypeOf(o)!==Object.prototype&&Object.getPrototypeOf(o)!==null)throw new ce("Resolver parameters must be JSON data; callbacks cannot travel");e.add(o);for(let t of Object.values(o))Td(t,e);e.delete(o)}}function Gn(o){if(Ni.has(o))return Ni.get(o);let e=Di.get(o.constructor);if(!e)throw new ce(`Unregistered resolver: ${o.constructor.name}`);let t=e.encode(o),r={resolver_module:e.module,resolver_class:e.name,args:t.args??[],kwargs:t.kwargs??{}};return Ed(r),Td(r),Ga+JSON.stringify(r)}function $i(o){if(typeof o!="string"||!o.startsWith(Ga))return null;let e=o.slice(Ga.length);if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+$/.test(e))return new lr(o);let t;try{t=JSON.parse(e)}catch{throw new ce("Invalid resolver JSON or signed token")}Ed(t);let r=Ci.get(JSON.stringify([t.resolver_module,t.resolver_class]));if(!r)return new lr(o);let n=r.decode({args:t.args??[],kwargs:t.kwargs});if(!(n instanceof r.cls))throw new ce("Resolver decoder returned an incompatible instance");return n}function Ri(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[e,t instanceof Y?Gn(t):t]))}function Ha(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[e,$i(t)??t]))}var Ke="__cls";function en(o,e){return o!==null&&o.tytxSuffix===e?o:Kr(e)}function Xm(o){let e=o.tytxSuffix,t=Object.entries(Pe(e)).filter(([,r])=>r===o).map(([r])=>r);if(t.length===0)throw new ce(`${o.name} is not in the TYTX subtype dictionary of '${e}'`);if(t.length>1)throw new ce(`${o.name} is in the TYTX subtype dictionary of '${e}' under several names: ${t.sort().join(", ")}`);return t[0]}function Xa(o,e){let t=Pe(o);if(!Object.hasOwn(t,e))throw new ce(`Unknown Bag class '${e}' for TYTX type '${o}'`);return t[e]}function Ya(o,e){return o===e?null:Xm(o)}function*Ad(o,e=[]){for(let t of o){let r=[...e,t.label];yield[r,t];let n=t.getValue(!0);!t.resolver&&n instanceof x&&(yield*Ad(n,r))}}function Ym(o){let e=o.toISOString(),t=o.getUTCFullYear()===1970&&o.getUTCMonth()===0&&o.getUTCDate()===1,r=o.getUTCHours()===0&&o.getUTCMinutes()===0&&o.getUTCSeconds()===0&&o.getUTCMilliseconds()===0;if(r&&!t)return e.slice(0,e.indexOf("T"));let n=e.replace(/\.000Z$/,"Z");return t&&!r?n.slice(n.indexOf("T")+1):n}function tn(o){if(o===null||typeof o!="object")return!1;let e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function Ut(o){return typeof o=="string"?o.includes("::")?`${o}::T`:o:Array.isArray(o)?o.map(Ut):tn(o)?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,Ut(t)])):o}function Za(o){if(!tn(o))throw new TypeError("Bag options must be an object");let{recursive:e=!0}=o;if(typeof e!="boolean")throw new TypeError("recursive must be a boolean");return e}var Sd=!1,x=class o{static tytxSuffix="X";constructor(e=null,t={}){this._nodes=new Qr,this._backref=!1,this._parent=null,this._parentNode=null,this._rootAttributes=null,this._updSubscribers={},this._insSubscribers={},this._delSubscribers={},Za(t),e!=null&&this.fillFrom(e,t)}get parent(){return this._parent}set parent(e){this._parent=e}get parentNode(){return this._parentNode}set parentNode(e){this._parentNode=e}get backref(){return!!this._backref}get nodeClass(){return Ue}createChildBag(){return new this.constructor}get fullpath(){if(this._parent!==null&&this._parentNode!==null){let e=this._parent.fullpath;return e?`${e}.${this._parentNode.label}`:this._parentNode.label}return null}relativePath(e){let t=[],r=e;for(;r!==null;){if(r.parentBag===this)return t.push(r.label),t.reverse(),t.join(".");t.push(r.label),r=r.parentNode}return null}get length(){return this._nodes.length}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}get attributes(){return this._parentNode!==null?this._parentNode.getAttr():{}}get rootAttributes(){return this._rootAttributes}set rootAttributes(e){this._rootAttributes=e!==null?{...e}:null}_htraverseBefore(e){let t=this,r;for(typeof e=="string"?(e=e.replace(/\.\.\//g,"#parent."),r=e.split(".").filter(n=>n)):r=[...e];r.length&&r[0]==="#parent"&&t!==null;)r.shift(),t=t.parent;return[t,r]}_htraverse(e,t=!1,r=!0){let[n,i]=this._htraverseBefore(e);if(n===null)return[null,null];if(i.length===0)return[n,""];for(;i.length>1&&n instanceof o;){let s=i[0];if(s==="#parent"){if(n.parent===null||n.parent===void 0)break;i.shift(),n=n.parent;continue}let a=n._nodes.get(s);if(!a)break;let l=a.getValue(r);if(l instanceof o)i.shift(),n=l;else if(t){let c=n.createChildBag();a.setValue(c,!0,null,!0,!0,"autocreate"),i.shift(),n=c}else break}if(!t)return i.length>1?[null,null]:[n,i[0]];for(;i.length>1;){let s=i.shift();if(s.startsWith("#"))throw new rn("Not existing index in #n syntax");let a=n.createChildBag();n._nodes.set(s,a,">",null,n,null,!1,!0,"autocreate"),n=a}return[n,i[0]]}get(e,t=null,r=!0,n={}){if(!e)return this;if(e==="#parent")return this.parent;let i=null;e.includes("?")&&([e,i]=e.split("?",2));let s=this._nodes.get(e);return s?s.getValue(r,i,n):t}getItem(e,t=null,r=!1,n={}){if(!e)return this;let[i,s]=this._htraverse(e,!1,r);return i instanceof o?i.get(s,t,r,n):t}setItem(e,t,r=null,n=">",i=!1,s=!0,a=null,l=!1,c=!0,u=null,d=null){if(e==="")throw new RangeError("setItem requires a non-empty path");let[f,h]=this._htraverse(e,!0);return f._nodes.set(h,t,n,r,f,u,i,s,a,c,l,d)}_pop(e,t=null){let r=this._nodes.index(e);if(r>=0){let n=this._nodes.pop(r);return this.backref&&this._onNodeDeleted(n,r,null,t),n}return null}pop(e,t=null,r=null){let n=this.popNode(e,r);return n?n.value:t}delItem(e,t=null,r=null){return this.pop(e,t,r)}popNode(e,t=null){let[r,n]=this._htraverse(e,!1,!0);if(!r||!n)return null;let i=r._nodes.get(n);if(!i)return null;try{return r._pop(n,t)}finally{i.parentBag===r&&r._nodes._dict[i.label]!==i&&(i.parentBag=null)}}clear(){let e=[...this._nodes];this._nodes.clear(),this.backref&&this._onNodeDeleted(e,-1);for(let t of e)t.parentBag=null}getNode(e,t=!0,r=!1,n=null){if(e==null||e==="")return this.parentNode;if(typeof e=="number")return this._nodes.get(e);typeof e=="string"&&(e=e.split("?",1)[0]);let[i,s]=this._htraverse(e,r,t);if(i instanceof o&&s){let a=i._nodes.get(s);if(a)return a;if(r)return i._nodes.set(s,n,">",null,i,null,!1,!0,"autocreate"),i._nodes.get(s)}return null}setBackref(e=null,t=null){let r=this._backref;if(this._backref=!0,this._parent=t,this._parentNode=e,!r){this._nodes._parentBag=this;for(let n of this)n.parentBag=this}}delParentRef(){this._parent=null,this._parentNode=null,this._backref=!1}clearBackref(){if(this._backref){this._backref=!1,this._parent=null,this._parentNode=null,this._nodes._parentBag=null;for(let e of this){e.parentBag=null;let t=e.getValue(!0);t instanceof o&&t.clearBackref()}}}_onNodeChanged(e,t,r,n=null,i=null,s=null,a=!1){for(let l of Object.values(this._updSubscribers))l({node:e,pathlist:t,oldvalue:n,attrs_diff:i,evt:r,reason:s,fired:a});this._parent&&this._parentNode&&this._parent._onNodeChanged(e,[this._parentNode.label,...t],r,n,i,s,a)}_onNodeInserted(e,t,r=null,n=null,i=!1){let s=e.parentBag,a=e.getValue(!0);s!==null&&s.backref&&a instanceof o&&a.setBackref(e,s),r===null&&(r=[]);for(let l of Object.values(this._insSubscribers))l({node:e,pathlist:r,ind:t,evt:"ins",reason:n,fired:i});this._parent&&this._parentNode&&this._parent._onNodeInserted(e,t,[this._parentNode.label,...r],n,i)}_onNodeDeleted(e,t,r=null,n=null){for(let i of Object.values(this._delSubscribers))i({node:e,pathlist:r,ind:t,evt:"del",reason:n});this._parent&&this._parentNode&&(r===null&&(r=[]),this._parent._onNodeDeleted(e,t,[this._parentNode.label,...r],n))}_subscribe(e,t,r){r!=null&&(t[e]=r)}subscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=null,insert:n=null,delete:i=null,any:s=null}=t;this.backref||this.setBackref(),this._subscribe(e,this._updSubscribers,r||s),this._subscribe(e,this._insSubscribers,n||s),this._subscribe(e,this._delSubscribers,i||s)}unsubscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=!1,insert:n=!1,delete:i=!1,any:s=!1}=t;(r||s)&&delete this._updSubscribers[e],(n||s)&&delete this._insSubscribers[e],(i||s)&&delete this._delSubscribers[e]}[Symbol.iterator](){return this._nodes[Symbol.iterator]()}keys(){return this._nodes.keys()}values(){return this._nodes.values()}items(){return[...this._nodes].map(e=>({key:e.label,value:e.getValue()}))}get nodes(){return this.getNodes()}node(e){return this._nodes.get(e)}setAttr(e=null,t=null,r=!0){let n=o.prototype.getNode.call(this,e,!0,!0);n&&n.setAttr(t,!0,!0,r)}getAttr(e=null,t=null,r=null){let n=this.getNode(e);return n?n.getAttr(t,r):r}delAttr(e=null,...t){let r=this.getNode(e);r&&r.delAttr(...t)}getInheritedAttributes(){return this._parentNode?this._parentNode.getInheritedAttributes():{}}getNodes(e=null){return e?[...this._nodes].filter(t=>e(t)):[...this._nodes]}getNodeByValue(e,t){for(let r of this._nodes){let n=r.value;if(n instanceof o){if(n.getItem(e)===t)return r}else if(n&&n.get&&n.get(e)===t)return r}return null}getNodeByAttr(e,t,r=!1,n=!1){let i=t===void 0,s=r&&typeof t=="string"?t.toLowerCase():t,a=l=>{let c=[];for(let u of l._nodes){if(e in u.attr){let d=r&&typeof u.attr[e]=="string"?u.attr[e].toLowerCase():u.attr[e];if(i||d==s)return u}if(u._value instanceof o)if(n){let d=a(u._value);if(d)return d}else c.push(u._value)}for(let u of c){let d=a(u);if(d)return d}return null};return a(this)}isEmpty(e=!1,t=!1){if(this._nodes.length===0)return!0;for(let r of this._nodes){if(r._resolver!==null)return!1;let n=r.getValue(!0);if(n!=null&&!(e&&n===0)&&!(t&&n===""))return!1}return!0}query(e=null,t=null,r=!1,n=!1,i=!0,s=!0,a=null,l=!0){e||(e="#k,#v,#a");let c=this,u;if(typeof e=="string"){if(e.includes(":")){let[h,p]=e.split(":");c=this.getItem(h),e=p}u=e.split(",").map(h=>h.trim())}else u=e;let d=(h,p,m,b,w)=>{if(p==="#k")return h.label;if(p==="#p")return m;if(p==="#n")return h;if(typeof p=="function")return p(h);if(p==="#v"){let _=w();return b&&_ instanceof o?null:_}else if(p.startsWith("#v.")){let _=p.split(".").slice(1).join("."),v=w();return v&&v.getItem?v.getItem(_):null}else{if(p==="#__v")return h.getValue(!0);if(p.startsWith("#a")){let _=p.includes(".")?p.split(".").slice(1).join("."):null;return h.getAttr(_)}else{let _=w();return _&&_.getItem?_.getItem(p):null}}};function*f(){let h=0;function*p(m,b){for(let w of m._nodes){let _=b?`${b}.${w.label}`:w.label,v=!1,E,D=()=>(v||(E=w.getValue(l),v=!0),E);if((i&&s||(D()instanceof o?s:i))&&(t===null||t(w))&&(yield u.length===1?d(w,u[0],_,n,D):u.map(C=>d(w,C,_,n,D)),h++,a!==null&&h>=a))return;if(n){let C=D();if(C instanceof o&&(yield*p(C,_),a!==null&&h>=a))return}}}yield*p(c,"")}return r?f():[...f()]}getLeaves(){let e=[],t=(r,n)=>{for(let i of r._nodes){let s=n?`${n}.${i.label}`:i.label,a=i.getValue(!1);a instanceof o?t(a,s):e.push([s,a])}};return t(this,""),e}digest(e=null,t=null,r=!1){typeof t=="boolean"&&(console.warn("Bag.digest(what, asColumns) is deprecated; use digest(what, null, asColumns)."),r=t,t=null);let n=this.query(e,t,!1,!1,!0,!0,null,!1);if(r){if(!n||n.length===0)return(typeof e=="string"?e:"#k,#v,#a").split(",").map(l=>l.trim()).map(()=>[]);let i=[...n];if(i.length&&Array.isArray(i[0])){let s=i[0].length,a=[];for(let l=0;l<s;l++)a.push(i.map(c=>c[l]));return a}return[i]}return[...n]}columns(e,t=!1){typeof e=="string"&&(e=e.split(","));let r=t?"#a.":"",n=e.map(i=>`${r}${i}`).join(",");return this.digest(n,null,!0)}sum(e="#v",t=!1,r=null){if(t!=null&&typeof t!="boolean")throw new TypeError("sum strict must be a boolean; pass condition as the third argument");if(r!=null&&typeof r!="function")throw new TypeError("sum condition must be callable; deep is no longer supported");let n=i=>{let s=0,a=!1;for(let l of this.query(i,r)){if(l==null||l===""){a=!0;continue}if(typeof l!="number"&&typeof l!="boolean"){if(t)throw new TypeError(`sum encountered non-numeric value: ${typeof l}`);continue}s+=l}return t&&a?null:s};return e.includes(",")?e.split(",").map(i=>n(i.trim())):n(e)}sort(e="#k:a"){let t=(n,i)=>n==null?[-1,""]:i&&typeof n=="string"?[0,n.toLowerCase()]:[0,n],r=(n,i)=>n[0]!==i[0]?n[0]-i[0]:n[1]<i[1]?-1:n[1]>i[1]?1:0;if(typeof e=="function")this._nodes._list.sort((n,i)=>{let s=e(n),a=e(i);return s<a?-1:s>a?1:0});else{let n=e.split(",");n.reverse();for(let i of n){let s,a;i.includes(":")?[s,a]=i.split(":",2):(s=i,a="a"),s=s.trim(),a=a.trim();let l=a==="d"||a==="D",c=a==="a"||a==="d",u;if(s.toLowerCase()==="#k")u=d=>t(d.label,c);else if(s.toLowerCase()==="#v")u=d=>t(d.value,c);else if(s.toLowerCase().startsWith("#a.")){let d=s.slice(3);u=f=>t(f.getAttr(d),c)}else u=d=>{let f=d.value,h=f instanceof o?f.getItem(s):f?f[s]:null;return t(h,c)};this._nodes._list.sort((d,f)=>{let h=r(u(d),u(f));return l?-h:h})}}return this}equalTo(e){return e instanceof o?this._nodes.isEqual(e._nodes):!1}has(e){if(typeof e=="string"){let t=null;e.includes("?")&&([e,t]=e.split("?",2));let r=this.getNode(e);return r===null?!1:t===null?!0:t.split("&").every(n=>n in r.attr)}else if(e&&e.label!==void 0)return[...this._nodes].includes(e);return!1}getResolver(e){let t=this.getNode(e);return t?t.resolver:null}setResolver(e,t){let r=this.getNode(e);r||(this.setItem(e,null),r=this.getNode(e)),r.resolver=t}setCallbackItem(e,t,r={}){let n=new _t({callback:t,...r});this.setResolver(e,n)}move(e,t,r=!0){this._nodes.move(e,t,r)}asDict(e=!1,t=!1,r=!1,n=!1){let i={};for(let s of this._nodes){let a=s.value;if(n&&a==null)continue;let l=s.label;e&&(l=String(l)),t&&(l=l.toLowerCase()),r&&a instanceof o&&(a=o.prototype.asDict.call(a,e,t,r,n)),Object.defineProperty(i,l,{value:a,enumerable:!0,writable:!0,configurable:!0})}return i}setdefault(e,t=null){let r=this.getNode(e);return r?r.value:(this.setItem(e,t),t)}deepcopy(e=!1){let t=this.createChildBag();for(let r of this._nodes){let n=r.getValue(!e);n instanceof o&&(n=n.deepcopy(e));let i=new t.nodeClass(t,r.label,n);i.setAttr({...r.attr},!1,!1,!1),i.nodeTag=r.nodeTag,i.xmlTag=r.xmlTag,t._nodes._list.push(i),t._nodes._dict[i.label]=i}return t}update(e,t=null,r=null,n=!1){if(!(e instanceof o)){for(let i in e){let s=e[i];(!n||s!==null||!this._nodes.has(i))&&this.setItem(i,s,null,">",!1,!1,r,!1,r!==!1)}return}for(let i of[...e]){let s=i.label,a=t==="static"?i.resolver:null,l=a?null:i.getValue(),c=i.attr.__replace;delete i.attr.__replace;let u=this._nodes.get(s);if(u)if(u.setAttr(i.attr,r===null?!0:r,!0,!1),i.nodeTag!=null&&(u.nodeTag=i.nodeTag),i.xmlTag!=null&&(u.xmlTag=i.xmlTag),a)u.resolver=a,u.setValue(null,r===null?!0:r,null,null,!1,r);else{i.resolver&&(u.resolver=null);let d=u.getValue();l instanceof o&&d instanceof o&&!c?d.update(l,t,r,n):(!n||l!==null)&&u.setValue(l,r===null?!0:r,null,null,!1,r)}else{let d=this.setItem(s,a||l,i.attr,">",!1,!1,r,!1,r!==!1);d.nodeTag=i.nodeTag,d.xmlTag=i.xmlTag}}}_fillFromBag(e){this.clear();for(let t of e){let r=new this.nodeClass(this,t.label);r.replace(t),r.nodeTag=t.nodeTag,r.xmlTag=t.xmlTag,this._nodes._list.push(r),this._nodes._dict[r.label]=r}}_appendLiteral(e,t,r=null,n=null,i=null){if(typeof e!="string")throw new TypeError("Bag labels must be strings");let s=new this.nodeClass(this,e,null,r,n,i,null,!1);return t instanceof Y?s.resolver=t:s._value=t,this._nodes._dict[e]=s,this._nodes._list.push(s),s}fillFrom(e=null,t={}){let r=Za(t);if(e!=null&&!tn(e)&&!Array.isArray(e))throw new TypeError("Bag source must be a dictionary, array or null");let n=this.createChildBag(),i=new Set,s=(a,l,c)=>{if(i.has(l))throw new TypeError(`Cyclic Bag source at ${c}`);i.add(l);try{let u=Array.isArray(l)?String(l.length).length+1:0,d=Array.isArray(l)?Array.from(l,(f,h)=>[`r_${String(h).padStart(u,"0")}`,f]):Object.entries(l);if(!Array.isArray(l)&&Object.getOwnPropertySymbols(l).some(f=>Object.prototype.propertyIsEnumerable.call(l,f)))throw new TypeError(`Bag labels must be strings at ${c}`);for(let[f,h]of d){let p=h;r&&(tn(p)||Array.isArray(p))&&(p=this.createChildBag(),s(p,h,`${c}[${JSON.stringify(f)}]`)),a._appendLiteral(f,p)}}finally{i.delete(l)}};return e!=null&&s(n,e,"$"),this._replacePrepared(n)}_loadSource(e,t={}){return this.fillFrom(e,t)}replace(e){if(!(e instanceof o))throw new TypeError("Bag.replace expects a Bag");if(e===this)return this;let t=this.createChildBag();return t._fillFromBag(e),this._replacePrepared(t)}_replacePrepared(e){for(let r of this._nodes){r.parentBag=null;let n=r.getValue(!0);n instanceof o&&n.clearBackref()}let t=this._nodes;this._nodes=e._nodes,e._nodes=t,this._nodes._parentBag=this.backref?this:null,e._nodes._parentBag=null;for(let r of this._nodes)r.parentBag=this;for(let r of e._nodes)r._parentBag=e;return this.backref&&this.parent&&this.parentNode&&this.parent._onNodeChanged(this.parentNode,[this.parentNode.label],"upd_value",e),this}forEach(e,{static:t=!0,deep:r=!1,kwargs:n={}}={}){if(typeof e!="function")throw new TypeError("forEach requires a callback");let i=(s,a)=>{for(let l=0;l<s._nodes.length;l++){let c=s._nodes._list[l],u={...a};"_pathlist"in a&&(u._pathlist=[...a._pathlist,c.label]),"_indexlist"in a&&(u._indexlist=[...a._indexlist,l]);let d=e(c,u,l);if(d)return d;if(d==null&&r){let f=c.getValue(t);if(f instanceof o){let h=i(f,u);if(h)return h}}}return null};return i(this,n)}*traverse(){for(let e of this._nodes){yield e;let t=e.getValue(!0);t instanceof o&&(yield*t.traverse())}}*_iterNodesWithPaths(e=!0,t=""){for(let r of this._nodes){let n=t?`${t}.${r.label}`:r.label;yield[n,r];let i=r.getValue(e);i instanceof o&&(yield*i._iterNodesWithPaths(e,n))}}*_nodeFlattener(e=null){let t=e!==null,r=t?Object.create(null):null,n=0,i=new Map([["[]",this.constructor]]);for(let[s,a]of Ad(this)){let l=s.slice(0,-1),c=JSON.stringify(s),u=JSON.stringify(l),d=a.getValue(!0),f,h=null;if(a.resolver)f=Gn(a.resolver);else if(d instanceof o){let b=d.constructor,w=b.tytxSuffix;i.set(c,b),h=Ya(b,en(i.get(u),w)),f=`::${w}`}else d===null?f="::NN":f=Ut(d);if(a.attr&&Object.hasOwn(a.attr,Ke))throw new ce(`node '${s}': the attribute '${Ke}' is reserved for the Bag class name`);let p=Ri(Ut(a.attr));h!==null&&(p[Ke]=h);let m=a.nodeTag;t?(yield[l.length?r[u]:null,a.label,m,f,p],d instanceof o&&(r[c]=n,e[n]=s,n++)):yield[l,a.label,m,f,p]}}toTytx(e="json",t=!1){let r=this._toTytxPayload(t),n=this.constructor.tytxSuffix;if(e==="json")return`${r}::${n}`;if(e==="msgpack")return yi(new He(4,new TextEncoder().encode(`${n}:${r}`)));throw new TypeError(`Unsupported transport: ${e}`)}_toTytxPayload(e=!1){let t;if(e){let i={};t={rows:[...this._nodeFlattener(i)],paths:i}}else t={rows:[...this._nodeFlattener(null)]};let r=this.constructor,n=Ya(r,en(null,r.tytxSuffix));return n!==null&&(t[Ke]=n),t.rows=t.rows.map(([i,s,a,l,c])=>[Ut(i),Ut(s),Ut(a),l,c]),t.paths&&(t.paths=Ut(t.paths)),R(t)}static fromTytx(e,t="json",r={}){if(tn(t)&&(r=t,t="json"),Za(r),typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("fromTytx requires serialized text or bytes");if(t!=="json"&&t!=="msgpack")throw new TypeError(`Unsupported transport: ${t}`);t==="json"&&e instanceof Uint8Array&&(e=new TextDecoder().decode(e));let n=j(e,t==="json"?null:t);if(n instanceof o)return n;if(!tn(n)&&!Array.isArray(n))throw new TypeError("fromTytx requires a dictionary, array or typed Bag root");return new this(n,r)}static _fromTytxPayload(e){let t=this.tytxSuffix;if(e==="")return new(en(null,t));let r=j(e);if(!r||!Array.isArray(r.rows))throw new ce("Invalid TYTX Bag: expected rows");let n=r.paths,i=n!=null,s=Object.hasOwn(r,Ke)?Xa(t,r[Ke]):en(null,t),a=new s,l=new Map([["[]",a]]);for(let c of r.rows){if(!Array.isArray(c)||c.length!==5)throw new ce("Invalid TYTX Bag row");let[u,d,f,h,p]=c,m=u??"";if(i){if(u!==null&&!Object.hasOwn(n,u))throw new ce(`Unknown TYTX parent reference: ${u}`);m=u===null?"":n[u]}if(typeof m=="string"&&(m=m?m.split("."):[]),!Array.isArray(m))throw new ce("Invalid TYTX parent path");let b=JSON.stringify(m);if(!l.has(b))throw new ce(`Missing or undecodable TYTX parent branch: ${m}`);let w=l.get(b),_=JSON.stringify([...m,d]),v=h,E=$i(v),D=Ha(p),k=Object.hasOwn(D,Ke)?D[Ke]:null;if(delete D[Ke],v instanceof o){let O=v.constructor.tytxSuffix,L=k!==null?Xa(O,k):en(w.constructor,O);v=new L,l.set(_,v)}else if(k!==null)throw new ce(`node '${_}': the attribute '${Ke}' is reserved for the Bag class name of a branch`);let C=w._appendLiteral(d,E?null:v,D,E);C.nodeTag=f??null}return a}toXml(e={}){let{pretty:t=!1,encoding:r="UTF-8",docHeader:n=null,selfClosedTags:i=null}=e,s=this._bagToXml(i,t);return n===!0?s=`<?xml version='1.0' encoding='${r}'?>
27
27
  ${s}`:typeof n=="string"&&(s=`${n}
28
28
  ${s}`),s}_bagToXml(e=null,t=!1,r=0){let n=[];for(let i of this._nodes)n.push((t?" ".repeat(r):"")+this._nodeToXml(i,e,t,r));return n.join(t?`
29
- `:"")}_nodeToXml(e,t=null,r=!1,n=0){let i=e.xmlTag||e.nodeTag||e.label,s=this._sanitizeTag(i),a=[];if(s!==i&&a.push(`_tag="${this._escapeAttr(i)}"`),e.resolver&&a.push(`_resolver="${this._escapeAttr(Wn(e.resolver))}"`),e.attr)for(let[f,h]of Object.entries($i(e.attr)))h!==null&&h!==!1&&h!==void 0&&a.push(`${f}="${this._escapeAttr(String(h))}"`);let l=a.length?" "+a.join(" "):"",c=e.resolver?null:e.getValue(!0);if(c&&typeof c._bagToXml=="function"){r=r&&e.attr?.["xml:space"]!=="preserve";let f=c._bagToXml(t,r,n+1);return f?r?`<${s}${l}>
29
+ `:"")}_nodeToXml(e,t=null,r=!1,n=0){let i=e.xmlTag||e.nodeTag||e.label,s=this._sanitizeTag(i),a=[];if(s!==i&&a.push(`_tag="${this._escapeAttr(i)}"`),e.resolver&&a.push(`_resolver="${this._escapeAttr(Gn(e.resolver))}"`),e.attr)for(let[f,h]of Object.entries(Ri(e.attr)))h!==null&&h!==!1&&h!==void 0&&a.push(`${f}="${this._escapeAttr(String(h))}"`);let l=a.length?" "+a.join(" "):"",c=e.resolver?null:e.getValue(!0);if(c&&typeof c._bagToXml=="function"){r=r&&e.attr?.["xml:space"]!=="preserve";let f=c._bagToXml(t,r,n+1);return f?r?`<${s}${l}>
30
30
  ${f}
31
- ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}${l}/>`:`<${s}${l}></${s}>`}if(c==null||c==="")return t===null||t.includes(s)?`<${s}${l}/>`:`<${s}${l}></${s}>`;let u=c instanceof Date&&!Number.isNaN(c.getTime())?Ym(c):String(c),d=this._escapeXml(u);return`<${s}${l}>${d}</${s}>`}_sanitizeTag(e){return e?e.replace(/[^a-zA-Z0-9_\-.:]/g,"_"):"_none_"}_escapeXml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}_escapeAttr(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}static fromXml(e,t={}){let{tagAttribute:r=null}=t,n;if(typeof DOMParser<"u"){n=new DOMParser().parseFromString(e,"application/xml");let s=n.querySelector("parsererror");if(s)throw new Error(`XML parse error: ${s.textContent}`)}else n=new Hr().parseFromString(e,"application/xml");return this._xmlElementToBag(n.documentElement,r)}static _xmlElementToBag(e,t=null){let r=new this,n=Array.from(e.childNodes).filter(i=>i.nodeType===1);for(let i of n){let s=i.tagName,a={};for(let m=0;m<i.attributes.length;m++){let b=i.attributes[m];a[b.name]=b.value}let l=Oi(a._resolver);l&&delete a._resolver;let c=String(a._T||"").toUpperCase()==="BAG";Object.assign(a,Ga(a));let u=s;"_tag"in a&&(u=a._tag,delete a._tag),t&&t in a&&(u=a[t],delete a[t]);let d=u,f=1;for(;r.getNode(u);)u=`${d}_${f++}`;let h=Array.from(i.childNodes).filter(m=>m.nodeType===1),p;if(h.length>0||c){let m=this._xmlElementToBag(i,t);p=r.setItem(u,m,Object.keys(a).length>0?a:null)}else{let m=i.textContent||"";p=r.setItem(u,m,Object.keys(a).length>0?a:null)}l&&(p.resolver=l),p.xmlTag=s}return r}static async fromUrl(e,t={}){let{timeout:r=30}=t,n={};r&&(n.signal=AbortSignal.timeout(r*1e3));let i=await fetch(e,n),s=i.headers.get("content-type")||"",a=await i.text();if(s.includes("json"))return o.fromTytx(a);if(s.includes("xml"))return o.fromXml(a);let l=a.trim();if(l.startsWith("<"))return o.fromXml(a);if(l.startsWith("{")||l.startsWith("["))return o.fromTytx(a);throw new rn(`Unsupported content-type: ${s}`)}toJson(e=!0){let t=[];for(let r of this._nodes)t.push(this._nodeToJsonDict(r,e));return e?R(t):JSON.stringify(t)}_nodeToJsonDict(e,t){let r=e.resolver?null:e.getValue(!0);if(r&&typeof r._nodeToJsonDict=="function"){let i=[];for(let s of r._nodes)i.push(r._nodeToJsonDict(s,t));r=i}let n={label:e.label,value:r,attr:$i(e.attr)};return e.nodeTag!==null&&(n.tag=e.nodeTag),e.resolver&&(n.resolver=Wn(e.resolver)),n}static fromJson(e,t={}){return Sd||(console.warn("Bag.fromJson is deprecated; use Bag.fromTytx"),Sd=!0),this.fromTytx(e,"json",t)}toStringTree(e=!0,t=null,r="",n=!0){t===null&&(t=new Map);let i=[],s=[...this._nodes];for(let a=0;a<s.length;a++){let l=s[a],c=a===s.length-1,u=l.getValue(e),d=l.getAttr(),f="",h=Object.keys(d);h.length>0&&(f=" ["+h.map(w=>`${w}=${JSON.stringify(d[w])}`).join(", ")+"]");let p=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",m=r+(c?" ":"\u2502 ");if(u instanceof o){let b=l,w=u.backref?"(*)":"";if(t.has(b))i.push(`${r}${p}${l.label}${w}${f} \u2192 (circular ref)`);else{t.set(b,l.label),i.push(`${r}${p}${l.label}${w}${f}`);let _=u.toStringTree(e,t,m,c);_&&i.push(_)}}else{let b;if(u===null)b="null";else if(u===void 0)b="undefined";else if(u instanceof ArrayBuffer||u instanceof Uint8Array){let w=new TextDecoder("utf-8",{fatal:!1}),_=u instanceof ArrayBuffer?new Uint8Array(u):u;b=w.decode(_)}else typeof u=="string"?u.length>50?b=JSON.stringify(u.slice(0,47)+"..."):b=JSON.stringify(u):b=String(u);i.push(`${r}${p}${l.label}: ${b}${f}`)}}return i.join(`
31
+ ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}${l}/>`:`<${s}${l}></${s}>`}if(c==null||c==="")return t===null||t.includes(s)?`<${s}${l}/>`:`<${s}${l}></${s}>`;let u=c instanceof Date&&!Number.isNaN(c.getTime())?Ym(c):String(c),d=this._escapeXml(u);return`<${s}${l}>${d}</${s}>`}_sanitizeTag(e){return e?e.replace(/[^a-zA-Z0-9_\-.:]/g,"_"):"_none_"}_escapeXml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}_escapeAttr(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}static fromXml(e,t={}){let{tagAttribute:r=null}=t,n;if(typeof DOMParser<"u"){n=new DOMParser().parseFromString(e,"application/xml");let s=n.querySelector("parsererror");if(s)throw new Error(`XML parse error: ${s.textContent}`)}else n=new Hr().parseFromString(e,"application/xml");return this._xmlElementToBag(n.documentElement,r)}static _xmlElementToBag(e,t=null){let r=new this,n=Array.from(e.childNodes).filter(i=>i.nodeType===1);for(let i of n){let s=i.tagName,a={};for(let m=0;m<i.attributes.length;m++){let b=i.attributes[m];a[b.name]=b.value}let l=$i(a._resolver);l&&delete a._resolver;let c=String(a._T||"").toUpperCase()==="BAG";Object.assign(a,Ha(a));let u=s;"_tag"in a&&(u=a._tag,delete a._tag),t&&t in a&&(u=a[t],delete a[t]);let d=u,f=1;for(;r.getNode(u);)u=`${d}_${f++}`;let h=Array.from(i.childNodes).filter(m=>m.nodeType===1),p;if(h.length>0||c){let m=this._xmlElementToBag(i,t);p=r.setItem(u,m,Object.keys(a).length>0?a:null)}else{let m=i.textContent||"";p=r.setItem(u,m,Object.keys(a).length>0?a:null)}l&&(p.resolver=l),p.xmlTag=s}return r}static async fromUrl(e,t={}){let{timeout:r=30}=t,n={};r&&(n.signal=AbortSignal.timeout(r*1e3));let i=await fetch(e,n),s=i.headers.get("content-type")||"",a=await i.text();if(s.includes("json"))return o.fromTytx(a);if(s.includes("xml"))return o.fromXml(a);let l=a.trim();if(l.startsWith("<"))return o.fromXml(a);if(l.startsWith("{")||l.startsWith("["))return o.fromTytx(a);throw new rn(`Unsupported content-type: ${s}`)}toJson(e=!0){let t=[];for(let r of this._nodes)t.push(this._nodeToJsonDict(r,e));return e?R(t):JSON.stringify(t)}_nodeToJsonDict(e,t){let r=e.resolver?null:e.getValue(!0);if(r&&typeof r._nodeToJsonDict=="function"){let i=[];for(let s of r._nodes)i.push(r._nodeToJsonDict(s,t));r=i}let n={label:e.label,value:r,attr:Ri(e.attr)};return e.nodeTag!==null&&(n.tag=e.nodeTag),e.resolver&&(n.resolver=Gn(e.resolver)),n}static fromJson(e,t={}){return Sd||(console.warn("Bag.fromJson is deprecated; use Bag.fromTytx"),Sd=!0),this.fromTytx(e,"json",t)}toStringTree(e=!0,t=null,r="",n=!0){t===null&&(t=new Map);let i=[],s=[...this._nodes];for(let a=0;a<s.length;a++){let l=s[a],c=a===s.length-1,u=l.getValue(e),d=l.getAttr(),f="",h=Object.keys(d);h.length>0&&(f=" ["+h.map(w=>`${w}=${JSON.stringify(d[w])}`).join(", ")+"]");let p=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",m=r+(c?" ":"\u2502 ");if(u instanceof o){let b=l,w=u.backref?"(*)":"";if(t.has(b))i.push(`${r}${p}${l.label}${w}${f} \u2192 (circular ref)`);else{t.set(b,l.label),i.push(`${r}${p}${l.label}${w}${f}`);let _=u.toStringTree(e,t,m,c);_&&i.push(_)}}else{let b;if(u===null)b="null";else if(u===void 0)b="undefined";else if(u instanceof ArrayBuffer||u instanceof Uint8Array){let w=new TextDecoder("utf-8",{fatal:!1}),_=u instanceof ArrayBuffer?new Uint8Array(u):u;b=w.decode(_)}else typeof u=="string"?u.length>50?b=JSON.stringify(u.slice(0,47)+"..."):b=JSON.stringify(u):b=String(u);i.push(`${r}${p}${l.label}: ${b}${f}`)}}return i.join(`
32
32
  `)}toString(e=!0,t=null,r=""){t||(t=new Set);let n=[],i=[...this._nodes];for(let s=0;s<i.length;s++){let a=i[s],l=s===i.length-1,c=a.getValue(e),u="",d=a.attr;d&&Object.keys(d).length>0&&(u=` [${Object.entries(d).map(([m,b])=>`${m}=${JSON.stringify(b)}`).join(", ")}]`);let f=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",h=r+(l?" ":"\u2502 ");if(c&&typeof c._htraverse=="function"){let p=a;if(t.has(p))n.push(`${r}${f}${a.label}${u} \u2192 (circular ref)`);else{t.add(p),n.push(`${r}${f}${a.label}${u}`);let m=c.toString(e,t,h);m&&n.push(m)}}else{let p;c==null?p="null":typeof c=="string"&&c.length>50?p=JSON.stringify(c.slice(0,47)+"..."):typeof c=="string"?p=JSON.stringify(c):p=String(c),n.push(`${r}${f}${a.label}: ${p}${u}`)}}return n.join(`
33
- `)}},rn=class extends Error{constructor(e){super(e),this.name="BagException"}};Y.registerBagClass(x);Vn(x,"X",o=>o._toTytxPayload(),o=>x._fromTytxPayload(o));wt(x.tytxSuffix,{...Pe(x.tytxSuffix),Bag:x});var Gn=class extends Y{static classKwargs={cacheTime:300,readOnly:!0,retryPolicy:{maxAttempts:3,delay:1,backoff:2,jitter:!0,on:["TypeError","NetworkError","AbortError"]},asBag:!1,url:null,method:"get",qs:null,body:null,timeout:5,transport:"json"};static classArgs=["url"];static internalParams=new Set(["cacheTime","readOnly","retryPolicy","asBag"]);constructor(e,t={}){typeof e=="string"?t={...t,url:e}:t=e||{},super(t)}async load(e){let t=e.url,r=e.method,n=e.qs,i=e.timeout,s=e.transport,a=e.body;e._body!==void 0&&(a=e._body);let l=[],c={};for(let[h,p]of Object.entries(e))if(h.startsWith("arg_")&&p!==null&&p!==void 0){let m=parseInt(h.slice(4),10);if(!isNaN(m)){for(;l.length<=m;)l.push(null);l[m]=p}}else!this.constructor.classKwargs.hasOwnProperty(h)&&!this.constructor.internalParams.has(h)&&!h.startsWith("_")&&p!=null&&(c[h]=p);l.length>0&&t.includes("{")&&(t.match(/\{([^}]+)\}/g)||[]).forEach((p,m)=>{m<l.length&&l[m]!==null&&(t=t.replace(p,String(l[m])))});let u={};if(n&&Object.assign(u,this._qsToDict(n)),Object.assign(u,c),Object.keys(u).length>0){let h=new URLSearchParams;for(let[m,b]of Object.entries(u))b!=null&&h.append(m,String(b));let p=t.includes("?")?"&":"?";t=`${t}${p}${h.toString()}`}let d={method:r.toUpperCase(),transport:s};return i&&(d.signal=AbortSignal.timeout(i*1e3)),a!=null&&(d.body=a),await Ai(t,d)}_qsToDict(e){if(!e)return{};if(typeof e.keys=="function"&&typeof e.getItem=="function"){let r={};for(let n of e.keys()){let i=e.getItem(n);i!=null&&(r[n]=i)}return r}let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}};var Hn=class extends Y{static classKwargs={cacheTime:-1,readOnly:!1,asBag:!1,retryPolicy:null,version:"uuid4"};static classArgs=["version"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy","version"]);load(){return globalThis.crypto.randomUUID()}};var Xn=class extends Y{static classKwargs={cacheTime:-1,readOnly:!0,asBag:!1,retryPolicy:null,key:null,storageType:"local",defaultValue:null,dtype:null};static classArgs=["key"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy"]);constructor(e,t={}){typeof e=="string"?t={...t,key:e}:t=e||{},super(t)}_getStorage(e){return(e.storageType||"local")==="session"?typeof sessionStorage<"u"?sessionStorage:null:typeof localStorage<"u"?localStorage:null}load(e){let t=e.key,r=e.defaultValue,n=t?this._getStorage(e):null,i=n?n.getItem(t):null,s=i!==null?i:r;if(e.dtype==null||s==null)return s;let a=String(s);if(e.dtype==="L"&&!/^[+-]?\d+(?:_\d+)*$/.test(a.trim()))throw new TypeError(`Invalid integer in Web Storage: ${a}`);if(e.dtype==="R"&&!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(a.trim()))throw new TypeError(`Invalid real number in Web Storage: ${a}`);let l=e.dtype==="L"?a.replaceAll("_",""):a,c=j(`${l}::${e.dtype}`);if(typeof c=="number"&&Number.isNaN(c)||c instanceof Date&&Number.isNaN(c.getTime()))throw new TypeError(`Invalid ${e.dtype} value in Web Storage: ${a}`);return c}};var Id=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield"]);function Cd(o){return o.endsWith("_")&&Id.has(o.slice(0,-1))?o.slice(0,-1):o}function Dd(o){let e=Cd(o);return e!==o?e:o.startsWith("_")&&Id.has(o.slice(1))?o.slice(1):o}function nn(o,{renderTag:e=null,ns:t=null,dialectName:r=null}={}){let n=e||o;if(!n)return n;if(n=Cd(n),t&&!e){let i=`${r}_`;n.startsWith(i)&&(n=n.slice(i.length)),n=`${t}:${n}`}return n}var cr=Symbol("value"),lt=new Set(["_meta","datapath","nodeId","ns","form","formId","_anchor","updateOn"]);function ge(o){return Object.entries(o||{}).filter(([e])=>!lt.has(e)).map(([e,t])=>[Dd(e),t])}var Se=class extends qe{constructor(e,t,r=null,n=null,i=null,s=null,a=null){super(e,t,r,n,i,s,a),this._builder=e?._insertingBuilder??e?._builder??null,this._targetId=null}get builder(){if(this._builder)return this._builder;let e=this.parentBag;return e?e._builder:null}get data(){return this.builder.data}get rootBuilder(){return this.parentBag.root._builder}_getMeta(e){let t=this.getAttr("_meta")||{},r=e.split(",").map(n=>n.trim());return r.length===1?t[r[0]]!==void 0?t[r[0]]:null:r.map(n=>t[n]!==void 0?t[n]:null)}pointerType(e){return typeof e=="string"&&(e[0]==="^"||e[0]==="=")&&!e.startsWith("==")?e[0]:null}pointers(){this.builder.validateCustomTypes(this);let e=[];for(let[t,r]of Object.entries(this.getAttr()||{}))this.pointerType(r)==="^"&&e.push([t,r.split(":",1)[0]]);return this.pointerType(this.value)==="^"&&e.push(["",this.value.split(":",1)[0]]),e}fixedAttrItems(){return ge(this.getAttr())}runtimeToEvaluate(){let e=new Map(this.fixedAttrItems());return e.set(cr,this.value),e}absDatapath(e){let t=e;this.pointerType(e)&&(e=(H(e)?.pointer??e).slice(1));let r=null;return e.includes("?")&&([e,r]=e.split("?",2)),e.startsWith("#")?this._finalizeAbsPath(this._resolveSymbolicDatapath(e,t),r):(e.startsWith(".")&&(e=this._composeRelativeDatapath(e,t)),this._finalizeAbsPath(e,r))}_finalizeAbsPath(e,t){return e=this._collapseParentDatapath(e,e),t?`${e}?${t}`:e}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let n=r.getAttr("datapath");n!=null&&(e=e==="."?n:n+e),r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_collapseParentDatapath(e,t){let r=[];for(let n of e.split("."))if(n==="#parent"){if(r.length===0)throw new Error(`#parent has no segment to cancel: ${t}`);r.pop()}else r.push(n);return r.join(".")}_resolveSymbolicDatapath(e,t){let r=e.slice(1),n=r.indexOf("."),i=n===-1?r:r.slice(0,n),s=n===-1?"":r.slice(n+1),a;if(i==="FORM")a=this._findMarkedDatapathAncestor(!0,!1,t);else if(i==="ANCHOR")a=this._findMarkedDatapathAncestor(!1,!0,t);else{let l=this.rootBuilder;if(!l)throw new Error(`#<id>: cannot resolve ${t} on a node without builder`);if(a=l.source.getNodeByAttr("nodeId",i),a==null)throw new Error(`#<id>: cannot resolve ${t}`)}return a.absDatapath(s?`.${s}`:".")}_findMarkedDatapathAncestor(e,t,r){let n=this;for(;n!=null;){let s=n.getAttr()||{};if(e&&(s.formId!=null||s.form===!0)||t&&"_anchor"in s)return n;n=n.parentNode}let i=e?"FORM":"ANCHOR";throw new Error(`#${i}: no marked ancestor found for ${r}`)}getRelativeData(e,t=null,{autocreate:r=!1}={}){let n=this.data,i=this.absDatapath(e);return r&&n.getItem(i)==null&&n.setItem(i,t),n.getItem(i,t)}setRelativeData(e,t,{attributes:r=null,fired:n=!1,reason:i=null}={}){let s=this.data,a=this.absDatapath(e);s.setItem(a,t,r,">",!1,!0,i===null?!0:i,n)}fireEvent(e,t=!0,{attributes:r=null,reason:n=null}={}){this.setRelativeData(e,t,{attributes:r,fired:!0,reason:n})}SET(e,t){this.setRelativeData(e,t)}GET(e){return this.getRelativeData(e)}PUT(e,t){this.setRelativeData(e,t,{reason:!1})}FIRE(e,t=!0){this.setRelativeData(e,t,{fired:!0})}},N=class o extends x{constructor(e=null,t=null){super(e),this._builder=t,this._insertingBuilder=null}get nodeClass(){return Se}_setBuilderItem(e,t,r,...n){let i=t?.map(([a])=>[a,a._builder])||null;if(t)for(let[a,l]of t)a._builder=l;let s=this._insertingBuilder;this._insertingBuilder=e;try{return this.setItem(r,...n)}catch(a){if(this.node(r)==null&&i)for(let[l,c]of i)l._builder=c;throw a}finally{this._insertingBuilder=s}}bindBuilder(e){if(!e)throw new Error("SourceBag.bindBuilder requires a builder");let t=this._builderBindingPlan(e);for(let[r,n]of t)r._builder=n;return this.setBackref(),this}_builderBindingPlan(e){let t=[],r=new WeakSet,n=(i,s)=>{if(r.has(i))throw new Error("source contains a cyclic or shared SourceBag branch");r.add(i),t.push([i,s]);for(let a of i.getNodes()){let l=s,c=a._getMeta("subbuilder");c!=null&&(l=s._resolveSubbuilderReference(c,a.getAttr()||{},a.nodeTag)),t.push([a,l]);let u=a.getValue(!0);u instanceof o&&n(u,l)}};return n(this,e),t}};if((Pe(N.tytxSuffix).SourceBag??N)!==N)throw new Error("TYTX subtype name 'SourceBag' is already registered for another class");wt(N.tytxSuffix,{...Pe(N.tytxSuffix),SourceBag:N});function Zm(o){if(o.length===0)return{value:null,attrs:{}};let e=o[0];if(e!==null&&typeof e=="object"){let t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null)return{value:null,attrs:e}}return{value:e,attrs:o[1]||{}}}var Km=new Set(["then","toJSON"]),Od=new WeakMap;function Z(o){return Od.get(o)||o}function on(o){if(o==null)return o;o=Z(o);let e=o._builder||o.parentBag&&o.parentBag._builder;return e?e.wrapSource(o):o}function $d(o,e){let t=e instanceof x,r=new Proxy(e,{get(n,i){if(typeof i=="symbol"||i.startsWith("_")||Km.has(i))return Reflect.get(n,i,n);let s=o.schemaTag(i);if(t&&s)return Nd(o,n,s,t);if(i in n){let l=Reflect.get(n,i,n);return typeof l=="function"?l.bind(n):l}if(s)return Nd(o,n,s,t);let a=o.containerMethod(i);if(a)return(...l)=>o[a](o.wrapSource(n),...l)}});return Od.set(r,e),r}function Nd(o,e,t,r){return(...n)=>{let{value:i,attrs:s}=Zm(n),a=r?o.bagCall(e,t,i,s):o.commandOnNode(e,t,i,s);return a.builder.wrapSource(a)}}function Rd(o,{transport:e="json"}={}){if(!(o instanceof N))throw new TypeError("sourceBagToTytx requires a SourceBag");return R(o,e==="json"?null:e)}function Ri(o,e,{transport:t="json"}={}){let r=j(o,t==="json"?null:t);if(!(r instanceof N))throw new TypeError("TYTX payload did not decode to SourceBag");return r.bindBuilder(e)}var Pd=/^[A-Za-z_][A-Za-z0-9_]*$/,Jm=new Set(["positional_only","positional_or_keyword","keyword_only","var_positional","var_keyword"]),Qm=new Set(["framework","value","attribute"]),eg=new Map([["builtins.str",o=>typeof o=="string"],["builtins.int",o=>Number.isInteger(o)],["builtins.float",o=>typeof o=="number"&&Number.isFinite(o)],["builtins.bool",o=>typeof o=="boolean"],["builtins.list",o=>Array.isArray(o)],["builtins.dict",o=>o!==null&&typeof o=="object"&&!Array.isArray(o)],["builtins.tuple",o=>Array.isArray(o)],["builtins.set",o=>Array.isArray(o)||o instanceof Set],["builtins.NoneType",o=>o===null],["builtins.object",o=>!0]]);function dr(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function $(o,e){throw new TypeError(`${o}: ${e}`)}function ct(o,e,t,r){dr(o)||$(r,"must be an object");for(let n of Object.keys(o))e.includes(n)||$(r,`unknown field '${n}'`);for(let n of t)Object.hasOwn(o,n)||$(r,`missing field '${n}'`)}function fr(o,e){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(Array.isArray(o))return o.forEach((t,r)=>fr(t,`${e}[${r}]`));if(dr(o))return Object.entries(o).forEach(([t,r])=>fr(r,`${e}.${t}`));$(e,"must be lossless JSON data")}}function tg(o,e){let t="",r=!1;for(let n=0;n<o.length;n++){let i=o[n];if(i==="\\"){t+=i+(o[++n]??"");continue}i==="["&&(r=!0),!r&&i==="."&&!(e&16)?t+="[^\\n]":!r&&i==="^"&&e&8?t+="(?:^|(?<=\\n))":!r&&i==="$"?t+=e&8?"(?=\\n|(?![\\s\\S]))":"(?=\\n?(?![\\s\\S]))":t+=i,i==="]"&&(r=!1)}return t}function ur(o,e,t=!1,r=null){if(o===null)return null;switch(ct(o,["kind","dtype","module","name","origin","arguments","items","values","base","metadata","pattern","flags","ge","le","gt","lt","value"],["kind"],e),o.kind){case"custom":return ct(o,["kind","name"],["kind","name"],e),r||$(e,"custom references require a catalog; nested catalog references are unsupported"),r.resolve(o.name,e);case"dtype":{ct(o,["kind","dtype"],["kind","dtype"],e);let n=o.dtype;typeof n!="string"&&$(e,"dtype must be a string");let i=Kr(n);return!i&&n!=="NN"&&$(e,`unknown dtype '${n}'`),{...o,test:a=>n==="NN"?a===null:n==="N"?U(a)&&!["NaN","Infinity","-Infinity"].includes(a.toString()):i===Number?typeof a=="number"&&Number.isFinite(a)&&(n!=="L"||Number.isInteger(a)):i===String?typeof a=="string":i===Boolean?typeof a=="boolean":i===Date?a instanceof Date&&Number.isFinite(a.getTime()):i===Object?dr(a)&&[Object.prototype,null].includes(Object.getPrototypeOf(a)):a instanceof i}}case"any":return{...o,test:n=>!0};case"type":{(typeof o.module!="string"||typeof o.name!="string")&&$(e,"type requires string module/name");let n=`${o.module}.${o.name}`;if(n==="collections.abc.Callable")return{...o,test:s=>typeof s=="function",portable:!1};let i=eg.get(n);return i||$(e,`unsupported type '${n}'`),{...o,test:i}}case"union":{(!Array.isArray(o.items)||!o.items.length)&&$(e,"union items must be non-empty");let n=o.items.map((i,s)=>ur(i,`${e}.items[${s}]`,!0,r));return{...o,items:n,inputConstraint:n.some(i=>i.inputConstraint),test:i=>n.some(s=>s.test&&s.test(i))}}case"literal":return Array.isArray(o.values)||$(e,"literal values must be an array"),o.values.forEach((n,i)=>fr(n,`${e}.values[${i}]`)),{...o,test:n=>o.values.some(i=>Object.is(i,n))};case"annotated":{Array.isArray(o.metadata)||$(e,"annotated metadata must be an array"),o.metadata.some(s=>!["regex","range","value"].includes(s?.kind))&&$(e,"unsupported annotation metadata kind");let n=ur(o.base,`${e}.base`,!0,r),i=o.metadata.map((s,a)=>ur(s,`${e}.metadata[${a}]`,!0,r));return{...o,base:n,metadata:i,inputConstraint:n.inputConstraint,test:s=>n.test(s)&&i.every(a=>!a.test||a.test(s))}}case"range":{for(let n of["ge","le","gt","lt"])Object.hasOwn(o,n)||$(e,`range missing '${n}'`);for(let n of["ge","le","gt","lt"])o[n]!==null&&(typeof o[n]!="number"||!Number.isFinite(o[n]))&&$(e,`${n} must be finite number or null`);return{...o,test:n=>typeof n=="number"&&(o.ge===null||n>=o.ge)&&(o.le===null||n<=o.le)&&(o.gt===null||n>o.gt)&&(o.lt===null||n<o.lt)}}case"regex":{(typeof o.pattern!="string"||!Number.isInteger(o.flags)||o.flags<0)&&$(e,"regex requires pattern and non-negative integer flags");let n=o.flags&-59;n&&$(e,`unsupported Python regex flags ${n}`),o.flags&2&&$(e,"IGNORECASE is not portable across Python and JavaScript Unicode rules"),/\\[AZzUwWdDsSabBN0-9]|\(\?P[<=!]|\(\?\(|\(\?>|\(\?#|\(\?[aiLmsux-]|[+*?}]\+|\{,/.test(o.pattern.replaceAll(String.raw`[\s\S]`,"."))&&$(e,"regex uses a non-portable construct or character class");let i="uy";o.flags&16&&(i+="s");let s;try{s=new RegExp(`(?:${tg(o.pattern,o.flags)})(?![\\s\\S])`,i)}catch(a){$(e,`invalid portable regex: ${a.message}`)}return{...o,test:a=>typeof a!="string"?!1:(s.lastIndex=0,s.test(a))}}case"value":return fr(o.value,`${e}.value`),{...o};case"generic":{let n=ur(o.origin,`${e}.origin`,!0,r);(o.origin?.kind!=="type"||o.origin.module!=="builtins"||!["list","dict","tuple","set"].includes(o.origin.name))&&$(e,"only list, dict, tuple and set generic origins are supported"),Array.isArray(o.arguments)||$(e,"generic arguments must be an array");let i=o.arguments.map((s,a)=>ur(s,`${e}.arguments[${a}]`,!0,r));return{...o,origin:n,arguments:i,inputConstraint:i.some(s=>s.inputConstraint),test:s=>n.test(s)&&rg(o.origin,i,s)}}case"arguments":$(e,"Callable argument-list descriptors are not supported by Python validation");case"ellipsis":return t||$(e,"ellipsis is only valid as a nested descriptor"),{...o};default:$(e,`unknown annotation kind '${o.kind}'`)}}function rg(o,e,t){let r=`${o.module}.${o.name}`;return r==="builtins.tuple"&&e.length&&e[1]?.kind!=="ellipsis"?t.length===e.length&&t.every((n,i)=>e[i].test(n)):r==="builtins.list"||r==="builtins.set"||r==="builtins.tuple"?[...t].every(n=>!e[0]?.test||e[0].test(n)):r==="builtins.dict"?Object.entries(t).every(([n,i])=>(!e[0]?.test||e[0].test(n))&&(!e[1]?.test||e[1].test(i))):!1}function Bd(o,e){if(o===null)return null;if(typeof o!="string"&&$(e,"must be string or null"),o==="")return new Map;let t=new Map;for(let r of o.split(",")){let n=r.trim();/^[A-Za-z_][A-Za-z0-9_]*\[\]$/.test(n)&&$(e,`invalid cardinality item '${r}'`);let i=n.match(/^([A-Za-z_][A-Za-z0-9_]*|\*)(?:\[(?:(\d+)|(?:(\d*):(\d*)))\])?$/);i||$(e,`invalid cardinality item '${r}'`);let[,s,a,l,c]=i;t.has(s)&&$(e,`duplicate tag '${s}'`);let u=0,d=1/0;n.includes("[")&&(n.includes(":")?(u=l?Number(l):0,d=c?Number(c):1/0):u=d=Number(a)),d<u&&$(e,`maximum ${d} is below minimum ${u}`),t.set(s,{min:u,max:d})}return t.has("*")&&t.size>1&&$(e,"wildcard '*' cannot be combined with named tags"),t}function Md(o,e){if(o===null)return null;typeof o!="string"&&$(e,"must be string or null");let t=new Set;for(let r of o.split(",")){let n=r.trim();n&&((!Pd.test(n)||t.has(n))&&$(e,`invalid or duplicate parent '${r}'`),t.add(n))}return t}function ng(o,e,t){if(o===null)return null;ct(o,["parameters","accepts_var_keyword","accepts_var_positional"],[],e);let r=o.parameters??[];Array.isArray(r)||$(e,"parameters must be an array"),o={parameters:r,accepts_var_keyword:r.some(l=>l.kind==="var_keyword"),accepts_var_positional:r.some(l=>l.kind==="var_positional"),...o},(!Array.isArray(o.parameters)||typeof o.accepts_var_keyword!="boolean"||typeof o.accepts_var_positional!="boolean")&&$(e,"invalid signature descriptor");let n=new Set,i=!1,s=!1,a=o.parameters.map((l,c)=>{let u=`${e}.parameters[${c}]`;return ct(l,["name","kind","role","annotation","has_default","default"],["name","kind","role","annotation","has_default"],u),(typeof l.name!="string"||!Pd.test(l.name)||n.has(l.name))&&$(u,"invalid or duplicate parameter name"),n.add(l.name),(!Jm.has(l.kind)||!Qm.has(l.role)||typeof l.has_default!="boolean")&&$(u,"invalid kind, role, or has_default"),l.has_default!==Object.hasOwn(l,"default")&&$(u,"default presence must equal has_default"),l.has_default&&fr(l.default,`${u}.default`),i||=l.kind==="var_keyword",s||=l.kind==="var_positional",{...l,annotation:ur(l.annotation,`${u}.annotation`,!1,t)}});return(i!==o.accepts_var_keyword||s!==o.accepts_var_positional)&&$(e,"variadic summary flags do not match parameters"),{...o,parameters:a}}function jd(o,e,t,r){let n=["doc","sub_tags","parent_tags","inherits_from","ns","attributes",...t?["node_label","collection_key"]:[],"_meta"];ct(o,n,[],e),o={...Object.fromEntries(n.map(i=>[i,null])),...o};for(let i of["doc","inherits_from","ns",...t?["node_label","collection_key"]:[]])o[i]!==null&&typeof o[i]!="string"&&$(e,`${i} must be string or null`);return o._meta!==null&&(dr(o._meta)||$(e,"_meta must be object or null"),fr(o._meta,`${e}._meta`)),Bd(o.sub_tags,`${e}.sub_tags`),Md(o.parent_tags,`${e}.parent_tags`),{...o,attributes:ng(o.attributes,`${e}.attributes`,r)}}function Ld(o){return o?o.split(",").map(e=>e.trim()).filter(Boolean):[]}function Fd(o,e){let t={...e};for(let[r,n]of Object.entries(o))r==="inherits_from"||r.startsWith("_")||t[r]||(t[r]=n);return t._meta={...o._meta||{},...e._meta||{}},t}function zd(o){let e={...o};return e._subSpec=Object.hasOwn(e,"sub_tags")?Bd(e.sub_tags,"resolved.sub_tags"):null,e._parentSpec=Object.hasOwn(e,"parent_tags")?Md(e.parent_tags,"resolved.parent_tags"):null,e}function qd(o,e,t,r){if(t.get(o)===1&&$(r,`inheritance cycle at '${o}'`),t.get(o)===2)return e[o];let n=e[o];n||$(r,`unknown abstract '${o}'`),t.set(o,1);let i={...n};for(let s of Ld(n.inherits_from))i=Fd(qd(s,e,t,r),i);return i=zd(i),t.set(o,2),e[o]=i,i}function Ka({abstracts:o={},elements:e={}}){let t={...o},r=new Map;for(let i of Object.keys(t))qd(i,t,r,`abstracts.${i}.inherits_from`);let n={};for(let[i,s]of Object.entries(e)){let a={...s};for(let l of Ld(s.inherits_from)){let c=t[l];c||$(`elements.${i}.inherits_from`,`unknown abstract '${l}'`),a=Fd(c,a)}n[i]=zd(a)}return{abstracts:t,elements:n}}function Ja(o){ct(o,["document_format","grammar","abstracts","elements","custom_types"],["document_format","grammar","abstracts","elements"],"grammar document"),ct(o.document_format,["name","version"],["name","version"],"document_format"),(o.document_format.name!=="builder_grammar"||!["1.1","1.2"].includes(o.document_format.version))&&$("document_format","expected builder_grammar version 1.1 or 1.2"),ct(o.grammar,["name","version","title","description"],["name","version","title","description"],"grammar"),(typeof o.grammar.name!="string"||!o.grammar.name)&&$("grammar.name","must be non-empty string");for(let n of["version","title","description"])o.grammar[n]!==null&&typeof o.grammar[n]!="string"&&$(`grammar.${n}`,"must be string or null");(!dr(o.abstracts)||!dr(o.elements))&&$("grammar document","abstracts/elements must be objects"),Object.hasOwn(o,"custom_types")&&o.document_format.version!=="1.2"&&$("custom_types","requires version 1.2");let e=hr.fromJSON(o.custom_types??{}),t={};for(let[n,i]of Object.entries(o.abstracts))(!n||n.startsWith("_"))&&$("abstracts",`invalid public name '${n}'`),t[n]=jd(i,`abstracts.${n}`,!1,e);let r={};for(let[n,i]of Object.entries(o.elements))(!n||n.startsWith("_"))&&$("elements",`invalid public name '${n}'`),r[n]=jd(i,`elements.${n}`,!0,e);return{grammar:structuredClone(o.grammar),abstracts:t,elements:r}}function Ud(o,e,t,r){let n=e.attributes;if(!n)return;let i={...r};t!=null&&(i.node_value=t);let s=new Set(n.parameters.filter(c=>c.role==="attribute").map(c=>c.name)),a=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]);if(!n.accepts_var_keyword)for(let c of Object.keys(r))!s.has(c)&&!a.has(c)&&$(o,`unknown attribute '${c}'`);let l=e._meta?.component?n.parameters.find(c=>c.role!=="framework"&&["positional_only","positional_or_keyword"].includes(c.kind))?.name:null;for(let c of n.parameters){if(c.name===l||c.role==="framework"||c.kind.startsWith("var_"))continue;let u=Object.hasOwn(i,c.name);!u&&!c.has_default&&$(o,`missing required ${c.role} '${c.name}'`),u&&c.annotation!==null&&(!c.annotation.test||!c.annotation.test(i[c.name]))&&$(o,`invalid value for ${c.role} '${c.name}'`)}}var hr=class o{#e=new Map;#t=new Map;register(e,t,r){let n=new Map([[String,"str"],[Number,"float"],["string","str"],["integer","int"],["number","float"]]),i=n.has(t)?{kind:"type",module:"builtins",name:n.get(t)}:t;return this.#r(e,{kind:"annotated",base:i,metadata:[r]})}#r(e,t){(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/.test(e)||e in this||["to_dict","from_dict"].includes(e)||og.has(e))&&$("custom_types",`invalid, reserved or duplicate name '${e}'`),ct(t,["kind","base","metadata"],["kind","base","metadata"],`custom_types.${e}`),(t.kind!=="annotated"||!Array.isArray(t.metadata)||t.metadata.length!==1||!["regex","range"].includes(t.metadata[0]?.kind))&&$(`custom_types.${e}`,"requires an annotated base with one Regex or Range validator");let r=t.metadata[0].kind==="regex"?["str"]:["int","float"];(t.base?.kind!=="type"||t.base.module!=="builtins"||!r.includes(t.base.name))&&$(`custom_types.${e}`,"portable Regex requires str; portable Range requires int or float"),fr(t,`custom_types.${e}`);let n=structuredClone(t),i=ur(n,`custom_types.${e}`),s=Object.freeze({kind:"custom",name:e});return Object.defineProperty(this,e,{value:s,enumerable:!0}),this.#e.set(e,n),this.#t.set(e,{...s,inputConstraint:!0,test:i.test}),s}resolve(e,t="custom_types"){return this.#t.has(e)||$(t,`unknown custom type '${e}'`),{...this.#t.get(e)}}validate(e,t){return this.resolve(e).test(t)||$(`custom_types.${e}`,"invalid input value"),!0}toJSON(){return structuredClone(Object.fromEntries(this.#e))}static fromJSON(e){dr(e)||$("custom_types","must be an object");let t=new o;for(let[r,n]of Object.entries(e))t.#r(r,n);return t}},og=new Set("False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield".split(" "));function Vd(o,e,t,r){let n=e?.attributes;if(n)for(let i of n.parameters){if(!i.annotation?.inputConstraint||i.role==="framework"||["var_keyword","var_positional"].includes(i.kind))continue;let s=i.role==="value"?t:r[i.name];s!==void 0&&(i.annotation.test(s)||$(o,`invalid input for '${i.name}' (custom type)`))}}function Wd(o,e,t=[]){if(e===null)return structuredClone(o);if(t.length===2&&t[0]==="custom_types"&&o!==void 0){if(!Qa(o,e))throw new TypeError(`conflicting custom type '${t[1]}'`);return structuredClone(o)}if(t.length===2&&["abstracts","elements"].includes(t[0]))return structuredClone(e);if(yt(o)&&yt(e)){let r=structuredClone(o);for(let[n,i]of Object.entries(e))i!==null&&Object.defineProperty(r,n,{value:Wd(r[n],i,[...t,n]),enumerable:!0,writable:!0,configurable:!0});return r}return structuredClone(e)}function Qa(o,e){return Object.is(o,e)?!0:Array.isArray(o)&&Array.isArray(e)?o.length===e.length&&o.every((t,r)=>Qa(t,e[r])):yt(o)&&yt(e)?Object.keys(o).length===Object.keys(e).length&&Object.keys(o).every(t=>Object.hasOwn(e,t)&&Qa(o[t],e[t])):!1}function yt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)&&Object.getPrototypeOf(o)===Object.prototype}function el(o){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(Array.isArray(o)){o.forEach(el);return}if(yt(o)){Object.values(o).forEach(el);return}throw new TypeError("collection must contain only finite JSON values")}}var ut=class o{#e;constructor(e){el(e);let t=["document_format","grammar","abstracts","elements"];if(!yt(e)||Object.keys(e).some(n=>![...t,"custom_types"].includes(n))||t.some(n=>!Object.hasOwn(e,n)))throw new TypeError("collection requires document_format, grammar, abstracts and elements");let r=e.document_format;if(!yt(r)||Object.keys(r).length!==2||r.name!=="builder_grammar"||!["1.1","1.2"].includes(r.version))throw new TypeError("expected builder_grammar version 1.1 or 1.2");for(let n of["grammar","abstracts","elements"])if(!yt(e[n]))throw new TypeError(`${n} must be an object`);if(Object.hasOwn(e,"custom_types")&&(r.version!=="1.2"||!yt(e.custom_types)))throw new TypeError("custom_types requires an object catalog and version 1.2");this.#e=structuredClone(e)}update(e){let t=new o(e),r=Wd(this.#e,t.#e);return(this.#e.document_format.version==="1.2"||t.#e.document_format.version==="1.2")&&(r.document_format.version="1.2"),this.#e=r,this}toDocument(){return structuredClone(this.#e)}};var Ut=class{static renderType="string";static mode=null;constructor(e){this._builder=e,this.renders=new Map([[e,this]])}get builder(){return this._builder}get renderType(){return this.constructor.renderType}get mode(){return this.constructor.mode}addRender(e,t){this.renders.set(e,t)}getRender(e){let t=this.renders.get(e);if(t!==void 0)return t;let r=e.getRenderer();return this.renders.set(e,r),r}render(e,t={}){let r=e.builder,[n,i]=r.runtimeValues(e);if(e._getMeta("data_element"))return null;if(e._getMeta("component"))return this._renderComponent(e,i,t);let s=this.getRender(r),a;return[a,i]=s._handleMeta(e,i),e._getMeta("subbuilder")||(i=s.adaptAttrs(i)),e.value instanceof N&&(n=this.renderChildren(e.value,t)),s.renderedItem(e,n,i,{tag:a,...t})}renderChildren(e,t={}){let r=[];for(let n of e.getNodes()){let i=this.render(n,t);i!==null&&(Array.isArray(i)?r.push(...i):r.push(i))}return r}_renderComponent(e,t,r){let[n,i,s,a]=this._expansionInputs(e,t);if(!Object.hasOwn(e.getAttr(),"iterate"))return this._expandBlock(e,n,s,a,r);if(i==null)return[];if(!(i instanceof x))throw new TypeError(`component '${e.nodeTag}': iterate must resolve to a Bag, got ${i?.constructor?.name||typeof i}`);return i.getNodes().map(l=>this._expandBlock(e,n,s,{node_label:l.label},r))}_expansionInputs(e,t){let r=e.builder,n=r.componentMethod(e.nodeTag),i=n&&r[n];if(typeof i!="function")throw new Error(`component '${e.nodeTag}' has no implementation`);let s=t.iterate;delete t.iterate,delete t.store;let a=e.getAttr("iterate")||e.getAttr("store");a!=null?(e.pointerType(a)&&(a=a.slice(1)),a.startsWith(".")&&(a=e._composeRelativeDatapath(a,a))):a=null;for(let l of Object.keys(t)){let c=e.getAttr(l);e.pointerType(c)==="^"&&(t[l]=`^${e.absDatapath(c)}`)}return[i,s,a,t]}_expandBlock(e,t,r,n,i){let s=e.builder._expansionRoot(r);t.call(e.builder,on(s),n);let a=s.getNodes();if(a.length!==1)throw new Error(`component '${e.nodeTag}' must build a tree, not a forest: ${a.length} root nodes`);let l={...i,depthOffset:this._nodeDepth(e,i.depthOffset||0)};return this.render(a[0],l)}preprocess(e){return e}renderedItem(e,t,r,n){throw new Error(`${this.constructor.name} does not implement renderedItem`)}_handleMeta(e,t){let[r,n]=e._getMeta("render_tag,render_attributes"),i=nn(e.nodeTag,{renderTag:r,ns:e.getAttr("ns"),dialectName:e.builder?.constructor._name});if(!i)throw new Error(`node ${e.label} has no tag to render (no render_tag, no node_tag)`);return n&&(t={...t,...n}),[i,t]}adaptAttrs(e){return e}adapt(e){let t=`${this.builder.constructor._name}_`;return e.startsWith(t)?e.slice(t.length):e}finalize(e,t=null,r={}){let n=this._composeStringFragments(e);if(t==null)return n;if(typeof t=="string")throw new TypeError("string render targets require filesystem support, which is unavailable in the portable renderer; pass a callable or writable target instead");if(typeof t.full=="function"&&typeof t.write!="function")return t.full(n),null;if(typeof t.write=="function")return t.write(n),null;if(typeof t=="function")return t(n),null;throw new TypeError("render target must be writable (.write), callable, or expose .full")}_composeStringFragments(e){if(!Array.isArray(e))return e;if(e.some(t=>typeof t!="string"))throw new TypeError("String composition requires string fragments; object renderers must define their own composition");return e.join("")}_escapeText(e){return String(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}_escapeAttr(e){return this._escapeText(e).replaceAll('"',"&quot;")}_nodeDepth(e,t=0){let n=((e.fullpath||"").match(/\./g)||[]).length;return Math.max(n-1,0)+t}};var Vt=class extends Ut{static mode="xml";renderedItem(e,t,r,{tag:n,pretty:i=!1,depthOffset:s=0}={}){let a=this._formatAttrs(r),l=i?" ".repeat(this._nodeDepth(e,s)):"",c=i?`
34
- `:"";if(Array.isArray(t)){let u=this._composeStringFragments(t);return`${l}<${n}${a}>${c}${u}${l}</${n}>${c}`}return t==null?`${l}<${n}${a}></${n}>${c}`:`${l}<${n}${a}>${this._escapeText(t)}</${n}>${c}`}finalize(e,t=null,{docHeader:r=null}={}){let n=this._composeStringFragments(e);return r===!0?n=`<?xml version='1.0' encoding='UTF-8'?>${n}`:typeof r=="string"&&(n=r+n),super.finalize(n,t)}_formatAttrs(e){return Object.entries(e||{}).map(([t,r])=>` ${t.startsWith("xmlns_")?`xmlns:${t.slice(6)}`:t}="${this._escapeAttr(r)}"`).join("")}};var Gd={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"base",version:null,title:null,description:null},abstracts:{},elements:{dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};function Hd(o){let e=[];for(;o&&o!==Function.prototype;)e.push(o),o=Object.getPrototypeOf(o);return e.reverse()}function sg(o){let e=Object.create(null),t=(r,n)=>{let i=r.toLowerCase(),s=e[i];if(s!==void 0&&s!==n)throw new Error(`container '${r}' is already tied to implementation method '${s}' (cannot rebind to '${n}')`);e[i]=n};for(let r of Hd(o))if(Object.hasOwn(r,"containers"))for(let n of r.containers||[])t(n,n);return e}function Yn(o){let e=Object.create(null);for(let t of Object.keys(o)){let r=t.toLowerCase();if(Object.hasOwn(e,r))throw new Error(`element declaration '${t}' has a case-insensitive collision with '${e[r]}'`);e[r]=t}return e}var sn="_root_",an="_root_",tl=new Set(["destination","func","value","_on_start"]),Ae=class o{static _sourceClass=N;static registerBuilder(e){if(typeof e!="function"||!(e.prototype instanceof o))throw new TypeError("registerBuilder requires a BuilderBase subclass");let t=e._name;if(typeof t!="string"||!t)throw new TypeError("registered builders require a non-empty static _name");let r=o._registry.get(t);if(r&&r!==e)throw new Error(`Builder name '${t}' is already registered to ${r.name}; cannot register ${e.name}`);return o._registry.set(t,e),e}static getBuilderClass(e){let t=o._registry.get(e);if(!t)throw new Error(`No builder registered with name '${e}'`);return t}constructor(e=null){this.name=e||this.constructor._name,this._dataroot=new x,this._dataroot.setBackref(),this._dataroot.setItem(an,new x),this.data=this._dataroot.getItem(an),this._defaultTargets=new Map,this.materialized=Object.create(null),this._collection=null,this._schemaOverride=null,this._tagNamesOverride=null,this._componentMap=null,this._targetSerial=0,this._subbuilders=new Map,this._sourceHandles=new WeakMap;let t=this.constructor._sourceClass;this._sourceroot=new t(null,this),this._sourceroot.setBackref(),this._sourceroot.setItem(sn,new t(null,this)),this.source=this._sourceroot.getItem(sn)}wrapSource(e){if(e=Z(e),!(e instanceof N)&&!(e instanceof Se))throw new TypeError("wrapSource requires a SourceBag or SourceBagNode");let t=this._sourceHandles.get(e);return t||(t=$d(this,e),this._sourceHandles.set(e,t)),t}get root(){return this.wrapSource(this.source)}getSubbuilder(e){if(typeof e!="string"||!e||e.includes(":"))throw new Error(`unsupported subbuilder reference '${e}'`);let t=this._subbuilders.get(e);if(!t){let r=o.getBuilderClass(e);t=new r,this._subbuilders.set(e,t)}return t._dataroot=this._dataroot,t.data=this.data,t}_resolveSubbuilderReference(e,t,r){if(typeof e!="string"||!e)throw new Error(`'${r}': subbuilder declaration must be a non-empty string`);if(e.includes(":"))throw new Error(`'${r}': runtime subbuilder reference '${e}' is unsupported`);return this.getSubbuilder(e)}static defineGrammar(e){let t=this._classCollection,r=t?new ut(t.toDocument()).update(e):new ut(e),n=Ja(r.toDocument()),i=Ka(n),s=Yn(i.elements);this._classCollection=r,this._classSchema=i.elements,this._abstracts=i.abstracts,this._tagNames=s}static{this.defineGrammar(Gd)}get _containers(){return sg(this.constructor)}containerMethod(e){return this._containers[e.toLowerCase()]||null}componentMethod(e){return this._componentMap?.[e.toLowerCase()]||null}get schema(){return this._schemaOverride||this.constructor._classSchema||{}}get schemaTagNames(){return this._schemaOverride?this._tagNamesOverride??=Yn(this.schema):this.constructor._tagNames??=Yn(this.schema)}schemaTag(e){let t=e.toLowerCase(),r=this.schemaTagNames[t];if(r)return r;let n=`${this.constructor._name}_`;return t.startsWith(n)&&this.schemaTagNames[t.slice(n.length)]||null}loadGrammar(e,{replace:t=!1}={}){let r=this._collection||this.constructor._classCollection,n=t?new ut(e):new ut(r.toDocument()).update(e),i=Ja(n.toDocument()),s=Ka(i),a=Yn(s.elements);return this._collection=n,this._schemaOverride=s.elements,this._tagNamesOverride=a,this}validateCustomTypes(e){let t=e.parentBag?.parentNode?.builder||e.parentBag?._builder,r=t&&t!==this&&t.schema[e.nodeTag]?._meta?.subbuilder?t:this;Vd(e.nodeTag,r.schema[e.nodeTag],e.value,e.getAttr()||{})}validateNodeValues(e,t,r={}){let n=this.schemaTag(e);if(!n)throw new Error(`unknown element '${e}'`);return Ud(n,this.schema[n],t,r),!0}validateNode(e,{value:t,attrs:r,childTags:n}={}){if(!e||typeof e.nodeTag!="string")throw new TypeError("validateNode requires a source node");let i=t!==void 0?t:e.value instanceof N?null:e.value;this.validateNodeValues(e.nodeTag,i,r||e.getAttr?.()||{});let s=this.schema[this.schemaTag(e.nodeTag)],a=n||(e.value instanceof N?e.value.getNodes().map(l=>l.nodeTag):null);return a&&this._validateChildren(e.nodeTag,s,a,!1),!0}validateChildren(e,t,{includeMinimum:r=!1}={}){let n=this.schemaTag(e);if(!n)throw new Error(`unknown element '${e}'`);if(!Array.isArray(t)||t.some(i=>typeof i!="string"))throw new TypeError("childTags must be an array of strings");return this._validateChildren(n,this.schema[n],t,r)}validateParent(e,t=null){let r=this.schemaTag(e);if(!r)throw new Error(`unknown element '${e}'`);let n=this.schema[r];if(!this._countsForGrammar(n))return!0;let i=n._parentSpec;if(i==null||i.has("*"))return!0;if(t===null)throw new Error(`'${r}' requires a declared parent`);let s=this.schemaTag(t);if(!s)throw new Error(`unknown parent element '${t}'`);return this._validateParent(r,n,s),!0}bagCall(e,t,r,n){return this.setChild(e,t,r,n)}commandOnNode(e,t,r,n){if(e=Z(e),e.value instanceof N)return this.setChild(e.value,t,r,n);let i=e.value,s=new e.parentBag.constructor(null,e.builder||this),a=this.setChild(s,t,r,n,e);return this.promoteNodeValue(e,i,s),a}promoteNodeValue(e,t,r){e.setValue(r)}setChild(e,t,r,n,i=null){let s={...n},a=this.schema[t];if(!a)throw new Error(`unknown element '${t}'`);this.validateNodeValues(t,r,s);let l=a._meta?.subbuilder,u=(l==null?null:this._resolveSubbuilderReference(l,s,t))||this,d=r instanceof N?r._builderBindingPlan(u):null,f=i?.rootBuilder||e.root._builder||this;if(s.nodeId!=null&&f.source.getNodeByAttr("nodeId",s.nodeId))throw new Error(`Duplicate nodeId '${s.nodeId}'`);r instanceof N&&this._validateChildren(t,a,r.getNodes().map(v=>v.nodeTag),!1);let h=i||e.parentNode,p=h?.nodeTag?this.schema[h.nodeTag]:null;if(p&&!h._getMeta("subbuilder")&&this._countsForGrammar(a))this._validateParent(t,a,h.nodeTag),this._validateChildren(h.nodeTag,p,[...e.getNodes().map(v=>v.nodeTag),t],!1);else if(!p&&!h?._getMeta("subbuilder")&&a._parentSpec!=null&&this._countsForGrammar(a))throw new Error(`'${t}' requires a declared parent`);a._meta&&!("_meta"in s)&&(s._meta=a._meta),a.ns&&!("ns"in s)&&(s.ns=a.ns);let m=s.node_position;delete s.node_position;let b=s.node_label;delete s.node_label;let w;if(p?.collection_key){if(b!=null)throw new Error(`'${t}': node_label is not allowed in a collection`);w=this._collectionLabel(p.collection_key,t,s)}else{let v=p?._subSpec?.get(t);if(v&&v.max===1){if(b!=null)throw new Error(`'${t}': node_label is not allowed on a singleton`);w=t}else w=b||a.node_label||this._autoLabel(e,t)}if(e.node(w)!=null)throw new Error(`duplicate node label '${w}'`);return e._setBuilderItem(u,d,w,r,s,m||">",!1,!0,null,!1,!0,null,t)}_countsForGrammar(e){let t=e?._meta||{};return!(t.data_element||t.subbuilder||t.component)}_validateParent(e,t,r){let n=t._parentSpec;if(!(n==null||n.has("*")||!this._countsForGrammar(t))&&!n.has(r))throw new Error(`'${e}' not allowed as child of '${r}'`)}_validateChildren(e,t,r,n){let i=t._subSpec;if(i==null||i.has("*")||t._meta?.subbuilder)return[];let s=new Map;for(let a of r){let l=this.schema[a];if(l&&!this._countsForGrammar(l))continue;let c=i.get(a);if(!c)throw new Error(`'${a}' not allowed as child of '${e}'`);let u=(s.get(a)||0)+1;if(s.set(a,u),u>c.max)throw new Error(`too many '${a}' in '${e}'`)}return n?[...i].filter(([a,l])=>(s.get(a)||0)<l.min).map(([a])=>a):[]}_collectionLabel(e,t,r){let n=i=>{if(r[i]===null||r[i]===void 0)throw new Error(`'${t}': collection key needs attribute '${i}'`);return String(r[i])};return e.includes("${")?e.replace(/\$\{([^}]+)\}/g,(i,s)=>n(s)):n(e)}validateSource(){let e=[],t=(r,n="")=>{for(let i of r.getNodes()){let s=n?`${n}.${i.label}`:i.label,a=i.builder;a.validateCustomTypes(i);let l=a.schema[i.nodeTag];if(l&&!i._getMeta("data_element,subbuilder,component").some(Boolean)){let c=i.value instanceof N?i.value.getNodes().map(d=>d.nodeTag):[],u=a._validateChildren(i.nodeTag,l,c,!0);u.length&&e.push([s,u])}i.value instanceof N&&t(i.value,s)}};return t(this.source),e}_autoLabel(e,t){let r=0;for(;e.node(`${t}_${r}`)!==null&&e.node(`${t}_${r}`)!==void 0;)r+=1;return`${t}_${r}`}nodeById(e){let t=this.source.getNodeByAttr("nodeId",e);if(t==null)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}runtimeValues(e){e.builder.validateCustomTypes(e);let t=new Map,r={},n=e.runtimeToEvaluate(),i=new Set(n.keys()),s=new Map([...Object.entries(e.getAttr()),...e.fixedAttrItems()]);for(let[u,d]of[...n])if(!(typeof u!="string"||!H(d)))for(let f of Ze(e,d))n.has(f)||n.set(f,s.get(f));let a=e._getMeta("data_element");for(let[u,d]of n){if(d instanceof Y){t.set(u,d.resolve());continue}let f=typeof u=="string"?H(d)?.pointer??d:d;if(!e.pointerType(f)){t.set(u,typeof u=="string"&&typeof d=="string"&&d.startsWith("==")?null:d);continue}let h=e.absDatapath(f);if(t.set(u,this.data.getItem(h)),!a&&!h.includes("?")&&u===cr){let p=this.data.getNode(h);p&&Object.assign(r,p.getAttr("_wdg"))}}let l=kd(n,t,(u,d,f,h)=>this.evaluatePointerExpression(e,u,d,f,h)),c=l.get(cr);l.delete(cr);for(let u of l.keys())i.has(u)||l.delete(u);return[c,{...Object.fromEntries(l),...r}]}evaluatePointerExpression(e,t,r,n,i){return null}targetId(e){if(e._targetId)return e._targetId;let t=e.rootBuilder;return e.parentBag.root!==t.source.root?null:(t._targetSerial+=1,e._targetId=`n${t._targetSerial}`,e._targetId)}get dataLogic(){if(!this._dataLogic){let e=this._buildDataLogic();this._dataLogic=Array.isArray(e)?e:[e]}return this._dataLogic}_buildDataLogic(){return this}_resolveLogicFunc(e){if(typeof e=="function")return e;if(typeof e!="string")throw new Error("data-element func must be a name or a function");for(let t of this.dataLogic){let n=(typeof t=="function"?t:t.constructor)[e];if(typeof n=="function")return n}throw new Error(`data-element func '${e}' not found on any data_logic source`)}_bindings(e){let[,t]=this.runtimeValues(e),r={};for(let[n,i]of Object.entries(t))tl.has(n)||(r[n]=i);return r}computeLogic(e){for(let t of e)this._computeNode(t)}_computeNode(e){let t=e.getAttr()||{};if(e.nodeTag==="dataSetter"){let r={};for(let[n,i]of Object.entries(t))n!=="destination"&&n!=="value"&&!n.startsWith("_")&&(r[n]=i);e.setRelativeData(t.destination,t.value,{attributes:Object.keys(r).length?r:null})}else if(e.nodeTag==="dataFormula"){let r=this._resolveLogicFunc(t.func);e.setRelativeData(t.destination,r(this._bindings(e)))}else e.nodeTag==="dataController"&&this._resolveLogicFunc(t.func)(e,this._bindings(e))}_dataElementNodes(){let e=[],t=r=>{for(let n of r.getNodes())n._getMeta("data_element")&&e.push(n),n.value instanceof N&&t(n.value)};return t(this.source),e}setup(e){}main(e){throw new Error(`${this.constructor.name}.main() not implemented: a bare builder is grammar, not a renderable page`)}_resolveComponents(){let e={};for(let a of Hd(this.constructor))if(Object.hasOwn(a,"components"))for(let l of a.components||[])e[l]=l;if(!Object.keys(e).length)return;let t={...this.schema},r={};for(let[a,l]of Object.entries(e))t[a]={sub_tags:"",_meta:{component:!0}},r[a.toLowerCase()]=l;let n=Yn(t),i=this._collection||this.constructor._classCollection,s=i.toDocument();s.abstracts={},s.elements=Object.fromEntries(Object.keys(e).map(a=>[a,t[a]])),this._collection=new ut(i.toDocument()).update(s),this._schemaOverride=t,this._componentMap=r,this._tagNamesOverride=n}_expansionRoot(e=null){let t=this.constructor._sourceClass,r=new t(null,this);return r.setBackref(),r.setItem(sn,new t(null,this),e?{datapath:e}:null),r.getItem(sn)}create(){this.setup(this.data),this._resolveComponents(),this.main(this.root),this.computeLogic(this._dataElementNodes())}get renderer_xml(){return new Vt(this)}getRenderer(e=null){e??=this.constructor._defaultRenderMode;let t=this[`renderer_${e}`];if(!t)throw new Error(`${this.constructor.name} does not expose renderer_${e}`);return t}materialize(e=null,t={}){e??=this.constructor._defaultRenderMode;let r=this.getRenderer(e),n=r.renderChildren(r.preprocess(this.source),t);return this.materialized[e]=n,n}setRenderTarget(e,t=null){t??=this.constructor._defaultRenderMode,this._defaultTargets.set(t,e)}render({mode:e=null,target:t=null,...r}={}){e??=this.constructor._defaultRenderMode;let n=this.getRenderer(e);if(t===!1&&n.renderType!=="string")throw new TypeError("target=false is not valid for an object renderer");let i=t===!1?null:t||this._defaultTargets.get(n.mode)||null,s={...i?.renderOpts,...r};return n.finalize(this.materialize(e,s),i,s)}};Ae._registry=new Map;var ag=new Set(["short","medium","long","full"]),lg=/('(?:[^']|'')*'|[a-zA-Z]+|[^a-zA-Z']+)/g;function cg(o,e){if(!(o instanceof Date))throw new TypeError("Temporal formats require a typed Date value");if(!Number.isFinite(o.getTime()))throw new RangeError("Invalid date");let t=e||R(o).split("::").at(-1);if(!["D","H","DH","DHZ"].includes(t))throw new RangeError(`Unsupported temporal dtype: ${t}`);return t}function ug(o,e,t,r){let n=e.match(lg)||[];if(n.join("")!==e)throw new RangeError("Unclosed format literal");let i=(u,d=2)=>String(u).padStart(d,"0"),s=u=>new Intl.DateTimeFormat(t,{timeZone:"UTC",...u}).format(o),c={...r==="H"?{}:{y:()=>String(o.getUTCFullYear()),yy:()=>i(o.getUTCFullYear()%100),yyyy:()=>i(o.getUTCFullYear(),4),M:()=>String(o.getUTCMonth()+1),MM:()=>i(o.getUTCMonth()+1),MMM:()=>s({month:"short"}),MMMM:()=>s({month:"long"}),d:()=>String(o.getUTCDate()),dd:()=>i(o.getUTCDate()),EEE:()=>s({weekday:"short"}),EEEE:()=>s({weekday:"long"})},...r==="D"?{}:{H:()=>String(o.getUTCHours()),HH:()=>i(o.getUTCHours()),h:()=>String(o.getUTCHours()%12||12),hh:()=>i(o.getUTCHours()%12||12),m:()=>String(o.getUTCMinutes()),mm:()=>i(o.getUTCMinutes()),s:()=>String(o.getUTCSeconds()),ss:()=>i(o.getUTCSeconds()),a:()=>new Intl.DateTimeFormat(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(o).find(u=>u.type==="dayPeriod").value}};return n.map(u=>{if(u.startsWith("'"))return u==="''"?"'":u.slice(1,-1).replaceAll("''","'");if(!/^[a-zA-Z]/.test(u))return u;if(!c[u])throw new RangeError(`Unsupported date format token: ${u}`);return c[u]()}).join("")}function Xd(o,{format:e,mask:t,locale:r,dtype:n,places:i}={}){let s=o==null?"":String(o);if(o!=null&&o!==""&&(e!=null&&e!==""||i!=null))if(typeof o=="number"||U(o))s=fg(o,{format:e,locale:r,places:i});else{let a=cg(o,n);if(ag.has(e)){let l={timeZone:"UTC"};a!=="H"&&(l.dateStyle=e),a!=="D"&&(l.timeStyle=e),s=new Intl.DateTimeFormat(r||void 0,l).format(o)}else s=ug(o,String(e),r||void 0,a)}return t==null?s:String(t).replaceAll("%s",()=>s)}function dg({format:o="decimal",places:e}={}){let t={maximumFractionDigits:20};if(!o||o==="decimal")t.style="decimal";else if(o==="percent")t.style="percent";else if(o==="scientific")t.notation="scientific";else{let r=/^(0|#,##0)(?:\.(0*)(#*))?$/.exec(o);if(!r||o.includes(".")&&!r[2]&&!r[3])throw new RangeError(`Unsupported number format: ${o}`);t.useGrouping=r[1].includes(","),t.minimumFractionDigits=(r[2]||"").length,t.maximumFractionDigits=(r[2]||"").length+(r[3]||"").length}if(e!=null&&e!==""){let r=Number(e);if(!Number.isInteger(r)||r<0||r>20)throw new RangeError("places must be an integer from 0 to 20");t.minimumFractionDigits=r,t.maximumFractionDigits=r}return t}function fg(o,e={}){if(typeof o!="number"&&!U(o))throw new TypeError("Number formatting requires a Number or Decimal");if(!Number.isFinite(Number(o)))throw new RangeError("Number must be finite");let t=new Intl.NumberFormat(e.locale||void 0,dg(e));if(U(o)&&new Intl.NumberFormat("en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal values without precision loss");return t.format(U(o)?o.toString():o)}var hg=new Set(["style","script"]),pg=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),Yd=new Set(["width","height","top","left","right","bottom","padding","margin","border","position","display","overflow","float","clear","resize","z_index","min_width","min_height","max_width","max_height","color","background","font","text","line_height","white_space","vertical_align","flex","gap","row_gap","column_gap","grid","align_content","justify_content","align_items","justify_items","visibility","opacity","cursor"]),Zn=new Set(["rounded","gradient","shadow","transform","transition","zoom","filter"]),Zd=o=>o===!0?"true":o===!1?"false":String(o),ji=o=>typeof o=="number"&&Number.isFinite(o)?`${o}px`:String(o);function mg(o){if(Yd.has(o))return!0;for(let e of Yd)if(o.startsWith(`${e}_`))return!0;return!1}function gg(o){let e=new Map;if(!o)return e;let t=[],r=0,n=null,i=!1,s=!1,a=0,l=String(o);for(let c=0;c<l.length;c+=1){let u=l[c],d=l[c+1];if(s){u==="*"&&d==="/"&&(s=!1,c+=1);continue}if(i){i=!1;continue}if(u==="\\"){i=!0;continue}if(n){u===n&&(n=null);continue}u==='"'||u==="'"?n=u:u==="/"&&d==="*"?(s=!0,c+=1):"([{".includes(u)?a+=1:")]}".includes(u)&&a>0?a-=1:u===";"&&a===0&&(t.push(l.slice(r,c)),r=c+1)}t.push(l.slice(r));for(let c of t){let u=c.trim();if(!u)continue;let d=u.indexOf(":");if(d<0)throw new TypeError(`malformed style declaration '${u}'`);e.set(u.slice(0,d).trim(),u.slice(d+1).trim())}return e}var Wt=class extends Ut{static mode="html";renderedItem(e,t,r,{tag:n,xml:i=!0,pretty:s=!1,depthOffset:a=0,includeDatapath:l=!1}={}){e.parentNode?._getMeta("subbuilder")==="html"&&(r={xmlns:"http://www.w3.org/1999/xhtml",...r});let{format:u,mask:d,locale:f,places:h,dtype:p,...m}=r;!Array.isArray(t)&&(u!=null||d!=null||h!=null)&&(t=Xd(t,{format:u,mask:d,places:h,dtype:p,locale:this._displayLocale(e,f)}));let b=this._formatAttrs(m);if(l){if(!Object.hasOwn(r,"id")){let E=this.builder.targetId(e);E!==null&&(b+=` id="${this._htmlAttrValue(E)}"`)}for(let[E,D]of Object.entries(e.getAttr()))e.pointerType(D)&&(b+=` data-${this.adapt(E)}-pointer="${this._htmlAttrValue(e.absDatapath(D))}"`)}let w=s?" ".repeat(this._nodeDepth(e,a)):"",_=s?`
35
- `:"";if(e._getMeta("void"))return`${w}<${n}${b}${i?"/":""}>${_}`;if(Array.isArray(t)){let E=this._composeStringFragments(t);return`${w}<${n}${b}>${_}${E}${w}</${n}>${_}`}if(t==null)return`${w}<${n}${b}></${n}>${_}`;let v=typeof t=="string"&&t.endsWith("::HTML")?t.slice(0,-6):hg.has(n)?String(t):this._escapeText(t);return`${w}<${n}${b}>${v}</${n}>${_}`}_displayLocale(e,t){if(t)return t;for(let r=e.parentNode;r;r=r.parentNode){let n=r.getAttr("locale");if(n==null)continue;let i=r.pointerType(n)?r.data.getItem(r.absDatapath(n)):n;if(i)return i}}adaptAttrs(e){let t={},r={};for(let[i,s]of Object.entries(e||{}))if(i.startsWith(`${this.builder.constructor._name}_`))t[this.adapt(i)]=s;else if(i==="dtype")t.dtype=s;else{if(this.builder.constructor.retainedAttrPrefixes.some(a=>i.startsWith(a)))continue;this._isStyleContribution(i)?r[i]=s:t[i]=s}let n=this._adaptStyle(r);return n&&(t.style=n),t}_isStyleContribution(e){if(e==="style"||e.startsWith("style_")||Zn.has(e))return!0;let t=e.includes("_")?e.slice(0,e.indexOf("_")):null;return t!==null&&Zn.has(t)||mg(e)}_adaptStyle(e){let t=gg(e.style),r=new Map,n=new Map;for(let[i,s]of Object.entries(e))if(i!=="style")if(i.startsWith("style_"))t.set(i.slice(6).replaceAll("_","-"),Zd(s));else if(Zn.has(i))r.set(i,s);else{let a=i.indexOf("_"),l=a<0?i:i.slice(0,a);a>=0&&Zn.has(l)?(n.has(l)||n.set(l,{}),n.get(l)[i.slice(a+1)]=s):t.set(i.replaceAll("_","-"),Zd(s))}for(let i of Zn)(r.has(i)||n.has(i))&&this[`_macro_${i}`](r.get(i),n.get(i)||{},t);return[...t].map(([i,s])=>`${i}: ${s}`).join("; ")}_formatAttrs(e){let t=[];for(let[r,n]of Object.entries(e||{}))pg.has(r)?n&&t.push(` ${r}`):t.push(` ${r}="${this._htmlAttrValue(n)}"`);return t.join("")}_htmlAttrValue(e){return(e===!0?"true":e===!1?"false":String(e)).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}_macro_rounded(e,t,r){let n=e===void 0?{}:{top_left:e,top_right:e,bottom_left:e,bottom_right:e};for(let[i,s]of Object.entries(t))if(i==="top"||i==="bottom")n[`${i}_left`]=s,n[`${i}_right`]=s;else if(i==="left"||i==="right")n[`top_${i}`]=s,n[`bottom_${i}`]=s;else if(["top_left","top_right","bottom_left","bottom_right"].includes(i))n[i]=s;else throw new TypeError(`rounded: unknown sub-kwarg '${i}'`);for(let[i,s]of Object.entries(n))r.set(`border-${i.replaceAll("_","-")}-radius`,ji(s))}_macro_transform(e,t,r){let n=e===void 0?[]:[String(e)];for(let[i,s]of Object.entries(t))i==="rotate"?n.push(`rotate(${s}deg)`):i==="scale"||i==="translate"?n.push(`${i}(${s})`):i==="translate_x"?n.push(`translateX(${ji(s)})`):i==="translate_y"?n.push(`translateY(${ji(s)})`):i==="skew_x"?n.push(`skewX(${s}deg)`):i==="skew_y"?n.push(`skewY(${s}deg)`):n.push(`${i.replaceAll("_","-")}(${s})`);n.length&&r.set("transform",n.join(" "))}_macro_filter(e,t,r){let n=e===void 0?[]:[String(e)];for(let[i,s]of Object.entries(t))i==="rotate"?n.push(`hue-rotate(${s}deg)`):i==="blur"?n.push(`blur(${ji(s)})`):i==="drop_shadow"?n.push(`drop-shadow(${s})`):n.push(`${i.replaceAll("_","-")}(${s})`);n.length&&r.set("filter",n.join(" "))}_macro_transition(e,t,r){e!==void 0&&r.set("transition",String(e));for(let[n,i]of Object.entries(t))r.set(`transition-${n.replaceAll("_","-")}`,String(i))}_macro_zoom(e,t,r){e!==void 0&&r.set("zoom",String(e))}_macro_shadow(e,t,r){e!==void 0&&r.set("box-shadow",String(e));for(let[n,i]of Object.entries(t))r.set(`box-shadow-${n.replaceAll("_","-")}`,String(i))}_macro_gradient(e,t,r){e!==void 0&&r.set("background-image",String(e))}};var bg=new Set(["alignment_baseline","baseline_shift","clip_path","clip_rule","color_interpolation","color_interpolation_filters","dominant_baseline","fill_opacity","fill_rule","flood_color","flood_opacity","font_family","font_size","font_size_adjust","font_stretch","font_style","font_variant","font_weight","glyph_orientation_horizontal","glyph_orientation_vertical","image_rendering","letter_spacing","lighting_color","marker_end","marker_mid","marker_start","overline_position","overline_thickness","paint_order","pointer_events","shape_rendering","stop_color","stop_opacity","strikethrough_position","strikethrough_thickness","stroke_dasharray","stroke_dashoffset","stroke_linecap","stroke_linejoin","stroke_miterlimit","stroke_opacity","stroke_width","text_anchor","text_decoration","text_rendering","underline_position","underline_thickness","unicode_bidi","word_spacing","writing_mode"]);function Kn(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[bg.has(e)?e.replaceAll("_","-"):e,t]))}var Gt=class extends Vt{static mode="svg";adaptAttrs(e){return Kn(e)}};var Kd={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"html",version:null,title:null,description:null},abstracts:{},elements:{svg:{doc:"Switch to the SVG dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to SVG from this node down. No ``render_tag``: ``<svg>`` is\n emitted verbatim (HTML5 has a native ``<svg>`` tag).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"svg"}},a:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},abbr:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},address:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},area:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},article:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},aside:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},audio:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},b:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},base:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},bdi:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},bdo:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},blockquote:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},body:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},br:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},button:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},canvas:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},caption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},cite:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},code:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},col:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},colgroup:{doc:null,sub_tags:"col,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},data:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},datalist:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,option,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dd:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},del_:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},details:{doc:null,sub_tags:"summary[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dfn:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dialog:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},div:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dl:{doc:null,sub_tags:"dd,div,dt,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dt:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},em:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},embed:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},fieldset:{doc:null,sub_tags:"legend[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figcaption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figure:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figcaption[0:1],figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},footer:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},form:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h1:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h2:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h3:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h4:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h5:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h6:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},head:{doc:null,sub_tags:"base[0:1],link,meta,noscript,script,style,template,title[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},header:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hgroup:{doc:null,sub_tags:"h1,h2,h3,h4,h5,h6,p,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},html:{doc:null,sub_tags:"head[0:1],body[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},i:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},iframe:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},img:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},input:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},ins:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},kbd:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},label:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},legend:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},li:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},link:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},main:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},map:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mark:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},menu:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},meta:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},meter:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},nav:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},noscript:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},object:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ol:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},optgroup:{doc:null,sub_tags:"div,legend,noscript,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},option:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,div,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},output:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},p:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},picture:{doc:null,sub_tags:"img[0:1],script,source,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pre:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},progress:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},q:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rp:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rt:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ruby:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},s:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},samp:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},script:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},search:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},section:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},select:{doc:null,sub_tags:"button,div,hr,noscript,optgroup,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},slot:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},small:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},source:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},span:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},strong:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},style:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sub:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},summary:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sup:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},table:{doc:null,sub_tags:"caption[0:1],colgroup,script,tbody,template,tfoot[0:1],thead[0:1],tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tbody:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},td:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},template:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,del_,details,dfn,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,legend,li,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,optgroup,option,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,tr,track,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textarea:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tfoot:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},th:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},thead:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},time:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tr:{doc:null,sub_tags:"script,td,template,th",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},track:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},u:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ul:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},var:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},video:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},wbr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},selectedcontent:{doc:"Mirror of the selected option for Customizable Select (HTML 2024).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var Je=class extends Ae{static _name="html";static _defaultRenderMode="html";static retainedAttrPrefixes=["validate_","dtype"];static{this.defineGrammar(Kd)}get renderer_html(){return new Wt(this)}};Ae.registerBuilder(Je);var Jd={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"svg",version:null,title:null,description:null},abstracts:{graphics:{doc:"SVG graphics content: any graphical element.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null},containerElement:{doc:"SVG container content: elements that can hold children.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null}},elements:{html:{doc:"Switch to the HTML dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to HTML from this node down. The source tag ``html`` is\n rendered as ``_meta['render_tag']`` (``<foreignObject>``) carrying\n ``_meta['render_attributes']`` (the SVG namespace). The immediate\n HTML child declares XHTML so both sides of the XML boundary retain\n their native namespace.\n ",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"html",render_tag:"foreignObject",render_attributes:{xmlns:"http://www.w3.org/2000/svg"}}},svg:{doc:"Root SVG container or nested SVG viewport.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},g:{doc:"Group container for applying transforms and styles.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},defs:{doc:"Container for referenced elements (gradients, patterns, etc.).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},symbol:{doc:"Reusable graphical template, rendered only when referenced by <use>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},use:{doc:"Reference and render a <symbol> or other element.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rect:{doc:"Rectangle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},circle:{doc:"Circle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ellipse:{doc:"Ellipse.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},line:{doc:"Line segment between two points.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polyline:{doc:"Open shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polygon:{doc:"Closed shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},path:{doc:"Arbitrary shape defined by path commands (d attribute).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},image:{doc:"Embedded raster image.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},text:{doc:"Text block. Contains text content and optional <tspan>/<textPath>.",sub_tags:"tspan,textPath",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tspan:{doc:"Inline text span within <text>.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textPath:{doc:"Text rendered along a path shape.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},linearGradient:{doc:"Linear gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},radialGradient:{doc:"Radial gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},stop:{doc:"Gradient stop (color and offset).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pattern:{doc:"Tile pattern definition. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},clipPath:{doc:"Clipping path definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mask:{doc:"Alpha mask definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},marker:{doc:"Marker symbol for line endpoints or vertices.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},filter:{doc:"Filter effect container. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feGaussianBlur:{doc:"Gaussian blur filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feOffset:{doc:"Offset filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feBlend:{doc:"Blend filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feColorMatrix:{doc:"Color matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feComposite:{doc:"Composite filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feFlood:{doc:"Flood fill filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMerge:{doc:"Merge filter primitive (container for feMergeNode).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMergeNode:{doc:"Single input for feMerge.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDropShadow:{doc:"Drop shadow filter primitive (SVG 2).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDiffuseLighting:{doc:"Diffuse lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpecularLighting:{doc:"Specular lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},fePointLight:{doc:"Point light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDistantLight:{doc:"Distant light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpotLight:{doc:"Spot light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMorphology:{doc:"Morphology filter primitive (erode/dilate).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTurbulence:{doc:"Turbulence noise filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDisplacementMap:{doc:"Displacement map filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feConvolveMatrix:{doc:"Convolution matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feImage:{doc:"Image filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTile:{doc:"Tile filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animate:{doc:"Animate an attribute over time.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateTransform:{doc:"Animate a transform attribute.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateMotion:{doc:"Animate motion along a path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},set:{doc:"Set an attribute to a value for a duration.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:"Accessible title (tooltip in browsers).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},desc:{doc:"Accessible description.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},metadata:{doc:"Metadata container (RDF, Dublin Core, etc.).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},a:{doc:"Hyperlink wrapper.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},foreignObject:{doc:"Container for non-SVG content (HTML, MathML).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},switch:{doc:"Conditional processing (renders first matching child).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var vt=class extends Ae{static _name="svg";static _defaultRenderMode="svg";static{this.defineGrammar(Jd)}get renderer_svg(){return new Gt(this)}};Ae.registerBuilder(vt);function Qe(o,e=new Set){if(!o||typeof o!="object")return;let t=o.ownerDocument?.defaultView?.Node??o.defaultView?.Node;if(Z(o)instanceof Se||t&&o instanceof t)throw new TypeError("Live Source/DOM references cannot cross a transport boundary");if(e.has(o))throw new TypeError("Transport data cannot contain circular references");e.add(o);let r=o instanceof x?o.getNodes().flatMap(n=>[n.staticValue,n.getAttr()]):Object.values(o);for(let n of r)Qe(n,e);e.delete(o)}var Jn=class{constructor(e=null){this.entries=new Map,this.sourceRoot=e}validate(e,t=new Set){let r=new Map,n=i=>{for(let s of i.getNodes()){let a=s.getAttr("__ref");if(a){if(r.has(a))throw new Error("Duplicate Source reference");let l=this.entries.get(a);if(e!==this.sourceRoot&&l&&l.node!==s&&!t.has(l.node))throw new Error("Duplicate Source reference");r.set(a,s)}s.value instanceof N&&n(s.value)}};n(e)}register(e,t){let r=e.getAttr("__ref");if(r){if(this.entries.has(r))throw new Error(`Duplicate Source reference: ${r}`);this.entries.set(r,{node:e,dom:t})}}remove(e){for(let[t,r]of this.entries)r.node===e&&this.entries.delete(t)}resolveArguments(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r&&typeof r=="object"&&Object.hasOwn(r,"$gramlotRef")?this.resolve(r):r]))}resolve(e){if(!e||!["node","dom"].includes(e.kind))throw new TypeError("Expected a node or DOM reference");let t=this.entries.get(e.$gramlotRef);if(!t)throw new Error("Source reference is not mounted");return t[e.kind]}};var nl={};ee(nl,{randomId:()=>G});function G(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),o=>o.toString(16).padStart(2,"0")).join("")}var Ne=class{constructor(e){this.gramlot=e}};var pr=class extends Error{name="RpcError";constructor({code:e,name:t,message:r,details:n}){super(r),this.code=e,this.remoteName=t,n!==void 0&&(this.details=n)}},Qn=class extends Ne{constructor(e,{rpcUrl:t,closeUrl:r,document:n,transport:i}){super(e),this.transport=i===!1?null:i??e.serverAdapter.createTransport({rpcUrl:t,closeUrl:r,document:n,channel:e._pageStore}),this.remoteRequests=new Map}get supportsCallSync(){return this.transport?.supportsCallSync===!0}callSync(e,t,r={}){if(!this.supportsCallSync)throw new Error(`rpc '${t}': the transport of this page has no synchronous call`);if(Qe(r),this.gramlot.abort.signal.aborted)throw this.gramlot.abort.signal.reason;let n=G(),i=j(this.transport.callSync(R({id:n,pageId:this.gramlot.pageId,contentType:e,name:t,params:r})));if(i.id!==n)throw new Error("rpc response id mismatch");if(i.error)throw new pr(i.error);return i.value}async call(e,t,r={},n={}){return(await this.callEnvelope(e,t,r,n)).value}async callEnvelope(e,t,r={},{signal:n=null}={}){if(!this.transport?.call)throw new Error(`rpc '${t}' is unavailable without a server transport`);Qe(r);let i=G(),s=R({id:i,pageId:this.gramlot.pageId,contentType:e,name:t,params:r}),a=n?[this.gramlot.abort.signal,n]:[this.gramlot.abort.signal],l=a.find(f=>f.aborted);if(l)throw l.reason;let c=new AbortController,u=f=>c.abort(f.target.reason);for(let f of a)f.addEventListener("abort",u,{once:!0});let d=new Promise((f,h)=>{c.signal.addEventListener("abort",()=>{this.remoteRequests.delete(i),h(c.signal.reason)},{once:!0})});this.remoteRequests.set(i,c);try{let f=j(await Promise.race([this.transport.call(s,c.signal),d]));if(f.id!==i)throw new Error("rpc response id mismatch");if(f.error)throw new pr(f.error);return f}finally{this.remoteRequests.delete(i);for(let f of a)f.removeEventListener("abort",u)}}};var Pi=class{constructor(e,t,r){this.gramlot=e,this.window=r.defaultView,this.frames=e._frames,this.binders=new Map,this.calls=new Map,this.routes=new Map,this.error=null,this.closed=!1,this.ready=!1,this.socket=null;let n=new URL(t,r.baseURI);n.protocol=n.protocol==="https:"?"wss:":"ws:",this.endpoint=n.href,this.origin=this.window.location.origin,this.parent=this.frames.parent?.window??null,this.frames.registerChannel("server",{changed:i=>this.peerChanged(i),disconnected:i=>{i.parent&&this.parent?this.fail(new Error("PageStore parent disconnected")):this.forget(i.window)},receive:(i,s)=>{try{this.receive(i,s)}catch(a){this.fail(a)}}},{endpoint:this.endpoint,ready:!1}),this.address=n,this.parent||this.open()}open(){let e=this.address;e.searchParams.set("pageId",this.gramlot.pageId),this.socket=new this.window.WebSocket(e.href),this.socket.addEventListener("open",()=>this.connected()),this.socket.addEventListener("message",t=>{try{this.deliver(t.data)}catch(r){this.fail(r)}}),this.socket.addEventListener("error",()=>this.fail(new Error("PageStore WebSocket failed"))),this.socket.addEventListener("close",t=>{this.closed||this.fail(new Error("PageStore disconnected ("+t.code+")"))})}peerChanged(e){if(this.closed||!e.parent||!this.parent)return;let t=e.channels.server;t?e.origin!==this.origin||t?.endpoint!==this.endpoint?this.fail(new Error("Parent does not provide the same PageStore endpoint")):t.ready?this.connected():this.ready&&this.fail(new Error("PageStore parent channel closed")):(this.parent=null,this.open())}connected(){if(!(this.closed||this.ready)){this.ready=!0,this.parent&&this.upstream({op:"attach",pageId:this.gramlot.pageId});for(let e of this.binders.values())this.subscribe(e);for(let e of this.calls.values())this.sendCall(e);this.frames.setChannelState("server",{endpoint:this.endpoint,ready:!0})}}receive(e,t){if(this.closed||e.origin!==this.origin||e.channels.server?.endpoint!==this.endpoint)return;if(e.parent){this.deliver(R(t));return}if(!this.ready)return;let r=t?.pageId;if(!(typeof r!="string"||!r||r===this.gramlot.pageId)){if(t.op==="attach"){if(this.routes.has(r))return;this.routes.set(r,e.window)}else if(this.routes.get(r)!==e.window)return;t.op==="detach"&&this.routes.delete(r),this.upstream(t)}}forget(e){for(let[t,r]of this.routes)r===e&&(this.routes.delete(t),this.ready&&!this.closed&&this.upstream({op:"detach",pageId:t}))}upstream(e){if(this.closed||!this.ready)throw new Error("PageStore is not connected");this.parent?this.frames.send(this.parent,"server",e):this.socket.send(R(e))}deliver(e){if(this.closed)return;let t=j(e);if(t.pageId===this.gramlot.pageId){if(t.op==="closed"){this.fail(new Error("PageStore page closed on the server"));return}if(!Object.hasOwn(t,"op")&&Object.hasOwn(t,"id")){this.calls.get(t.id)?.finish(null,e);return}if(t.op==="publish"){try{this.gramlot._subscriptions.publish(t.topic,t.payload,t.metadata)}catch(n){this.window.console.error("PageStore publication subscriber failed",n)}return}let r=this.binders.get(t.binderId);r&&r.apply(t)}else{let r=this.routes.get(t.pageId);r&&this.frames.send(r,"server",t)}}register(e){if(this.closed)throw new Error("PageStore connection is closed");this.binders.set(e.id,e),this.ready&&this.subscribe(e)}subscribe(e){this.send({op:"subscribe",binderId:e.id,path:e.serverPath})}unregister(e){this.binders.delete(e.id)&&!this.closed&&this.ready&&this.send({op:"unsubscribe",binderId:e.id})}send(e){this.upstream({...e,pageId:this.gramlot.pageId})}preparePublish(e,t){if(this.closed||!this.ready)throw new Error("PageStore is not connected");Qe(t);let r={op:"publish",id:G(),pageId:this.gramlot.pageId,topic:e.topic,payload:t};e.pageId!==void 0&&(r.targetPageId=e.pageId);let n=R(r);return async()=>{let i=j(await this.call(n));if(i.error)throw new pr(i.error);return i.value}}call(e,t){if(this.closed)return Promise.reject(this.error??new Error("PageStore connection is closed"));if(t?.aborted)return Promise.reject(t.reason);let r=j(e);return r.pageId!==this.gramlot.pageId||typeof r.id!="string"||!r.id||Object.hasOwn(r,"op")&&r.op!=="publish"||this.calls.has(r.id)?Promise.reject(new Error("Invalid or duplicate RPC identity")):new Promise((n,i)=>{let s={message:r,sent:!1,finish:(l,c)=>{this.calls.delete(r.id)&&(t?.removeEventListener("abort",a),c===void 0?i(l):n(c))}},a=()=>{if(s.finish(t.reason),s.sent&&this.ready&&!this.closed)try{this.send({op:"cancel",id:r.id})}catch(l){this.fail(l)}};this.calls.set(r.id,s),t?.addEventListener("abort",a,{once:!0}),this.ready&&this.sendCall(s)})}sendCall(e){try{this.upstream(e.message),e.sent=!0}catch(t){e.finish(t),this.fail(t)}}fail(e){this.error=e,this.close(),this.window.console.error("PageStore channel failed",e)}close(){if(!this.closed){if(this.closed=!0,this.parent&&this.ready&&this.frames.isConnected(this.parent))for(let e of[...this.routes.keys(),this.gramlot.pageId])this.frames.send(this.parent,"server",{op:"detach",pageId:e});this.ready=!1;for(let e of this.calls.values())e.finish(this.error??new Error("PageStore connection is closed"));this.binders.clear(),this.routes.clear(),this.frames.unregisterChannel("server"),this.socket?.close()}}};var Qd="gramlot:message",Bi=class{#e;#t;#r;#n=G();#o=new Map;#i=new Map;#s=!1;#a;#l;#c;#u;#d;constructor(e,t){this.#e=e,this.#r=t,this.#t=t.defaultView,this.#a=r=>this.#g(r),this.#l=r=>{if(r.target?.localName!=="iframe")return;let n=this.#v(r.target);n&&this.#w(n)},this.#c=r=>{r.persisted||this.#e.dispose({beacon:!0})},this.#u=()=>this.ready(),this.#t.addEventListener("message",this.#a),this.#t.addEventListener("pagehide",this.#c),this.#t.addEventListener("pageshow",this.#u),t.addEventListener("load",this.#l,!0)}#f(){this.#d===void 0&&(this.#d=this.#t.setInterval(()=>{if(this.parent?.window.closed){this.#p();return}for(let e of this.children)e.window.closed?this.#h(e.window):e.node&&!this.#v(this.#e.dom.getDomNode(e.node))&&this.#h(e.window,!0)},500))}get parent(){let e=this.#t.parent!==this.#t,t=e?this.#t.parent:this.#t.opener;return t?{window:t,parent:!0,kind:e?"iframe":"popup",origin:this.#x(this.#r.referrer||this.#r.baseURI)}:null}get children(){return[...this.#o.values()].filter(e=>!e.parent)}isConnected(e){return!this.#s&&this.#o.has(e)}connect(){this.parent&&(this.#f(),this.#w(this.parent));for(let e of this.#r.getElementsByTagName("iframe")){let t=this.#v(e);t&&this.#w(t)}}ready(){if(!this.#s){this.connect();for(let e of this.#o.values())this.#_(e)}}registerChannel(e,t,r){if(this.#s||e==="publish"||this.#i.has(e))throw new Error("Invalid family channel");this.#i.set(e,{handler:t,state:r});for(let n of this.#o.values())t.changed(n)}setChannelState(e,t){this.#i.get(e).state=t;for(let r of this.#o.values())this.#_(r)}unregisterChannel(e){if(this.#i.delete(e),this.#e.state!=="disposed")for(let t of this.#o.values())this.#_(t)}send(e,t,r){let n=this.#o.get(e);if(this.#s||!n)throw new Error("Destination page is not connected");Qe(r),this.#y(n,{kind:"message",recipient:n.session,channel:t,wire:R(r)})}prepare(e,t){let r=[];if(e.parent){if(!this.parent)throw new Error("This page has no parent frame or opener");r.push(this.parent)}if(e.iframe!==void 0){let s=e.iframe,a=Z(s),l=typeof s=="string"?this.#r.getElementById(s):a instanceof Se?this.#e.dom.getDomNode(a):null,c=this.#v(l);if(!c)throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");r.push(c)}if(e.pageId!==void 0){let s=this.children.find(a=>a.pageId===e.pageId);if(!s)throw new Error("pageId destination must be a registered direct Gramlot child");r.push(s)}let n=r.map(s=>{let a=this.#o.get(s.window);if(!a?.ready||a.origin!==s.origin)throw new Error("Destination page is not ready");return{...s,session:a.session}});Qe(t);let i=R({topic:e.topic,payload:t});return()=>{if(!this.#s)for(let s of n){let a=this.#E(s.window);if(!a||a.origin!==s.origin||this.#o.get(s.window)?.session!==s.session)throw new Error("Destination page disconnected before publication");this.#y(s,{kind:"message",recipient:s.session,channel:"publish",wire:i})}}}dispose(){if(this.#s)return;for(let t of this.children)this.#h(t.window,!0);let e=this.parent;e&&this.#o.has(e.window)&&(this.#y(this.#o.get(e.window),{kind:"close"}),this.#h(e.window)),this.#s=!0,this.#i.clear(),this.#t.removeEventListener("message",this.#a),this.#t.removeEventListener("pagehide",this.#c),this.#t.removeEventListener("pageshow",this.#u),this.#t.clearInterval(this.#d),this.#r.removeEventListener("load",this.#l,!0)}#p(){this.#e.dispose({beacon:!0}),this.#t.parent===this.#t&&this.#t.opener&&this.#t.close()}#h(e,t=!1){let r=this.#o.get(e);if(r){t&&this.#y(r,{kind:"close"}),this.#o.delete(e),r.release?.();for(let{handler:n}of this.#i.values())n.disconnected(r);t&&r.kind==="popup"&&!r.parent&&e.close()}}#m(e,t){let r=this.#o.get(e.window),n=r?.session!==t.session;n&&this.#h(e.window);let i=n?{...e,session:t.session}:r;Object.assign(i,{ready:t.ready===!0,pageId:t.pageId,channels:t.channels}),this.#o.set(e.window,i),this.#f(),n&&e.node&&(i.release=this.#e.src.binding.bindingFor(e.node).track(()=>{this.#h(e.window,!0)}));for(let{handler:s}of this.#i.values())s.changed(i);return n}#g(e){if(this.#s||e.data?.type!==Qd)return;let t=this.#E(e.source);if(!t||e.origin!==t.origin)return;let r=e.data;if(typeof r.session!="string"||!r.session)return;if(r.kind==="hello"||r.kind==="ready"){if(r.kind==="ready"&&r.recipient!==this.#n||!r.channels||typeof r.channels!="object"||Array.isArray(r.channels))return;let i=this.#m(t,r);(r.kind==="hello"||i)&&this.#_(this.#o.get(t.window));return}let n=this.#o.get(t.window);if(!(!n||n.session!==r.session||r.recipient!==this.#n)){if(r.kind==="close")t.parent?this.#p():this.#h(t.window);else if(r.kind==="message"&&typeof r.wire=="string"){let i=j(r.wire);if(r.channel==="publish"){if(this.#e.state!=="started"||!n.ready||typeof i.topic!="string"||!i.topic)return;this.#e.publish(i.topic,i.payload)}else this.#i.get(r.channel)?.handler.receive(n,i)}}}#b(){return{pageId:this.#e.pageId,ready:this.#e.state==="started",channels:Object.fromEntries([...this.#i].map(([e,t])=>[e,t.state]))}}#w(e){this.#y(e,{kind:"hello",...this.#b()})}#_(e){this.#y(e,{kind:"ready",recipient:e.session,...this.#b()})}#y(e,t){e.window.postMessage({type:Qd,session:this.#n,recipient:e.session,...t},e.origin==="null"?"*":e.origin)}#v(e){if(e?.localName!=="iframe"||!e.isConnected||!e.contentWindow)return null;let t=this.#e.dom.getBaseSourceNode(e);if(!t||!this.#e.src.binding.bindingFor(t)||this.#e.dom.getDomNode(t)!==e)return null;let r=e.getAttribute("sandbox"),i=r!==null&&!r.split(/\s+/).includes("allow-same-origin")?"null":this.#x(e.hasAttribute("srcdoc")?this.#r.baseURI:e.getAttribute("src")||this.#r.baseURI);return{window:e.contentWindow,origin:i,node:t,parent:!1,kind:"iframe"}}#x(e){let t=new URL(e,this.#r.baseURI);return t.protocol==="file:"?"null":t.origin}#E(e){let t=this.parent;if(t?.window===e)return t;for(let r of this.#r.getElementsByTagName("iframe")){let n=this.#v(r);if(n?.window===e)return n}try{if(e&&e!==this.#t&&e.opener===this.#t&&e.location.origin===this.#t.location.origin)return{window:e,origin:this.#x(this.#r.baseURI),parent:!1,kind:"popup"}}catch{}return null}};var mr=class o{#e;constructor(e,t=0){this.pattern=e,this.flags=t,this.#e=hr.fromJSON({nameSyntax:{kind:"annotated",base:{kind:"type",module:"builtins",name:"str"},metadata:[this.toJSON()]}}).resolve("nameSyntax").test,Object.freeze(this)}static fromJSON(e){if((e!==null&&typeof e=="object"?Object.keys(e).sort():[]).join()!=="flags,kind,pattern"||e.kind!=="regex")throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(e)}`);return new o(e.pattern,e.flags)}toJSON(){return{kind:"regex",pattern:this.pattern,flags:this.flags}}matches(e){return this.#e(e)}},eo=new mr(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);var ll={};ee(ll,{createLabelbox:()=>sl,labelboxContent:()=>Ie,labelboxPositions:()=>Li,labelboxPresentation:()=>Ht,labelboxStyle:()=>il,projectLabelbox:()=>al});var ol={};ee(ol,{choiceCaption:()=>to,parseChoices:()=>gr});function gr(o,e=","){if(typeof e!="string"||!e)throw new TypeError("separator must be a nonempty string");if(o==="")return[];let t=new Set;return o.split(e).map(r=>{let n=r.indexOf(":"),i=n<0?r:r.slice(0,n),s=n<0?r:r.slice(n+1);if(!i||t.has(i))throw new Error("Invalid or duplicate choice code");return t.add(i),{id:i,caption:s}})}function to(o,e,t=""){return o.find(r=>r.id===e)?.caption??t??""}var Mi=class{constructor(e,t){this.layout=e;let r=e.box.ownerDocument;this.button=r.createElement("button"),this.button.type="button",this.button.className="label-menu-trigger",this.button.setAttribute("aria-haspopup","menu"),this.button.setAttribute("aria-expanded","false"),this.menu=r.createElement("gramlot-menu"),this.menu.projectAttributes({}),e.labelBox.append(this.button,this.menu),this.button.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),this.menu.opened?this.menu.close():this.menu.open(this.button)}),this.button.addEventListener("keydown",n=>{["ArrowDown","ArrowUp"].includes(n.key)&&(n.preventDefault(),n.stopPropagation(),this.menu.open(this.button,n.key==="ArrowUp"))}),this.choose=t}project({lbl:e,lbl_value:t,lbl_values:r,disabled:n,readonly:i},s){let a=gr(r);if(this.values!==r){this.menu.close(!1);for(let c of this.menu.items)c.releaseCommand();this.menu.replaceChildren(...a.map(({id:c,caption:u})=>{let d=this.menu.ownerDocument.createElement("gramlot-menu-line");return d.projectAttributes({code:c,caption:u},s),d.activateCommand=f=>{d.prepareCommand(f)&&this.choose(c)},d.control.addEventListener("click",f=>d.activateCommand(f)),d})),this.values=r}let l=to(a,t,e);this.button.textContent=l,this.button.disabled=!!(n||i||!a.length),this.button.disabled&&this.menu.close(!1);for(let c of this.menu.items)c.projectAttributes({...c.parameters,checked:c.parameters.code===t},s);this.layout.fieldLabel.textContent=l,this.layout.fieldLabel.hidden=!0,this.layout.labelBox.hidden=!1}dispose(){this.menu.close(!1);for(let e of this.menu.items)e.releaseCommand();this.menu.remove(),this.button.remove(),this.layout.fieldLabel.hidden=!1}};var Li=["TL","TC","TR","L","R","BL","BC","BR"],il=`.gramlot-labelbox>.label-box>.label-menu-trigger{font:inherit;color:inherit;background:transparent;border:0;padding:0;min-width:0;min-height:var(--gramlot-touch-target,0px);height:auto;display:inline-flex;align-items:center;gap:.4em;cursor:pointer;text-align:inherit;line-height:inherit}
33
+ `)}},rn=class extends Error{constructor(e){super(e),this.name="BagException"}};Y.registerBagClass(x);Wn(x,"X",o=>o._toTytxPayload(),o=>x._fromTytxPayload(o));wt(x.tytxSuffix,{...Pe(x.tytxSuffix),Bag:x});var Hn=class extends Y{static classKwargs={cacheTime:300,readOnly:!0,retryPolicy:{maxAttempts:3,delay:1,backoff:2,jitter:!0,on:["TypeError","NetworkError","AbortError"]},asBag:!1,url:null,method:"get",qs:null,body:null,timeout:5,transport:"json"};static classArgs=["url"];static internalParams=new Set(["cacheTime","readOnly","retryPolicy","asBag"]);constructor(e,t={}){typeof e=="string"?t={...t,url:e}:t=e||{},super(t)}async load(e){let t=e.url,r=e.method,n=e.qs,i=e.timeout,s=e.transport,a=e.body;e._body!==void 0&&(a=e._body);let l=[],c={};for(let[h,p]of Object.entries(e))if(h.startsWith("arg_")&&p!==null&&p!==void 0){let m=parseInt(h.slice(4),10);if(!isNaN(m)){for(;l.length<=m;)l.push(null);l[m]=p}}else!this.constructor.classKwargs.hasOwnProperty(h)&&!this.constructor.internalParams.has(h)&&!h.startsWith("_")&&p!=null&&(c[h]=p);l.length>0&&t.includes("{")&&(t.match(/\{([^}]+)\}/g)||[]).forEach((p,m)=>{m<l.length&&l[m]!==null&&(t=t.replace(p,String(l[m])))});let u={};if(n&&Object.assign(u,this._qsToDict(n)),Object.assign(u,c),Object.keys(u).length>0){let h=new URLSearchParams;for(let[m,b]of Object.entries(u))b!=null&&h.append(m,String(b));let p=t.includes("?")?"&":"?";t=`${t}${p}${h.toString()}`}let d={method:r.toUpperCase(),transport:s};return i&&(d.signal=AbortSignal.timeout(i*1e3)),a!=null&&(d.body=a),await Ii(t,d)}_qsToDict(e){if(!e)return{};if(typeof e.keys=="function"&&typeof e.getItem=="function"){let r={};for(let n of e.keys()){let i=e.getItem(n);i!=null&&(r[n]=i)}return r}let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}};var Xn=class extends Y{static classKwargs={cacheTime:-1,readOnly:!1,asBag:!1,retryPolicy:null,version:"uuid4"};static classArgs=["version"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy","version"]);load(){return globalThis.crypto.randomUUID()}};var Yn=class extends Y{static classKwargs={cacheTime:-1,readOnly:!0,asBag:!1,retryPolicy:null,key:null,storageType:"local",defaultValue:null,dtype:null};static classArgs=["key"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy"]);constructor(e,t={}){typeof e=="string"?t={...t,key:e}:t=e||{},super(t)}_getStorage(e){return(e.storageType||"local")==="session"?typeof sessionStorage<"u"?sessionStorage:null:typeof localStorage<"u"?localStorage:null}load(e){let t=e.key,r=e.defaultValue,n=t?this._getStorage(e):null,i=n?n.getItem(t):null,s=i!==null?i:r;if(e.dtype==null||s==null)return s;let a=String(s);if(e.dtype==="L"&&!/^[+-]?\d+(?:_\d+)*$/.test(a.trim()))throw new TypeError(`Invalid integer in Web Storage: ${a}`);if(e.dtype==="R"&&!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(a.trim()))throw new TypeError(`Invalid real number in Web Storage: ${a}`);let l=e.dtype==="L"?a.replaceAll("_",""):a,c=j(`${l}::${e.dtype}`);if(typeof c=="number"&&Number.isNaN(c)||c instanceof Date&&Number.isNaN(c.getTime()))throw new TypeError(`Invalid ${e.dtype} value in Web Storage: ${a}`);return c}};var Id=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield"]);function Cd(o){return o.endsWith("_")&&Id.has(o.slice(0,-1))?o.slice(0,-1):o}function Dd(o){let e=Cd(o);return e!==o?e:o.startsWith("_")&&Id.has(o.slice(1))?o.slice(1):o}function nn(o,{renderTag:e=null,ns:t=null,dialectName:r=null}={}){let n=e||o;if(!n)return n;if(n=Cd(n),t&&!e){let i=`${r}_`;n.startsWith(i)&&(n=n.slice(i.length)),n=`${t}:${n}`}return n}var cr=Symbol("value"),lt=new Set(["_meta","datapath","nodeId","ns","form","formId","_anchor","updateOn"]);function ge(o){return Object.entries(o||{}).filter(([e])=>!lt.has(e)).map(([e,t])=>[Dd(e),t])}var Se=class extends Ue{constructor(e,t,r=null,n=null,i=null,s=null,a=null){super(e,t,r,n,i,s,a),this._builder=e?._insertingBuilder??e?._builder??null,this._targetId=null}get builder(){if(this._builder)return this._builder;let e=this.parentBag;return e?e._builder:null}get data(){return this.builder.data}get rootBuilder(){return this.parentBag.root._builder}_getMeta(e){let t=this.getAttr("_meta")||{},r=e.split(",").map(n=>n.trim());return r.length===1?t[r[0]]!==void 0?t[r[0]]:null:r.map(n=>t[n]!==void 0?t[n]:null)}pointerType(e){return typeof e=="string"&&(e[0]==="^"||e[0]==="=")&&!e.startsWith("==")?e[0]:null}pointers(){this.builder.validateCustomTypes(this);let e=[];for(let[t,r]of Object.entries(this.getAttr()||{}))this.pointerType(r)==="^"&&e.push([t,r.split(":",1)[0]]);return this.pointerType(this.value)==="^"&&e.push(["",this.value.split(":",1)[0]]),e}fixedAttrItems(){return ge(this.getAttr())}runtimeToEvaluate(){let e=new Map(this.fixedAttrItems());return e.set(cr,this.value),e}absDatapath(e){let t=e;this.pointerType(e)&&(e=(H(e)?.pointer??e).slice(1));let r=null;return e.includes("?")&&([e,r]=e.split("?",2)),e.startsWith("#")?this._finalizeAbsPath(this._resolveSymbolicDatapath(e,t),r):(e.startsWith(".")&&(e=this._composeRelativeDatapath(e,t)),this._finalizeAbsPath(e,r))}_finalizeAbsPath(e,t){return e=this._collapseParentDatapath(e,e),t?`${e}?${t}`:e}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let n=r.getAttr("datapath");n!=null&&(e=e==="."?n:n+e),r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_collapseParentDatapath(e,t){let r=[];for(let n of e.split("."))if(n==="#parent"){if(r.length===0)throw new Error(`#parent has no segment to cancel: ${t}`);r.pop()}else r.push(n);return r.join(".")}_resolveSymbolicDatapath(e,t){let r=e.slice(1),n=r.indexOf("."),i=n===-1?r:r.slice(0,n),s=n===-1?"":r.slice(n+1),a;if(i==="FORM")a=this._findMarkedDatapathAncestor(!0,!1,t);else if(i==="ANCHOR")a=this._findMarkedDatapathAncestor(!1,!0,t);else{let l=this.rootBuilder;if(!l)throw new Error(`#<id>: cannot resolve ${t} on a node without builder`);if(a=l.source.getNodeByAttr("nodeId",i),a==null)throw new Error(`#<id>: cannot resolve ${t}`)}return a.absDatapath(s?`.${s}`:".")}_findMarkedDatapathAncestor(e,t,r){let n=this;for(;n!=null;){let s=n.getAttr()||{};if(e&&(s.formId!=null||s.form===!0)||t&&"_anchor"in s)return n;n=n.parentNode}let i=e?"FORM":"ANCHOR";throw new Error(`#${i}: no marked ancestor found for ${r}`)}getRelativeData(e,t=null,{autocreate:r=!1}={}){let n=this.data,i=this.absDatapath(e);return r&&n.getItem(i)==null&&n.setItem(i,t),n.getItem(i,t)}setRelativeData(e,t,{attributes:r=null,fired:n=!1,reason:i=null}={}){let s=this.data,a=this.absDatapath(e);s.setItem(a,t,r,">",!1,!0,i===null?!0:i,n)}fireEvent(e,t=!0,{attributes:r=null,reason:n=null}={}){this.setRelativeData(e,t,{attributes:r,fired:!0,reason:n})}SET(e,t){this.setRelativeData(e,t)}GET(e){return this.getRelativeData(e)}PUT(e,t){this.setRelativeData(e,t,{reason:!1})}FIRE(e,t=!0){this.setRelativeData(e,t,{fired:!0})}},N=class o extends x{constructor(e=null,t=null){super(e),this._builder=t,this._insertingBuilder=null}get nodeClass(){return Se}_setBuilderItem(e,t,r,...n){let i=t?.map(([a])=>[a,a._builder])||null;if(t)for(let[a,l]of t)a._builder=l;let s=this._insertingBuilder;this._insertingBuilder=e;try{return this.setItem(r,...n)}catch(a){if(this.node(r)==null&&i)for(let[l,c]of i)l._builder=c;throw a}finally{this._insertingBuilder=s}}bindBuilder(e){if(!e)throw new Error("SourceBag.bindBuilder requires a builder");let t=this._builderBindingPlan(e);for(let[r,n]of t)r._builder=n;return this.setBackref(),this}_builderBindingPlan(e){let t=[],r=new WeakSet,n=(i,s)=>{if(r.has(i))throw new Error("source contains a cyclic or shared SourceBag branch");r.add(i),t.push([i,s]);for(let a of i.getNodes()){let l=s,c=a._getMeta("subbuilder");c!=null&&(l=s._resolveSubbuilderReference(c,a.getAttr()||{},a.nodeTag)),t.push([a,l]);let u=a.getValue(!0);u instanceof o&&n(u,l)}};return n(this,e),t}};if((Pe(N.tytxSuffix).SourceBag??N)!==N)throw new Error("TYTX subtype name 'SourceBag' is already registered for another class");wt(N.tytxSuffix,{...Pe(N.tytxSuffix),SourceBag:N});function Zm(o){if(o.length===0)return{value:null,attrs:{}};let e=o[0];if(e!==null&&typeof e=="object"){let t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null)return{value:null,attrs:e}}return{value:e,attrs:o[1]||{}}}var Km=new Set(["then","toJSON"]),Od=new WeakMap;function Z(o){return Od.get(o)||o}function on(o){if(o==null)return o;o=Z(o);let e=o._builder||o.parentBag&&o.parentBag._builder;return e?e.wrapSource(o):o}function $d(o,e){let t=e instanceof x,r=new Proxy(e,{get(n,i){if(typeof i=="symbol"||i.startsWith("_")||Km.has(i))return Reflect.get(n,i,n);let s=o.schemaTag(i);if(t&&s)return Nd(o,n,s,t);if(i in n){let l=Reflect.get(n,i,n);return typeof l=="function"?l.bind(n):l}if(s)return Nd(o,n,s,t);let a=o.containerMethod(i);if(a)return(...l)=>o[a](o.wrapSource(n),...l)}});return Od.set(r,e),r}function Nd(o,e,t,r){return(...n)=>{let{value:i,attrs:s}=Zm(n),a=r?o.bagCall(e,t,i,s):o.commandOnNode(e,t,i,s);return a.builder.wrapSource(a)}}function Rd(o,{transport:e="json"}={}){if(!(o instanceof N))throw new TypeError("sourceBagToTytx requires a SourceBag");return R(o,e==="json"?null:e)}function ji(o,e,{transport:t="json"}={}){let r=j(o,t==="json"?null:t);if(!(r instanceof N))throw new TypeError("TYTX payload did not decode to SourceBag");return r.bindBuilder(e)}var Pd=/^[A-Za-z_][A-Za-z0-9_]*$/,Jm=new Set(["positional_only","positional_or_keyword","keyword_only","var_positional","var_keyword"]),Qm=new Set(["framework","value","attribute"]),eg=new Map([["builtins.str",o=>typeof o=="string"],["builtins.int",o=>Number.isInteger(o)],["builtins.float",o=>typeof o=="number"&&Number.isFinite(o)],["builtins.bool",o=>typeof o=="boolean"],["builtins.list",o=>Array.isArray(o)],["builtins.dict",o=>o!==null&&typeof o=="object"&&!Array.isArray(o)],["builtins.tuple",o=>Array.isArray(o)],["builtins.set",o=>Array.isArray(o)||o instanceof Set],["builtins.NoneType",o=>o===null],["builtins.object",o=>!0]]);function dr(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function $(o,e){throw new TypeError(`${o}: ${e}`)}function ct(o,e,t,r){dr(o)||$(r,"must be an object");for(let n of Object.keys(o))e.includes(n)||$(r,`unknown field '${n}'`);for(let n of t)Object.hasOwn(o,n)||$(r,`missing field '${n}'`)}function fr(o,e){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(Array.isArray(o))return o.forEach((t,r)=>fr(t,`${e}[${r}]`));if(dr(o))return Object.entries(o).forEach(([t,r])=>fr(r,`${e}.${t}`));$(e,"must be lossless JSON data")}}function tg(o,e){let t="",r=!1;for(let n=0;n<o.length;n++){let i=o[n];if(i==="\\"){t+=i+(o[++n]??"");continue}i==="["&&(r=!0),!r&&i==="."&&!(e&16)?t+="[^\\n]":!r&&i==="^"&&e&8?t+="(?:^|(?<=\\n))":!r&&i==="$"?t+=e&8?"(?=\\n|(?![\\s\\S]))":"(?=\\n?(?![\\s\\S]))":t+=i,i==="]"&&(r=!1)}return t}function ur(o,e,t=!1,r=null){if(o===null)return null;switch(ct(o,["kind","dtype","module","name","origin","arguments","items","values","base","metadata","pattern","flags","ge","le","gt","lt","value"],["kind"],e),o.kind){case"custom":return ct(o,["kind","name"],["kind","name"],e),r||$(e,"custom references require a catalog; nested catalog references are unsupported"),r.resolve(o.name,e);case"dtype":{ct(o,["kind","dtype"],["kind","dtype"],e);let n=o.dtype;typeof n!="string"&&$(e,"dtype must be a string");let i=Kr(n);return!i&&n!=="NN"&&$(e,`unknown dtype '${n}'`),{...o,test:a=>n==="NN"?a===null:n==="N"?q(a)&&!["NaN","Infinity","-Infinity"].includes(a.toString()):i===Number?typeof a=="number"&&Number.isFinite(a)&&(n!=="L"||Number.isInteger(a)):i===String?typeof a=="string":i===Boolean?typeof a=="boolean":i===Date?a instanceof Date&&Number.isFinite(a.getTime()):i===Object?dr(a)&&[Object.prototype,null].includes(Object.getPrototypeOf(a)):a instanceof i}}case"any":return{...o,test:n=>!0};case"type":{(typeof o.module!="string"||typeof o.name!="string")&&$(e,"type requires string module/name");let n=`${o.module}.${o.name}`;if(n==="collections.abc.Callable")return{...o,test:s=>typeof s=="function",portable:!1};let i=eg.get(n);return i||$(e,`unsupported type '${n}'`),{...o,test:i}}case"union":{(!Array.isArray(o.items)||!o.items.length)&&$(e,"union items must be non-empty");let n=o.items.map((i,s)=>ur(i,`${e}.items[${s}]`,!0,r));return{...o,items:n,inputConstraint:n.some(i=>i.inputConstraint),test:i=>n.some(s=>s.test&&s.test(i))}}case"literal":return Array.isArray(o.values)||$(e,"literal values must be an array"),o.values.forEach((n,i)=>fr(n,`${e}.values[${i}]`)),{...o,test:n=>o.values.some(i=>Object.is(i,n))};case"annotated":{Array.isArray(o.metadata)||$(e,"annotated metadata must be an array"),o.metadata.some(s=>!["regex","range","value"].includes(s?.kind))&&$(e,"unsupported annotation metadata kind");let n=ur(o.base,`${e}.base`,!0,r),i=o.metadata.map((s,a)=>ur(s,`${e}.metadata[${a}]`,!0,r));return{...o,base:n,metadata:i,inputConstraint:n.inputConstraint,test:s=>n.test(s)&&i.every(a=>!a.test||a.test(s))}}case"range":{for(let n of["ge","le","gt","lt"])Object.hasOwn(o,n)||$(e,`range missing '${n}'`);for(let n of["ge","le","gt","lt"])o[n]!==null&&(typeof o[n]!="number"||!Number.isFinite(o[n]))&&$(e,`${n} must be finite number or null`);return{...o,test:n=>typeof n=="number"&&(o.ge===null||n>=o.ge)&&(o.le===null||n<=o.le)&&(o.gt===null||n>o.gt)&&(o.lt===null||n<o.lt)}}case"regex":{(typeof o.pattern!="string"||!Number.isInteger(o.flags)||o.flags<0)&&$(e,"regex requires pattern and non-negative integer flags");let n=o.flags&-59;n&&$(e,`unsupported Python regex flags ${n}`),o.flags&2&&$(e,"IGNORECASE is not portable across Python and JavaScript Unicode rules"),/\\[AZzUwWdDsSabBN0-9]|\(\?P[<=!]|\(\?\(|\(\?>|\(\?#|\(\?[aiLmsux-]|[+*?}]\+|\{,/.test(o.pattern.replaceAll(String.raw`[\s\S]`,"."))&&$(e,"regex uses a non-portable construct or character class");let i="uy";o.flags&16&&(i+="s");let s;try{s=new RegExp(`(?:${tg(o.pattern,o.flags)})(?![\\s\\S])`,i)}catch(a){$(e,`invalid portable regex: ${a.message}`)}return{...o,test:a=>typeof a!="string"?!1:(s.lastIndex=0,s.test(a))}}case"value":return fr(o.value,`${e}.value`),{...o};case"generic":{let n=ur(o.origin,`${e}.origin`,!0,r);(o.origin?.kind!=="type"||o.origin.module!=="builtins"||!["list","dict","tuple","set"].includes(o.origin.name))&&$(e,"only list, dict, tuple and set generic origins are supported"),Array.isArray(o.arguments)||$(e,"generic arguments must be an array");let i=o.arguments.map((s,a)=>ur(s,`${e}.arguments[${a}]`,!0,r));return{...o,origin:n,arguments:i,inputConstraint:i.some(s=>s.inputConstraint),test:s=>n.test(s)&&rg(o.origin,i,s)}}case"arguments":$(e,"Callable argument-list descriptors are not supported by Python validation");case"ellipsis":return t||$(e,"ellipsis is only valid as a nested descriptor"),{...o};default:$(e,`unknown annotation kind '${o.kind}'`)}}function rg(o,e,t){let r=`${o.module}.${o.name}`;return r==="builtins.tuple"&&e.length&&e[1]?.kind!=="ellipsis"?t.length===e.length&&t.every((n,i)=>e[i].test(n)):r==="builtins.list"||r==="builtins.set"||r==="builtins.tuple"?[...t].every(n=>!e[0]?.test||e[0].test(n)):r==="builtins.dict"?Object.entries(t).every(([n,i])=>(!e[0]?.test||e[0].test(n))&&(!e[1]?.test||e[1].test(i))):!1}function Bd(o,e){if(o===null)return null;if(typeof o!="string"&&$(e,"must be string or null"),o==="")return new Map;let t=new Map;for(let r of o.split(",")){let n=r.trim();/^[A-Za-z_][A-Za-z0-9_]*\[\]$/.test(n)&&$(e,`invalid cardinality item '${r}'`);let i=n.match(/^([A-Za-z_][A-Za-z0-9_]*|\*)(?:\[(?:(\d+)|(?:(\d*):(\d*)))\])?$/);i||$(e,`invalid cardinality item '${r}'`);let[,s,a,l,c]=i;t.has(s)&&$(e,`duplicate tag '${s}'`);let u=0,d=1/0;n.includes("[")&&(n.includes(":")?(u=l?Number(l):0,d=c?Number(c):1/0):u=d=Number(a)),d<u&&$(e,`maximum ${d} is below minimum ${u}`),t.set(s,{min:u,max:d})}return t.has("*")&&t.size>1&&$(e,"wildcard '*' cannot be combined with named tags"),t}function Md(o,e){if(o===null)return null;typeof o!="string"&&$(e,"must be string or null");let t=new Set;for(let r of o.split(",")){let n=r.trim();n&&((!Pd.test(n)||t.has(n))&&$(e,`invalid or duplicate parent '${r}'`),t.add(n))}return t}function ng(o,e,t){if(o===null)return null;ct(o,["parameters","accepts_var_keyword","accepts_var_positional"],[],e);let r=o.parameters??[];Array.isArray(r)||$(e,"parameters must be an array"),o={parameters:r,accepts_var_keyword:r.some(l=>l.kind==="var_keyword"),accepts_var_positional:r.some(l=>l.kind==="var_positional"),...o},(!Array.isArray(o.parameters)||typeof o.accepts_var_keyword!="boolean"||typeof o.accepts_var_positional!="boolean")&&$(e,"invalid signature descriptor");let n=new Set,i=!1,s=!1,a=o.parameters.map((l,c)=>{let u=`${e}.parameters[${c}]`;return ct(l,["name","kind","role","annotation","has_default","default"],["name","kind","role","annotation","has_default"],u),(typeof l.name!="string"||!Pd.test(l.name)||n.has(l.name))&&$(u,"invalid or duplicate parameter name"),n.add(l.name),(!Jm.has(l.kind)||!Qm.has(l.role)||typeof l.has_default!="boolean")&&$(u,"invalid kind, role, or has_default"),l.has_default!==Object.hasOwn(l,"default")&&$(u,"default presence must equal has_default"),l.has_default&&fr(l.default,`${u}.default`),i||=l.kind==="var_keyword",s||=l.kind==="var_positional",{...l,annotation:ur(l.annotation,`${u}.annotation`,!1,t)}});return(i!==o.accepts_var_keyword||s!==o.accepts_var_positional)&&$(e,"variadic summary flags do not match parameters"),{...o,parameters:a}}function jd(o,e,t,r){let n=["doc","sub_tags","parent_tags","inherits_from","ns","attributes",...t?["node_label","collection_key"]:[],"_meta"];ct(o,n,[],e),o={...Object.fromEntries(n.map(i=>[i,null])),...o};for(let i of["doc","inherits_from","ns",...t?["node_label","collection_key"]:[]])o[i]!==null&&typeof o[i]!="string"&&$(e,`${i} must be string or null`);return o._meta!==null&&(dr(o._meta)||$(e,"_meta must be object or null"),fr(o._meta,`${e}._meta`)),Bd(o.sub_tags,`${e}.sub_tags`),Md(o.parent_tags,`${e}.parent_tags`),{...o,attributes:ng(o.attributes,`${e}.attributes`,r)}}function Ld(o){return o?o.split(",").map(e=>e.trim()).filter(Boolean):[]}function Fd(o,e){let t={...e};for(let[r,n]of Object.entries(o))r==="inherits_from"||r.startsWith("_")||t[r]||(t[r]=n);return t._meta={...o._meta||{},...e._meta||{}},t}function zd(o){let e={...o};return e._subSpec=Object.hasOwn(e,"sub_tags")?Bd(e.sub_tags,"resolved.sub_tags"):null,e._parentSpec=Object.hasOwn(e,"parent_tags")?Md(e.parent_tags,"resolved.parent_tags"):null,e}function Ud(o,e,t,r){if(t.get(o)===1&&$(r,`inheritance cycle at '${o}'`),t.get(o)===2)return e[o];let n=e[o];n||$(r,`unknown abstract '${o}'`),t.set(o,1);let i={...n};for(let s of Ld(n.inherits_from))i=Fd(Ud(s,e,t,r),i);return i=zd(i),t.set(o,2),e[o]=i,i}function Ja({abstracts:o={},elements:e={}}){let t={...o},r=new Map;for(let i of Object.keys(t))Ud(i,t,r,`abstracts.${i}.inherits_from`);let n={};for(let[i,s]of Object.entries(e)){let a={...s};for(let l of Ld(s.inherits_from)){let c=t[l];c||$(`elements.${i}.inherits_from`,`unknown abstract '${l}'`),a=Fd(c,a)}n[i]=zd(a)}return{abstracts:t,elements:n}}function Qa(o){ct(o,["document_format","grammar","abstracts","elements","custom_types"],["document_format","grammar","abstracts","elements"],"grammar document"),ct(o.document_format,["name","version"],["name","version"],"document_format"),(o.document_format.name!=="builder_grammar"||!["1.1","1.2"].includes(o.document_format.version))&&$("document_format","expected builder_grammar version 1.1 or 1.2"),ct(o.grammar,["name","version","title","description"],["name","version","title","description"],"grammar"),(typeof o.grammar.name!="string"||!o.grammar.name)&&$("grammar.name","must be non-empty string");for(let n of["version","title","description"])o.grammar[n]!==null&&typeof o.grammar[n]!="string"&&$(`grammar.${n}`,"must be string or null");(!dr(o.abstracts)||!dr(o.elements))&&$("grammar document","abstracts/elements must be objects"),Object.hasOwn(o,"custom_types")&&o.document_format.version!=="1.2"&&$("custom_types","requires version 1.2");let e=hr.fromJSON(o.custom_types??{}),t={};for(let[n,i]of Object.entries(o.abstracts))(!n||n.startsWith("_"))&&$("abstracts",`invalid public name '${n}'`),t[n]=jd(i,`abstracts.${n}`,!1,e);let r={};for(let[n,i]of Object.entries(o.elements))(!n||n.startsWith("_"))&&$("elements",`invalid public name '${n}'`),r[n]=jd(i,`elements.${n}`,!0,e);return{grammar:structuredClone(o.grammar),abstracts:t,elements:r}}function qd(o,e,t,r){let n=e.attributes;if(!n)return;let i={...r};t!=null&&(i.node_value=t);let s=new Set(n.parameters.filter(c=>c.role==="attribute").map(c=>c.name)),a=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]);if(!n.accepts_var_keyword)for(let c of Object.keys(r))!s.has(c)&&!a.has(c)&&$(o,`unknown attribute '${c}'`);let l=e._meta?.component?n.parameters.find(c=>c.role!=="framework"&&["positional_only","positional_or_keyword"].includes(c.kind))?.name:null;for(let c of n.parameters){if(c.name===l||c.role==="framework"||c.kind.startsWith("var_"))continue;let u=Object.hasOwn(i,c.name);!u&&!c.has_default&&$(o,`missing required ${c.role} '${c.name}'`),u&&c.annotation!==null&&(!c.annotation.test||!c.annotation.test(i[c.name]))&&$(o,`invalid value for ${c.role} '${c.name}'`)}}var hr=class o{#e=new Map;#t=new Map;register(e,t,r){let n=new Map([[String,"str"],[Number,"float"],["string","str"],["integer","int"],["number","float"]]),i=n.has(t)?{kind:"type",module:"builtins",name:n.get(t)}:t;return this.#r(e,{kind:"annotated",base:i,metadata:[r]})}#r(e,t){(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/.test(e)||e in this||["to_dict","from_dict"].includes(e)||og.has(e))&&$("custom_types",`invalid, reserved or duplicate name '${e}'`),ct(t,["kind","base","metadata"],["kind","base","metadata"],`custom_types.${e}`),(t.kind!=="annotated"||!Array.isArray(t.metadata)||t.metadata.length!==1||!["regex","range"].includes(t.metadata[0]?.kind))&&$(`custom_types.${e}`,"requires an annotated base with one Regex or Range validator");let r=t.metadata[0].kind==="regex"?["str"]:["int","float"];(t.base?.kind!=="type"||t.base.module!=="builtins"||!r.includes(t.base.name))&&$(`custom_types.${e}`,"portable Regex requires str; portable Range requires int or float"),fr(t,`custom_types.${e}`);let n=structuredClone(t),i=ur(n,`custom_types.${e}`),s=Object.freeze({kind:"custom",name:e});return Object.defineProperty(this,e,{value:s,enumerable:!0}),this.#e.set(e,n),this.#t.set(e,{...s,inputConstraint:!0,test:i.test}),s}resolve(e,t="custom_types"){return this.#t.has(e)||$(t,`unknown custom type '${e}'`),{...this.#t.get(e)}}validate(e,t){return this.resolve(e).test(t)||$(`custom_types.${e}`,"invalid input value"),!0}toJSON(){return structuredClone(Object.fromEntries(this.#e))}static fromJSON(e){dr(e)||$("custom_types","must be an object");let t=new o;for(let[r,n]of Object.entries(e))t.#r(r,n);return t}},og=new Set("False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield".split(" "));function Vd(o,e,t,r){let n=e?.attributes;if(n)for(let i of n.parameters){if(!i.annotation?.inputConstraint||i.role==="framework"||["var_keyword","var_positional"].includes(i.kind))continue;let s=i.role==="value"?t:r[i.name];s!==void 0&&(i.annotation.test(s)||$(o,`invalid input for '${i.name}' (custom type)`))}}function Wd(o,e,t=[]){if(e===null)return structuredClone(o);if(t.length===2&&t[0]==="custom_types"&&o!==void 0){if(!el(o,e))throw new TypeError(`conflicting custom type '${t[1]}'`);return structuredClone(o)}if(t.length===2&&["abstracts","elements"].includes(t[0]))return structuredClone(e);if(yt(o)&&yt(e)){let r=structuredClone(o);for(let[n,i]of Object.entries(e))i!==null&&Object.defineProperty(r,n,{value:Wd(r[n],i,[...t,n]),enumerable:!0,writable:!0,configurable:!0});return r}return structuredClone(e)}function el(o,e){return Object.is(o,e)?!0:Array.isArray(o)&&Array.isArray(e)?o.length===e.length&&o.every((t,r)=>el(t,e[r])):yt(o)&&yt(e)?Object.keys(o).length===Object.keys(e).length&&Object.keys(o).every(t=>Object.hasOwn(e,t)&&el(o[t],e[t])):!1}function yt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)&&Object.getPrototypeOf(o)===Object.prototype}function tl(o){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(Array.isArray(o)){o.forEach(tl);return}if(yt(o)){Object.values(o).forEach(tl);return}throw new TypeError("collection must contain only finite JSON values")}}var ut=class o{#e;constructor(e){tl(e);let t=["document_format","grammar","abstracts","elements"];if(!yt(e)||Object.keys(e).some(n=>![...t,"custom_types"].includes(n))||t.some(n=>!Object.hasOwn(e,n)))throw new TypeError("collection requires document_format, grammar, abstracts and elements");let r=e.document_format;if(!yt(r)||Object.keys(r).length!==2||r.name!=="builder_grammar"||!["1.1","1.2"].includes(r.version))throw new TypeError("expected builder_grammar version 1.1 or 1.2");for(let n of["grammar","abstracts","elements"])if(!yt(e[n]))throw new TypeError(`${n} must be an object`);if(Object.hasOwn(e,"custom_types")&&(r.version!=="1.2"||!yt(e.custom_types)))throw new TypeError("custom_types requires an object catalog and version 1.2");this.#e=structuredClone(e)}update(e){let t=new o(e),r=Wd(this.#e,t.#e);return(this.#e.document_format.version==="1.2"||t.#e.document_format.version==="1.2")&&(r.document_format.version="1.2"),this.#e=r,this}toDocument(){return structuredClone(this.#e)}};var qt=class{static renderType="string";static mode=null;constructor(e){this._builder=e,this.renders=new Map([[e,this]])}get builder(){return this._builder}get renderType(){return this.constructor.renderType}get mode(){return this.constructor.mode}addRender(e,t){this.renders.set(e,t)}getRender(e){let t=this.renders.get(e);if(t!==void 0)return t;let r=e.getRenderer();return this.renders.set(e,r),r}render(e,t={}){let r=e.builder,[n,i]=r.runtimeValues(e);if(e._getMeta("data_element"))return null;if(e._getMeta("component"))return this._renderComponent(e,i,t);let s=this.getRender(r),a;return[a,i]=s._handleMeta(e,i),e._getMeta("subbuilder")||(i=s.adaptAttrs(i)),e.value instanceof N&&(n=this.renderChildren(e.value,t)),s.renderedItem(e,n,i,{tag:a,...t})}renderChildren(e,t={}){let r=[];for(let n of e.getNodes()){let i=this.render(n,t);i!==null&&(Array.isArray(i)?r.push(...i):r.push(i))}return r}_renderComponent(e,t,r){let[n,i,s,a]=this._expansionInputs(e,t);if(!Object.hasOwn(e.getAttr(),"iterate"))return this._expandBlock(e,n,s,a,r);if(i==null)return[];if(!(i instanceof x))throw new TypeError(`component '${e.nodeTag}': iterate must resolve to a Bag, got ${i?.constructor?.name||typeof i}`);return i.getNodes().map(l=>this._expandBlock(e,n,s,{node_label:l.label},r))}_expansionInputs(e,t){let r=e.builder,n=r.componentMethod(e.nodeTag),i=n&&r[n];if(typeof i!="function")throw new Error(`component '${e.nodeTag}' has no implementation`);let s=t.iterate;delete t.iterate,delete t.store;let a=e.getAttr("iterate")||e.getAttr("store");a!=null?(e.pointerType(a)&&(a=a.slice(1)),a.startsWith(".")&&(a=e._composeRelativeDatapath(a,a))):a=null;for(let l of Object.keys(t)){let c=e.getAttr(l);e.pointerType(c)==="^"&&(t[l]=`^${e.absDatapath(c)}`)}return[i,s,a,t]}_expandBlock(e,t,r,n,i){let s=e.builder._expansionRoot(r);t.call(e.builder,on(s),n);let a=s.getNodes();if(a.length!==1)throw new Error(`component '${e.nodeTag}' must build a tree, not a forest: ${a.length} root nodes`);let l={...i,depthOffset:this._nodeDepth(e,i.depthOffset||0)};return this.render(a[0],l)}preprocess(e){return e}renderedItem(e,t,r,n){throw new Error(`${this.constructor.name} does not implement renderedItem`)}_handleMeta(e,t){let[r,n]=e._getMeta("render_tag,render_attributes"),i=nn(e.nodeTag,{renderTag:r,ns:e.getAttr("ns"),dialectName:e.builder?.constructor._name});if(!i)throw new Error(`node ${e.label} has no tag to render (no render_tag, no node_tag)`);return n&&(t={...t,...n}),[i,t]}adaptAttrs(e){return e}adapt(e){let t=`${this.builder.constructor._name}_`;return e.startsWith(t)?e.slice(t.length):e}finalize(e,t=null,r={}){let n=this._composeStringFragments(e);if(t==null)return n;if(typeof t=="string")throw new TypeError("string render targets require filesystem support, which is unavailable in the portable renderer; pass a callable or writable target instead");if(typeof t.full=="function"&&typeof t.write!="function")return t.full(n),null;if(typeof t.write=="function")return t.write(n),null;if(typeof t=="function")return t(n),null;throw new TypeError("render target must be writable (.write), callable, or expose .full")}_composeStringFragments(e){if(!Array.isArray(e))return e;if(e.some(t=>typeof t!="string"))throw new TypeError("String composition requires string fragments; object renderers must define their own composition");return e.join("")}_escapeText(e){return String(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}_escapeAttr(e){return this._escapeText(e).replaceAll('"',"&quot;")}_nodeDepth(e,t=0){let n=((e.fullpath||"").match(/\./g)||[]).length;return Math.max(n-1,0)+t}};var Vt=class extends qt{static mode="xml";renderedItem(e,t,r,{tag:n,pretty:i=!1,depthOffset:s=0}={}){let a=this._formatAttrs(r),l=i?" ".repeat(this._nodeDepth(e,s)):"",c=i?`
34
+ `:"";if(Array.isArray(t)){let u=this._composeStringFragments(t);return`${l}<${n}${a}>${c}${u}${l}</${n}>${c}`}return t==null?`${l}<${n}${a}></${n}>${c}`:`${l}<${n}${a}>${this._escapeText(t)}</${n}>${c}`}finalize(e,t=null,{docHeader:r=null}={}){let n=this._composeStringFragments(e);return r===!0?n=`<?xml version='1.0' encoding='UTF-8'?>${n}`:typeof r=="string"&&(n=r+n),super.finalize(n,t)}_formatAttrs(e){return Object.entries(e||{}).map(([t,r])=>` ${t.startsWith("xmlns_")?`xmlns:${t.slice(6)}`:t}="${this._escapeAttr(r)}"`).join("")}};var Gd={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"base",version:null,title:null,description:null},abstracts:{},elements:{dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};function Hd(o){let e=[];for(;o&&o!==Function.prototype;)e.push(o),o=Object.getPrototypeOf(o);return e.reverse()}function sg(o){let e=Object.create(null),t=(r,n)=>{let i=r.toLowerCase(),s=e[i];if(s!==void 0&&s!==n)throw new Error(`container '${r}' is already tied to implementation method '${s}' (cannot rebind to '${n}')`);e[i]=n};for(let r of Hd(o))if(Object.hasOwn(r,"containers"))for(let n of r.containers||[])t(n,n);return e}function Zn(o){let e=Object.create(null);for(let t of Object.keys(o)){let r=t.toLowerCase();if(Object.hasOwn(e,r))throw new Error(`element declaration '${t}' has a case-insensitive collision with '${e[r]}'`);e[r]=t}return e}var sn="_root_",an="_root_",rl=new Set(["destination","func","value","_on_start"]),Ae=class o{static _sourceClass=N;static registerBuilder(e){if(typeof e!="function"||!(e.prototype instanceof o))throw new TypeError("registerBuilder requires a BuilderBase subclass");let t=e._name;if(typeof t!="string"||!t)throw new TypeError("registered builders require a non-empty static _name");let r=o._registry.get(t);if(r&&r!==e)throw new Error(`Builder name '${t}' is already registered to ${r.name}; cannot register ${e.name}`);return o._registry.set(t,e),e}static getBuilderClass(e){let t=o._registry.get(e);if(!t)throw new Error(`No builder registered with name '${e}'`);return t}constructor(e=null){this.name=e||this.constructor._name,this._dataroot=new x,this._dataroot.setBackref(),this._dataroot.setItem(an,new x),this.data=this._dataroot.getItem(an),this._defaultTargets=new Map,this.materialized=Object.create(null),this._collection=null,this._schemaOverride=null,this._tagNamesOverride=null,this._componentMap=null,this._targetSerial=0,this._subbuilders=new Map,this._sourceHandles=new WeakMap;let t=this.constructor._sourceClass;this._sourceroot=new t(null,this),this._sourceroot.setBackref(),this._sourceroot.setItem(sn,new t(null,this)),this.source=this._sourceroot.getItem(sn)}wrapSource(e){if(e=Z(e),!(e instanceof N)&&!(e instanceof Se))throw new TypeError("wrapSource requires a SourceBag or SourceBagNode");let t=this._sourceHandles.get(e);return t||(t=$d(this,e),this._sourceHandles.set(e,t)),t}get root(){return this.wrapSource(this.source)}getSubbuilder(e){if(typeof e!="string"||!e||e.includes(":"))throw new Error(`unsupported subbuilder reference '${e}'`);let t=this._subbuilders.get(e);if(!t){let r=o.getBuilderClass(e);t=new r,this._subbuilders.set(e,t)}return t._dataroot=this._dataroot,t.data=this.data,t}_resolveSubbuilderReference(e,t,r){if(typeof e!="string"||!e)throw new Error(`'${r}': subbuilder declaration must be a non-empty string`);if(e.includes(":"))throw new Error(`'${r}': runtime subbuilder reference '${e}' is unsupported`);return this.getSubbuilder(e)}static defineGrammar(e){let t=this._classCollection,r=t?new ut(t.toDocument()).update(e):new ut(e),n=Qa(r.toDocument()),i=Ja(n),s=Zn(i.elements);this._classCollection=r,this._classSchema=i.elements,this._abstracts=i.abstracts,this._tagNames=s}static{this.defineGrammar(Gd)}get _containers(){return sg(this.constructor)}containerMethod(e){return this._containers[e.toLowerCase()]||null}componentMethod(e){return this._componentMap?.[e.toLowerCase()]||null}get schema(){return this._schemaOverride||this.constructor._classSchema||{}}get schemaTagNames(){return this._schemaOverride?this._tagNamesOverride??=Zn(this.schema):this.constructor._tagNames??=Zn(this.schema)}schemaTag(e){let t=e.toLowerCase(),r=this.schemaTagNames[t];if(r)return r;let n=`${this.constructor._name}_`;return t.startsWith(n)&&this.schemaTagNames[t.slice(n.length)]||null}loadGrammar(e,{replace:t=!1}={}){let r=this._collection||this.constructor._classCollection,n=t?new ut(e):new ut(r.toDocument()).update(e),i=Qa(n.toDocument()),s=Ja(i),a=Zn(s.elements);return this._collection=n,this._schemaOverride=s.elements,this._tagNamesOverride=a,this}validateCustomTypes(e){let t=e.parentBag?.parentNode?.builder||e.parentBag?._builder,r=t&&t!==this&&t.schema[e.nodeTag]?._meta?.subbuilder?t:this;Vd(e.nodeTag,r.schema[e.nodeTag],e.value,e.getAttr()||{})}validateNodeValues(e,t,r={}){let n=this.schemaTag(e);if(!n)throw new Error(`unknown element '${e}'`);return qd(n,this.schema[n],t,r),!0}validateNode(e,{value:t,attrs:r,childTags:n}={}){if(!e||typeof e.nodeTag!="string")throw new TypeError("validateNode requires a source node");let i=t!==void 0?t:e.value instanceof N?null:e.value;this.validateNodeValues(e.nodeTag,i,r||e.getAttr?.()||{});let s=this.schema[this.schemaTag(e.nodeTag)],a=n||(e.value instanceof N?e.value.getNodes().map(l=>l.nodeTag):null);return a&&this._validateChildren(e.nodeTag,s,a,!1),!0}validateChildren(e,t,{includeMinimum:r=!1}={}){let n=this.schemaTag(e);if(!n)throw new Error(`unknown element '${e}'`);if(!Array.isArray(t)||t.some(i=>typeof i!="string"))throw new TypeError("childTags must be an array of strings");return this._validateChildren(n,this.schema[n],t,r)}validateParent(e,t=null){let r=this.schemaTag(e);if(!r)throw new Error(`unknown element '${e}'`);let n=this.schema[r];if(!this._countsForGrammar(n))return!0;let i=n._parentSpec;if(i==null||i.has("*"))return!0;if(t===null)throw new Error(`'${r}' requires a declared parent`);let s=this.schemaTag(t);if(!s)throw new Error(`unknown parent element '${t}'`);return this._validateParent(r,n,s),!0}bagCall(e,t,r,n){return this.setChild(e,t,r,n)}commandOnNode(e,t,r,n){if(e=Z(e),e.value instanceof N)return this.setChild(e.value,t,r,n);let i=e.value,s=new e.parentBag.constructor(null,e.builder||this),a=this.setChild(s,t,r,n,e);return this.promoteNodeValue(e,i,s),a}promoteNodeValue(e,t,r){e.setValue(r)}setChild(e,t,r,n,i=null){let s={...n},a=this.schema[t];if(!a)throw new Error(`unknown element '${t}'`);this.validateNodeValues(t,r,s);let l=a._meta?.subbuilder,u=(l==null?null:this._resolveSubbuilderReference(l,s,t))||this,d=r instanceof N?r._builderBindingPlan(u):null,f=i?.rootBuilder||e.root._builder||this;if(s.nodeId!=null&&f.source.getNodeByAttr("nodeId",s.nodeId))throw new Error(`Duplicate nodeId '${s.nodeId}'`);r instanceof N&&this._validateChildren(t,a,r.getNodes().map(v=>v.nodeTag),!1);let h=i||e.parentNode,p=h?.nodeTag?this.schema[h.nodeTag]:null;if(p&&!h._getMeta("subbuilder")&&this._countsForGrammar(a))this._validateParent(t,a,h.nodeTag),this._validateChildren(h.nodeTag,p,[...e.getNodes().map(v=>v.nodeTag),t],!1);else if(!p&&!h?._getMeta("subbuilder")&&a._parentSpec!=null&&this._countsForGrammar(a))throw new Error(`'${t}' requires a declared parent`);a._meta&&!("_meta"in s)&&(s._meta=a._meta),a.ns&&!("ns"in s)&&(s.ns=a.ns);let m=s.node_position;delete s.node_position;let b=s.node_label;delete s.node_label;let w;if(p?.collection_key){if(b!=null)throw new Error(`'${t}': node_label is not allowed in a collection`);w=this._collectionLabel(p.collection_key,t,s)}else{let v=p?._subSpec?.get(t);if(v&&v.max===1){if(b!=null)throw new Error(`'${t}': node_label is not allowed on a singleton`);w=t}else w=b||a.node_label||this._autoLabel(e,t)}if(e.node(w)!=null)throw new Error(`duplicate node label '${w}'`);return e._setBuilderItem(u,d,w,r,s,m||">",!1,!0,null,!1,!0,null,t)}_countsForGrammar(e){let t=e?._meta||{};return!(t.data_element||t.subbuilder||t.component)}_validateParent(e,t,r){let n=t._parentSpec;if(!(n==null||n.has("*")||!this._countsForGrammar(t))&&!n.has(r))throw new Error(`'${e}' not allowed as child of '${r}'`)}_validateChildren(e,t,r,n){let i=t._subSpec;if(i==null||i.has("*")||t._meta?.subbuilder)return[];let s=new Map;for(let a of r){let l=this.schema[a];if(l&&!this._countsForGrammar(l))continue;let c=i.get(a);if(!c)throw new Error(`'${a}' not allowed as child of '${e}'`);let u=(s.get(a)||0)+1;if(s.set(a,u),u>c.max)throw new Error(`too many '${a}' in '${e}'`)}return n?[...i].filter(([a,l])=>(s.get(a)||0)<l.min).map(([a])=>a):[]}_collectionLabel(e,t,r){let n=i=>{if(r[i]===null||r[i]===void 0)throw new Error(`'${t}': collection key needs attribute '${i}'`);return String(r[i])};return e.includes("${")?e.replace(/\$\{([^}]+)\}/g,(i,s)=>n(s)):n(e)}validateSource(){let e=[],t=(r,n="")=>{for(let i of r.getNodes()){let s=n?`${n}.${i.label}`:i.label,a=i.builder;a.validateCustomTypes(i);let l=a.schema[i.nodeTag];if(l&&!i._getMeta("data_element,subbuilder,component").some(Boolean)){let c=i.value instanceof N?i.value.getNodes().map(d=>d.nodeTag):[],u=a._validateChildren(i.nodeTag,l,c,!0);u.length&&e.push([s,u])}i.value instanceof N&&t(i.value,s)}};return t(this.source),e}_autoLabel(e,t){let r=0;for(;e.node(`${t}_${r}`)!==null&&e.node(`${t}_${r}`)!==void 0;)r+=1;return`${t}_${r}`}nodeById(e){let t=this.source.getNodeByAttr("nodeId",e);if(t==null)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}runtimeValues(e){e.builder.validateCustomTypes(e);let t=new Map,r={},n=e.runtimeToEvaluate(),i=new Set(n.keys()),s=new Map([...Object.entries(e.getAttr()),...e.fixedAttrItems()]);for(let[u,d]of[...n])if(!(typeof u!="string"||!H(d)))for(let f of Ze(e,d))n.has(f)||n.set(f,s.get(f));let a=e._getMeta("data_element");for(let[u,d]of n){if(d instanceof Y){t.set(u,d.resolve());continue}let f=typeof u=="string"?H(d)?.pointer??d:d;if(!e.pointerType(f)){t.set(u,typeof u=="string"&&typeof d=="string"&&d.startsWith("==")?null:d);continue}let h=e.absDatapath(f);if(t.set(u,this.data.getItem(h)),!a&&!h.includes("?")&&u===cr){let p=this.data.getNode(h);p&&Object.assign(r,p.getAttr("_wdg"))}}let l=kd(n,t,(u,d,f,h)=>this.evaluatePointerExpression(e,u,d,f,h)),c=l.get(cr);l.delete(cr);for(let u of l.keys())i.has(u)||l.delete(u);return[c,{...Object.fromEntries(l),...r}]}evaluatePointerExpression(e,t,r,n,i){return null}targetId(e){if(e._targetId)return e._targetId;let t=e.rootBuilder;return e.parentBag.root!==t.source.root?null:(t._targetSerial+=1,e._targetId=`n${t._targetSerial}`,e._targetId)}get dataLogic(){if(!this._dataLogic){let e=this._buildDataLogic();this._dataLogic=Array.isArray(e)?e:[e]}return this._dataLogic}_buildDataLogic(){return this}_resolveLogicFunc(e){if(typeof e=="function")return e;if(typeof e!="string")throw new Error("data-element func must be a name or a function");for(let t of this.dataLogic){let n=(typeof t=="function"?t:t.constructor)[e];if(typeof n=="function")return n}throw new Error(`data-element func '${e}' not found on any data_logic source`)}_bindings(e){let[,t]=this.runtimeValues(e),r={};for(let[n,i]of Object.entries(t))rl.has(n)||(r[n]=i);return r}computeLogic(e){for(let t of e)this._computeNode(t)}_computeNode(e){let t=e.getAttr()||{};if(e.nodeTag==="dataSetter"){let r={};for(let[n,i]of Object.entries(t))n!=="destination"&&n!=="value"&&!n.startsWith("_")&&(r[n]=i);e.setRelativeData(t.destination,t.value,{attributes:Object.keys(r).length?r:null})}else if(e.nodeTag==="dataFormula"){let r=this._resolveLogicFunc(t.func);e.setRelativeData(t.destination,r(this._bindings(e)))}else e.nodeTag==="dataController"&&this._resolveLogicFunc(t.func)(e,this._bindings(e))}_dataElementNodes(){let e=[],t=r=>{for(let n of r.getNodes())n._getMeta("data_element")&&e.push(n),n.value instanceof N&&t(n.value)};return t(this.source),e}setup(e){}main(e){throw new Error(`${this.constructor.name}.main() not implemented: a bare builder is grammar, not a renderable page`)}_resolveComponents(){let e={};for(let a of Hd(this.constructor))if(Object.hasOwn(a,"components"))for(let l of a.components||[])e[l]=l;if(!Object.keys(e).length)return;let t={...this.schema},r={};for(let[a,l]of Object.entries(e))t[a]={sub_tags:"",_meta:{component:!0}},r[a.toLowerCase()]=l;let n=Zn(t),i=this._collection||this.constructor._classCollection,s=i.toDocument();s.abstracts={},s.elements=Object.fromEntries(Object.keys(e).map(a=>[a,t[a]])),this._collection=new ut(i.toDocument()).update(s),this._schemaOverride=t,this._componentMap=r,this._tagNamesOverride=n}_expansionRoot(e=null){let t=this.constructor._sourceClass,r=new t(null,this);return r.setBackref(),r.setItem(sn,new t(null,this),e?{datapath:e}:null),r.getItem(sn)}create(){this.setup(this.data),this._resolveComponents(),this.main(this.root),this.computeLogic(this._dataElementNodes())}get renderer_xml(){return new Vt(this)}getRenderer(e=null){e??=this.constructor._defaultRenderMode;let t=this[`renderer_${e}`];if(!t)throw new Error(`${this.constructor.name} does not expose renderer_${e}`);return t}materialize(e=null,t={}){e??=this.constructor._defaultRenderMode;let r=this.getRenderer(e),n=r.renderChildren(r.preprocess(this.source),t);return this.materialized[e]=n,n}setRenderTarget(e,t=null){t??=this.constructor._defaultRenderMode,this._defaultTargets.set(t,e)}render({mode:e=null,target:t=null,...r}={}){e??=this.constructor._defaultRenderMode;let n=this.getRenderer(e);if(t===!1&&n.renderType!=="string")throw new TypeError("target=false is not valid for an object renderer");let i=t===!1?null:t||this._defaultTargets.get(n.mode)||null,s={...i?.renderOpts,...r};return n.finalize(this.materialize(e,s),i,s)}};Ae._registry=new Map;var ag=new Set(["short","medium","long","full"]),lg=/('(?:[^']|'')*'|[a-zA-Z]+|[^a-zA-Z']+)/g;function cg(o,e){if(!(o instanceof Date))throw new TypeError("Temporal formats require a typed Date value");if(!Number.isFinite(o.getTime()))throw new RangeError("Invalid date");let t=e||R(o).split("::").at(-1);if(!["D","H","DH","DHZ"].includes(t))throw new RangeError(`Unsupported temporal dtype: ${t}`);return t}function ug(o,e,t,r){let n=e.match(lg)||[];if(n.join("")!==e)throw new RangeError("Unclosed format literal");let i=(u,d=2)=>String(u).padStart(d,"0"),s=u=>new Intl.DateTimeFormat(t,{timeZone:"UTC",...u}).format(o),c={...r==="H"?{}:{y:()=>String(o.getUTCFullYear()),yy:()=>i(o.getUTCFullYear()%100),yyyy:()=>i(o.getUTCFullYear(),4),M:()=>String(o.getUTCMonth()+1),MM:()=>i(o.getUTCMonth()+1),MMM:()=>s({month:"short"}),MMMM:()=>s({month:"long"}),d:()=>String(o.getUTCDate()),dd:()=>i(o.getUTCDate()),EEE:()=>s({weekday:"short"}),EEEE:()=>s({weekday:"long"})},...r==="D"?{}:{H:()=>String(o.getUTCHours()),HH:()=>i(o.getUTCHours()),h:()=>String(o.getUTCHours()%12||12),hh:()=>i(o.getUTCHours()%12||12),m:()=>String(o.getUTCMinutes()),mm:()=>i(o.getUTCMinutes()),s:()=>String(o.getUTCSeconds()),ss:()=>i(o.getUTCSeconds()),a:()=>new Intl.DateTimeFormat(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(o).find(u=>u.type==="dayPeriod").value}};return n.map(u=>{if(u.startsWith("'"))return u==="''"?"'":u.slice(1,-1).replaceAll("''","'");if(!/^[a-zA-Z]/.test(u))return u;if(!c[u])throw new RangeError(`Unsupported date format token: ${u}`);return c[u]()}).join("")}function Xd(o,{format:e,mask:t,locale:r,dtype:n,places:i}={}){let s=o==null?"":String(o);if(o!=null&&o!==""&&(e!=null&&e!==""||i!=null))if(typeof o=="number"||q(o))s=fg(o,{format:e,locale:r,places:i});else{let a=cg(o,n);if(ag.has(e)){let l={timeZone:"UTC"};a!=="H"&&(l.dateStyle=e),a!=="D"&&(l.timeStyle=e),s=new Intl.DateTimeFormat(r||void 0,l).format(o)}else s=ug(o,String(e),r||void 0,a)}return t==null?s:String(t).replaceAll("%s",()=>s)}function dg({format:o="decimal",places:e}={}){let t={maximumFractionDigits:20};if(!o||o==="decimal")t.style="decimal";else if(o==="percent")t.style="percent";else if(o==="scientific")t.notation="scientific";else{let r=/^(0|#,##0)(?:\.(0*)(#*))?$/.exec(o);if(!r||o.includes(".")&&!r[2]&&!r[3])throw new RangeError(`Unsupported number format: ${o}`);t.useGrouping=r[1].includes(","),t.minimumFractionDigits=(r[2]||"").length,t.maximumFractionDigits=(r[2]||"").length+(r[3]||"").length}if(e!=null&&e!==""){let r=Number(e);if(!Number.isInteger(r)||r<0||r>20)throw new RangeError("places must be an integer from 0 to 20");t.minimumFractionDigits=r,t.maximumFractionDigits=r}return t}function fg(o,e={}){if(typeof o!="number"&&!q(o))throw new TypeError("Number formatting requires a Number or Decimal");if(!Number.isFinite(Number(o)))throw new RangeError("Number must be finite");let t=new Intl.NumberFormat(e.locale||void 0,dg(e));if(q(o)&&new Intl.NumberFormat("en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal values without precision loss");return t.format(q(o)?o.toString():o)}var hg=new Set(["style","script"]),pg=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),Yd=new Set(["width","height","top","left","right","bottom","padding","margin","border","position","display","overflow","float","clear","resize","z_index","min_width","min_height","max_width","max_height","color","background","font","text","line_height","white_space","vertical_align","flex","gap","row_gap","column_gap","grid","align_content","justify_content","align_items","justify_items","visibility","opacity","cursor"]),Kn=new Set(["rounded","gradient","shadow","transform","transition","zoom","filter"]),Zd=o=>o===!0?"true":o===!1?"false":String(o),Pi=o=>typeof o=="number"&&Number.isFinite(o)?`${o}px`:String(o);function mg(o){if(Yd.has(o))return!0;for(let e of Yd)if(o.startsWith(`${e}_`))return!0;return!1}function gg(o){let e=new Map;if(!o)return e;let t=[],r=0,n=null,i=!1,s=!1,a=0,l=String(o);for(let c=0;c<l.length;c+=1){let u=l[c],d=l[c+1];if(s){u==="*"&&d==="/"&&(s=!1,c+=1);continue}if(i){i=!1;continue}if(u==="\\"){i=!0;continue}if(n){u===n&&(n=null);continue}u==='"'||u==="'"?n=u:u==="/"&&d==="*"?(s=!0,c+=1):"([{".includes(u)?a+=1:")]}".includes(u)&&a>0?a-=1:u===";"&&a===0&&(t.push(l.slice(r,c)),r=c+1)}t.push(l.slice(r));for(let c of t){let u=c.trim();if(!u)continue;let d=u.indexOf(":");if(d<0)throw new TypeError(`malformed style declaration '${u}'`);e.set(u.slice(0,d).trim(),u.slice(d+1).trim())}return e}var Wt=class extends qt{static mode="html";renderedItem(e,t,r,{tag:n,xml:i=!0,pretty:s=!1,depthOffset:a=0,includeDatapath:l=!1}={}){e.parentNode?._getMeta("subbuilder")==="html"&&(r={xmlns:"http://www.w3.org/1999/xhtml",...r});let{format:u,mask:d,locale:f,places:h,dtype:p,...m}=r;!Array.isArray(t)&&(u!=null||d!=null||h!=null)&&(t=Xd(t,{format:u,mask:d,places:h,dtype:p,locale:this._displayLocale(e,f)}));let b=this._formatAttrs(m);if(l){if(!Object.hasOwn(r,"id")){let E=this.builder.targetId(e);E!==null&&(b+=` id="${this._htmlAttrValue(E)}"`)}for(let[E,D]of Object.entries(e.getAttr()))e.pointerType(D)&&(b+=` data-${this.adapt(E)}-pointer="${this._htmlAttrValue(e.absDatapath(D))}"`)}let w=s?" ".repeat(this._nodeDepth(e,a)):"",_=s?`
35
+ `:"";if(e._getMeta("void"))return`${w}<${n}${b}${i?"/":""}>${_}`;if(Array.isArray(t)){let E=this._composeStringFragments(t);return`${w}<${n}${b}>${_}${E}${w}</${n}>${_}`}if(t==null)return`${w}<${n}${b}></${n}>${_}`;let v=typeof t=="string"&&t.endsWith("::HTML")?t.slice(0,-6):hg.has(n)?String(t):this._escapeText(t);return`${w}<${n}${b}>${v}</${n}>${_}`}_displayLocale(e,t){if(t)return t;for(let r=e.parentNode;r;r=r.parentNode){let n=r.getAttr("locale");if(n==null)continue;let i=r.pointerType(n)?r.data.getItem(r.absDatapath(n)):n;if(i)return i}}adaptAttrs(e){let t={},r={};for(let[i,s]of Object.entries(e||{}))if(i.startsWith(`${this.builder.constructor._name}_`))t[this.adapt(i)]=s;else if(i==="dtype")t.dtype=s;else{if(this.builder.constructor.retainedAttrPrefixes.some(a=>i.startsWith(a)))continue;this._isStyleContribution(i)?r[i]=s:t[i]=s}let n=this._adaptStyle(r);return n&&(t.style=n),t}_isStyleContribution(e){if(e==="style"||e.startsWith("style_")||Kn.has(e))return!0;let t=e.includes("_")?e.slice(0,e.indexOf("_")):null;return t!==null&&Kn.has(t)||mg(e)}_adaptStyle(e){let t=gg(e.style),r=new Map,n=new Map;for(let[i,s]of Object.entries(e))if(i!=="style")if(i.startsWith("style_"))t.set(i.slice(6).replaceAll("_","-"),Zd(s));else if(Kn.has(i))r.set(i,s);else{let a=i.indexOf("_"),l=a<0?i:i.slice(0,a);a>=0&&Kn.has(l)?(n.has(l)||n.set(l,{}),n.get(l)[i.slice(a+1)]=s):t.set(i.replaceAll("_","-"),Zd(s))}for(let i of Kn)(r.has(i)||n.has(i))&&this[`_macro_${i}`](r.get(i),n.get(i)||{},t);return[...t].map(([i,s])=>`${i}: ${s}`).join("; ")}_formatAttrs(e){let t=[];for(let[r,n]of Object.entries(e||{}))pg.has(r)?n&&t.push(` ${r}`):t.push(` ${r}="${this._htmlAttrValue(n)}"`);return t.join("")}_htmlAttrValue(e){return(e===!0?"true":e===!1?"false":String(e)).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}_macro_rounded(e,t,r){let n=e===void 0?{}:{top_left:e,top_right:e,bottom_left:e,bottom_right:e};for(let[i,s]of Object.entries(t))if(i==="top"||i==="bottom")n[`${i}_left`]=s,n[`${i}_right`]=s;else if(i==="left"||i==="right")n[`top_${i}`]=s,n[`bottom_${i}`]=s;else if(["top_left","top_right","bottom_left","bottom_right"].includes(i))n[i]=s;else throw new TypeError(`rounded: unknown sub-kwarg '${i}'`);for(let[i,s]of Object.entries(n))r.set(`border-${i.replaceAll("_","-")}-radius`,Pi(s))}_macro_transform(e,t,r){let n=e===void 0?[]:[String(e)];for(let[i,s]of Object.entries(t))i==="rotate"?n.push(`rotate(${s}deg)`):i==="scale"||i==="translate"?n.push(`${i}(${s})`):i==="translate_x"?n.push(`translateX(${Pi(s)})`):i==="translate_y"?n.push(`translateY(${Pi(s)})`):i==="skew_x"?n.push(`skewX(${s}deg)`):i==="skew_y"?n.push(`skewY(${s}deg)`):n.push(`${i.replaceAll("_","-")}(${s})`);n.length&&r.set("transform",n.join(" "))}_macro_filter(e,t,r){let n=e===void 0?[]:[String(e)];for(let[i,s]of Object.entries(t))i==="rotate"?n.push(`hue-rotate(${s}deg)`):i==="blur"?n.push(`blur(${Pi(s)})`):i==="drop_shadow"?n.push(`drop-shadow(${s})`):n.push(`${i.replaceAll("_","-")}(${s})`);n.length&&r.set("filter",n.join(" "))}_macro_transition(e,t,r){e!==void 0&&r.set("transition",String(e));for(let[n,i]of Object.entries(t))r.set(`transition-${n.replaceAll("_","-")}`,String(i))}_macro_zoom(e,t,r){e!==void 0&&r.set("zoom",String(e))}_macro_shadow(e,t,r){e!==void 0&&r.set("box-shadow",String(e));for(let[n,i]of Object.entries(t))r.set(`box-shadow-${n.replaceAll("_","-")}`,String(i))}_macro_gradient(e,t,r){e!==void 0&&r.set("background-image",String(e))}};var bg=new Set(["alignment_baseline","baseline_shift","clip_path","clip_rule","color_interpolation","color_interpolation_filters","dominant_baseline","fill_opacity","fill_rule","flood_color","flood_opacity","font_family","font_size","font_size_adjust","font_stretch","font_style","font_variant","font_weight","glyph_orientation_horizontal","glyph_orientation_vertical","image_rendering","letter_spacing","lighting_color","marker_end","marker_mid","marker_start","overline_position","overline_thickness","paint_order","pointer_events","shape_rendering","stop_color","stop_opacity","strikethrough_position","strikethrough_thickness","stroke_dasharray","stroke_dashoffset","stroke_linecap","stroke_linejoin","stroke_miterlimit","stroke_opacity","stroke_width","text_anchor","text_decoration","text_rendering","underline_position","underline_thickness","unicode_bidi","word_spacing","writing_mode"]);function Jn(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[bg.has(e)?e.replaceAll("_","-"):e,t]))}var Gt=class extends Vt{static mode="svg";adaptAttrs(e){return Jn(e)}};var Kd={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"html",version:null,title:null,description:null},abstracts:{},elements:{svg:{doc:"Switch to the SVG dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to SVG from this node down. No ``render_tag``: ``<svg>`` is\n emitted verbatim (HTML5 has a native ``<svg>`` tag).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"svg"}},a:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},abbr:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},address:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},area:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},article:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},aside:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},audio:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},b:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},base:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},bdi:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},bdo:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},blockquote:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},body:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},br:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},button:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},canvas:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},caption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},cite:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},code:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},col:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},colgroup:{doc:null,sub_tags:"col,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},data:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},datalist:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,option,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dd:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},del_:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},details:{doc:null,sub_tags:"summary[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dfn:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dialog:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},div:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dl:{doc:null,sub_tags:"dd,div,dt,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dt:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},em:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},embed:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},fieldset:{doc:null,sub_tags:"legend[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figcaption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figure:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figcaption[0:1],figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},footer:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},form:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h1:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h2:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h3:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h4:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h5:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h6:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},head:{doc:null,sub_tags:"base[0:1],link,meta,noscript,script,style,template,title[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},header:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hgroup:{doc:null,sub_tags:"h1,h2,h3,h4,h5,h6,p,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},html:{doc:null,sub_tags:"head[0:1],body[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},i:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},iframe:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},img:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},input:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},ins:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},kbd:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},label:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},legend:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},li:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},link:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},main:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},map:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mark:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},menu:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},meta:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},meter:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},nav:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},noscript:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},object:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ol:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},optgroup:{doc:null,sub_tags:"div,legend,noscript,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},option:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,div,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},output:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},p:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},picture:{doc:null,sub_tags:"img[0:1],script,source,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pre:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},progress:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},q:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rp:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rt:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ruby:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},s:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},samp:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},script:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},search:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},section:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},select:{doc:null,sub_tags:"button,div,hr,noscript,optgroup,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},slot:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},small:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},source:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},span:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},strong:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},style:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sub:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},summary:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sup:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},table:{doc:null,sub_tags:"caption[0:1],colgroup,script,tbody,template,tfoot[0:1],thead[0:1],tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tbody:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},td:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},template:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,del_,details,dfn,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,legend,li,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,optgroup,option,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,tr,track,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textarea:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tfoot:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},th:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},thead:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},time:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tr:{doc:null,sub_tags:"script,td,template,th",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},track:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},u:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ul:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},var:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},video:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},wbr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},selectedcontent:{doc:"Mirror of the selected option for Customizable Select (HTML 2024).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var Je=class extends Ae{static _name="html";static _defaultRenderMode="html";static retainedAttrPrefixes=["validate_","dtype"];static{this.defineGrammar(Kd)}get renderer_html(){return new Wt(this)}};Ae.registerBuilder(Je);var Jd={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"svg",version:null,title:null,description:null},abstracts:{graphics:{doc:"SVG graphics content: any graphical element.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null},containerElement:{doc:"SVG container content: elements that can hold children.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null}},elements:{html:{doc:"Switch to the HTML dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to HTML from this node down. The source tag ``html`` is\n rendered as ``_meta['render_tag']`` (``<foreignObject>``) carrying\n ``_meta['render_attributes']`` (the SVG namespace). The immediate\n HTML child declares XHTML so both sides of the XML boundary retain\n their native namespace.\n ",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"html",render_tag:"foreignObject",render_attributes:{xmlns:"http://www.w3.org/2000/svg"}}},svg:{doc:"Root SVG container or nested SVG viewport.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},g:{doc:"Group container for applying transforms and styles.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},defs:{doc:"Container for referenced elements (gradients, patterns, etc.).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},symbol:{doc:"Reusable graphical template, rendered only when referenced by <use>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},use:{doc:"Reference and render a <symbol> or other element.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rect:{doc:"Rectangle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},circle:{doc:"Circle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ellipse:{doc:"Ellipse.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},line:{doc:"Line segment between two points.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polyline:{doc:"Open shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polygon:{doc:"Closed shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},path:{doc:"Arbitrary shape defined by path commands (d attribute).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},image:{doc:"Embedded raster image.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},text:{doc:"Text block. Contains text content and optional <tspan>/<textPath>.",sub_tags:"tspan,textPath",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tspan:{doc:"Inline text span within <text>.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textPath:{doc:"Text rendered along a path shape.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},linearGradient:{doc:"Linear gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},radialGradient:{doc:"Radial gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},stop:{doc:"Gradient stop (color and offset).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pattern:{doc:"Tile pattern definition. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},clipPath:{doc:"Clipping path definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mask:{doc:"Alpha mask definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},marker:{doc:"Marker symbol for line endpoints or vertices.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},filter:{doc:"Filter effect container. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feGaussianBlur:{doc:"Gaussian blur filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feOffset:{doc:"Offset filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feBlend:{doc:"Blend filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feColorMatrix:{doc:"Color matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feComposite:{doc:"Composite filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feFlood:{doc:"Flood fill filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMerge:{doc:"Merge filter primitive (container for feMergeNode).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMergeNode:{doc:"Single input for feMerge.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDropShadow:{doc:"Drop shadow filter primitive (SVG 2).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDiffuseLighting:{doc:"Diffuse lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpecularLighting:{doc:"Specular lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},fePointLight:{doc:"Point light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDistantLight:{doc:"Distant light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpotLight:{doc:"Spot light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMorphology:{doc:"Morphology filter primitive (erode/dilate).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTurbulence:{doc:"Turbulence noise filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDisplacementMap:{doc:"Displacement map filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feConvolveMatrix:{doc:"Convolution matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feImage:{doc:"Image filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTile:{doc:"Tile filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animate:{doc:"Animate an attribute over time.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateTransform:{doc:"Animate a transform attribute.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateMotion:{doc:"Animate motion along a path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},set:{doc:"Set an attribute to a value for a duration.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:"Accessible title (tooltip in browsers).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},desc:{doc:"Accessible description.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},metadata:{doc:"Metadata container (RDF, Dublin Core, etc.).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},a:{doc:"Hyperlink wrapper.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},foreignObject:{doc:"Container for non-SVG content (HTML, MathML).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},switch:{doc:"Conditional processing (renders first matching child).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var vt=class extends Ae{static _name="svg";static _defaultRenderMode="svg";static{this.defineGrammar(Jd)}get renderer_svg(){return new Gt(this)}};Ae.registerBuilder(vt);function Qe(o,e=new Set){if(!o||typeof o!="object")return;let t=o.ownerDocument?.defaultView?.Node??o.defaultView?.Node;if(Z(o)instanceof Se||t&&o instanceof t)throw new TypeError("Live Source/DOM references cannot cross a transport boundary");if(e.has(o))throw new TypeError("Transport data cannot contain circular references");e.add(o);let r=o instanceof x?o.getNodes().flatMap(n=>[n.staticValue,n.getAttr()]):Object.values(o);for(let n of r)Qe(n,e);e.delete(o)}var Qn=class{constructor(e=null){this.entries=new Map,this.sourceRoot=e}validate(e,t=new Set){let r=new Map,n=i=>{for(let s of i.getNodes()){let a=s.getAttr("__ref");if(a){if(r.has(a))throw new Error("Duplicate Source reference");let l=this.entries.get(a);if(e!==this.sourceRoot&&l&&l.node!==s&&!t.has(l.node))throw new Error("Duplicate Source reference");r.set(a,s)}s.value instanceof N&&n(s.value)}};n(e)}register(e,t){let r=e.getAttr("__ref");if(r){if(this.entries.has(r))throw new Error(`Duplicate Source reference: ${r}`);this.entries.set(r,{node:e,dom:t})}}remove(e){for(let[t,r]of this.entries)r.node===e&&this.entries.delete(t)}resolveArguments(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r&&typeof r=="object"&&Object.hasOwn(r,"$gramlotRef")?this.resolve(r):r]))}resolve(e){if(!e||!["node","dom"].includes(e.kind))throw new TypeError("Expected a node or DOM reference");let t=this.entries.get(e.$gramlotRef);if(!t)throw new Error("Source reference is not mounted");return t[e.kind]}};var ol={};ee(ol,{randomId:()=>G});function G(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),o=>o.toString(16).padStart(2,"0")).join("")}var Ne=class{constructor(e){this.gramlot=e}};var pr=class extends Error{name="RpcError";constructor({code:e,name:t,message:r,details:n}){super(r),this.code=e,this.remoteName=t,n!==void 0&&(this.details=n)}},eo=class extends Ne{constructor(e,{rpcUrl:t,closeUrl:r,document:n,transport:i}){super(e),this.transport=i===!1?null:i??e.serverAdapter.createTransport({rpcUrl:t,closeUrl:r,document:n,channel:e._pageStore}),this.remoteRequests=new Map}get supportsCallSync(){return this.transport?.supportsCallSync===!0}callSync(e,t,r={}){if(!this.supportsCallSync)throw new Error(`rpc '${t}': the transport of this page has no synchronous call`);if(Qe(r),this.gramlot.abort.signal.aborted)throw this.gramlot.abort.signal.reason;let n=G(),i=j(this.transport.callSync(R({id:n,pageId:this.gramlot.pageId,contentType:e,name:t,params:r})));if(i.id!==n)throw new Error("rpc response id mismatch");if(i.error)throw new pr(i.error);return i.value}async call(e,t,r={},n={}){return(await this.callEnvelope(e,t,r,n)).value}async callEnvelope(e,t,r={},{signal:n=null}={}){if(!this.transport?.call)throw new Error(`rpc '${t}' is unavailable without a server transport`);Qe(r);let i=G(),s=R({id:i,pageId:this.gramlot.pageId,contentType:e,name:t,params:r}),a=n?[this.gramlot.abort.signal,n]:[this.gramlot.abort.signal],l=a.find(f=>f.aborted);if(l)throw l.reason;let c=new AbortController,u=f=>c.abort(f.target.reason);for(let f of a)f.addEventListener("abort",u,{once:!0});let d=new Promise((f,h)=>{c.signal.addEventListener("abort",()=>{this.remoteRequests.delete(i),h(c.signal.reason)},{once:!0})});this.remoteRequests.set(i,c);try{let f=j(await Promise.race([this.transport.call(s,c.signal),d]));if(f.id!==i)throw new Error("rpc response id mismatch");if(f.error)throw new pr(f.error);return f}finally{this.remoteRequests.delete(i);for(let f of a)f.removeEventListener("abort",u)}}};var Bi=class{constructor(e,t,r){this.gramlot=e,this.window=r.defaultView,this.frames=e._frames,this.binders=new Map,this.calls=new Map,this.routes=new Map,this.error=null,this.closed=!1,this.ready=!1,this.socket=null;let n=new URL(t,r.baseURI);n.protocol=n.protocol==="https:"?"wss:":"ws:",this.endpoint=n.href,this.origin=this.window.location.origin,this.parent=this.frames.parent?.window??null,this.frames.registerChannel("server",{changed:i=>this.peerChanged(i),disconnected:i=>{i.parent&&this.parent?this.fail(new Error("PageStore parent disconnected")):this.forget(i.window)},receive:(i,s)=>{try{this.receive(i,s)}catch(a){this.fail(a)}}},{endpoint:this.endpoint,ready:!1}),this.address=n,this.parent||this.open()}terminalUrl(e){let t=new URL("terminal",this.endpoint);return t.searchParams.set("pageId",this.gramlot.pageId),t.searchParams.set("session",e),t.href}open(){let e=this.address;e.searchParams.set("pageId",this.gramlot.pageId),this.socket=new this.window.WebSocket(e.href),this.socket.addEventListener("open",()=>this.connected()),this.socket.addEventListener("message",t=>{try{this.deliver(t.data)}catch(r){this.fail(r)}}),this.socket.addEventListener("error",()=>this.fail(new Error("PageStore WebSocket failed"))),this.socket.addEventListener("close",t=>{this.closed||this.fail(new Error("PageStore disconnected ("+t.code+")"))})}peerChanged(e){if(this.closed||!e.parent||!this.parent)return;let t=e.channels.server;t?e.origin!==this.origin||t?.endpoint!==this.endpoint?this.fail(new Error("Parent does not provide the same PageStore endpoint")):t.ready?this.connected():this.ready&&this.fail(new Error("PageStore parent channel closed")):(this.parent=null,this.open())}connected(){if(!(this.closed||this.ready)){this.ready=!0,this.parent&&this.upstream({op:"attach",pageId:this.gramlot.pageId});for(let e of this.binders.values())this.subscribe(e);for(let e of this.calls.values())this.sendCall(e);this.frames.setChannelState("server",{endpoint:this.endpoint,ready:!0})}}receive(e,t){if(this.closed||e.origin!==this.origin||e.channels.server?.endpoint!==this.endpoint)return;if(e.parent){this.deliver(R(t));return}if(!this.ready)return;let r=t?.pageId;if(!(typeof r!="string"||!r||r===this.gramlot.pageId)){if(t.op==="attach"){if(this.routes.has(r))return;this.routes.set(r,e.window)}else if(this.routes.get(r)!==e.window)return;t.op==="detach"&&this.routes.delete(r),this.upstream(t)}}forget(e){for(let[t,r]of this.routes)r===e&&(this.routes.delete(t),this.ready&&!this.closed&&this.upstream({op:"detach",pageId:t}))}upstream(e){if(this.closed||!this.ready)throw new Error("PageStore is not connected");this.parent?this.frames.send(this.parent,"server",e):this.socket.send(R(e))}deliver(e){if(this.closed)return;let t=j(e);if(t.pageId===this.gramlot.pageId){if(t.op==="closed"){this.fail(new Error("PageStore page closed on the server"));return}if(!Object.hasOwn(t,"op")&&Object.hasOwn(t,"id")){this.calls.get(t.id)?.finish(null,e);return}if(t.op==="publish"){try{this.gramlot._subscriptions.publish(t.topic,t.payload,t.metadata)}catch(n){this.window.console.error("PageStore publication subscriber failed",n)}return}let r=this.binders.get(t.binderId);r&&r.apply(t)}else{let r=this.routes.get(t.pageId);r&&this.frames.send(r,"server",t)}}register(e){if(this.closed)throw new Error("PageStore connection is closed");this.binders.set(e.id,e),this.ready&&this.subscribe(e)}subscribe(e){this.send({op:"subscribe",binderId:e.id,path:e.serverPath})}unregister(e){this.binders.delete(e.id)&&!this.closed&&this.ready&&this.send({op:"unsubscribe",binderId:e.id})}send(e){this.upstream({...e,pageId:this.gramlot.pageId})}preparePublish(e,t){if(this.closed||!this.ready)throw new Error("PageStore is not connected");Qe(t);let r={op:"publish",id:G(),pageId:this.gramlot.pageId,topic:e.topic,payload:t};e.pageId!==void 0&&(r.targetPageId=e.pageId);let n=R(r);return async()=>{let i=j(await this.call(n));if(i.error)throw new pr(i.error);return i.value}}call(e,t){if(this.closed)return Promise.reject(this.error??new Error("PageStore connection is closed"));if(t?.aborted)return Promise.reject(t.reason);let r=j(e);return r.pageId!==this.gramlot.pageId||typeof r.id!="string"||!r.id||Object.hasOwn(r,"op")&&r.op!=="publish"||this.calls.has(r.id)?Promise.reject(new Error("Invalid or duplicate RPC identity")):new Promise((n,i)=>{let s={message:r,sent:!1,finish:(l,c)=>{this.calls.delete(r.id)&&(t?.removeEventListener("abort",a),c===void 0?i(l):n(c))}},a=()=>{if(s.finish(t.reason),s.sent&&this.ready&&!this.closed)try{this.send({op:"cancel",id:r.id})}catch(l){this.fail(l)}};this.calls.set(r.id,s),t?.addEventListener("abort",a,{once:!0}),this.ready&&this.sendCall(s)})}sendCall(e){try{this.upstream(e.message),e.sent=!0}catch(t){e.finish(t),this.fail(t)}}fail(e){this.error=e,this.close(),this.window.console.error("PageStore channel failed",e)}close(){if(!this.closed){if(this.closed=!0,this.parent&&this.ready&&this.frames.isConnected(this.parent))for(let e of[...this.routes.keys(),this.gramlot.pageId])this.frames.send(this.parent,"server",{op:"detach",pageId:e});this.ready=!1;for(let e of this.calls.values())e.finish(this.error??new Error("PageStore connection is closed"));this.binders.clear(),this.routes.clear(),this.frames.unregisterChannel("server"),this.socket?.close()}}};var Qd="gramlot:message",Mi=class{#e;#t;#r;#n=G();#o=new Map;#i=new Map;#s=!1;#a;#l;#c;#u;#d;constructor(e,t){this.#e=e,this.#r=t,this.#t=t.defaultView,this.#a=r=>this.#g(r),this.#l=r=>{if(r.target?.localName!=="iframe")return;let n=this.#v(r.target);n&&this.#w(n)},this.#c=r=>{r.persisted||this.#e.dispose({beacon:!0})},this.#u=()=>this.ready(),this.#t.addEventListener("message",this.#a),this.#t.addEventListener("pagehide",this.#c),this.#t.addEventListener("pageshow",this.#u),t.addEventListener("load",this.#l,!0)}#f(){this.#d===void 0&&(this.#d=this.#t.setInterval(()=>{if(this.parent?.window.closed){this.#p();return}for(let e of this.children)e.window.closed?this.#h(e.window):e.node&&!this.#v(this.#e.dom.getDomNode(e.node))&&this.#h(e.window,!0)},500))}get parent(){let e=this.#t.parent!==this.#t,t=e?this.#t.parent:this.#t.opener;return t?{window:t,parent:!0,kind:e?"iframe":"popup",origin:this.#x(this.#r.referrer||this.#r.baseURI)}:null}get children(){return[...this.#o.values()].filter(e=>!e.parent)}isConnected(e){return!this.#s&&this.#o.has(e)}connect(){this.parent&&(this.#f(),this.#w(this.parent));for(let e of this.#r.getElementsByTagName("iframe")){let t=this.#v(e);t&&this.#w(t)}}ready(){if(!this.#s){this.connect();for(let e of this.#o.values())this.#_(e)}}registerChannel(e,t,r){if(this.#s||e==="publish"||this.#i.has(e))throw new Error("Invalid family channel");this.#i.set(e,{handler:t,state:r});for(let n of this.#o.values())t.changed(n)}setChannelState(e,t){this.#i.get(e).state=t;for(let r of this.#o.values())this.#_(r)}unregisterChannel(e){if(this.#i.delete(e),this.#e.state!=="disposed")for(let t of this.#o.values())this.#_(t)}send(e,t,r){let n=this.#o.get(e);if(this.#s||!n)throw new Error("Destination page is not connected");Qe(r),this.#y(n,{kind:"message",recipient:n.session,channel:t,wire:R(r)})}prepare(e,t){let r=[];if(e.parent){if(!this.parent)throw new Error("This page has no parent frame or opener");r.push(this.parent)}if(e.iframe!==void 0){let s=e.iframe,a=Z(s),l=typeof s=="string"?this.#r.getElementById(s):a instanceof Se?this.#e.dom.getDomNode(a):null,c=this.#v(l);if(!c)throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");r.push(c)}if(e.pageId!==void 0){let s=this.children.find(a=>a.pageId===e.pageId);if(!s)throw new Error("pageId destination must be a registered direct Gramlot child");r.push(s)}let n=r.map(s=>{let a=this.#o.get(s.window);if(!a?.ready||a.origin!==s.origin)throw new Error("Destination page is not ready");return{...s,session:a.session}});Qe(t);let i=R({topic:e.topic,payload:t});return()=>{if(!this.#s)for(let s of n){let a=this.#E(s.window);if(!a||a.origin!==s.origin||this.#o.get(s.window)?.session!==s.session)throw new Error("Destination page disconnected before publication");this.#y(s,{kind:"message",recipient:s.session,channel:"publish",wire:i})}}}dispose(){if(this.#s)return;for(let t of this.children)this.#h(t.window,!0);let e=this.parent;e&&this.#o.has(e.window)&&(this.#y(this.#o.get(e.window),{kind:"close"}),this.#h(e.window)),this.#s=!0,this.#i.clear(),this.#t.removeEventListener("message",this.#a),this.#t.removeEventListener("pagehide",this.#c),this.#t.removeEventListener("pageshow",this.#u),this.#t.clearInterval(this.#d),this.#r.removeEventListener("load",this.#l,!0)}#p(){this.#e.dispose({beacon:!0}),this.#t.parent===this.#t&&this.#t.opener&&this.#t.close()}#h(e,t=!1){let r=this.#o.get(e);if(r){t&&this.#y(r,{kind:"close"}),this.#o.delete(e),r.release?.();for(let{handler:n}of this.#i.values())n.disconnected(r);t&&r.kind==="popup"&&!r.parent&&e.close()}}#m(e,t){let r=this.#o.get(e.window),n=r?.session!==t.session;n&&this.#h(e.window);let i=n?{...e,session:t.session}:r;Object.assign(i,{ready:t.ready===!0,pageId:t.pageId,channels:t.channels}),this.#o.set(e.window,i),this.#f(),n&&e.node&&(i.release=this.#e.src.binding.bindingFor(e.node).track(()=>{this.#h(e.window,!0)}));for(let{handler:s}of this.#i.values())s.changed(i);return n}#g(e){if(this.#s||e.data?.type!==Qd)return;let t=this.#E(e.source);if(!t||e.origin!==t.origin)return;let r=e.data;if(typeof r.session!="string"||!r.session)return;if(r.kind==="hello"||r.kind==="ready"){if(r.kind==="ready"&&r.recipient!==this.#n||!r.channels||typeof r.channels!="object"||Array.isArray(r.channels))return;let i=this.#m(t,r);(r.kind==="hello"||i)&&this.#_(this.#o.get(t.window));return}let n=this.#o.get(t.window);if(!(!n||n.session!==r.session||r.recipient!==this.#n)){if(r.kind==="close")t.parent?this.#p():this.#h(t.window);else if(r.kind==="message"&&typeof r.wire=="string"){let i=j(r.wire);if(r.channel==="publish"){if(this.#e.state!=="started"||!n.ready||typeof i.topic!="string"||!i.topic)return;this.#e.publish(i.topic,i.payload)}else this.#i.get(r.channel)?.handler.receive(n,i)}}}#b(){return{pageId:this.#e.pageId,ready:this.#e.state==="started",channels:Object.fromEntries([...this.#i].map(([e,t])=>[e,t.state]))}}#w(e){this.#y(e,{kind:"hello",...this.#b()})}#_(e){this.#y(e,{kind:"ready",recipient:e.session,...this.#b()})}#y(e,t){e.window.postMessage({type:Qd,session:this.#n,recipient:e.session,...t},e.origin==="null"?"*":e.origin)}#v(e){if(e?.localName!=="iframe"||!e.isConnected||!e.contentWindow)return null;let t=this.#e.dom.getBaseSourceNode(e);if(!t||!this.#e.src.binding.bindingFor(t)||this.#e.dom.getDomNode(t)!==e)return null;let r=e.getAttribute("sandbox"),i=r!==null&&!r.split(/\s+/).includes("allow-same-origin")?"null":this.#x(e.hasAttribute("srcdoc")?this.#r.baseURI:e.getAttribute("src")||this.#r.baseURI);return{window:e.contentWindow,origin:i,node:t,parent:!1,kind:"iframe"}}#x(e){let t=new URL(e,this.#r.baseURI);return t.protocol==="file:"?"null":t.origin}#E(e){let t=this.parent;if(t?.window===e)return t;for(let r of this.#r.getElementsByTagName("iframe")){let n=this.#v(r);if(n?.window===e)return n}try{if(e&&e!==this.#t&&e.opener===this.#t&&e.location.origin===this.#t.location.origin)return{window:e,origin:this.#x(this.#r.baseURI),parent:!1,kind:"popup"}}catch{}return null}};var mr=class o{#e;constructor(e,t=0){this.pattern=e,this.flags=t,this.#e=hr.fromJSON({nameSyntax:{kind:"annotated",base:{kind:"type",module:"builtins",name:"str"},metadata:[this.toJSON()]}}).resolve("nameSyntax").test,Object.freeze(this)}static fromJSON(e){if((e!==null&&typeof e=="object"?Object.keys(e).sort():[]).join()!=="flags,kind,pattern"||e.kind!=="regex")throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(e)}`);return new o(e.pattern,e.flags)}toJSON(){return{kind:"regex",pattern:this.pattern,flags:this.flags}}matches(e){return this.#e(e)}},to=new mr(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);var cl={};ee(cl,{createLabelbox:()=>al,labelboxContent:()=>Ie,labelboxPositions:()=>Fi,labelboxPresentation:()=>Ht,labelboxStyle:()=>sl,projectLabelbox:()=>ll});var il={};ee(il,{choiceCaption:()=>ro,parseChoices:()=>gr});function gr(o,e=","){if(typeof e!="string"||!e)throw new TypeError("separator must be a nonempty string");if(o==="")return[];let t=new Set;return o.split(e).map(r=>{let n=r.indexOf(":"),i=n<0?r:r.slice(0,n),s=n<0?r:r.slice(n+1);if(!i||t.has(i))throw new Error("Invalid or duplicate choice code");return t.add(i),{id:i,caption:s}})}function ro(o,e,t=""){return o.find(r=>r.id===e)?.caption??t??""}var Li=class{constructor(e,t){this.layout=e;let r=e.box.ownerDocument;this.button=r.createElement("button"),this.button.type="button",this.button.className="label-menu-trigger",this.button.setAttribute("aria-haspopup","menu"),this.button.setAttribute("aria-expanded","false"),this.menu=r.createElement("gramlot-menu"),this.menu.projectAttributes({}),e.labelBox.append(this.button,this.menu),this.button.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),this.menu.opened?this.menu.close():this.menu.open(this.button)}),this.button.addEventListener("keydown",n=>{["ArrowDown","ArrowUp"].includes(n.key)&&(n.preventDefault(),n.stopPropagation(),this.menu.open(this.button,n.key==="ArrowUp"))}),this.choose=t}project({lbl:e,lbl_value:t,lbl_values:r,disabled:n,readonly:i},s){let a=gr(r);if(this.values!==r){this.menu.close(!1);for(let c of this.menu.items)c.releaseCommand();this.menu.replaceChildren(...a.map(({id:c,caption:u})=>{let d=this.menu.ownerDocument.createElement("gramlot-menu-line");return d.projectAttributes({code:c,caption:u},s),d.activateCommand=f=>{d.prepareCommand(f)&&this.choose(c)},d.control.addEventListener("click",f=>d.activateCommand(f)),d})),this.values=r}let l=ro(a,t,e);this.button.textContent=l,this.button.disabled=!!(n||i||!a.length),this.button.disabled&&this.menu.close(!1);for(let c of this.menu.items)c.projectAttributes({...c.parameters,checked:c.parameters.code===t},s);this.layout.fieldLabel.textContent=l,this.layout.fieldLabel.hidden=!0,this.layout.labelBox.hidden=!1}dispose(){this.menu.close(!1);for(let e of this.menu.items)e.releaseCommand();this.menu.remove(),this.button.remove(),this.layout.fieldLabel.hidden=!1}};var Fi=["TL","TC","TR","L","R","BL","BC","BR"],sl=`.gramlot-labelbox>.label-box>.label-menu-trigger{font:inherit;color:inherit;background:transparent;border:0;padding:0;min-width:0;min-height:var(--gramlot-touch-target,0px);height:auto;display:inline-flex;align-items:center;gap:.4em;cursor:pointer;text-align:inherit;line-height:inherit}
36
36
  .gramlot-labelbox>.label-box>.label-menu-trigger::after{content:'';width:.35em;height:.35em;border-right:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:translateY(-.1em) rotate(45deg);flex:none}
37
37
  .gramlot-labelbox>.label-box>.label-menu-trigger:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:3px;border-radius:2px}
38
38
  .gramlot-labelbox>.label-box>.label-menu-trigger:disabled{opacity:.5;cursor:default}
@@ -84,7 +84,7 @@ ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}
84
84
  .gramlot-labelbox>.tray-resize[hidden]{display:none}
85
85
  .gramlot-labelbox>.tray-resize svg{width:16px;height:16px;pointer-events:none}
86
86
  .gramlot-labelbox>.tray-resize:hover,.gramlot-labelbox>.tray-resize:focus-visible{opacity:1}
87
- .gramlot-labelbox>.tray-resize:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}`;function sl(o,e){let t=o.createElement("div"),r=o.createElement("div"),n=o.createElement("label");r.append(n),t.append(r,e);let i={box:t,labelBox:r,fieldLabel:n,controlBox:e,previous:{box:{},label:{},labelBox:{},controlBox:{}}};return t.labelbox=i,i}function al(o,e,t){let{lbl:r,lbl_value:n,lbl_values:i,lbl_variant:s,lbl_position:a=s==="card"?"TC":"TL",...l}=e;if(!Li.includes(a))throw new TypeError(`Invalid lbl_position: ${a}`);let c={box:{},label:{},labelBox:{},controlBox:{}},u=[["box_l_","labelBox"],["box_c_","controlBox"],["lbl_","label"],["box_","box"]];for(let[f,h]of Object.entries(l)){let p=u.find(([m])=>f.startsWith(m));p&&(c[p[1]][f.slice(p[0].length)]=h,delete l[f])}let d={box:o.box,label:o.fieldLabel,labelBox:o.labelBox,controlBox:o.controlBox};for(let[f,h]of Object.entries(d)){let p=t(c[f]),m=o.previous[f];for(let b of new Set([...Object.keys(m),...Object.keys(p)]))p[b]==null?h.removeAttribute(b):h.setAttribute(b,String(p[b]));o.previous[f]=p}return e.lbl_width==null?o.box.style.removeProperty("--gramlot-label-width"):o.box.style.setProperty("--gramlot-label-width",e.lbl_width),o.box.classList.add("labelbox","gramlot-labelbox"),o.labelBox.classList.add("label-box"),o.controlBox.classList.add("control-box"),o.box.dataset.position=a,s==null?delete o.box.dataset.variant:o.box.dataset.variant=s,o.fieldLabel.textContent=r??"",o.labelBox.hidden=r==null||r==="",i!=null?(o.menu??=new Mi(o,f=>o.choose(f)),o.menu.project(e,t)):o.menu&&(o.menu.dispose(),o.menu=null),o.box.dispatchEvent(new o.box.ownerDocument.defaultView.Event("gramlot-label-layout",{bubbles:!0})),l}function Ie(o){return o?.labelbox?o.labelbox.controlBox.firstElementChild:o}function Ht(o){let e=o?.parentElement?.parentElement;return e?.labelbox&&Ie(e)===o?e:o}var ul={};ee(ul,{choiceFieldStyles:()=>cl});var cl=`
87
+ .gramlot-labelbox>.tray-resize:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}`;function al(o,e){let t=o.createElement("div"),r=o.createElement("div"),n=o.createElement("label");r.append(n),t.append(r,e);let i={box:t,labelBox:r,fieldLabel:n,controlBox:e,previous:{box:{},label:{},labelBox:{},controlBox:{}}};return t.labelbox=i,i}function ll(o,e,t){let{lbl:r,lbl_value:n,lbl_values:i,lbl_variant:s,lbl_position:a=s==="card"?"TC":"TL",...l}=e;if(!Fi.includes(a))throw new TypeError(`Invalid lbl_position: ${a}`);let c={box:{},label:{},labelBox:{},controlBox:{}},u=[["box_l_","labelBox"],["box_c_","controlBox"],["lbl_","label"],["box_","box"]];for(let[f,h]of Object.entries(l)){let p=u.find(([m])=>f.startsWith(m));p&&(c[p[1]][f.slice(p[0].length)]=h,delete l[f])}let d={box:o.box,label:o.fieldLabel,labelBox:o.labelBox,controlBox:o.controlBox};for(let[f,h]of Object.entries(d)){let p=t(c[f]),m=o.previous[f];for(let b of new Set([...Object.keys(m),...Object.keys(p)]))p[b]==null?h.removeAttribute(b):h.setAttribute(b,String(p[b]));o.previous[f]=p}return e.lbl_width==null?o.box.style.removeProperty("--gramlot-label-width"):o.box.style.setProperty("--gramlot-label-width",e.lbl_width),o.box.classList.add("labelbox","gramlot-labelbox"),o.labelBox.classList.add("label-box"),o.controlBox.classList.add("control-box"),o.box.dataset.position=a,s==null?delete o.box.dataset.variant:o.box.dataset.variant=s,o.fieldLabel.textContent=r??"",o.labelBox.hidden=r==null||r==="",i!=null?(o.menu??=new Li(o,f=>o.choose(f)),o.menu.project(e,t)):o.menu&&(o.menu.dispose(),o.menu=null),o.box.dispatchEvent(new o.box.ownerDocument.defaultView.Event("gramlot-label-layout",{bubbles:!0})),l}function Ie(o){return o?.labelbox?o.labelbox.controlBox.firstElementChild:o}function Ht(o){let e=o?.parentElement?.parentElement;return e?.labelbox&&Ie(e)===o?e:o}var dl={};ee(dl,{choiceFieldStyles:()=>ul});var ul=`
88
88
  .choice-field{position:relative;min-width:0}
89
89
  .choice-field>input{box-sizing:border-box;width:100%;padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .4em)}
90
90
  .choice-field>.choice-toggle{position:absolute;inset-inline-end:1px;inset-block:1px;
@@ -96,7 +96,7 @@ ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}
96
96
  .choice-toggle:disabled{opacity:.5;cursor:default}
97
97
  .choice-toggle:focus-visible{outline:1px solid var(--gramlot-focus-ring,Highlight);outline-offset:-3px}
98
98
  .choice-field>input::-webkit-calendar-picker-indicator{opacity:0}
99
- `;var yg=/^[a-z][.0-9_a-z\-\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*$/u,vg=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function xt(o){let e=o.code;if(typeof e!="string"||yg.exec(e)?.[0]!==e||!e.includes("-")||vg.has(e))throw new TypeError("webcomponent: code must be a literal custom-element name");return e}function dl(o){for(let e of Object.values(o))e&&typeof e=="object"&&dl(e);return Object.freeze(o)}function ef(o){if(!o.annotation&&typeof o.dtype!="string"&&!Array.isArray(o.dtype))throw new TypeError("Component parameter requires dtype");let e=o.annotation?[structuredClone(o.annotation)]:(Array.isArray(o.dtype)?o.dtype:[o.dtype]).map(t=>({kind:"dtype",dtype:t}));return o.nullable&&e.push({kind:"dtype",dtype:"NN"}),o.binding&&o.dtype!=="T"&&e.push({kind:"annotated",base:{kind:"dtype",dtype:"T"},metadata:[{kind:"regex",pattern:"^[\\^=].+",flags:0}]}),e.length===1?e[0]:{kind:"union",items:e}}function Yt({name:o,tag:e,base:t,doc:r=null,mixins:n=[],parameters:i={},subTags:s="",presentationDefaults:a=[],dataScope:l=!1,command:c=!1,childParameters:u={},sourceContext:d=!1,bagStore:f=!1,bagStruct:h=!1,dragSource:p=!1,implementation:m}){if(xt({code:e}),!/^[a-zA-Z][a-zA-Z0-9]*$/.test(o))throw new TypeError("Invalid component authoring name");let b={...t.parameters};for(let w of n)for(let[_,v]of Object.entries(w.parameters)){if(Object.hasOwn(b,_))throw new Error(`Duplicate mixin parameter: ${_}`);b[_]=v}Object.assign(b,i);for(let w of Object.values(b))if(ef(w),w.required!==void 0&&(w.required!==!0||Object.hasOwn(w,"default")))throw new TypeError("A required component parameter is true and has no default");return Object.freeze({name:o,tag:e,base:t,doc:r,subTags:s,presentationDefaults:Object.freeze([...a]),dataScope:l,command:c,bagStore:f,bagStruct:h,mixins:Object.freeze([...n]),labelbox:n.some(w=>w.labelbox===!0),parameters:dl(structuredClone(b)),childParameters:dl(structuredClone(u)),sourceContext:d,dragSource:p,implementation:m})}var Xt=class o{#e=new WeakMap;constructor({name:e,components:t,dependencies:r=[],css:n=[],assets:i={},registerCommands:s=()=>{}}){if(typeof e!="string"||!e)throw new TypeError("Collection name must be nonempty");if(!Array.isArray(r)||r.some(c=>!(c instanceof o)))throw new TypeError("Collection dependencies must be collection objects");if(!Array.isArray(n)||n.some(c=>!(c instanceof URL))||!i||typeof i!="object"||Array.isArray(i)||Object.values(i).some(c=>!(c instanceof URL)))throw new TypeError("Collection css/assets require URL objects");if(typeof s!="function")throw new TypeError("registerCommands must be a function");this.dependencies=Object.freeze([...r]),this.css=Object.freeze([...n]),this.assets=Object.freeze({...i}),this.registerCommands=s,this.name=e,this.components=Object.freeze([...t]);let a=new Set,l=new Set;for(let c of t){if(a.has(c.name.toLowerCase())||l.has(c.tag))throw new Error(`Duplicate component: ${c.name}`);a.add(c.name.toLowerCase()),l.add(c.tag)}}toDocument(){return{document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:this.name,version:null,title:this.name,description:null},abstracts:{},elements:Object.fromEntries(this.components.map(e=>[e.name,{doc:e.doc,sub_tags:e.subTags,parent_tags:null,inherits_from:null,ns:null,node_label:null,collection_key:null,attributes:{parameters:[...Object.entries(e.parameters).map(([t,r])=>({name:t,kind:"keyword_only",role:"attribute",annotation:ef(r),...r.required?{has_default:!1}:{has_default:!0,default:r.default??null}})),{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:{render_tag:e.tag,gramlot_component:{parameters:structuredClone(e.parameters),presentationDefaults:[...e.presentationDefaults],dataScope:e.dataScope,command:e.command,...Object.keys(e.childParameters).length?{childParameters:structuredClone(e.childParameters)}:{},...e.sourceContext?{sourceContext:!0}:{},...e.labelbox?{labelbox:!0}:{},...e.dragSource?{dragSource:!0}:{},...e.bagStore?{bagStore:!0}:{},...e.bagStruct?{bagStruct:!0}:{}}}}]))}}register(e){if(this.#e.has(e))return;let t=[];for(let r of this.components){if(e.customElements.get(r.tag))throw new Error(`Custom element already registered: ${r.tag}`);let n=r.base(e.HTMLElement);for(let s of r.mixins)n=s(n);let i=r.implementation(n);Object.defineProperty(i,"gramlotComponent",{value:r}),t.push([r.tag,i])}for(let[r,n]of t)e.customElements.define(r,n);this.#e.set(e,t)}};function fl(o){return new Xt(o)}var gl={};ee(gl,{ChoiceGroup:()=>ml,NativeControl:()=>pl,controlElement:()=>ro});var hl={};ee(hl,{parameterValues:()=>Fi,projectParameters:()=>br});function br(o,e){return o.parameters=Fi(o.constructor.gramlotComponent,e),Object.fromEntries(Object.entries(e).filter(([t])=>!Object.hasOwn(o.parameters,t)))}function Fi(o,e){return Object.fromEntries(Object.entries(o.parameters).map(([t,r])=>[t,Object.hasOwn(e,t)?e[t]:r.default]))}function ro(o){return class extends o{constructor(){super();let e=this.attachShadow({mode:"open"}),t=this.ownerDocument.createElement("style");t.textContent=`:host{display:inline-block;font:inherit} *,*::before,*::after{box-sizing:border-box}
99
+ `;var yg=/^[a-z][.0-9_a-z\-\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*$/u,vg=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function xt(o){let e=o.code;if(typeof e!="string"||yg.exec(e)?.[0]!==e||!e.includes("-")||vg.has(e))throw new TypeError("webcomponent: code must be a literal custom-element name");return e}function fl(o){for(let e of Object.values(o))e&&typeof e=="object"&&fl(e);return Object.freeze(o)}function ef(o){if(!o.annotation&&typeof o.dtype!="string"&&!Array.isArray(o.dtype))throw new TypeError("Component parameter requires dtype");let e=o.annotation?[structuredClone(o.annotation)]:(Array.isArray(o.dtype)?o.dtype:[o.dtype]).map(t=>({kind:"dtype",dtype:t}));return o.nullable&&e.push({kind:"dtype",dtype:"NN"}),o.binding&&o.dtype!=="T"&&e.push({kind:"annotated",base:{kind:"dtype",dtype:"T"},metadata:[{kind:"regex",pattern:"^[\\^=].+",flags:0}]}),e.length===1?e[0]:{kind:"union",items:e}}function Yt({name:o,tag:e,base:t,doc:r=null,mixins:n=[],parameters:i={},subTags:s="",presentationDefaults:a=[],dataScope:l=!1,command:c=!1,childParameters:u={},sourceContext:d=!1,bagStore:f=!1,bagStruct:h=!1,dragSource:p=!1,implementation:m}){if(xt({code:e}),!/^[a-zA-Z][a-zA-Z0-9]*$/.test(o))throw new TypeError("Invalid component authoring name");let b={...t.parameters};for(let w of n)for(let[_,v]of Object.entries(w.parameters)){if(Object.hasOwn(b,_))throw new Error(`Duplicate mixin parameter: ${_}`);b[_]=v}Object.assign(b,i);for(let w of Object.values(b))if(ef(w),w.required!==void 0&&(w.required!==!0||Object.hasOwn(w,"default")))throw new TypeError("A required component parameter is true and has no default");return Object.freeze({name:o,tag:e,base:t,doc:r,subTags:s,presentationDefaults:Object.freeze([...a]),dataScope:l,command:c,bagStore:f,bagStruct:h,mixins:Object.freeze([...n]),labelbox:n.some(w=>w.labelbox===!0),parameters:fl(structuredClone(b)),childParameters:fl(structuredClone(u)),sourceContext:d,dragSource:p,implementation:m})}var Xt=class o{#e=new WeakMap;constructor({name:e,components:t,dependencies:r=[],css:n=[],assets:i={},registerCommands:s=()=>{}}){if(typeof e!="string"||!e)throw new TypeError("Collection name must be nonempty");if(!Array.isArray(r)||r.some(c=>!(c instanceof o)))throw new TypeError("Collection dependencies must be collection objects");if(!Array.isArray(n)||n.some(c=>!(c instanceof URL))||!i||typeof i!="object"||Array.isArray(i)||Object.values(i).some(c=>!(c instanceof URL)))throw new TypeError("Collection css/assets require URL objects");if(typeof s!="function")throw new TypeError("registerCommands must be a function");this.dependencies=Object.freeze([...r]),this.css=Object.freeze([...n]),this.assets=Object.freeze({...i}),this.registerCommands=s,this.name=e,this.components=Object.freeze([...t]);let a=new Set,l=new Set;for(let c of t){if(a.has(c.name.toLowerCase())||l.has(c.tag))throw new Error(`Duplicate component: ${c.name}`);a.add(c.name.toLowerCase()),l.add(c.tag)}}toDocument(){return{document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:this.name,version:null,title:this.name,description:null},abstracts:{},elements:Object.fromEntries(this.components.map(e=>[e.name,{doc:e.doc,sub_tags:e.subTags,parent_tags:null,inherits_from:null,ns:null,node_label:null,collection_key:null,attributes:{parameters:[...Object.entries(e.parameters).map(([t,r])=>({name:t,kind:"keyword_only",role:"attribute",annotation:ef(r),...r.required?{has_default:!1}:{has_default:!0,default:r.default??null}})),{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:{render_tag:e.tag,gramlot_component:{parameters:structuredClone(e.parameters),presentationDefaults:[...e.presentationDefaults],dataScope:e.dataScope,command:e.command,...Object.keys(e.childParameters).length?{childParameters:structuredClone(e.childParameters)}:{},...e.sourceContext?{sourceContext:!0}:{},...e.labelbox?{labelbox:!0}:{},...e.dragSource?{dragSource:!0}:{},...e.bagStore?{bagStore:!0}:{},...e.bagStruct?{bagStruct:!0}:{}}}}]))}}register(e){if(this.#e.has(e))return;let t=[];for(let r of this.components){if(e.customElements.get(r.tag))throw new Error(`Custom element already registered: ${r.tag}`);let n=r.base(e.HTMLElement);for(let s of r.mixins)n=s(n);let i=r.implementation(n);Object.defineProperty(i,"gramlotComponent",{value:r}),t.push([r.tag,i])}for(let[r,n]of t)e.customElements.define(r,n);this.#e.set(e,t)}};function hl(o){return new Xt(o)}var bl={};ee(bl,{ChoiceGroup:()=>gl,NativeControl:()=>ml,controlElement:()=>no});var pl={};ee(pl,{parameterValues:()=>zi,projectParameters:()=>br});function br(o,e){return o.parameters=zi(o.constructor.gramlotComponent,e),Object.fromEntries(Object.entries(e).filter(([t])=>!Object.hasOwn(o.parameters,t)))}function zi(o,e){return Object.fromEntries(Object.entries(o.parameters).map(([t,r])=>[t,Object.hasOwn(e,t)?e[t]:r.default]))}function no(o){return class extends o{constructor(){super();let e=this.attachShadow({mode:"open"}),t=this.ownerDocument.createElement("style");t.textContent=`:host{display:inline-block;font:inherit} *,*::before,*::after{box-sizing:border-box}
100
100
  input,textarea{font:inherit;max-width:100%} .control-box{min-width:0;color:var(--gramlot-ink,CanvasText)}
101
101
  input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea{
102
102
  appearance:none;box-sizing:border-box;width:100%;border:1px solid var(--gramlot-border-control,#7a8798);
@@ -112,7 +112,7 @@ ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}
112
112
  input[type=range],input[type=color],button{min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
113
113
  input[type=checkbox],input[type=radio]{min-width:calc(var(--gramlot-touch-target,0px) / 2);min-height:calc(var(--gramlot-touch-target,0px) / 2)}
114
114
  .options{display:grid;gap:.3em .8em} .option{display:flex;align-items:center;gap:.35em;min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
115
- .caption:empty{display:none}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",e.append(t,this.controlBox)}projectAttributes(e){return br(this,e)}setPageContext(e){this.pageContext=e}connectedCallback(){}releaseControl(){}get liveWrites(){return this.control.localName==="textarea"||["text","password","range","color"].includes(this.control.type)}validateCandidate(e,t){return t(e),{ok:!0,value:e,isCurrent:()=>this.pageContext.isActive()}}finishValidation(){}validationValueCheck(){return this.constructor.validationValueCheck(this.pageContext)}static validationValueCheck(){let e=this.gramlotComponent.parameters.value.nullable;return(t,r)=>{if(t==null&&!e)throw new TypeError("This component requires a non-null value.");if(t!=null&&r!=null&&typeof t!=typeof r)throw new TypeError("Validation must preserve the component value type.")}}validationSelection(){return this.constructor.validationSelection(this.parameters,this.pageContext)}static validationSelection(){return()=>{throw new TypeError("validate_select requires a constrained choice editor.")}}validateSelection(e){return this.validationSelection()(e)}shouldProjectControlValue(){return!0}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>{this.validationValueCheck()(t,e),this.sameControlValue(e,t)||this.writeControlValue(t)})}restoreFormDraft(e){this.control.value=e}restoreFormValue(e){this.writeControlValue(e)}sameControlValue(e,t){return Object.is(e,t)}focus(e){this.control.focus(e)}}}function pl(o){return class extends ro(o){constructor(){super(),this.control=this.createControl(),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.setAttribute("autocomplete","off"),this.control.setAttribute("autocorrect","off"),this.control.setAttribute("autocapitalize","off"),this.control.setAttribute("spellcheck","false")),this.control.id="control";let e=this.ownerDocument.createElement("label");e.className="option",this.optionCaption=this.ownerDocument.createElement("span"),this.optionCaption.className="caption",e.append(this.control,this.optionCaption),this.controlBox.append(e)}projectAttributes(e,t){let r=super.projectAttributes(e,t),{disabled:n,readonly:i}=this.parameters;this.control.disabled=!!n,this.control.readOnly=!!i;for(let[s,a]of Object.entries(this.constructor.gramlotComponent.parameters)){if(a.target==="control"){let l=this.parameters[s]??"";String(this.control[s])!==String(l)&&(this.control[s]=l)}a.target==="optionCaption"&&(this.optionCaption.textContent=this.parameters[s]??"")}return r}}}pl.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"},live:{dtype:"B",default:!1,binding:"read"}};function ml(o){return class extends ro(o){#e=new Map;#t;#r=null;constructor(){super(),this.control=this.ownerDocument.createElement("div"),this.control.className="options",this.control.id="control",this.control.setAttribute("role",this.multiple?"group":"radiogroup"),this.controlBox.append(this.control),this.control.addEventListener("keydown",e=>{if(!this.multiple||!["ArrowDown","ArrowUp","ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;let t=[...this.control.querySelectorAll("input:not(:disabled)")],r=t.indexOf(e.target);if(r<0)return;e.preventDefault();let n=e.key==="Home"?0:e.key==="End"?t.length-1:Math.max(0,Math.min(t.length-1,r+(["ArrowDown","ArrowRight"].includes(e.key)?1:-1)));t[n].focus()})}choiceOptions(){return gr(this.parameters.values??"")}projectAttributes(e,t){let r=super.projectAttributes(e,t),n=this.choiceOptions(),i=JSON.stringify(n);if(i!==this.#t){let a=n,l=new Set,c=null;for(let{id:u,caption:d}of a){let f=this.#e.get(u);if(!f){let p=this.ownerDocument.createElement("label");p.className="option";let m=this.ownerDocument.createElement("input");m.type=this.choiceType,m.name="choice",m.value=u;let b=this.ownerDocument.createElement("span");p.append(m,b),f={label:p,input:m,text:b},this.#e.set(u,f)}f.text.textContent=d;let h=c?c.nextSibling:this.control.firstChild;h!==f.label&&this.control.insertBefore(f.label,h),c=f.label,l.add(u)}for(let[u,d]of this.#e)l.has(u)||(d.label.remove(),this.#e.delete(u));this.#t=i}let s=this.parameters.cols;if(!Number.isInteger(s)||s<1)throw new TypeError("cols must be a positive integer");this.control.style.gridTemplateColumns=`repeat(${s}, minmax(0, 1fr))`,this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly;for(let{input:a}of this.#e.values())a.disabled=this.control.disabled||this.control.readOnly;return r}readControlValue(){if(this.multiple){let t=(this.#r?this.#r.split(","):[]).filter(r=>!this.#e.has(r)||this.#e.get(r).input.checked);for(let[r,{input:n}]of this.#e)n.checked&&!t.includes(r)&&t.push(r);return t.join(",")||null}for(let[e,{input:t}]of this.#e)if(t.checked)return e;return null}writeControlValue(e){this.#r=e;let t=this.multiple?new Set(e?e.split(","):[]):null;for(let[r,{input:n}]of this.#e)n.checked=this.multiple?t.has(r):r===e}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>this.writeControlValue(t))}focus(e){let t=[...this.#e.values()];(t.find(({input:r})=>r.checked&&!r.disabled)??t.find(({input:r})=>!r.disabled))?.input.focus(e)}}}ml.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"}};var bl={};ee(bl,{positionPopup:()=>wr});function wr(o,e,{align:t="start",matchWidth:r=!1,inset:n=0,placement:i="bottom",point:s=null}={}){let a=e.ownerDocument.defaultView,l=s?{left:s.x,right:s.x,top:s.y,bottom:s.y,width:0}:e.getBoundingClientRect(),c=Math.max(0,a.innerWidth-16);o.style.setProperty("--gramlot-popup-available-width",`${c}px`),r&&(o.style.width=`${Math.min(Math.max(0,l.width-2*n),c)}px`),o.style.removeProperty("--gramlot-popup-available-height");let u=o.getBoundingClientRect();if(i==="side"){let w=Math.max(0,a.innerWidth-8-l.right-3),_=Math.max(0,l.left-8-3),v=u.width>w&&_>w;o.style.setProperty("--gramlot-popup-available-width",`${v?_:w}px`),o.style.setProperty("--gramlot-popup-available-height",`${Math.max(0,a.innerHeight-16)}px`);let E=o.getBoundingClientRect(),D=v?l.left-E.width-3:l.right+3;o.style.left=`${Math.max(8,Math.min(D,a.innerWidth-E.width-8))}px`,o.style.top=`${Math.max(8,Math.min(l.top,a.innerHeight-E.height-8))}px`;return}let d=Math.max(0,a.innerHeight-8-l.bottom-3),f=Math.max(0,l.top-8-3),h=u.height>d&&f>d;o.style.setProperty("--gramlot-popup-available-height",`${h?f:d}px`);let p=o.getBoundingClientRect(),m=t==="end"?l.right-p.width-n:l.left+n,b=h?l.top-p.height-3:l.bottom+3;o.style.left=`${Math.max(8,Math.min(m,a.innerWidth-p.width-8))}px`,o.style.top=`${Math.max(8,Math.min(b,a.innerHeight-p.height-8))}px`}var xl={};ee(xl,{SVG_NS:()=>kt,XHTML_NS:()=>be,boundaryAttributes:()=>io,displayItem:()=>un,domNames:()=>cn,isExpression:()=>Le,requireNoScriptAttributes:()=>vr,requireStyleClassAttributes:()=>yr,splitNativeAttributes:()=>vl,textValue:()=>_r,withDataSrcdocSandbox:()=>yl,withoutBindingAttributes:()=>Et,withoutNullValues:()=>xr});var _l={};ee(_l,{applyMask:()=>no,formatValue:()=>oo,validateMask:()=>wl});var ln=new Map;function zi(o,e,t){let r=JSON.stringify([o,e,t]),n=ln.get(r);if(n)ln.delete(r);else{let i=o?Intl.DateTimeFormat:Intl.NumberFormat;if(!i.supportedLocalesOf([e]).length)throw new RangeError(`Unsupported format locale: ${e}`);n=new i(e,t),ln.size===64&&ln.delete(ln.keys().next().value)}return ln.set(r,n),n}function wl(o){if(o!=null&&(typeof o!="string"||/[{}]/.test(o.replaceAll("{}",""))))throw new RangeError("This formatter mask supports only {} placeholders")}function no(o,e){return wl(e),e==null?o:e.replaceAll("{}",()=>o)}function xg(o){if(o instanceof Date)return bt(o);if(U(o))return"N";if(typeof o=="number")return Number.isInteger(o)?"L":"R";throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects")}function kg(o,e,{pattern:t="short",locale:r,timeZone:n}){if(!["short","medium","long","full"].includes(t))throw new RangeError("Temporal formatting currently supports short, medium, long and full only");if(e==="DHZ"&&(typeof n!="string"||!n))throw new TypeError("DHZ formatting currently requires an explicit timeZone");let i={timeZone:e==="DHZ"?n:"UTC"};return e!=="H"&&(i.dateStyle=t),e!=="D"&&(i.timeStyle=t),zi(!0,r,i).format(o)}function qi(o){let e=/^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(o);if(!e||e[1]==="("!=(e[4]===")")||o.endsWith("."))throw new RangeError(`Unsupported numeric pattern section: ${o}`);let t=e[3]??"";return{prefix:e[1]??"",suffix:e[4]??"",intl:{useGrouping:e[2].startsWith("#,##")?"always":!1,minimumIntegerDigits:e[2].replace("#,##","").length,minimumFractionDigits:t.replaceAll("#","").length,maximumFractionDigits:t.length}}}function Eg(o){let e=o.split(";");if(e.length>3)throw new RangeError("Numeric patterns support at most three sections");let t=qi(e[0]);if(t.prefix||t.suffix)throw new RangeError("Positive-section affixes are not implemented");let r=e.length===3?e[1]:null;r!==null&&r!==""&&r!=="-"&&qi(r);let n=e.length>1?qi(e.at(-1)):null;return{positive:t,zero:r,negative:n}}function oo(o,e={},t={}){if(o===null)return"";if(typeof e=="string"&&(e={pattern:e}),!e||typeof e!="object"||Array.isArray(e))throw new TypeError("Format options must be a pattern string or an options object");for(let b of Object.keys(e))if(!["pattern","locale","mask","dtype","timeZone"].includes(b))throw new RangeError(`Unsupported format option: ${b}`);e={...e,locale:e.locale??t.locale,timeZone:e.timeZone??t.timeZone};let r=e.dtype===void 0?xg(o):e.dtype,n=["D","H","DHZ"].includes(r);if(!n&&!["L","R","N"].includes(r))throw new RangeError(`Unsupported format dtype: ${r}`);if(n){if(!(o instanceof Date)||!Number.isFinite(o.getTime()))throw new TypeError(`${r} requires a valid Date object`)}else if(!(typeof o=="number"&&Number.isFinite(o))&&!(U(o)&&!["NaN","Infinity","-Infinity"].includes(o.toString())))throw new TypeError(`${r} formatting requires finite JavaScript numbers or TYTX Decimal values`);if(r==="L"&&!Number.isInteger(o))throw new TypeError("L formatting requires an integer");let{pattern:i,locale:s,mask:a}=e;if(!n&&typeof i!="string")throw new TypeError("Numeric formatting currently requires an explicit pattern");if(typeof s!="string"||!s)throw new TypeError("Formatting currently requires an explicit locale");if(wl(a),n){let b=kg(o,r,e);return no(b,a)}let{positive:l,zero:c,negative:u}=Eg(i),d=zi(!1,s,l.intl),f=U(o),h=f?o.eq(0):o===0,p=f?o.lt(0):o<0;if(f&&zi(!1,"en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal without precision loss");let m;if(h&&c!==null){if(c==="")return"";if(c==="-")m="-";else{let b=qi(c);m=b.prefix+zi(!1,s,b.intl).format(0)+b.suffix}}else{let b=p&&u?u:l,w=f?(p&&u?o.abs():o).toString():p&&u?-o:o===0?0:o;m=b.prefix+d.format(w)+b.suffix}return no(m,a)}var be="http://www.w3.org/1999/xhtml",kt="http://www.w3.org/2000/svg",Tg=new Set(["default","default_value","live","group","visible","action","fire","ask","_ask","_ask_if","_ask_title","_ask_onCancel","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","remote","_cachedRemote","_onRemote","_onCalling","onComplete","onClose","onEnd","onChecked","onDrag","onDrop","dropTargetCb","onDragEnd","dropTarget","dropTypes","dragTags","dropTags","effectAllowed","dropEffect","dragClass"]),Sg=["default_","attr_","fire_","connect_on","subscribe_","selfsubscribe_","formsubscribe_","remote_"],Ag={table:["width","border"],editor:["height"],embed:["width","height"],img:["width","height"],canvas:["width","height"]},Ig=["format","mask","locale","timeZone","places","dtype"],Cg=new Set(["href","src","data","action","formaction","xlink:href","xlink_href"]);function Et(o){return Object.fromEntries(Object.entries(o).filter(([e,t])=>!(t&&typeof t=="object"&&Object.hasOwn(t,"$gramlotRef"))&&!Tg.has(e)&&!Sg.some(r=>e.startsWith(r))))}function yr(o,e,t=[]){for(let[r,n]of Object.entries(e)){let i=t.find(a=>r.startsWith(a))??"",s=r.slice(i.length);if(["style","class","_class"].includes(s)&&n!=null&&typeof n!="string")throw new TypeError(`${o.nodeTag} '${o.label}': '${r}' must be a string or null`)}}function vr(o,e,t=[]){if(o.nodeTag==="script"){let r=[["",o.staticValue],...ge(o.getAttr()).filter(([n])=>["src","href","xlink:href","xlink_href","_text"].includes(n.slice((t.find(i=>n.startsWith(i))??"").length).toLowerCase()))];for(let[n,i]of r)if(o.pointerType(i)||Le(i))throw new Error(`script '${o.label}': '${n}' must be literal Source; script code and URLs cannot come from Data`)}if(e.onEnd!=null&&(o.nodeTag.toLowerCase()!=="transformpane"||!o._getMeta("gramlot_component")?.parameters?.onEnd))throw new Error("onEnd is only supported on transformPane");if(e.onChecked!=null&&!o._getMeta("gramlot_component")?.parameters?.onChecked)throw new Error("onChecked is only supported on a component that declares it");if(e.onComplete!=null&&!["uploader","imageUploader"].includes(o.nodeTag))throw new Error("onComplete is only supported on an uploader or imageUploader");if(e.onClose!=null&&!o.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose)throw new Error("onClose is only supported on a tab/stack panel");for(let[r,n]of Object.entries(xr(Et(e)))){let i=t.find(a=>r.startsWith(a)),s=i?r.slice(i.length):r;if(/^on./i.test(s))throw new Error(`${o.nodeTag} '${o.label}': '${r}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${s} for an event, or rename the attribute`);if(Cg.has(s.toLowerCase())&&Dg(n))throw new Error(`${o.nodeTag} '${o.label}': '${r}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`)}}function Dg(o){return typeof o=="string"&&/^javascript:/i.test(o.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""))}function yl(o,e,t=[]){if(o.nodeTag!=="iframe")return e;let r=a=>{let l=t.find(c=>a.startsWith(c))??"";return[l,a.slice(l.length).toLowerCase()]},n=Object.fromEntries(ge(o.getAttr())),i=[...Object.keys(n),...Object.keys(e)].find(a=>r(a)[1]==="srcdoc");if(i===void 0||Object.keys(n).some(a=>r(a)[1]==="sandbox")||o.pointerType(o.value)===null&&!(Object.hasOwn(n,i)&&(o.pointerType(n[i])!==null||Le(n[i]))))return e;let s=Object.fromEntries(Object.entries(e).filter(([a])=>r(a)[1]!=="sandbox"));return{[`${r(i)[0]}sandbox`]:"",...s}}function xr(o){return Object.fromEntries(Object.entries(o).filter(([,e])=>e!=null))}function cn(o){return Object.fromEntries(Object.entries(o).map(([e,t])=>e.startsWith("xmlns_")?[`xmlns:${e.slice(6)}`,t]:e.startsWith("data_")||e.startsWith("aria_")?[e.replaceAll("_","-"),t]:[e,t]))}function io(o){let{_meta:e,...t}=o;return cn(xr(Et(t)))}function vl(o,e){let t=Ag[String(o).toLowerCase()]??[],r={},n={};for(let[i,s]of Object.entries(e))t.includes(i)?n[i]=s:r[i]=s;return[r,n]}function _r(o){return String(o)}function un(o,e,t=null){let r={...e},{mask:n,format:i,locale:s,timeZone:a,dtype:l,places:c}=r;for(let d of Ig)delete r[d];let u=d=>{if(t&&i!=null){if(c!=null)throw new RangeError("places is not implemented; specify precision in format");return t(d,{pattern:i,mask:n,...s==null?{}:{locale:s},...a==null?{}:{timeZone:a},...l==null?{}:{dtype:l}})}if(typeof d=="boolean"&&(d=_r(d)),n==null)return d;let f=d==null?"":_r(d);return f===""?f:no(f,n)};return Array.isArray(o)?(Object.hasOwn(r,"_text")&&(r._text=u(r._text)),[o,r]):[u(o),r]}function Le(o){return typeof o=="string"&&o.startsWith("==")}var Ui=class{#e;#t;#r;#n;#o;#i;#s;#a=null;#l=!1;#c=[];#u=new Set;constructor(e,t){this.#e=e;let r=e.ownerDocument;this.#t=r.createElement("div"),this.#t.className="toolbar-viewport",this.#t.append(t),this.#n=r.createElement("button"),this.#n.type="button",this.#n.className="toolbar-more",this.#n.hidden=!0,this.#n.title="More commands";let n=r.createElementNS(kt,"svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let i=r.createElementNS(kt,"path");i.setAttribute("d","m5 6 6 6-6 6m8-12 6 6-6 6"),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.8"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),n.append(i),this.#n.append(n),this.#n.setAttribute("aria-label","More commands"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.#r=r.createElement("div"),this.#r.className="toolbar-overflow",this.#r.setAttribute("popover","manual"),this.#r.setAttribute("role","menu"),this.#r.tabIndex=-1;let s=r.createElement("slot");s.name="overflow",this.#r.append(s),this.#n.addEventListener("click",()=>this.#l?this.close():this.open()),this.#n.addEventListener("keydown",l=>{["ArrowDown","ArrowRight"].includes(l.key)&&(l.preventDefault(),l.stopPropagation(),this.open())}),this.#r.addEventListener("keydown",l=>{l.key==="Escape"&&!l.composedPath().some(c=>c.localName==="gramlot-menu"&&c!==e)&&(l.preventDefault(),l.stopPropagation(),this.close())});let a=r.createElement("style");a.textContent=`
115
+ .caption:empty{display:none}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",e.append(t,this.controlBox)}projectAttributes(e){return br(this,e)}setPageContext(e){this.pageContext=e}connectedCallback(){}releaseControl(){}get liveWrites(){return this.control.localName==="textarea"||["text","password","range","color"].includes(this.control.type)}validateCandidate(e,t){return t(e),{ok:!0,value:e,isCurrent:()=>this.pageContext.isActive()}}finishValidation(){}validationValueCheck(){return this.constructor.validationValueCheck(this.pageContext)}static validationValueCheck(){let e=this.gramlotComponent.parameters.value.nullable;return(t,r)=>{if(t==null&&!e)throw new TypeError("This component requires a non-null value.");if(t!=null&&r!=null&&typeof t!=typeof r)throw new TypeError("Validation must preserve the component value type.")}}validationSelection(){return this.constructor.validationSelection(this.parameters,this.pageContext)}static validationSelection(){return()=>{throw new TypeError("validate_select requires a constrained choice editor.")}}validateSelection(e){return this.validationSelection()(e)}shouldProjectControlValue(){return!0}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>{this.validationValueCheck()(t,e),this.sameControlValue(e,t)||this.writeControlValue(t)})}restoreFormDraft(e){this.control.value=e}restoreFormValue(e){this.writeControlValue(e)}sameControlValue(e,t){return Object.is(e,t)}focus(e){this.control.focus(e)}}}function ml(o){return class extends no(o){constructor(){super(),this.control=this.createControl(),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.setAttribute("autocomplete","off"),this.control.setAttribute("autocorrect","off"),this.control.setAttribute("autocapitalize","off"),this.control.setAttribute("spellcheck","false")),this.control.id="control";let e=this.ownerDocument.createElement("label");e.className="option",this.optionCaption=this.ownerDocument.createElement("span"),this.optionCaption.className="caption",e.append(this.control,this.optionCaption),this.controlBox.append(e)}projectAttributes(e,t){let r=super.projectAttributes(e,t),{disabled:n,readonly:i}=this.parameters;this.control.disabled=!!n,this.control.readOnly=!!i;for(let[s,a]of Object.entries(this.constructor.gramlotComponent.parameters)){if(a.target==="control"){let l=this.parameters[s]??"";String(this.control[s])!==String(l)&&(this.control[s]=l)}a.target==="optionCaption"&&(this.optionCaption.textContent=this.parameters[s]??"")}return r}}}ml.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"},live:{dtype:"B",default:!1,binding:"read"}};function gl(o){return class extends no(o){#e=new Map;#t;#r=null;constructor(){super(),this.control=this.ownerDocument.createElement("div"),this.control.className="options",this.control.id="control",this.control.setAttribute("role",this.multiple?"group":"radiogroup"),this.controlBox.append(this.control),this.control.addEventListener("keydown",e=>{if(!this.multiple||!["ArrowDown","ArrowUp","ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;let t=[...this.control.querySelectorAll("input:not(:disabled)")],r=t.indexOf(e.target);if(r<0)return;e.preventDefault();let n=e.key==="Home"?0:e.key==="End"?t.length-1:Math.max(0,Math.min(t.length-1,r+(["ArrowDown","ArrowRight"].includes(e.key)?1:-1)));t[n].focus()})}choiceOptions(){return gr(this.parameters.values??"")}projectAttributes(e,t){let r=super.projectAttributes(e,t),n=this.choiceOptions(),i=JSON.stringify(n);if(i!==this.#t){let a=n,l=new Set,c=null;for(let{id:u,caption:d}of a){let f=this.#e.get(u);if(!f){let p=this.ownerDocument.createElement("label");p.className="option";let m=this.ownerDocument.createElement("input");m.type=this.choiceType,m.name="choice",m.value=u;let b=this.ownerDocument.createElement("span");p.append(m,b),f={label:p,input:m,text:b},this.#e.set(u,f)}f.text.textContent=d;let h=c?c.nextSibling:this.control.firstChild;h!==f.label&&this.control.insertBefore(f.label,h),c=f.label,l.add(u)}for(let[u,d]of this.#e)l.has(u)||(d.label.remove(),this.#e.delete(u));this.#t=i}let s=this.parameters.cols;if(!Number.isInteger(s)||s<1)throw new TypeError("cols must be a positive integer");this.control.style.gridTemplateColumns=`repeat(${s}, minmax(0, 1fr))`,this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly;for(let{input:a}of this.#e.values())a.disabled=this.control.disabled||this.control.readOnly;return r}readControlValue(){if(this.multiple){let t=(this.#r?this.#r.split(","):[]).filter(r=>!this.#e.has(r)||this.#e.get(r).input.checked);for(let[r,{input:n}]of this.#e)n.checked&&!t.includes(r)&&t.push(r);return t.join(",")||null}for(let[e,{input:t}]of this.#e)if(t.checked)return e;return null}writeControlValue(e){this.#r=e;let t=this.multiple?new Set(e?e.split(","):[]):null;for(let[r,{input:n}]of this.#e)n.checked=this.multiple?t.has(r):r===e}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>this.writeControlValue(t))}focus(e){let t=[...this.#e.values()];(t.find(({input:r})=>r.checked&&!r.disabled)??t.find(({input:r})=>!r.disabled))?.input.focus(e)}}}gl.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"}};var wl={};ee(wl,{positionPopup:()=>wr});function wr(o,e,{align:t="start",matchWidth:r=!1,inset:n=0,placement:i="bottom",point:s=null}={}){let a=e.ownerDocument.defaultView,l=s?{left:s.x,right:s.x,top:s.y,bottom:s.y,width:0}:e.getBoundingClientRect(),c=Math.max(0,a.innerWidth-16);o.style.setProperty("--gramlot-popup-available-width",`${c}px`),r&&(o.style.width=`${Math.min(Math.max(0,l.width-2*n),c)}px`),o.style.removeProperty("--gramlot-popup-available-height");let u=o.getBoundingClientRect();if(i==="side"){let w=Math.max(0,a.innerWidth-8-l.right-3),_=Math.max(0,l.left-8-3),v=u.width>w&&_>w;o.style.setProperty("--gramlot-popup-available-width",`${v?_:w}px`),o.style.setProperty("--gramlot-popup-available-height",`${Math.max(0,a.innerHeight-16)}px`);let E=o.getBoundingClientRect(),D=v?l.left-E.width-3:l.right+3;o.style.left=`${Math.max(8,Math.min(D,a.innerWidth-E.width-8))}px`,o.style.top=`${Math.max(8,Math.min(l.top,a.innerHeight-E.height-8))}px`;return}let d=Math.max(0,a.innerHeight-8-l.bottom-3),f=Math.max(0,l.top-8-3),h=u.height>d&&f>d;o.style.setProperty("--gramlot-popup-available-height",`${h?f:d}px`);let p=o.getBoundingClientRect(),m=t==="end"?l.right-p.width-n:l.left+n,b=h?l.top-p.height-3:l.bottom+3;o.style.left=`${Math.max(8,Math.min(m,a.innerWidth-p.width-8))}px`,o.style.top=`${Math.max(8,Math.min(b,a.innerHeight-p.height-8))}px`}var kl={};ee(kl,{SVG_NS:()=>kt,XHTML_NS:()=>be,boundaryAttributes:()=>so,displayItem:()=>un,domNames:()=>cn,isExpression:()=>Le,requireNoScriptAttributes:()=>vr,requireStyleClassAttributes:()=>yr,splitNativeAttributes:()=>xl,textValue:()=>_r,withDataSrcdocSandbox:()=>vl,withoutBindingAttributes:()=>Et,withoutNullValues:()=>xr});var yl={};ee(yl,{applyMask:()=>oo,formatValue:()=>io,validateMask:()=>_l});var ln=new Map;function Ui(o,e,t){let r=JSON.stringify([o,e,t]),n=ln.get(r);if(n)ln.delete(r);else{let i=o?Intl.DateTimeFormat:Intl.NumberFormat;if(!i.supportedLocalesOf([e]).length)throw new RangeError(`Unsupported format locale: ${e}`);n=new i(e,t),ln.size===64&&ln.delete(ln.keys().next().value)}return ln.set(r,n),n}function _l(o){if(o!=null&&(typeof o!="string"||/[{}]/.test(o.replaceAll("{}",""))))throw new RangeError("This formatter mask supports only {} placeholders")}function oo(o,e){return _l(e),e==null?o:e.replaceAll("{}",()=>o)}function xg(o){if(o instanceof Date)return bt(o);if(q(o))return"N";if(typeof o=="number")return Number.isInteger(o)?"L":"R";throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects")}function kg(o,e,{pattern:t="short",locale:r,timeZone:n}){if(!["short","medium","long","full"].includes(t))throw new RangeError("Temporal formatting currently supports short, medium, long and full only");if(e==="DHZ"&&(typeof n!="string"||!n))throw new TypeError("DHZ formatting currently requires an explicit timeZone");let i={timeZone:e==="DHZ"?n:"UTC"};return e!=="H"&&(i.dateStyle=t),e!=="D"&&(i.timeStyle=t),Ui(!0,r,i).format(o)}function qi(o){let e=/^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(o);if(!e||e[1]==="("!=(e[4]===")")||o.endsWith("."))throw new RangeError(`Unsupported numeric pattern section: ${o}`);let t=e[3]??"";return{prefix:e[1]??"",suffix:e[4]??"",intl:{useGrouping:e[2].startsWith("#,##")?"always":!1,minimumIntegerDigits:e[2].replace("#,##","").length,minimumFractionDigits:t.replaceAll("#","").length,maximumFractionDigits:t.length}}}function Eg(o){let e=o.split(";");if(e.length>3)throw new RangeError("Numeric patterns support at most three sections");let t=qi(e[0]);if(t.prefix||t.suffix)throw new RangeError("Positive-section affixes are not implemented");let r=e.length===3?e[1]:null;r!==null&&r!==""&&r!=="-"&&qi(r);let n=e.length>1?qi(e.at(-1)):null;return{positive:t,zero:r,negative:n}}function io(o,e={},t={}){if(o===null)return"";if(typeof e=="string"&&(e={pattern:e}),!e||typeof e!="object"||Array.isArray(e))throw new TypeError("Format options must be a pattern string or an options object");for(let b of Object.keys(e))if(!["pattern","locale","mask","dtype","timeZone"].includes(b))throw new RangeError(`Unsupported format option: ${b}`);e={...e,locale:e.locale??t.locale,timeZone:e.timeZone??t.timeZone};let r=e.dtype===void 0?xg(o):e.dtype,n=["D","H","DHZ"].includes(r);if(!n&&!["L","R","N"].includes(r))throw new RangeError(`Unsupported format dtype: ${r}`);if(n){if(!(o instanceof Date)||!Number.isFinite(o.getTime()))throw new TypeError(`${r} requires a valid Date object`)}else if(!(typeof o=="number"&&Number.isFinite(o))&&!(q(o)&&!["NaN","Infinity","-Infinity"].includes(o.toString())))throw new TypeError(`${r} formatting requires finite JavaScript numbers or TYTX Decimal values`);if(r==="L"&&!Number.isInteger(o))throw new TypeError("L formatting requires an integer");let{pattern:i,locale:s,mask:a}=e;if(!n&&typeof i!="string")throw new TypeError("Numeric formatting currently requires an explicit pattern");if(typeof s!="string"||!s)throw new TypeError("Formatting currently requires an explicit locale");if(_l(a),n){let b=kg(o,r,e);return oo(b,a)}let{positive:l,zero:c,negative:u}=Eg(i),d=Ui(!1,s,l.intl),f=q(o),h=f?o.eq(0):o===0,p=f?o.lt(0):o<0;if(f&&Ui(!1,"en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal without precision loss");let m;if(h&&c!==null){if(c==="")return"";if(c==="-")m="-";else{let b=qi(c);m=b.prefix+Ui(!1,s,b.intl).format(0)+b.suffix}}else{let b=p&&u?u:l,w=f?(p&&u?o.abs():o).toString():p&&u?-o:o===0?0:o;m=b.prefix+d.format(w)+b.suffix}return oo(m,a)}var be="http://www.w3.org/1999/xhtml",kt="http://www.w3.org/2000/svg",Tg=new Set(["default","default_value","live","group","visible","action","fire","ask","_ask","_ask_if","_ask_title","_ask_onCancel","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","remote","_cachedRemote","_onRemote","_onCalling","onComplete","onClose","onEnd","onChecked","onDrag","onDrop","dropTargetCb","onDragEnd","dropTarget","dropTypes","dragTags","dropTags","effectAllowed","dropEffect","dragClass"]),Sg=["default_","attr_","fire_","connect_on","subscribe_","selfsubscribe_","formsubscribe_","remote_"],Ag={table:["width","border"],editor:["height"],embed:["width","height"],img:["width","height"],canvas:["width","height"]},Ig=["format","mask","locale","timeZone","places","dtype"],Cg=new Set(["href","src","data","action","formaction","xlink:href","xlink_href"]);function Et(o){return Object.fromEntries(Object.entries(o).filter(([e,t])=>!(t&&typeof t=="object"&&Object.hasOwn(t,"$gramlotRef"))&&!Tg.has(e)&&!Sg.some(r=>e.startsWith(r))))}function yr(o,e,t=[]){for(let[r,n]of Object.entries(e)){let i=t.find(a=>r.startsWith(a))??"",s=r.slice(i.length);if(["style","class","_class"].includes(s)&&n!=null&&typeof n!="string")throw new TypeError(`${o.nodeTag} '${o.label}': '${r}' must be a string or null`)}}function vr(o,e,t=[]){if(o.nodeTag==="script"){let r=[["",o.staticValue],...ge(o.getAttr()).filter(([n])=>["src","href","xlink:href","xlink_href","_text"].includes(n.slice((t.find(i=>n.startsWith(i))??"").length).toLowerCase()))];for(let[n,i]of r)if(o.pointerType(i)||Le(i))throw new Error(`script '${o.label}': '${n}' must be literal Source; script code and URLs cannot come from Data`)}if(e.onEnd!=null&&(o.nodeTag.toLowerCase()!=="transformpane"||!o._getMeta("gramlot_component")?.parameters?.onEnd))throw new Error("onEnd is only supported on transformPane");if(e.onChecked!=null&&!o._getMeta("gramlot_component")?.parameters?.onChecked)throw new Error("onChecked is only supported on a component that declares it");if(e.onComplete!=null&&!["uploader","imageUploader"].includes(o.nodeTag))throw new Error("onComplete is only supported on an uploader or imageUploader");if(e.onClose!=null&&!o.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose)throw new Error("onClose is only supported on a tab/stack panel");for(let[r,n]of Object.entries(xr(Et(e)))){let i=t.find(a=>r.startsWith(a)),s=i?r.slice(i.length):r;if(/^on./i.test(s))throw new Error(`${o.nodeTag} '${o.label}': '${r}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${s} for an event, or rename the attribute`);if(Cg.has(s.toLowerCase())&&Dg(n))throw new Error(`${o.nodeTag} '${o.label}': '${r}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`)}}function Dg(o){return typeof o=="string"&&/^javascript:/i.test(o.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""))}function vl(o,e,t=[]){if(o.nodeTag!=="iframe")return e;let r=a=>{let l=t.find(c=>a.startsWith(c))??"";return[l,a.slice(l.length).toLowerCase()]},n=Object.fromEntries(ge(o.getAttr())),i=[...Object.keys(n),...Object.keys(e)].find(a=>r(a)[1]==="srcdoc");if(i===void 0||Object.keys(n).some(a=>r(a)[1]==="sandbox")||o.pointerType(o.value)===null&&!(Object.hasOwn(n,i)&&(o.pointerType(n[i])!==null||Le(n[i]))))return e;let s=Object.fromEntries(Object.entries(e).filter(([a])=>r(a)[1]!=="sandbox"));return{[`${r(i)[0]}sandbox`]:"",...s}}function xr(o){return Object.fromEntries(Object.entries(o).filter(([,e])=>e!=null))}function cn(o){return Object.fromEntries(Object.entries(o).map(([e,t])=>e.startsWith("xmlns_")?[`xmlns:${e.slice(6)}`,t]:e.startsWith("data_")||e.startsWith("aria_")?[e.replaceAll("_","-"),t]:[e,t]))}function so(o){let{_meta:e,...t}=o;return cn(xr(Et(t)))}function xl(o,e){let t=Ag[String(o).toLowerCase()]??[],r={},n={};for(let[i,s]of Object.entries(e))t.includes(i)?n[i]=s:r[i]=s;return[r,n]}function _r(o){return String(o)}function un(o,e,t=null){let r={...e},{mask:n,format:i,locale:s,timeZone:a,dtype:l,places:c}=r;for(let d of Ig)delete r[d];let u=d=>{if(t&&i!=null){if(c!=null)throw new RangeError("places is not implemented; specify precision in format");return t(d,{pattern:i,mask:n,...s==null?{}:{locale:s},...a==null?{}:{timeZone:a},...l==null?{}:{dtype:l}})}if(typeof d=="boolean"&&(d=_r(d)),n==null)return d;let f=d==null?"":_r(d);return f===""?f:oo(f,n)};return Array.isArray(o)?(Object.hasOwn(r,"_text")&&(r._text=u(r._text)),[o,r]):[u(o),r]}function Le(o){return typeof o=="string"&&o.startsWith("==")}var Vi=class{#e;#t;#r;#n;#o;#i;#s;#a=null;#l=!1;#c=[];#u=new Set;constructor(e,t){this.#e=e;let r=e.ownerDocument;this.#t=r.createElement("div"),this.#t.className="toolbar-viewport",this.#t.append(t),this.#n=r.createElement("button"),this.#n.type="button",this.#n.className="toolbar-more",this.#n.hidden=!0,this.#n.title="More commands";let n=r.createElementNS(kt,"svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let i=r.createElementNS(kt,"path");i.setAttribute("d","m5 6 6 6-6 6m8-12 6 6-6 6"),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.8"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),n.append(i),this.#n.append(n),this.#n.setAttribute("aria-label","More commands"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.#r=r.createElement("div"),this.#r.className="toolbar-overflow",this.#r.setAttribute("popover","manual"),this.#r.setAttribute("role","menu"),this.#r.tabIndex=-1;let s=r.createElement("slot");s.name="overflow",this.#r.append(s),this.#n.addEventListener("click",()=>this.#l?this.close():this.open()),this.#n.addEventListener("keydown",l=>{["ArrowDown","ArrowRight"].includes(l.key)&&(l.preventDefault(),l.stopPropagation(),this.open())}),this.#r.addEventListener("keydown",l=>{l.key==="Escape"&&!l.composedPath().some(c=>c.localName==="gramlot-menu"&&c!==e)&&(l.preventDefault(),l.stopPropagation(),this.close())});let a=r.createElement("style");a.textContent=`
116
116
  :host([role=toolbar]){min-width:0;min-height:0;max-width:100%;width:100%;flex-shrink:1;gap:0}
117
117
  :host([role=toolbar][aria-orientation=vertical]){width:auto;height:100%;max-height:100%}
118
118
  .toolbar-viewport{display:contents}
@@ -138,7 +138,7 @@ ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}
138
138
  :host([role=menu]) ::slotted([role=separator]){margin:5px 7px 5px 2.5rem;border-top:1px solid var(--gramlot-border-control,#888)}
139
139
  :host([role=toolbar][aria-orientation=horizontal]) ::slotted([role=separator]){border-top:0;border-left:1px solid var(--gramlot-border-control,#888);align-self:stretch;margin:4px}
140
140
  :host([hidden]){display:none!important} slot{display:contents} .status{padding:.4em;opacity:.75}
141
- .status:empty{display:none} button{font:inherit}`,this.#l=e.createElement("slot"),this.#s=e.createElement("span"),this.#s.className="status",this.#s.setAttribute("role","status"),this.#a=e.createElement("button"),this.#a.textContent="Riprova",this.#a.hidden=!0,this.#a.addEventListener("click",n=>{n.stopPropagation(),this.menuBinding.load(!0)}),t.append(r,this.#l,this.#s,this.#a),this.#i=new Ui(this,this.#l),this.addEventListener("keydown",n=>this.#h(n)),this.addEventListener("focusin",n=>{let i=n.composedPath().find(s=>this.items.includes(s));i&&(this.#r=i,this.refreshItems())})}get permanent(){return this.parameters.presentation==="bar"}get opened(){return this.permanent||this.#c}get items(){return[...this.querySelectorAll("gramlot-menu-line")].filter(e=>e.menuOwner===this&&!e.parameters.group)}get overflow(){return this.#i}isOverflowed(e){return this.#i.contains(e)}get visibleItems(){return this.items.filter(e=>Ht(e).slot!=="suppressed"&&!e.hidden&&!e.closest("[hidden]")&&e.getAttribute("role")!=="separator")}get usableItems(){return this.visibleItems.filter(e=>!e.disabled)}get parentMenu(){return this.parentElement?.closest("gramlot-menu")??null}connectedCallback(){this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>{this.refreshItems(),this.#i.schedule()}),this.#t.observe(this,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["hidden","disabled"]}),this.refreshItems(),this.#p(),this.#i.connect(),this.permanent&&this.menuBinding?.load()}disconnectedCallback(){this.#i.disconnect(),this.#t?.disconnect(),this.#e?.abort(),this.#d?.abort(),this.#u=null,this.#c=!1}projectAttributes(e){let t=br(this,e);if(this.#f(),!Number.isFinite(this.parameters.iconSize)||this.parameters.iconSize<=0)throw new TypeError("menu iconSize must be positive");return this.setAttribute("role",this.permanent?"toolbar":"menu"),this.setAttribute("aria-orientation",this.permanent?this.parameters.orientation:"vertical"),this.tabIndex=-1,this.permanent?this.removeAttribute("popover"):this.setAttribute("popover","manual"),this.refreshItems(),this.#i.schedule(),t}#f(){let e=this.parameters.modifiers;if(e==null)return null;if(e==="*")return[];let t=e.trim().toLowerCase().split(/[,\s]+/);if(!t.length||t.some(r=>!["shift","ctrl","alt","meta"].includes(r))||new Set(t).size!==t.length)throw new TypeError("Menu modifiers require *, or a combination of Shift, Ctrl, Alt and Meta");return t}#p(){let e=Ht(this).parentElement;if(this.permanent||!e)return;if(["gramlot-menu-line","gramlot-drop-down-button"].includes(e.localName)){Ht(this).slot="menu";return}if(e.localName==="gramlot-grouplet-card"){Ht(this).slot="card-menu";return}if(Ht(this).removeAttribute("slot"),e.localName==="gramlot-menu")return;this.#u=e,this.#d=new this.ownerDocument.defaultView.AbortController;let t={signal:this.#d.signal},r=i=>!i.composedPath().some(s=>s.localName==="gramlot-menu"),n=i=>{if(this.hidden||this.permanent||!r(i)||i.composedPath().some(c=>c instanceof this.ownerDocument.defaultView.Element&&(c.disabled===!0||c.getAttribute("aria-disabled")==="true")))return;let s=this.#f();if(i.type==="click"){if(s===null||i.button!==0||["shift","ctrl","alt","meta"].some(c=>!!i[c+"Key"]!==s.includes(c)))return}else if(s!==null)return;i.preventDefault(),i.stopPropagation();let a=i.type==="keydown",l=a?e.getBoundingClientRect():null;this.open(e,!1,a?{x:l.left+8,y:l.top+8}:{x:i.clientX,y:i.clientY})};e.addEventListener("click",n,t),e.addEventListener("contextmenu",n,t),e.addEventListener("keydown",i=>{(i.key==="ContextMenu"||i.key==="F10"&&i.shiftKey&&!i.ctrlKey&&!i.altKey&&!i.metaKey)&&n(i)},t)}setStatus(e){this.status=e,this.#s.textContent={loading:"Caricamento\u2026",empty:"Nessuna voce",error:"Impossibile caricare"}[e]??"",this.#a.hidden=e!=="error",this.setAttribute("aria-busy",String(e==="loading"));for(let t of this.items)t.refreshAvailability();this.refreshItems()}refreshItems(){for(let r of this.querySelectorAll("gramlot-menu-line"))r.menuOwner===this&&r.parameters.group&&r.refreshAvailability();for(let r of this.items)r.refreshAvailability();let e=this.usableItems;for(let[r,n,i]of[["check",this.visibleItems.some(s=>s.parameters.checked!=null),"1.4em"],["icon",this.visibleItems.some(s=>s.entryIcon||s.entryIconSrc),"1.5em"],["arrow",this.visibleItems.some(s=>s.submenu),".9em"]])this.style.setProperty(`--gramlot-menu-${r}-track`,n?i:"0px");if(this.#r&&!e.includes(this.#r)){let r=this.#n.indexOf(this.#r),n=this.#n.slice(r+1).find(i=>e.includes(i))??this.#n.slice(0,r).reverse().find(i=>e.includes(i));this.#r=n??null,this.opened&&this.status!=="loading"&&(n?n.focus():this.permanent?this.focus():this.close())}let t=e.filter(r=>!this.isOverflowed(r));for(let r of this.items)r.control.tabIndex=this.permanent&&r===(t.includes(this.#r)?this.#r:t[0])?0:-1;this.#n=this.items}open(e,t=!1,r=null){if(this.permanent)return;this.#o=e,this.#c||(this.showPopover(),this.#c=!0),e.setAttribute("aria-expanded","true"),this.#e?.abort(),this.#e=new this.ownerDocument.defaultView.AbortController;let n={signal:this.#e.signal},i=()=>wr(this,e,{point:r,placement:this.parentMenu&&(!this.parentMenu.permanent||this.parentMenu.parameters.orientation==="vertical"||this.parentMenu.isOverflowed(this.parentElement))?"side":"bottom"});i(),this.ownerDocument.defaultView.addEventListener("resize",i,n),this.ownerDocument.addEventListener("scroll",i,{...n,capture:!0}),this.ownerDocument.addEventListener("pointerdown",s=>{!s.composedPath().includes(this)&&(e===this.#u||!s.composedPath().includes(e))&&this.closeChain(!1)},n),this.menuBinding?.load().then(()=>{this.#c&&(this.ownerDocument.activeElement===this||!this.contains(this.ownerDocument.activeElement))&&this.focusEntry(t),this.#c&&i()}),this.focusEntry(t)}focusEntry(e=!1){let t=this.usableItems,r=t[e?t.length-1:0];r?(this.#r=r,r.focus()):this.focus()}close(e=!0){for(let t of this.querySelectorAll("gramlot-menu"))t.permanent||t.close(!1);if(this.permanent){this.#i.close(e);return}this.#c&&(this.hidePopover(),this.#c=!1,this.#e?.abort(),this.#o?.setAttribute("aria-expanded","false"),e&&this.#o?.isConnected&&this.#o.focus())}closeChain(e=!0){let t=this.parentMenu;this.close(e&&!t),t&&!t.permanent?t.closeChain(e):t?.isOverflowed(this.parentElement)?t.overflow.close(e):e&&this.#o?.isConnected&&this.#o.focus()}#h(e){if(e.defaultPrevented||e.composedPath().find(c=>c.localName==="gramlot-menu")!==this)return;let t=e.composedPath().find(c=>this.items.includes(c));if(!t&&e.target!==this)return;let r=t&&this.isOverflowed(t),n=this.usableItems.filter(c=>this.isOverflowed(c)===!!r),i=n.indexOf(t),s=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowRight":"ArrowDown",a=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowLeft":"ArrowUp",l;if(e.key===s&&(l=Math.min(n.length-1,i+1)),e.key===a&&(l=Math.max(0,i-1)),e.key==="Home"&&(l=0),e.key==="End"&&(l=n.length-1),l!==void 0){e.preventDefault(),e.stopPropagation(),n[l]?.focus();return}(!this.permanent||r)&&e.key==="ArrowRight"&&t?.submenu?(e.preventDefault(),e.stopPropagation(),t.openSubmenu()):e.key==="Escape"&&(!this.permanent||this.overflow.opened||this.items.some(c=>c.submenu?.opened))||!this.permanent&&e.key==="ArrowLeft"&&this.parentMenu?(e.preventDefault(),e.stopPropagation(),this.close()):e.key==="Tab"&&this.closeChain(!1)}}}function rf(o){return class extends o{#e;#t;#r;#n;#o;#i;#s=null;#a=!1;constructor(){super();let e=this.ownerDocument;this.#r=e.createElement("span"),this.#n=e.createElement("span"),this.#r.className="menu-caption",this.#n.className="menu-check",this.#o=e.createElement("span"),this.#o.className="menu-arrow",this.#o.setAttribute("aria-hidden","true"),this.#n.setAttribute("aria-hidden","true"),this.control.prepend(this.#n),this.control.append(this.#r,this.#o);let t=e.createElement("style");t.textContent=`:host{color:var(--gramlot-ink,CanvasText)} .control-box{color:inherit;height:100%} :host button{color:inherit}
141
+ .status:empty{display:none} button{font:inherit}`,this.#l=e.createElement("slot"),this.#s=e.createElement("span"),this.#s.className="status",this.#s.setAttribute("role","status"),this.#a=e.createElement("button"),this.#a.textContent="Riprova",this.#a.hidden=!0,this.#a.addEventListener("click",n=>{n.stopPropagation(),this.menuBinding.load(!0)}),t.append(r,this.#l,this.#s,this.#a),this.#i=new Vi(this,this.#l),this.addEventListener("keydown",n=>this.#h(n)),this.addEventListener("focusin",n=>{let i=n.composedPath().find(s=>this.items.includes(s));i&&(this.#r=i,this.refreshItems())})}get permanent(){return this.parameters.presentation==="bar"}get opened(){return this.permanent||this.#c}get items(){return[...this.querySelectorAll("gramlot-menu-line")].filter(e=>e.menuOwner===this&&!e.parameters.group)}get overflow(){return this.#i}isOverflowed(e){return this.#i.contains(e)}get visibleItems(){return this.items.filter(e=>Ht(e).slot!=="suppressed"&&!e.hidden&&!e.closest("[hidden]")&&e.getAttribute("role")!=="separator")}get usableItems(){return this.visibleItems.filter(e=>!e.disabled)}get parentMenu(){return this.parentElement?.closest("gramlot-menu")??null}connectedCallback(){this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>{this.refreshItems(),this.#i.schedule()}),this.#t.observe(this,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["hidden","disabled"]}),this.refreshItems(),this.#p(),this.#i.connect(),this.permanent&&this.menuBinding?.load()}disconnectedCallback(){this.#i.disconnect(),this.#t?.disconnect(),this.#e?.abort(),this.#d?.abort(),this.#u=null,this.#c=!1}projectAttributes(e){let t=br(this,e);if(this.#f(),!Number.isFinite(this.parameters.iconSize)||this.parameters.iconSize<=0)throw new TypeError("menu iconSize must be positive");return this.setAttribute("role",this.permanent?"toolbar":"menu"),this.setAttribute("aria-orientation",this.permanent?this.parameters.orientation:"vertical"),this.tabIndex=-1,this.permanent?this.removeAttribute("popover"):this.setAttribute("popover","manual"),this.refreshItems(),this.#i.schedule(),t}#f(){let e=this.parameters.modifiers;if(e==null)return null;if(e==="*")return[];let t=e.trim().toLowerCase().split(/[,\s]+/);if(!t.length||t.some(r=>!["shift","ctrl","alt","meta"].includes(r))||new Set(t).size!==t.length)throw new TypeError("Menu modifiers require *, or a combination of Shift, Ctrl, Alt and Meta");return t}#p(){let e=Ht(this).parentElement;if(this.permanent||!e)return;if(["gramlot-menu-line","gramlot-drop-down-button"].includes(e.localName)){Ht(this).slot="menu";return}if(e.localName==="gramlot-grouplet-card"){Ht(this).slot="card-menu";return}if(Ht(this).removeAttribute("slot"),e.localName==="gramlot-menu")return;this.#u=e,this.#d=new this.ownerDocument.defaultView.AbortController;let t={signal:this.#d.signal},r=i=>!i.composedPath().some(s=>s.localName==="gramlot-menu"),n=i=>{if(this.hidden||this.permanent||!r(i)||i.composedPath().some(c=>c instanceof this.ownerDocument.defaultView.Element&&(c.disabled===!0||c.getAttribute("aria-disabled")==="true")))return;let s=this.#f();if(i.type==="click"){if(s===null||i.button!==0||["shift","ctrl","alt","meta"].some(c=>!!i[c+"Key"]!==s.includes(c)))return}else if(s!==null)return;i.preventDefault(),i.stopPropagation();let a=i.type==="keydown",l=a?e.getBoundingClientRect():null;this.open(e,!1,a?{x:l.left+8,y:l.top+8}:{x:i.clientX,y:i.clientY})};e.addEventListener("click",n,t),e.addEventListener("contextmenu",n,t),e.addEventListener("keydown",i=>{(i.key==="ContextMenu"||i.key==="F10"&&i.shiftKey&&!i.ctrlKey&&!i.altKey&&!i.metaKey)&&n(i)},t)}setStatus(e){this.status=e,this.#s.textContent={loading:"Caricamento\u2026",empty:"Nessuna voce",error:"Impossibile caricare"}[e]??"",this.#a.hidden=e!=="error",this.setAttribute("aria-busy",String(e==="loading"));for(let t of this.items)t.refreshAvailability();this.refreshItems()}refreshItems(){for(let r of this.querySelectorAll("gramlot-menu-line"))r.menuOwner===this&&r.parameters.group&&r.refreshAvailability();for(let r of this.items)r.refreshAvailability();let e=this.usableItems;for(let[r,n,i]of[["check",this.visibleItems.some(s=>s.parameters.checked!=null),"1.4em"],["icon",this.visibleItems.some(s=>s.entryIcon||s.entryIconSrc),"1.5em"],["arrow",this.visibleItems.some(s=>s.submenu),".9em"]])this.style.setProperty(`--gramlot-menu-${r}-track`,n?i:"0px");if(this.#r&&!e.includes(this.#r)){let r=this.#n.indexOf(this.#r),n=this.#n.slice(r+1).find(i=>e.includes(i))??this.#n.slice(0,r).reverse().find(i=>e.includes(i));this.#r=n??null,this.opened&&this.status!=="loading"&&(n?n.focus():this.permanent?this.focus():this.close())}let t=e.filter(r=>!this.isOverflowed(r));for(let r of this.items)r.control.tabIndex=this.permanent&&r===(t.includes(this.#r)?this.#r:t[0])?0:-1;this.#n=this.items}open(e,t=!1,r=null){if(this.permanent)return;this.#o=e,this.#c||(this.showPopover(),this.#c=!0),e.setAttribute("aria-expanded","true"),this.#e?.abort(),this.#e=new this.ownerDocument.defaultView.AbortController;let n={signal:this.#e.signal},i=()=>wr(this,e,{point:r,placement:this.parentMenu&&(!this.parentMenu.permanent||this.parentMenu.parameters.orientation==="vertical"||this.parentMenu.isOverflowed(this.parentElement))?"side":"bottom"});i(),this.ownerDocument.defaultView.addEventListener("resize",i,n),this.ownerDocument.addEventListener("scroll",i,{...n,capture:!0}),this.ownerDocument.addEventListener("pointerdown",s=>{!s.composedPath().includes(this)&&(e===this.#u||!s.composedPath().includes(e))&&this.closeChain(!1)},n),this.menuBinding?.load().then(()=>{this.#c&&(this.ownerDocument.activeElement===this||!this.contains(this.ownerDocument.activeElement))&&this.focusEntry(t),this.#c&&i()}),this.focusEntry(t)}focusEntry(e=!1){let t=this.usableItems,r=t[e?t.length-1:0];r?(this.#r=r,r.focus()):this.focus()}close(e=!0){for(let t of this.querySelectorAll("gramlot-menu"))t.permanent||t.close(!1);if(this.permanent){this.#i.close(e);return}this.#c&&(this.hidePopover(),this.#c=!1,this.#e?.abort(),this.#o?.setAttribute("aria-expanded","false"),e&&this.#o?.isConnected&&this.#o.focus())}closeChain(e=!0){let t=this.parentMenu;this.close(e&&!t),t&&!t.permanent?t.closeChain(e):t?.isOverflowed(this.parentElement)?t.overflow.close(e):e&&this.#o?.isConnected&&this.#o.focus()}#h(e){if(e.defaultPrevented||e.composedPath().find(c=>c.localName==="gramlot-menu")!==this)return;let t=e.composedPath().find(c=>this.items.includes(c));if(!t&&e.target!==this)return;let r=t&&this.isOverflowed(t),n=this.usableItems.filter(c=>this.isOverflowed(c)===!!r),i=n.indexOf(t),s=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowRight":"ArrowDown",a=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowLeft":"ArrowUp",l;if(e.key===s&&(l=Math.min(n.length-1,i+1)),e.key===a&&(l=Math.max(0,i-1)),e.key==="Home"&&(l=0),e.key==="End"&&(l=n.length-1),l!==void 0){e.preventDefault(),e.stopPropagation(),n[l]?.focus();return}(!this.permanent||r)&&e.key==="ArrowRight"&&t?.submenu?(e.preventDefault(),e.stopPropagation(),t.openSubmenu()):e.key==="Escape"&&(!this.permanent||this.overflow.opened||this.items.some(c=>c.submenu?.opened))||!this.permanent&&e.key==="ArrowLeft"&&this.parentMenu?(e.preventDefault(),e.stopPropagation(),this.close()):e.key==="Tab"&&this.closeChain(!1)}}}function rf(o){return class extends o{#e;#t;#r;#n;#o;#i;#s=null;#a=!1;constructor(){super();let e=this.ownerDocument;this.#r=e.createElement("span"),this.#n=e.createElement("span"),this.#r.className="menu-caption",this.#n.className="menu-check",this.#o=e.createElement("span"),this.#o.className="menu-arrow",this.#o.setAttribute("aria-hidden","true"),this.#n.setAttribute("aria-hidden","true"),this.control.prepend(this.#n),this.control.append(this.#r,this.#o);let t=e.createElement("style");t.textContent=`:host{color:var(--gramlot-ink,CanvasText)} .control-box{color:inherit;height:100%} :host button{color:inherit}
142
142
  .menu-check:empty,.menu-arrow:empty{display:none}
143
143
  button.menu-row{display:grid;grid-template-columns:var(--gramlot-menu-check-track,0px) var(--gramlot-menu-icon-track,0px) minmax(0,1fr) var(--gramlot-menu-arrow-track,0px);column-gap:0;
144
144
  align-items:center;width:100%;min-height:max(24px,var(--gramlot-touch-target,0px));padding:2px 7px;
@@ -175,7 +175,7 @@ ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}
175
175
  :host([data-menu-overflow]) .menu-group,:host([data-menu-group-rows]) .menu-group{flex-direction:column;align-items:stretch;padding:3px 0}
176
176
  :host([data-menu-overflow][role=group]){border-block-end:1px solid var(--gramlot-border-control,#888);margin-block-end:4px}
177
177
  :host([role=group][aria-disabled=true]) .menu-group{opacity:.45;pointer-events:none}
178
- :host([hidden]){display:none!important}`,this.caption.name="command-caption",this.#t=e.createElement("div"),this.#t.className="menu-group",this.#t.append(e.createElement("slot")),this.#t.hidden=!0,this.shadowRoot.append(t,this.#t);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.addEventListener("pointerenter",()=>{this.menuOwner&&(!this.menuOwner.permanent||this.menuOwner.isOverflowed(this))&&!this.disabled&&(clearTimeout(this.#i),this.#i=setTimeout(()=>{if(!(!this.isConnected||this.disabled||!this.menuOwner.opened))if(this.control.focus({preventScroll:!0}),this.submenu)this.openSubmenu();else for(let n of this.menuOwner.items)n.submenu?.close(!1)},180))}),this.addEventListener("pointerleave",()=>clearTimeout(this.#i))}get menuOwner(){return this.parentElement?.closest("gramlot-menu")??null}get submenu(){return[...this.children].map(Ie).find(e=>e?.localName==="gramlot-menu")??null}get entryCaption(){return this.parameters.caption??this.#s?.label??""}get entryIcon(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.icon:this.#s?.icon}get entryIconSrc(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.iconSrc:this.#s?.iconSrc}get occurrence(){return this.parameters.code??this.sourceLabel}setCommandDefinition(e,t){this.#s=e,this.sourceLabel=t,this.#l()}projectAttributes(e,t){let r=super.projectAttributes(e,t);if(this.#e=e["aria-label"],this.parameters.iconSize!=null&&(!Number.isFinite(this.parameters.iconSize)||this.parameters.iconSize<=0))throw new TypeError("menuline iconSize must be positive");return this.#a=!!this.parameters.disabled,this.#l(),this.menuOwner?.refreshItems(),this.menuOwner?.overflow.schedule(),r}#l(){let e=[...this.childNodes].filter(r=>r.nodeType===3).map(r=>r.textContent).join("").trim()==="-"&&!this.parameters.command;this.setAttribute("role",this.parameters.group?"group":e?"separator":this.parameters.checked==null?"menuitem":"menuitemcheckbox"),this.#t.hidden=!this.parameters.group,this.setAttribute("aria-disabled",String(this.#a)),this.parameters.checked!=null?(this.setAttribute("aria-checked",String(this.parameters.checked)),this.control.setAttribute("aria-checked",String(this.parameters.checked))):(this.removeAttribute("aria-checked"),this.control.removeAttribute("aria-checked")),this.#n.textContent=this.parameters.checked?"\u2713":"",this.#r.textContent=this.parameters.command&&!this.#s?"???":this.entryCaption,this.caption.hidden=!0,this.renderIcon(this.entryIcon,this.entryIconSrc);let t=this.parameters.tooltip??this.#s?.tooltip??this.entryCaption;this.control.title=t,this.control.setAttribute("aria-label",this.#e??(this.entryCaption||t)),this.submenu?this.control.setAttribute("aria-haspopup","menu"):this.control.removeAttribute("aria-haspopup"),this.refreshAvailability()}refreshAvailability(){let e=this.menuOwner,t=e&&(!e.permanent||e.isOverflowed(this)),r=a=>{for(let l=this;l&&l!==e;l=l.parentElement)if(l.localName==="gramlot-menu-line"&&l.parameters[a]!=null)return l.parameters[a];return e?.parameters[a]},n=!!(e?.permanent&&!t),i=r("labelPosition");this.control.classList.toggle("toolbar-button",n),this.control.classList.toggle("toolbar-below",n&&i==="below"),this.control.classList.toggle("toolbar-tooltip",n&&i==="tooltip"),n?this.control.style.setProperty("--gramlot-toolbar-icon-size",`${r("iconSize")}px`):this.control.style.removeProperty("--gramlot-toolbar-icon-size"),this.toggleAttribute("data-menu-group-rows",!!(t||e?.parameters.orientation==="vertical")),this.control.classList.toggle("menu-row",t),this.#o.textContent=this.submenu?n&&i==="tooltip"?"\u2304":t||e?.parameters.orientation==="vertical"?"\u203A":"\u25BE":"";let s=this.#a||this.getAttribute("role")==="separator"||!!(this.parameters.command&&!this.#s)||["loading","error"].includes(e?.status)||!!this.closest("gramlot-drop-down-button")?.parameters.disabled;this.control.disabled!==s&&(this.control.disabled=s),this.refreshIconOnly()}get disabled(){for(let e=this.parentElement;e&&e!==this.menuOwner;e=e.parentElement)if(e.localName==="gramlot-menu-line"&&e.parameters.disabled)return!0;return this.control.disabled||!!this.closest("gramlot-drop-down-button")?.parameters.disabled}set disabled(e){this.control.disabled=!!e}attachCommand(){this.#l()}releaseCommand(){clearTimeout(this.#i),this.submenu?.close(!1)}openSubmenu(){if(!(this.disabled||!this.submenu)){for(let e of this.menuOwner.items)e!==this&&e.submenu?.close(!1);this.submenu.open(this.control)}}prepareCommand(e){if(this.parameters.group||this.disabled||this.hidden)return!1;if(this.submenu)return e.stopPropagation(),this.submenu.opened?this.submenu.close():this.openSubmenu(),!1;let t=Ht(this.menuOwner)?.parentElement;return t?.localName==="gramlot-drop-down-button"?t.selectCommand(this,e.shiftKey):this.menuOwner.closeChain(),!0}}}function so(o){return class extends ro(o){#e=null;#t;constructor(){super();let e=this.ownerDocument;this.control=e.createElement("button"),this.control.type="button",this.control.id="control",this.icon=e.createElement("span"),this.icon.className="icon",this.icon.setAttribute("aria-hidden","true"),this.caption=e.createElement("slot"),this.control.append(this.icon,this.caption),this.controlBox.append(this.control);let t=e.createElement("style");t.textContent=`:host{vertical-align:middle} :host([hidden]){display:none} .control-box{display:flex;align-items:stretch}
178
+ :host([hidden]){display:none!important}`,this.caption.name="command-caption",this.#t=e.createElement("div"),this.#t.className="menu-group",this.#t.append(e.createElement("slot")),this.#t.hidden=!0,this.shadowRoot.append(t,this.#t);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.addEventListener("pointerenter",()=>{this.menuOwner&&(!this.menuOwner.permanent||this.menuOwner.isOverflowed(this))&&!this.disabled&&(clearTimeout(this.#i),this.#i=setTimeout(()=>{if(!(!this.isConnected||this.disabled||!this.menuOwner.opened))if(this.control.focus({preventScroll:!0}),this.submenu)this.openSubmenu();else for(let n of this.menuOwner.items)n.submenu?.close(!1)},180))}),this.addEventListener("pointerleave",()=>clearTimeout(this.#i))}get menuOwner(){return this.parentElement?.closest("gramlot-menu")??null}get submenu(){return[...this.children].map(Ie).find(e=>e?.localName==="gramlot-menu")??null}get entryCaption(){return this.parameters.caption??this.#s?.label??""}get entryIcon(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.icon:this.#s?.icon}get entryIconSrc(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.iconSrc:this.#s?.iconSrc}get occurrence(){return this.parameters.code??this.sourceLabel}setCommandDefinition(e,t){this.#s=e,this.sourceLabel=t,this.#l()}projectAttributes(e,t){let r=super.projectAttributes(e,t);if(this.#e=e["aria-label"],this.parameters.iconSize!=null&&(!Number.isFinite(this.parameters.iconSize)||this.parameters.iconSize<=0))throw new TypeError("menuline iconSize must be positive");return this.#a=!!this.parameters.disabled,this.#l(),this.menuOwner?.refreshItems(),this.menuOwner?.overflow.schedule(),r}#l(){let e=[...this.childNodes].filter(r=>r.nodeType===3).map(r=>r.textContent).join("").trim()==="-"&&!this.parameters.command;this.setAttribute("role",this.parameters.group?"group":e?"separator":this.parameters.checked==null?"menuitem":"menuitemcheckbox"),this.#t.hidden=!this.parameters.group,this.setAttribute("aria-disabled",String(this.#a)),this.parameters.checked!=null?(this.setAttribute("aria-checked",String(this.parameters.checked)),this.control.setAttribute("aria-checked",String(this.parameters.checked))):(this.removeAttribute("aria-checked"),this.control.removeAttribute("aria-checked")),this.#n.textContent=this.parameters.checked?"\u2713":"",this.#r.textContent=this.parameters.command&&!this.#s?"???":this.entryCaption,this.caption.hidden=!0,this.renderIcon(this.entryIcon,this.entryIconSrc);let t=this.parameters.tooltip??this.#s?.tooltip??this.entryCaption;this.control.title=t,this.control.setAttribute("aria-label",this.#e??(this.entryCaption||t)),this.submenu?this.control.setAttribute("aria-haspopup","menu"):this.control.removeAttribute("aria-haspopup"),this.refreshAvailability()}refreshAvailability(){let e=this.menuOwner,t=e&&(!e.permanent||e.isOverflowed(this)),r=a=>{for(let l=this;l&&l!==e;l=l.parentElement)if(l.localName==="gramlot-menu-line"&&l.parameters[a]!=null)return l.parameters[a];return e?.parameters[a]},n=!!(e?.permanent&&!t),i=r("labelPosition");this.control.classList.toggle("toolbar-button",n),this.control.classList.toggle("toolbar-below",n&&i==="below"),this.control.classList.toggle("toolbar-tooltip",n&&i==="tooltip"),n?this.control.style.setProperty("--gramlot-toolbar-icon-size",`${r("iconSize")}px`):this.control.style.removeProperty("--gramlot-toolbar-icon-size"),this.toggleAttribute("data-menu-group-rows",!!(t||e?.parameters.orientation==="vertical")),this.control.classList.toggle("menu-row",t),this.#o.textContent=this.submenu?n&&i==="tooltip"?"\u2304":t||e?.parameters.orientation==="vertical"?"\u203A":"\u25BE":"";let s=this.#a||this.getAttribute("role")==="separator"||!!(this.parameters.command&&!this.#s)||["loading","error"].includes(e?.status)||!!this.closest("gramlot-drop-down-button")?.parameters.disabled;this.control.disabled!==s&&(this.control.disabled=s),this.refreshIconOnly()}get disabled(){for(let e=this.parentElement;e&&e!==this.menuOwner;e=e.parentElement)if(e.localName==="gramlot-menu-line"&&e.parameters.disabled)return!0;return this.control.disabled||!!this.closest("gramlot-drop-down-button")?.parameters.disabled}set disabled(e){this.control.disabled=!!e}attachCommand(){this.#l()}releaseCommand(){clearTimeout(this.#i),this.submenu?.close(!1)}openSubmenu(){if(!(this.disabled||!this.submenu)){for(let e of this.menuOwner.items)e!==this&&e.submenu?.close(!1);this.submenu.open(this.control)}}prepareCommand(e){if(this.parameters.group||this.disabled||this.hidden)return!1;if(this.submenu)return e.stopPropagation(),this.submenu.opened?this.submenu.close():this.openSubmenu(),!1;let t=Ht(this.menuOwner)?.parentElement;return t?.localName==="gramlot-drop-down-button"?t.selectCommand(this,e.shiftKey):this.menuOwner.closeChain(),!0}}}function ao(o){return class extends no(o){#e=null;#t;constructor(){super();let e=this.ownerDocument;this.control=e.createElement("button"),this.control.type="button",this.control.id="control",this.icon=e.createElement("span"),this.icon.className="icon",this.icon.setAttribute("aria-hidden","true"),this.caption=e.createElement("slot"),this.control.append(this.icon,this.caption),this.controlBox.append(this.control);let t=e.createElement("style");t.textContent=`:host{vertical-align:middle} :host([hidden]){display:none} .control-box{display:flex;align-items:stretch}
179
179
  button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
180
180
  color:var(--gramlot-button-color,var(--gramlot-ink,CanvasText));background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
181
181
  border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
@@ -215,23 +215,23 @@ ${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}
215
215
  #control.icon-only .led{display:none}
216
216
  @media(forced-colors:active){#control.icon-only{background:ButtonFace;color:ButtonText;border-color:ButtonText}
217
217
  #control.icon-only:is([aria-pressed=true],[aria-checked=true],[aria-expanded=true]){background:Highlight;color:HighlightText}}
218
- `,this.shadowRoot.append(t),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.refreshIconOnly())}connectedCallback(){super.connectedCallback();let e={childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["hidden","slot"]};this.#t.observe(this,e),this.#t.observe(this.control,e),this.refreshIconOnly()}disconnectedCallback(){this.#t.disconnect()}releaseControl(){this.#t.disconnect(),super.releaseControl()}refreshIconOnly(){let e=n=>n.nodeType===3?!!n.textContent.trim():n.nodeType===1&&!n.hidden&&n.getAttribute("slot")!=="menu",t=!this.caption.hidden&&this.caption.assignedNodes().some(e),r=[...this.control.children].some(n=>n!==this.icon&&n!==this.caption&&!n.hidden&&!n.matches(".led,.menu-check,.menu-arrow")&&!(n.matches(".menu-caption")&&this.control.classList.contains("toolbar-tooltip"))&&!!n.textContent.trim());this.control.classList.toggle("icon-only",!this.control.classList.contains("menu-row")&&!!(this.icon.textContent||this.icon.firstElementChild)&&!t&&!r)}get disabled(){return this.control.disabled}set disabled(e){this.control.disabled=!!e}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly,this.renderIcon(this.parameters.icon,this.parameters.iconSrc),e["aria-label"]!=null?this.control.setAttribute("aria-label",e["aria-label"]):this.control.removeAttribute("aria-label"),this.#e&&this.setActionPresentation(this.#e),r}renderIcon(e,t){if(!t){this.icon.textContent=e??"",this.refreshIconOnly();return}let r=this.icon.firstElementChild;r||(r=this.ownerDocument.createElement("img"),r.alt="",r.draggable=!1,this.icon.replaceChildren(r)),r.getAttribute("src")!==t&&r.setAttribute("src",t),this.refreshIconOnly()}get entryIcon(){return this.parameters.icon}get entryIconSrc(){return this.parameters.iconSrc}setActionPresentation(e){this.#e=e,this.hidden=e.hidden,this.icon.textContent=e.icon,this.title=e.title,this.control.setAttribute("aria-label",e.title),this.refreshIconOnly()}attachCommand(){}releaseCommand(){}commandTarget(){return this}prepareCommand(){return!this.disabled}}}so.parameters={action:{dtype:"T",nullable:!0},disabled:{dtype:"B",default:!1,binding:"read"},icon:{dtype:"T",default:"",binding:"read"},iconSrc:{dtype:"T",default:"",binding:"read"}};var Ng=Yt({name:"button",tag:"gramlot-button",base:so,command:!0,subTags:"*",implementation:o=>class extends o{}}),Og=Yt({name:"toggleButton",tag:"gramlot-toggle-button",base:so,command:!0,subTags:"*",parameters:{value:{dtype:"B",default:!1,binding:"twoWay"},readonly:{dtype:"B",default:!1,binding:"read"}},implementation:o=>class extends o{#e=!1;constructor(){super();let e=this.ownerDocument.createElement("span");e.className="led",e.setAttribute("aria-hidden","true"),this.control.prepend(e),this.writeControlValue(!1)}get commitOnChange(){return!0}readControlValue(){return this.#e}writeControlValue(e){this.#e=e,this.control.setAttribute("aria-pressed",String(e))}prepareCommand(e){return!super.prepareCommand(e)||this.control.readOnly?!1:(this.writeControlValue(!this.#e),this.control.dispatchEvent(new this.ownerDocument.defaultView.Event("change")),!0)}}}),$g=Yt({name:"menu",tag:"gramlot-menu",base:tf,subTags:"menuline,spacer,contentPane",parameters:{presentation:{dtype:"T",default:"popup",enum:["popup","bar"]},orientation:{dtype:"T",default:"horizontal",enum:["horizontal","vertical"]},modifiers:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",default:"beside",enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",default:24},resolver:{dtype:"T",nullable:!0},cacheTime:{dtype:"R",default:-1},sync:{dtype:"B",default:!1}},implementation:o=>class extends o{}}),Rg=Yt({name:"menuline",tag:"gramlot-menu-line",base:so,command:!0,subTags:"*",parameters:{command:{dtype:"T",nullable:!0},caption:{dtype:"T",nullable:!0},code:{dtype:"T",nullable:!0},checked:{dtype:"B",nullable:!0,binding:"read"},tooltip:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",nullable:!0,enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",nullable:!0},group:{dtype:"B",default:!1},parameters:{annotation:{kind:"type",module:"builtins",name:"dict"},nullable:!0},favorite:{dtype:"B",default:!1}},implementation:rf}),jg=Yt({name:"spacer",tag:"gramlot-spacer",base:o=>class extends o{projectAttributes(e){let t=br(this,e),{size:r,flex:n}=this.parameters;if(r!=null&&n!=null)throw new TypeError("spacer accepts size or flex, not both");if(r!=null&&(!Number.isFinite(r)||r<0)||n!=null&&(!Number.isFinite(n)||n<=0))throw new TypeError("Invalid spacer size/flex");return this.style.flex=n!=null?`${n} 1 0px`:`0 0 ${r??0}px`,this.setAttribute("aria-hidden","true"),t}},parameters:{size:{dtype:"R",nullable:!0},flex:{dtype:"R",nullable:!0}},implementation:o=>class extends o{}}),Pg=Yt({name:"dropDownButton",tag:"gramlot-drop-down-button",base:so,command:!0,subTags:"*",parameters:{persist:{dtype:"B",default:!1}},implementation:o=>class extends o{#e=null;#t;#r=null;#n;#o;constructor(){super();let e=this.ownerDocument;this.control.classList.add("split"),this.controlBox.classList.add("choice-field");let t=e.createElement("style");t.textContent=cl+".split{border-radius:var(--gramlot-radius-sm,4px);padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .5em)}",this.shadowRoot.append(t),this.#o=e.createElement("span"),this.#o.hidden=!0,this.control.append(this.#o),this.#n=e.createElement("button"),this.#n.type="button",this.#n.className="arrow choice-toggle",this.#n.setAttribute("aria-label","Open menu"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.controlBox.append(this.#n);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.#n.addEventListener("click",n=>{n.stopPropagation(),this.menu.opened?this.closeMenu():this.openMenu()}),this.#n.addEventListener("keydown",n=>{["ArrowDown","ArrowUp"].includes(n.key)&&(n.preventDefault(),this.openMenu(n.key==="ArrowUp"))})}get menu(){return[...this.children].map(Ie).find(e=>e.localName==="gramlot-menu")}get menuItems(){return this.menu?.items??[]}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.#n.disabled=this.disabled,this.disabled&&this.menu?.close(!1),this.#i(),r}attachCommand(){if(this.parameters.persist){if(!this.id)throw new TypeError("dropDownButton persist requires an explicit id");this.#r=`gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;try{this.#e=this.ownerDocument.defaultView.localStorage.getItem(this.#r)}catch{}}this.#i(),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.#i()),this.#t.observe(this,{childList:!0,subtree:!0,characterData:!0})}releaseCommand(){this.#t?.disconnect(),this.menu?.close(!1)}commandTarget(e){return e?.composedPath().includes(this.menu)?null:this.menuItems.find(t=>t.occurrence===this.#e)??this}selectCommand(e,t){if(t){if(this.#e=e.occurrence,this.#r)try{this.ownerDocument.defaultView.localStorage.setItem(this.#r,this.#e)}catch{}this.#i()}this.closeMenu()}#i(){let e=this.menuItems.map(n=>n.occurrence).filter(Boolean);if(new Set(e).size!==e.length)throw new TypeError("Dropdown menu codes must be unique");let t=this.commandTarget(),r=t!==this;this.caption.hidden=r,this.#o.hidden=!r,this.#o.textContent=r?t.entryCaption:"",this.renderIcon(t.entryIcon,t.entryIconSrc)}openMenu(e=!1){this.disabled||this.menu?.open(this.#n,e)}closeMenu(){this.menu?.close()}}}),Vi=fl({name:"buttons",components:[Ng,Og,Pg,$g,Rg,jg]});var kl={};ee(kl,{ValidationRun:()=>kr});var kr=class{epoch=0;controller=null;cancel(){this.epoch++,this.controller?.abort(),this.controller=null}start(e,t,r,n,i,s=()=>{}){this.cancel();let a=new AbortController,l=this.epoch;this.controller=a;let c=r.validationCurrent(),u=()=>l===this.epoch&&!a.signal.aborted&&c(),d=m=>({value:e,modified:!1,error:m.message,warnings:[],issues:[],datachanges:[]}),f=!1,h=m=>{if(f||!u())return{ok:!1};f=!0,this.controller=null;let b={ok:!m.error,value:m.value,result:m,rules:t,isCurrent:u};return i(b),b},p;try{if(t.validate_timeout!=null&&(!Number.isInteger(t.validate_timeout)||t.validate_timeout<=0))throw new TypeError("validate_timeout must be a positive integer in milliseconds.");p=n(e,t,{...r,signal:a.signal})}catch(m){return h(d(m))}return p instanceof Promise?(s(),new Promise(m=>{let b,w=()=>{clearTimeout(b),m({ok:!1})};a.signal.addEventListener("abort",w,{once:!0});let _=v=>{clearTimeout(b),a.signal.removeEventListener("abort",w);try{m(h(v))}catch(E){r.reportError(E,"Validation completion failed"),m({ok:!1})}};t.validate_timeout!=null&&(b=setTimeout(()=>{_(d(new Error("Validation timed out."))),a.abort()},t.validate_timeout)),p.then(_,v=>_(d(v)))})):h(p)}};function ao(o){return typeof o=="string"&&!["null","true","false"].includes(o)&&/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(o)}function Tt(o,e,t,r){let{group:n,method:i}=o.logicRegistry.resolve(t,e);return i.call(n,e,r)}function dt(o,e,t,r,n,i=Object.keys(n)){return ao(r)?Tt(o,e,r,n):o.inlineCompiler.compile(e,t,r,i)(n)}function Wi(o){let e=o.node,t=o.runtime.gramlot,r=(n,i,s,a=!1)=>a?o.runtime.inlineCompiler.compile(e,n,i,Object.keys(s),`return (${i});`)(s):dt(o.runtime,e,n,i,s);return{isDecimal:U,invoke:r,callLogic:(n,i)=>Tt(o.runtime,e,n,i),remote:(n,i,s)=>t.rpc.call("data",n,i,{signal:s}),reportError:(n,i)=>{o.closed||o.runtime.reportError(n,i)},validationCurrent:()=>{let n=e.getAttr("value"),i=e.pointerType(n)?e.absDatapath(n):null;return()=>!o.closed&&e.getAttr("value")===n&&(i===null||e.absDatapath(n)===i)},finishValidation:({ok:n,result:i,rules:s})=>{if(o.closed)return;if(n)for(let l of i.datachanges)e.getRelativeData(".").update(l);let a=n?"validate_onAccept":"validate_onReject";if(s[a]){let l=c=>{o.closed||o.runtime.reportError(c,"Validation callback failed")};try{let c=Object.fromEntries(Object.entries(s).map(([d,f])=>[d.slice(9),f])),u=r(a,s[a],{value:i.value,result:i,validations:c,userChange:!0});u instanceof Promise&&u.catch(l)}catch(c){l(c)}}},checkDataPatch:n=>{if(!(n instanceof x))throw new TypeError("Validation data changes must be a Bag.");if(!(e.getRelativeData(".")instanceof x))throw new TypeError("Validation data changes require a Bag datapath.")}}}var Zt=o=>j(R(o)),Er=(o,e)=>R(o)===R(e),lo=o=>o.absDatapath(o.getAttr("value")),Ue=o=>encodeURIComponent(o).replaceAll(".","%2E"),Kt=o=>Ue(lo(o)),nf=(o,e)=>Ue(o.fullpath)+":"+e,co=class{constructor(e,t,r=e.absDatapath(".")){if(this.node=e,this.runtime=t,this.registers=new x,this.validationQueue=new Set,this.fields=new Map,this.validations=new Map,this.disposed=!1,this.scheduled=!1,this.writing=0,this.path=r,this.retainedFields=new Map,this.listeners=new Set,this.navigators=new Set,this.validationSources=new Set,this.validationDependencies=new Map,this.validationRevision=0,this.validatedRevision=-1,this.fullValidation=null,this.derived=new Set,!(this.data instanceof x))throw new TypeError("A form requires a Bag at its datapath.");this.registers.setItem("baseline",Zt(this.data));for(let n of["changes","errors","pending","drafts"])this.registers.setItem(n,new x);this.subscription=t.router.register({path:this.path,recipient:this,subtree:!0}),t.bindingFor(e).track(()=>this.dispose())}rebind(){let e=this.node.absDatapath(".");if(e!==this.path){if(!(this.data instanceof x))throw new TypeError("A form requires a Bag at its datapath.");this.subscription.close();for(let t of["errors","pending","drafts"])this.registers.setItem(t,new x);this.path=e,this.subscription=this.runtime.router.register({path:e,recipient:this,subtree:!0}),this.updateChanges();for(let t of this.fields.values())t.element.cancelValidation(),this.clearDraft(t.node),this.scheduleValidation(t)}}get data(){return this.runtime.gramlot.data.getItem(this.path)}registerDerived(e){return this.derived.add(e),this.updateChanges(),()=>{this.derived.delete(e)}}isDerived(e){for(let t of this.derived)if(t(e))return!0;return!1}ownAttributes(e,t){return Object.fromEntries(Object.entries(e.attr).filter(([r])=>!this.isDerived(`${t}?${r}`)))}onlyDerived(e,t){return e?Object.keys(this.ownAttributes(e,t)).length?!1:e.value instanceof x?e.value.getNodes().every(r=>this.onlyDerived(r,t?`${t}.${r.label}`:r.label)):this.isDerived(t):!0}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get errorEntries(){return this.registers.getItem("errors").getNodes().map(e=>({path:decodeURIComponent(e.label),message:e.value.getNodes().map(t=>t.value).join(`
219
- `)}))}get changeEntries(){let e=[];for(let t of this.registers.getItem("changes").getNodes()){let r=t.value,n=[this.path,r.getItem("path")].filter(Boolean).join("."),i=r.getItem("existed"),s=r.getItem("exists"),a=r.getItem("previous"),l=r.getItem("current");if((!i||!s||!Er(a,l))&&e.push({path:n,previous:a,current:l,existed:i,exists:s}),i&&s){let c=r.getItem("previousAttributes"),u=r.getItem("currentAttributes");for(let d of new Set([...c.getNodes(),...u.getNodes()].map(f=>f.label))){let f=c.getNode(d)!==null,h=u.getNode(d)!==null;(f!==h||!Er(c.getItem(d),u.getItem(d)))&&e.push({path:n+"?"+d,previous:c.getItem(d),current:u.getItem(d),existed:f,exists:h})}}}return e}registerNavigator(e){return this.navigators.add(e),()=>this.navigators.delete(e)}focusField(e){if(this.disposed)return!1;for(let t of this.fields.values())if(lo(t.node)===e&&t.element.isConnected)return t.element.control.focus(),!0;for(let t of this.navigators)if(t(e))return!0;return!1}retainField(e){this.retainedFields.set(e,(this.retainedFields.get(e)??0)+1)}releaseField(e){let t=this.retainedFields.get(e);if(t>1){this.retainedFields.set(e,t-1);return}if(this.retainedFields.delete(e),![...this.validations.values()].some(r=>r.path===e)){for(let r of["errors","pending","drafts"]){let n=this.registers.getItem(r),i=Ue(e);n.getNode(i)&&n.popNode(i)}this.notify()}}fieldStatus(e){let t=Ue(e);return{error:this.registers.getItem("errors").getItem(t),pending:this.registers.getItem("pending").getItem(t),draft:this.registers.getItem("drafts").getItem(t)}}get status(){let e=this.registers.getItem("changes").length>0,t=this.fullValidation!==null||this.registers.getItem("pending").length>0,r=this.registers.getItem("errors").length>0,n=this.registers.getItem("drafts").length>0;return{dirty:e,pending:t,valid:!r&&!n,canSave:e&&!r&&!n&&!t,status:r?"error":t||n?"pending":e?"changed":"ok"}}register(e){let t=e.node;this.fields.set(t,e);let r=this.registerField(t,e.element.constructor);return r.selection=e.element.validationSelection(),this.schedule(()=>{if(this.fields.get(t)!==e)return;let n=this.registers.getItem("drafts").getNode(Kt(t));n&&(t.formDraft=n.value,e.element.restoreFormDraft(n.value)),r.result&&e.element.presentValidation(r.result);let i=this.registers.getItem("errors").getItem(Kt(t));i&&e.element.error(i.getNodes().map(s=>s.value).join(`
220
- `)),e.element.setFieldState({invalid:!!i,pending:!!this.fieldStatus(r.path).pending})}),()=>{this.fields.delete(t)}}registerField(e,t,r=!0){let n=this.validations.get(e);if(n)return n;if(!t.validationExecutor)throw new TypeError("Grid editors require shared input validation.");let i=this.runtime.bindingFor(e),s=Wi(i);return n={node:e,binding:i,context:s,component:t,run:new kr,execute:t.validationExecutor,checkValue:t.validationValueCheck(s),path:lo(e),rules:null,value:void 0,target:null,result:null,selection:null},this.validations.set(e,n),i.editingSession=this,n.release=i.track(()=>this.forgetField(e)),this.refreshField(e,r),n}registerValidationSource(e){return this.validationSources.add(e),this.invalidateValidation(),()=>{this.validationSources.delete(e),this.invalidateValidation()}}invalidateValidation(){if(this.validationRevision++,this.fullValidation)for(let e of this.fullValidation.active)this.cancelValidation(e)}trackValidationDependency(e){if(e===null||this.validationDependencies.has(e))return;let[t,r=null]=e.split("?",2);this.validationDependencies.set(e,this.runtime.router.register({path:t,attr:r,subtree:!0,recipient:{receive:()=>this.invalidateValidation()}}))}clearValidationDependencies(){for(let e of this.validationDependencies.values())e.close();this.validationDependencies.clear()}validate(){if(this.disposed)return Promise.resolve(!1);if(this.fullValidation)return this.fullValidation.promise;for(let s of this.fields.values())Object.hasOwn(s.node,"formDraft")&&s.commit();this.clearValidationDependencies();let e={revision:this.validationRevision,promise:null,active:new Set,failed:!1,complete:!0};this.fullValidation=e,this.notify();let t=this.validationFields(),r=()=>!this.disposed&&!e.failed&&e.revision===this.validationRevision,n=new WeakSet,i=async()=>{let s=0;for(;r();){let a=t.next();if(a.done)return;let{node:l,release:c}=a.value;try{if(n.has(l))continue;n.add(l);for(let[d,f]of l.pointers())d!=="value"&&this.trackValidationDependency((d==="datapath"?l.parentNode:l).absDatapath(f));e.active.add(l),(await this.validateField(l))?.ok||(e.complete=!1)}finally{e.active.delete(l),c()}++s%20===0&&await new Promise(u=>setTimeout(u,0))}};return e.promise=Promise.resolve().then(async()=>{let a=(await Promise.allSettled(Array.from({length:8},()=>i().catch(c=>{e.failed=!0;for(let u of e.active)this.cancelValidation(u);throw c})))).find(c=>c.status==="rejected");if(a)throw a.reason;if(!r())return!1;let l=e.complete&&this.status.valid&&this.registers.getItem("pending").length===0;return l&&(this.validatedRevision=this.validationRevision),l}).finally(()=>{t.return(),this.fullValidation=null,this.notify()}),e.promise}*validationFields(){let e=[...this.validations.keys()];for(let t of this.validationSources)yield*t();for(let t of e)this.validations.has(t)&&(yield{node:t,release:()=>{}})}forgetField(e){let t=this.validations.get(e);if(t){t.run.cancel(),t.release(),t.binding.editingSession===this&&(t.binding.editingSession=null),this.validations.delete(e),this.validationQueue.delete(e);for(let r of["errors","pending"]){let n=this.registers.getItem(r).getItem(Ue(t.path));if(n){for(let i of[...n.getNodes()])i.label.startsWith(Ue(e.fullpath)+":")&&n.popNode(i.label);n.length||this.registers.getItem(r).popNode(Ue(t.path))}}if(![...this.validations.values()].some(r=>r.path===t.path)){let r=this.registers.getItem("drafts");r.getNode(Ue(t.path))&&r.popNode(Ue(t.path))}delete e.formDraft,this.notify()}}refreshField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||this.writing)return;let[,n]=e.rootBuilder.runtimeValues(e),i=r.component.validationParameters(this.runtime.renderer.evaluateExpressions(e,n)),s=Object.fromEntries(Object.entries(i).filter(([f])=>f.startsWith("validate_"))),a=R(Object.fromEntries(Object.entries(i).filter(([f])=>f!=="value"))),l=lo(e),c=this.runtime.gramlot.data.getNode(l.split("?")[0]),u=e.getRelativeData(e.getAttr("value")),d=r.path!==l||r.target!==c||!Er(r.value,u);if(!(!d&&r.configuration===a)){if(r.rules!==null&&this.invalidateValidation(),this.cancelValidation(e),r.path!==l)for(let f of["errors","pending","drafts"]){let h=this.registers.getItem(f);h.getNode(Ue(r.path))&&h.popNode(Ue(r.path))}Object.assign(r,{path:l,target:c,value:u,rules:s,configuration:a,result:null,selection:r.component.validationSelection(i,r.context)}),d&&this.clearDraft(e),t&&this.scheduleField(e)}}cancelValidation(e){this.validations.get(e)?.run.cancel(),this.validationQueue.delete(e),this.pendingPart(e,"validation",null)}writeCandidate(e,t){this.clearDraft(e),this.writing++;try{this.runtime.renderer.html.writeParameter(e,"value",t)}finally{this.writing--}let r=this.validations.get(e);r&&(r.value=e.getRelativeData(e.getAttr("value")),r.target=this.runtime.gramlot.data.getNode(r.path.split("?")[0]));for(let n of this.validations.keys())n!==e&&this.refreshField(n)}validateCandidate(e,t,r){this.invalidateValidation(),this.cancelValidation(e),this.writeCandidate(e,t);let n=this.validations.get(e);return n.selection=r,this.validateField(e,!1)}scheduleField(e){this.disposed||!this.validations.has(e)||this.validationQueue.has(e)||this.registers.getItem("drafts").getNode(Kt(e))||(this.validationQueue.add(e),this.pendingPart(e,"validation","scheduled"),this.schedule(()=>{this.validationQueue.delete(e)&&this.validateField(e)}))}scheduleValidation(e){this.refreshField(e.node);let t=this.validations.get(e.node);t&&!t.result&&!t.run.controller&&this.scheduleField(e.node)}validateField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||r.binding.closed||(this.validationQueue.delete(e),this.registers.getItem("drafts").getNode(Kt(e)))||this.registers.getItem("pending").getItem(Kt(e))?.getItem(nf(e,"selection")))return;let n=e.getRelativeData(e.getAttr("value")),i=this.fields.get(e);t&&i&&(r.selection=i.element.validationSelection());let s=r.selection,a=r.target,l=r.context.validationCurrent();return r.run.start(n,r.rules,{...r.context,validationCurrent:()=>()=>!this.disposed&&l()&&this.validations.get(e)===r&&this.runtime.gramlot.data.getNode(r.path.split("?")[0])===a,selection:s},r.execute,c=>{if(c.ok)try{r.checkValue(c.value,n)}catch(d){c.ok=!1,c.result.error=d.message}this.result(e,c.result),r.result=c.result,c.ok&&this.writeCandidate(e,c.value);let u=this.fields.get(e);u&&u.element.presentValidation(c.result),r.context.finishValidation(c)},()=>{this.pendingPart(e,"validation","active"),this.fields.get(e)?.element.setFieldState({pending:!0})})}remove(e,t){let r=this.registers.getItem(e),n=Kt(t);r.getNode(n)&&r.popNode(n)}set(e,t,r){r==null?this.remove(e,t):this.registers.getItem(e).setItem(Kt(t),r),this.notify()}draft(e,t){this.invalidateValidation(),this.cancelValidation(e),e.formDraft=t,this.set("drafts",e,t)}clearDraft(e){delete e.formDraft,this.set("drafts",e,null),this.issue(e,"parse",null)}result(e,t){this.pendingPart(e,"validation",null),this.issue(e,"validation",t.error||null)}part(e,t,r,n){r=nf(t,r);let i=this.registers.getItem(e),s=Kt(t),a=i.getItem(s);!a&&n!=null&&(a=new x,i.setItem(s,a)),a&&(n==null?a.getNode(r)&&a.popNode(r):a.setItem(r,n),a.length||this.remove(e,t)),this.notify()}issue(e,t,r){this.part("errors",e,t,r||null)}pendingPart(e,t,r){this.part("pending",e,t,r)}parseError(e,t){this.issue(e,"parse",t)}schedule(e){queueMicrotask(()=>{this.disposed||e()})}receive(e){if(!this.disposed&&(this.updateChanges(e.path),!this.writing)){this.invalidateValidation();for(let t of this.validations.keys())this.refreshField(t)}}updateChanges(e=null){let t=this.registers.getItem("changes"),r=e===this.path?"":e?.startsWith(this.path+".")?e.slice(this.path.length+1).split("?")[0]:"",n=(l,c,u)=>{if(u&&this.isDerived(u))return;let d=l&&this.ownAttributes(l,u),f=c&&this.ownAttributes(c,u);if(l&&c&&l.value instanceof x&&c.value instanceof x&&Er(d,f)){let h=new Set([...l.value.getNodes(),...c.value.getNodes()].map(p=>p.label));for(let p of h)n(l.value.getNode(p),c.value.getNode(p),u?u+"."+p:p)}else(l&&c?!Er([l.value,d],[c.value,f]):!(this.onlyDerived(l,u)&&this.onlyDerived(c,u)))&&t.setItem(Ue(u),new x({path:u,existed:!!l,exists:!!c,previous:l?Zt(l.value):null,current:c?Zt(c.value):null,previousAttributes:l?Zt(d):null,currentAttributes:c?Zt(f):null}))},i=this.registers.getItem("baseline"),s=r;for(let l of t.getNodes()){let c=l.value.getItem("path");s.startsWith(c+".")&&(s=c)}let a=s;for(;a.includes(".");){a=a.slice(0,a.lastIndexOf("."));let l=i.getNode(a),c=this.data.getNode(a);(!l||!c||!Er(l.attr,c.attr))&&(s=a)}for(let l of[...t.getNodes()]){let c=l.value.getItem("path");(!s||c===s||c.startsWith(s+"."))&&t.popNode(l.label)}s?n(i.getNode(s),this.data.getNode(s),s):n({value:i,attr:{}},{value:this.data,attr:{}},""),this.notify()}notify(){this.disposed||this.scheduled||(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1;let e=this.status,t=this.registers.getItem("status");(!t||!Er(t,new x(e)))&&(this.registers.setItem("status",new x(e)),this.node.publish("formStatus",e));for(let r of this.listeners)r()}))}commitField(e){for(let t of this.fields.values())lo(t.node)===e&&Object.hasOwn(t.node,"formDraft")&&t.commit()}accept(){if(this.disposed)return!1;for(let e of this.fields.values())Object.hasOwn(e.node,"formDraft")&&e.commit();return!this.status.valid||this.status.pending||this.validationSources.size&&this.validatedRevision!==this.validationRevision?!1:(this.registers.setItem("baseline",Zt(this.data)),this.updateChanges(),!0)}load(e){if(!(e instanceof x))throw new TypeError("Editing load requires a Bag.");this.disposed||(this.registers.setItem("baseline",Zt(e)),this.restore())}restore(){if(!this.disposed){this.invalidateValidation();for(let e of this.validations.keys())this.cancelValidation(e);for(let e of this.fields.values())e.element.cancelValidation(),this.clearDraft(e.node),e.element.restoreFormValue(this.registers.getItem("baseline").getItem(e.node.absDatapath(e.node.getAttr("value")).slice(this.path?this.path.length+1:0)));this.runtime.gramlot.data.setItem(this.path,Zt(this.registers.getItem("baseline")));for(let e of["errors","pending","drafts"])this.registers.setItem(e,new x);this.updateChanges();for(let e of this.validations.keys())this.scheduleField(e)}}dispose(){if(!this.disposed){this.disposed=!0,this.subscription.close();for(let e of this.validations.keys())this.forgetField(e);this.fields.clear(),this.validationQueue.clear(),this.retainedFields.clear(),this.listeners.clear(),this.navigators.clear(),this.validationSources.clear(),this.clearValidationDependencies()}}};function Bg(o,e,t=o){let r=new Map,n=new Set,i=new Map;for(let[a,l]of e){if(typeof a!="string")continue;let c=H(l)?.pointer??l;i.set(a,c instanceof Y?c.resolve():o.pointerType(c)?t.getRelativeData(c):Le(c)?null:c)}let s=a=>{if(r.has(a))return r.get(a);if(!e.has(a))throw new Error(`Source attribute '${a}' does not exist`);if(n.has(a))throw new Error(`cyclic attribute dependency: ${[...n,a].join(" -> ")}`);n.add(a);let l=e.get(a),c=H(l),u=c?i.get(a):null,d,f=h=>h?s(h):u;try{if(c)if(c.expression){let h=Jr(c.body),p=h.slots.map(f);d=o.rootBuilder.evaluatePointerExpression(o,a,l,h,p)}else d=zt(c.body,f),u==null&&(d=null);else d=i.get(a);return r.set(a,d),d}finally{n.delete(a)}};return{resolve:s}}function Jt(o,e,t=o){let r=new Map([...Object.entries(o.getAttr()),...ge(o.getAttr())]);return Bg(o,r,t).resolve(e)}var Mg={dataFormula:["formula","_if","_else","_ask_if","_ask_onCancel"],dataController:["script","_if","_else","_ask_if","_ask_onCancel"],dataRpc:["_ask_if","_ask_onCancel","_if","_else","_onCalling","_onResult","_onError"],dataRemote:["_if","_else","_onCalling"]},El=["_cachedRemote","_if","_else","_onRemote","_onCalling","_delay","_timing","_userChanges"],Lg=["_if","_else","_onRemote","_onCalling"],Tl=class{#e;#t=null;#r=null;#n=!1;constructor(e){this.#e=e}get inflight(){return this.#t?.view??null}get pending(){let e=this.#r;return e?Object.freeze({method:e.method,get params(){return j(e.text)}}):null}calling(e){if(!e)return!0;let t=!1,r=this.#n;this.#n=!0;try{t=e()!==!1}finally{this.#n=r,!t&&!this.#t&&this.#o()}return t}submit(e,t,r){try{let n=R(t);return this.#t?this.#r?Promise.resolve(void 0):new Promise((i,s)=>{this.#r={method:e,text:n,perform:r,resolve:i,reject:s}}):(this.#r?.resolve(void 0),this.#r=null,this.#i(e,t,n,r))}catch(n){return Promise.reject(n)}}submitSync(e,t){if(this.#t)throw new Error("A synchronous call cannot start while a request of the node is in flight");if(!this.#e.matches(e))throw new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`);return t()}#o(){let e=this.#r;if(!e)return;this.#r=null;let t;try{t=this.#i(e.method,j(e.text),e.text,e.perform)}catch(r){t=Promise.reject(r)}t.then(e.resolve,e.reject)}#i(e,t,r,n){if(!this.#e.matches(e))return Promise.reject(new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`));let i=new AbortController,s={method:e,params:t,text:r,controller:i,ignored:!1};s.view=Object.freeze({method:e,get params(){return j(r)},sentAt:Date.now(),cancel:()=>this.#a(s)}),this.#t=s,i.signal.addEventListener("abort",()=>this.#s(s),{once:!0});let a;try{a=Promise.resolve(n(s))}catch(l){a=Promise.reject(l)}return a.then(()=>this.#s(s),()=>this.#s(s)),a}#s(e){this.#t===e&&(this.#t=null,this.#o())}#a(e){this.#t===e&&(e.ignored=!0,this.#t=null,this.#n||this.#o())}};function of(o){return typeof o=="string"&&o.startsWith("==")}function Fg(o){let e=[],t=r=>{for(let n of r.getNodes())n.nodeTag==="column"&&typeof n.getAttr("formula")=="string"?e.push([`struct.${n.getAttr("field")}.formula`,n.getAttr("formula")]):(n._getMeta("gridStruct")||n.nodeTag==="colgroup")&&n.staticValue instanceof N&&t(n.staticValue)};return o.staticValue instanceof N&&t(o.staticValue),e}var Tr=class extends Se{#e=null;#t=null;get treeStore(){return this.#t}setTreeStore(e){if(this.nodeTag!=="tree")throw new TypeError("setTreeStore requires a tree Source node");if(e!==null&&!(e instanceof x))throw new TypeError("setTreeStore requires a Bag or null");if(e===this.#t)return;this.#t=e;let t=this.rootBuilder.binding,r=t?.bindingFor(this);r&&!r.closed&&(r.rebind(),t.renderer.attached(this)&&t.renderer.project(this))}get formState(){for(let e=this;e;e=e.parentNode){if(e.#e&&e._getMeta("gramlot_component")?.bagStore)return e.#e;if(e.getAttr("formId")!=null||e.getAttr("form")===!0){let t=e.#e??=new co(e,this.rootBuilder.binding);return t.rebind(),t}}return null}editCollection(e){let t=this.parentNode?.formState;if(t){if(e!==t.path&&!e.startsWith(t.path+"."))throw new Error("An edited grid in a form must use data within that form.");return t}if(this.#e&&this.#e.path!==e)throw new Error("An active grid editing session cannot change its storepath.");return this.#e??=new co(this,this.rootBuilder.binding,e)}get frame(){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("frame accessor requires a window");let e=this.value instanceof N?this.value.getNodes():[];if(e.length){if(e.length!==1||e[0].nodeTag!=="framePane")throw new TypeError("A window requires exactly one framePane");return this.builder.wrapSource(e[0])}return this.builder.wrapSource(this.builder.commandOnNode(this,"framePane",null,{node_label:"frame"}))}requestClose(e="application"){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("requestClose requires a window");return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(e)}get grid(){if(this.nodeTag==="framePane"){let e=this.staticValue instanceof N?this.staticValue.getNode("center.grid"):null;if(!e||e.nodeTag!=="grid")throw new TypeError("This frame has no central grid");return this.builder.wrapSource(e)}return(e={})=>this.builder.wrapSource(this.builder.commandOnNode(this,"grid",null,e))}get toolbar(){if(this.nodeTag!=="framePane")throw new TypeError("toolbar accessor requires framePane");let e=this.staticValue instanceof N?this.staticValue.getNode("top.bar"):null;if(!e||e.nodeTag!=="menu")throw new TypeError("This frame has no toolbar");return this.builder.wrapSource(e)}get top(){return this.frameRegion("top")}get bottom(){return this.frameRegion("bottom")}get left(){return this.frameRegion("left")}get right(){return this.frameRegion("right")}get center(){return this.frameRegion("center")}frameRegion(e){if(this.nodeTag!=="framePane")throw new TypeError("Region accessors require framePane");let t=this.value instanceof N?this.value.getNodes().find(n=>n.getAttr("region")===e):null;if(t)return this.builder.wrapSource(t);let r={region:e,node_label:e};return e!=="center"&&Object.assign(r,{display:"flex",flex_direction:["top","bottom"].includes(e)?"column":"row"}),this.builder.wrapSource(this.builder.commandOnNode(this,"contentPane",null,r))}#r=new Set;#n=null;#o=null;get requests(){return this.#o??=new Tl(this.rootBuilder.nameSyntax)}codeAttributes(){let e=[...Mg[this.nodeTag]??[],...Object.entries(this.parentNode?._getMeta("gramlot_component")?.childParameters??{}).filter(([,r])=>r.inline).map(([r])=>r),...this._getMeta("gramlot_component")?.command?["action","_ask_if"]:[],...typeof this.getAttr("remote")=="string"?Lg:[]],t=[];for(let[r,n]of Object.entries(this.getAttr()??{}))typeof n=="string"&&(e.includes(r)||r==="validate_call"||r==="validate__onResult"||r==="validate_onAccept"||r==="validate_onReject"||/^validate_\w+_if$/.test(r)||r.startsWith("connect_on")||r.startsWith("subscribe_")||r.startsWith("selfsubscribe_"))&&t.push([r,n]);for(let r of["ask","_ask"]){let n=this.getAttr(r);if(n&&typeof n=="object")for(let i of["_if","askIf"])typeof n[i]=="string"&&t.push([`${r}.${i}`,n[i]])}for(let[r,n]of ge(this.getAttr()))if(of(n)&&t.push([r,n]),this.nodeTag==="script"&&typeof n=="string"){let i=this.builder.constructor.dialectPrefixes.find(s=>r.startsWith(s))??"";["src","href","xlink:href","xlink_href","_text"].includes(r.slice(i.length).toLowerCase())&&t.push([r,n])}return(of(this.staticValue)||this.nodeTag==="script"&&typeof this.staticValue=="string")&&t.push(["",this.staticValue]),this._getMeta("gramlot_component")?.bagStruct&&t.push(...Fg(this)),t}activateCode(){let e=new Map;for(let[t,r]of this.codeAttributes()){if(this.pointerType(r))throw new Error(`${this.nodeTag} '${this.label}': '${t}' is inline code and cannot be the pointer '${r}'; inline code is never read from Data`);e.set(t,r)}for(let[t,r]of[...ge(this.getAttr()),["datapath",this.getAttr("datapath")]])H(r)?.expression&&e.set(t,r);this.#n=e}activatedCode(e){return this.#n?.get(e)??null}remote(e,t={}){let r=this.rootBuilder.nameSyntax;if(typeof e!="string"||!(this.pointerType(e)||r.matches(e)))throw new TypeError(`${this.nodeTag} '${this.label}': remote name must be a pointer or match ${r.pattern}, not ${JSON.stringify(e)}`);let n=Object.keys(t).find(s=>s.startsWith("_")&&!El.includes(s));if(n)throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${n}' is not accepted; the control attributes are ${El.join(", ")}`);let i={remote:e};for(let[s,a]of Object.entries(t))i[El.includes(s)?s:`remote_${s}`]=a;return this.setAttr(i),on(this)}publish(e,t={}){return this.rootBuilder.binding.subscriptions.publishNode(this,e,t)}pointers(){let e=this.getAttr("datapath"),t=H(e)?Ze(this,e):new Set,r=super.pointers().filter(([n,i])=>!(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(n))&&!t.has(n)&&!this.#a(n,i)).map(([n,i])=>[n,H(i)?.pointer??i]);for(let n of t){let i=this.getAttr(n);this.pointerType(i)==="^"&&r.push(["datapath",H(i)?.pointer??i])}return r}runtimeToEvaluate(){let e=super.runtimeToEvaluate();for(let[t,r]of e){if(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(t)){e.set(t,new _t(()=>r));continue}if(this.pointerType(r)){if(H(r)){if(typeof t!="string")throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);this.absDatapath(r)===null&&e.set(t,new _t(()=>Jt(this,t)));continue}this.#a(t,r)?e.set(t,r.slice(1)):this.absDatapath(r)===null&&e.set(t,null)}}return e}pathAttribute(e){let t=this.getAttr(e);return H(t)?Jt(this,e):this.pointerType(t)&&this.#a(e,t)?t.slice(1):t}getRelativeData(e,t=null,r={}){return this.absDatapath(e)===null?null:super.getRelativeData(e,t,r)}setRelativeData(e,t,r={}){this.#l(e),super.setRelativeData(e,t,r)}PUT(e,t){this.#l(e),this.data.setItem(this.absDatapath(e),t,null,">",!1,!0,this,!1,!1)}FIRE(e,t=!0,r=null){t===null&&(t=!0),this.#l(e);let n=this.absDatapath(e);if(n.includes("?")){this.#i(n,t);return}this.data.getNode(n)?.setValue(null,!1);try{this.fireEvent(e,t,{attributes:r})}finally{this.data.getNode(n)?.setValue(null,!1)}}#i(e,t){let[r,n]=e.split("?",2),i=this.data;i.getNode(r)?.setAttr({[n]:null},!1);try{let s=i.getNode(r);s?s.setValue(s.staticValue,!0,{[n]:t},!0,!0,!0,!0):i.setItem(r,null,{[n]:t},">",!0,!0,!0,!0)}finally{i.getNode(r)?.setAttr({[n]:null},!1)}}FIRE_AFTER(e,t=!0,r=10){this.#l(e);let n=this.rootBuilder?.binding?.bindingFor(this)??null,i=null,s=setTimeout(()=>{i?.(),this.FIRE(e,t)},r);return i=n?.track(()=>clearTimeout(s))??null,()=>{clearTimeout(s),i?.()}}absDatapath(e){e=H(e)?.pointer??e;let t=this.pointerType(e)?e.slice(1):e;if(t.startsWith("#")&&t.includes("?")){let[r,n]=t.split("?",2),i=super.absDatapath(r);return i===null?null:`${i}?${n}`}return super.absDatapath(e)}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let n=r.getAttr("datapath");if(this.pointerType(n)&&(n=this.#s(r,n),n===null))return null;if(n!=null&&(e=e==="."?n:n+e),e.startsWith("#"))return r.parentNode._resolveSymbolicDatapath(e,t);r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_finalizeAbsPath(e,t){return e===null?null:super._finalizeAbsPath(e,t)}_resolveSymbolicDatapath(e,t){let r=e.slice(1).split(".",1)[0];if(r==="FORM"||r==="ANCHOR")return super._resolveSymbolicDatapath(e,t);let n=this.rootBuilder?.binding;if(!n)return super._resolveSymbolicDatapath(e,t);let i=n.nodeIds.get(r);if(!i)throw new Error(`#<id>: cannot resolve ${t}`);let s=e.slice(r.length+2);return i.absDatapath(s?`.${s}`:".")}#s(e,t){if(H(t)){let i=Jt(e,"datapath",e.parentNode);return i==null||i===""?null:i}let r=e.parentNode.absDatapath(t);if(r===null)return null;let n=this.data.getItem(r);return n==null||n===""?null:n}#a(e,t){return H(t)||typeof e!="string"||!e.endsWith("_path")?!1:(this.#r.has(e)||(this.#r.add(e),console.warn(`${this.nodeTag} '${this.label}': '${e}' holds a bare Data path; the pointer symbol of '${t}' is removed`)),!0)}#l(e){if(this.absDatapath(e)===null)throw new Error(`${this.nodeTag} '${this.label}': write on a null path: '${e}'`)}},de=class o extends N{get nodeClass(){return Tr}authorizedCopy(e){let t=new this.constructor;for(let r of this.getNodes()){let n=r.getAttr("auth")??null;if(n!==null){if(typeof n!="string")throw new TypeError(`${r.nodeTag} '${r.label}': 'auth' must be a string rule, not ${typeof n}`);if(e(n)!==null)continue}let i=r.staticValue;i instanceof o&&(i=i.authorizedCopy(e));let{auth:s,...a}=r.getAttr(),l=t.setItem(r.label,i,a,">",!1,!1,null,!1,!0,null,r.nodeTag);l.xmlTag=r.xmlTag}return t}activateCode(){for(let e of this.getNodes())e.activateCode(),e.staticValue instanceof o&&e.staticValue.activateCode();return this}};if((Pe(de.tytxSuffix).GramlotBuilderBag??de)!==de)throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");wt(de.tytxSuffix,{...Pe(de.tytxSuffix),GramlotBuilderBag:de});var zg=new Set(["animate","animateMotion","animateTransform","circle","ellipse","feBlend","feColorMatrix","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feGaussianBlur","feImage","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","image","line","metadata","path","polygon","polyline","rect","set","stop","use"]),uo=class extends Gt{constructor(e,t){super(e),this._owner=t}get owner(){return this._owner}_handleMeta(e,t){let r=this.owner.evaluateExpressions(e,t);vr(e,r);let[n,i]=super._handleMeta(e,r);return yr(e,i),e._getMeta("subbuilder")?[n,Kn(io(i))]:[n,i]}adaptAttrs(e){let{_meta:t,...r}=e;return cn(super.adaptAttrs(xr(Et(r))))}renderedItem(e,t,r,n={}){if(this.owner.renderType==="object")return this.owner.renderedItem(e,t,r,n);let{_text:i,...s}=r;return t=this.owner.expressionValue(e,t),Array.isArray(t)&&i!=null&&(t=[this._escapeText(_r(i)),...t]),zg.has(n.tag)?`${n.pretty?" ".repeat(this._nodeDepth(e,n.depthOffset??0)):""}<${n.tag}${this._formatAttrs(s)} />${n.pretty?`
221
- `:""}`:super.renderedItem(e,t,s,n)}};var Sr=class extends Wt{#e=new WeakMap;#t=new WeakMap;get inlineCompiler(){return null}getRender(e){return this.renders.has(e)||(e instanceof Je?this.addRender(e,this):e instanceof vt&&this.addRender(e,new uo(e,this))),super.getRender(e)}render(e,t={}){if(e._getMeta("data_element"))return null;let[r,n]=e.rootBuilder.runtimeValues(e),i=this.getRender(e.builder),[s,a]=i._handleMeta(e,n);return e._getMeta("subbuilder")||(a=i.adaptAttrs(a)),i.renderedItem(e,e.value instanceof N?this.renderChildren(e.value,t):r,a,{tag:s,...t})}_handleMeta(e,t){let r=this.builder.constructor.dialectPrefixes,n=this.evaluateExpressions(e,t);vr(e,n,r);let[i,s]=super._handleMeta(e,yl(e,n,r));if(yr(e,s,r),e.nodeTag==="webcomponent"){i=xt(e.getAttr());let{code:c,...u}=s;s=u}if(e._getMeta("subbuilder")){let c=io(s);return e._getMeta("subbuilder")==="html"&&(c.xmlns=kt),[i,c]}let[a,l]=vl(i,s);return Object.keys(l).length&&this.#e.set(e,l),[i,a]}evaluateExpressions(e,t){let r=this.inlineCompiler,n=(s,a)=>r?r.compileExpression(e,s,a)(t):null,i={...t};for(let[s,a]of ge(e.getAttr()))e.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(s)||Le(a)&&Object.hasOwn(i,s)&&(i[s]=n(s,a));return Le(e.value)&&this.#t.set(e,n("",e.value)),i}expressionValue(e,t){return Le(e.value)?this.#t.get(e)??null:t}restoreNativeAttributes(e,t){let r=this.#e.get(e);return r?(this.#e.delete(e),{...t,...xr(r)}):t}adaptAttrs(e){let{_meta:t,...r}=e,n=`${this.builder.constructor._name}_`,i=this.builder.constructor.dialectPrefixes,s={},a={};for(let[l,c]of Object.entries(Et(r))){if(c==null)continue;if(l.startsWith(n))throw new Error(`${l}: the attribute prefix '${n}' is not accepted; use the prefix '${i[0]}'`);let u=i.find(d=>l.startsWith(d));u?s[l.slice(u.length)]=c:a[l]=c}return cn({...super.adaptAttrs(a),...s})}renderedItem(e,t,r,n={}){let i;[t,i]=un(this.expressionValue(e,t),this.restoreNativeAttributes(e,r));let{_text:s,...a}=i;Array.isArray(t)&&s!=null&&(t=[this._escapeText(_r(s)),...t]);let l=e.parentNode?._getMeta("subbuilder")==="html"?{xmlns:be,...a}:a;return super.renderedItem(e,t,l,n)}finalize(e,t=null,r={}){if(!r.doctype)return super.finalize(e,t,r);let n=this._composeStringFragments(e),i=this.builder.source.getNodes().filter(s=>!s._getMeta("data_element"));return i.length===1&&i[0].nodeTag==="html"||(n=`<html>${n}</html>`),super.finalize(`<!doctype html>${n}`,t,r)}};var sf={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"binding",version:null,title:"Gramlot binding",description:"Gramlot Data declarations and the plain HTML button; loaded after the HTML grammar."},abstracts:{},elements:{dataBinder:{doc:"Bidirectional subscription between a client Data branch and its page's server store.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"server_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataSetter:{doc:"Initial Data value, written literally at destination_path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!0,default:null},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:"Computed Data value written at result_path; formula is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"formula",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:"Side effects on Data; script is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"script",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRpc:{doc:"Server endpoint called through gramlot.rpc; the value is written at result_path when given.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"timeout",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRemote:{doc:"Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires; with sync (default) the read waits for the answer when the transport supports it.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"cacheTime",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"sync",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"bool"},has_default:!0,default:!0},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},html_button:{doc:"Plain native HTML button without Gramlot click mechanisms.",sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"button"}},html_dialog:{doc:"Native HTML dialog, distinct from the layout window component.",sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"dialog"}}}};var af={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"webcomponent",version:null,title:"Gramlot webcomponent",description:"An explicitly loaded autonomous custom element."},abstracts:{},elements:{webcomponent:{doc:"Create the custom-element tag named by literal code.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"code",kind:"keyword_only",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null}}};var Vg="data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element",Wg=new Set,Gg=new Set(["serverpath","dbenv","shared_id"]),Hg=["formsubscribe_"],Xg={dataSetter:"destination_path",dataFormula:"result_path",dataRpc:"result_path",dataRemote:"destination_path"},Yg={dataFormula:"formula",dataController:"script"},ff=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]),Gi={csv:"CSV",json:"JSON",tytx:"TYTX",xml:"XML",xlsx:"Excel"},lf=new Set(["node_label","frameTarget","nodeId"]),Zg=new Set(["storepath","rowMode","structpath"]);function cf(o,e){let t=o?._meta?.keywordPattern;if(!t)return null;let r=new Set(o.attributes.parameters.filter(i=>!i.kind.startsWith("var_")).map(i=>i.name)),n=Object.keys(e).find(i=>!r.has(i)&&!ff.has(i)&&!new RegExp(t).test(i));return n===void 0?null:`unknown attribute '${n}'`}function Kg(o){if(typeof o=="boolean")return o?Object.keys(Gi):[];if(typeof o!="string"||!o.trim())throw new TypeError("frameGrid export requires a boolean or a list of formats");let e=o.split(",").map(r=>r.trim()),t=e.find(r=>!Object.hasOwn(Gi,r));if(t!==void 0)throw new TypeError(`frameGrid export format '${t}' is not one of ${Object.keys(Gi).join(", ")}`);return e}function uf(o,e){if(["input","textarea","select","webcomponent"].includes(o)&&H(e.value))return"'value' does not accept pointer suffixes; use an ordinary value pointer";if(o==="html_button"&&Object.keys(e).some(n=>["action","ask","_delay","fire"].includes(n)||n.startsWith("fire_")))return"plain HTML button: use button for action, ask, fire or _delay";if(Object.hasOwn(e,"ask")&&!["button","toggleButton","dropDownButton","menuline"].includes(o))return"'ask' is supported on buttons";if(Object.hasOwn(e,"_ask")&&!["dataController","dataFormula","dataRpc"].includes(o))return"'_ask' requires a controller, formula or RPC";if(["dataSetter","dataRemote"].includes(o)&&Object.keys(e).some(n=>n.startsWith("subscribe_")||n.startsWith("selfsubscribe_")))return"topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";let t=Xg[o];if(t&&String(e[t]??"").includes("?"))return`'${t}' does not accept '?attr': '${e[t]}'`;let r=Yg[o];return r&&e[r]!=null&&e.func!=null?`'func' and '${r}' cannot be declared on the same node`:r&&e._if!=null&&e.func!=null?"'_if' is inline and cannot be declared with 'func': write the condition in the method":null}function df(o){return Object.keys(o).find(e=>Gg.has(e)||Hg.some(t=>e.startsWith(t)))}var me=class o extends Je{static _name="gramlot";static containers=["frameGrid"];static _sourceClass=de;static{this.defineGrammar(sf)}static{this.defineGrammar(af)}static{this.defineGrammar(Vi.toDocument())}frameGrid(e,{storepath:t,rowMode:r,structpath:n,searchOn:i=!1,searchHelp:s=!1,chart:a=!1,export:l=!1,printRows:c=!1,advancedTools:u=!1,addrow:d=!1,addrow_defaults:f=null,duprow:h=!1,delrow:p=!1,gridsemaphore:m=!1,...b}={}){for(let z of["framePane","grid"])if(!this.schemaTag(z))throw new TypeError(`frameGrid requires the ${z} collection`);let w={};for(let z of Object.keys(b))z.startsWith("chart_")&&(w[z.slice(6)]=b[z],delete b[z]);let[_,v]=this.frameGridRoute(b),E=Object.keys(v).find(z=>["storepath","rowMode"].includes(z)||z==="structpath"&&n!=null);if(E!==void 0)throw new TypeError(`frameGrid: '${E}' is given twice`);if(a!==!1){if(a!==!0&&(typeof a!="string"||!a))throw new TypeError("chart requires a boolean or chart type");if(!_.datapath)throw new TypeError("A chart frameGrid requires its own datapath");if(!this.schemaTag("chartPane"))throw new TypeError("frameGrid requires the chartPane collection");typeof a=="string"&&(w.chartType=a)}else if(Object.keys(w).length)throw new TypeError("chart_* options require chart");let D=Kg(l);for(let[z,V]of Object.entries({printRows:c,advancedTools:u,addrow:d,duprow:h,delrow:p,gridsemaphore:m}))if(typeof V!="boolean")throw new TypeError(`frameGrid ${z} requires a boolean`);if(f!==null&&(!d||typeof f!="object"||Array.isArray(f)))throw new TypeError("addrow_defaults requires addrow and a mapping");if(m){if(!_.datapath)throw new TypeError("A gridsemaphore frameGrid requires its own datapath");if(!this.schemaTag("editingStatus"))throw new TypeError("frameGrid requires the editingStatus collection");_.form=!0}let k={storepath:t,rowMode:r,...n==null?{}:{structpath:n},node_label:"grid",frameTarget:!0,height:"100%",width:"100%",..._.datapath?{selectedId:"^.selectedId"}:{},...v};a!==!1&&(k.nodeId=G()),this.validateNodeValues("grid",null,k),i!==!1&&this.validateNodeValues("searchBox",null,{searchOn:i,searchHelp:s});let C=e.framePane(_);C.center.grid(k);let O=C.top.menu({presentation:"bar",node_label:"bar",aria_label:"Grid toolbar",class:"gramlot-grid-toolbar"});i!==!1&&O.menuline({group:!0,node_label:"search",class:"gramlot-grid-search"}).searchBox({searchOn:i,searchHelp:s}),d&&O.menuline({command:"grid:addrow",node_label:"addrow",...f===null?{}:{parameters:{defaults:f}}}),h&&O.menuline({command:"grid:duprow",node_label:"duprow"}),p&&O.menuline({command:"grid:delrow",node_label:"delrow"});let L=z=>{let V=z.menuline({caption:"Export",icon:"\u21E9",labelPosition:"tooltip",node_label:"export"}).menu();for(let le of D)V.menuline({command:"grid:export",caption:Gi[le],parameters:{format:le},node_label:le})};if(D.length&&L(O),c&&O.menuline({command:"grid:printRows",node_label:"printRows"}),u){let z=O.menuline({caption:"Advanced tools",icon:"\u2026",labelPosition:"tooltip",node_label:"advancedTools"}).menu();z.menuline({command:"grid:lineNumbers",node_label:"lineNumbers"}),D.length&&L(z),c&&z.menuline({command:"grid:printRows",node_label:"printRows"})}return m&&O.menuline({group:!0,node_label:"semaphore"}).editingStatus(),a!==!1&&(O.menuline({caption:"Chart",icon:"\u25A5",labelPosition:"tooltip",node_label:"chart",action:"this.SET('._chart.open',true)"}),C.center.floatingPane({title:"Chart",open:"^._chart.open",width:"820px",height:"560px",movable:!0,resizable:!0,maximizable:!0,node_label:"chartWindow"}).frame.center.chartPane({storepath:t,rowMode:r,gridId:k.nodeId,configpath:"._chart",configDefaults:new x(w),height:"100%"})),C}frameGridRoute(e){let t=u=>new Set(this.schema[u].attributes.parameters.filter(d=>!d.kind.startsWith("var_")).map(d=>d.name)),r=new Set([...ff,...lt]),n=t("grid"),i=t("framePane"),s=new RegExp(this.schema.grid._meta.parameterPattern),a=u=>(n.has(u)||s.test(u))&&!i.has(u)&&!r.has(u)&&!lf.has(u)&&!Zg.has(u),l={},c={};for(let[u,d]of Object.entries(e)){let f,h;if(u.startsWith("grid_")){if(f=u.slice(5),h=c,lf.has(f))throw new TypeError(`frameGrid: '${u}' is composed by frameGrid`)}else u.startsWith("frame_")?(f=u.slice(6),h=l):(f=u,h=a(u)?c:l);if(Object.hasOwn(h,f))throw new TypeError(`frameGrid: '${f}' is given twice`);h[f]=d}return[l,c]}static get dialectPrefixes(){let e=[];for(let t=Object.getPrototypeOf(o);t&&t!==Function.prototype;t=Object.getPrototypeOf(t))Object.hasOwn(t,"_name")&&t._name&&e.push(`${t._name}_`);return e}constructor(e=null,{collections:t=[],auth:r=null,nameSyntax:n=eo}={}){if(!(n instanceof mr))throw new TypeError(`nameSyntax must be a NameSyntax, not ${n}`);super(e),this._binding=null,this._auth=r,this._nameSyntax=n;for(let i of t)this.loadCollection(i)}get auth(){return this._auth}get nameSyntax(){return this._nameSyntax}get binding(){return this._binding}set binding(e){this._binding=e}evaluatePointerExpression(e,t,r,n,i){return this.binding?this.binding.inlineCompiler.compilePointerExpression(e,t,r,n.text)(i):null}nodeById(e){if(!this.binding)return super.nodeById(e);let t=this.binding.nodeIds.get(e);if(!t)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}loadCollection(e){return this.loadGrammar(e instanceof Xt?e.toDocument():e),this}schemaTag(e){let t=e.toLowerCase(),r=o.dialectPrefixes;if(t.startsWith(`${o._name}_`))throw new Error(`${e}: the tag prefix '${o._name}_' is not accepted; use the prefix '${r[0]}'`);if(Wg.has(t))throw new Error(`${e}: excluded from Gramlot`);let n=this.schemaTagNames[t];if(n)return n;for(let i of r)if(t.startsWith(i)&&this.schemaTagNames[t.slice(i.length)])return t;return null}bagCall(e,t,r,n){return t=this.#e(t),[r,n]=this.menuArguments(t,r,n),super.bagCall(e,t,r,n)}commandOnNode(e,t,r,n){return t=this.#e(t),[r,n]=this.menuArguments(t,r,n),super.commandOnNode(e,t,r,n)}menuArguments(e,t,r={}){if(e==="menu"&&t==null)return[new de(null,this),r];if(e==="menuline"&&t!=null&&t!=="-"){if(Object.hasOwn(r,"command"))throw new TypeError("menuline command must be declared once");return[null,{...r,command:t}]}return[t,r]}validateNodeValues(e,t,r={}){if(this.schema[e]?._meta?.gramlot_component&&H(r.value))throw new Error("'value' does not accept pointer suffixes");e==="webcomponent"&&xt(r);let n=df(r);if(n)throw new Error(`${e}: attribute '${n}' is excluded from Gramlot`);let i=uf(e,r)??cf(this.schema[e],r);if(i)throw new Error(`${e}: ${i}`);return super.validateNodeValues(e,t,r)}validateNode(e,t={}){if(e._getMeta("gramlot_component")&&H((t.attrs??e.getAttr()).value))throw new Error("'value' does not accept pointer suffixes");e.nodeTag==="webcomponent"&&xt(t.attrs??e.getAttr());let r=df(t.attrs??e.getAttr());if(r)throw new Error(`${e.nodeTag} '${e.label}': attribute '${r}' is excluded from Gramlot`);let n=uf(e.nodeTag,t.attrs??e.getAttr())??cf(this.schema[e.nodeTag],t.attrs??e.getAttr());if(n)throw new Error(`${e.nodeTag} '${e.label}': ${n}`);return super.validateNode(e,t)}_validateChildren(e,t,r,n){return super._validateChildren(e,t,r.map(i=>i==="html_button"?"button":i==="html_dialog"?"dialog":i),n)}_countsForGrammar(e){return e===this.schema.button||!e?._meta?.gramlot_component&&e!==this.schema.webcomponent&&super._countsForGrammar(e)}setChild(e,t,r,n,i=null){n=Object.fromEntries(Object.entries(n??{}).map(([l,c])=>[l,Z(c)instanceof Se?this.reference(c):c]));let a=t==="dataSetter"&&n?.value!==null&&typeof n?.value=="object"&&Object.getPrototypeOf(n.value)===Object.prototype?{...n,value:new x(n.value)}:n;return super.setChild(e,t,r,a,i)}#e(e){if(e==="data")throw new Error(Vg);if(this.schemaTagNames[e.toLowerCase()]===e)return e;let t=o.dialectPrefixes.find(r=>e.startsWith(r));return this.schemaTagNames[e.slice(t.length)]}get renderer_html(){return new Sr(this)}create(){this.setup(this.data),this.main(this.root)}computeLogic(){}promoteNodeValue(e,t,r){let n=t!=null?{_text:t}:null;e.setValue(r,!0,n,!0)}reference(e,t="node"){if(e=Z(e),!(e instanceof Se)||!["node","dom"].includes(t))throw new TypeError("Reference requires an element and node/dom kind");let r=e.getAttr("__ref");return r==null&&(r=G(),e.setAttr({__ref:r})),{$gramlotRef:r,kind:t}}toTytx(){return R(this.auth===null?this.source:this.source.authorizedCopy(this.auth))}};function Sl(o){for(let e=o.parentNode;e;e=e.parentNode)if(e.nodeTag==="framePane")return e;return null}function Hi(o){if(!o||!(o.value instanceof N))return null;let e=o.value.getNodes().find(n=>n.getAttr("region")==="center"),t=[];function r(n){if(n.nodeTag!=="framePane"&&(n.getAttr("frameTarget")===!0&&t.push(n),n.value instanceof N))for(let i of n.value.getNodes())r(i)}return e&&r(e),t.length===1?t[0]:null}function Jg(o){if(o.closed||!o.runtime.renderer.attached(o.node))return!1;for(let e=o.node;e;e=e.parentNode){let[,t]=e.rootBuilder.runtimeValues(e);if(t.hidden===!0||t.disabled===!0)return!1}return!0}function hf(o){if(o&&typeof o=="object"){for(let e of Object.values(o))hf(e);Object.freeze(o)}return o}function pf(o,e){let t=o.node,r=t.getAttr("command"),n=o.runtime.gramlot.commands.get(r),i=Sl(t),s=Hi(i);if(!n||!s)return console.warn(`Cannot dispatch command '${r}' at '${t.label}': missing or duplicate frame recipient`),null;let a=t.getAttr("parameters")??{};if(typeof a!="object"||Array.isArray(a))throw new TypeError("Command parameters require a mapping");let l=Object.fromEntries(Object.entries(a).map(([m,b])=>[m,t.pointerType(b)?t.getRelativeData(b):b])),c=hf(j(R(l))),u=Object.freeze(Object.fromEntries(["shift","ctrl","alt","meta"].map(m=>[m,!!e[`${m}Key`]]))),d=Object.freeze({sender:t,target:s,command:r,parameters:c,modifiers:u}),f=!1,h=o.runtime.bindingFor(s).track(()=>{f=!0}),p=()=>!f&&Jg(o)&&Hi(i)===s&&o.runtime.renderer.attached(s)&&t.getAttr("command")===r;return{message:d,current:p,release:h,cancel(){f=!0},deliver(){p()&&s.publish(n.publish,d)}}}var Qg=new Set(["input","select","textarea"]),eb=["type","multiple"];function mf(o,e){let t=o.node,r=t.getAttr(e);return t.pointerType(r)?t.getRelativeData(r):o.resolved[e]}var ve=class o{static liveWrites=!1;static writesDefault=!0;static preservesUnchangedValue=!1;#e;#t=!1;#r;#n;#o=!1;#i=!1;#s=!1;static for(e,t){let r=o.classFor(t.element,t.attrs);return r?new r(e,t):null}static classFor(e,t){if(e.namespaceURI!==be)return null;if(e.constructor.gramlotComponent)return e.constructor.gramlotComponent.parameters.value?.binding!=="twoWay"?null:e.control.type==="radio"?Nl:Al;if(e.localName==="textarea")return ft;if(e.localName==="select")return fo;if(e.localName!=="input")return null;let r=t.type==null?"text":String(t.type).toLowerCase();return Object.hasOwn(gf,r)?gf[r]:ft}static shape(e,t){return e?.constructor.gramlotComponent?.parameters.value?.binding==="twoWay"&&e.control.type==="radio"?JSON.stringify([]):e?.namespaceURI!==be||!Qg.has(e.localName)?null:JSON.stringify(eb.filter(r=>(r!=="type"||e.localName!=="input")&&(r!=="multiple"||!["input","select"].includes(e.localName))).map(r=>t[r]??null))}constructor(e,t){this.#r=e,this.#n=t}get binding(){return this.#r}get element(){return this.#n.element}get node(){return this.binding.node}get eventElement(){return this.element}get resolved(){return this.#n.resolved}get live(){return!!this.resolved.live}get writeEvent(){return this.constructor.liveWrites&&this.live?"input":"change"}project(e,t){if(this.#i){this.#s=!0;return}this.constructor.preservesUnchangedValue&&this.#t&&this.same(this.#e,e)&&(!this.#o||this.same(this.read(),e))||(this.#e=e,this.#t=!0,!(this.#o&&this.same(this.read(),e))&&(this.constructor.writesDefault&&!this.node.pointerType(this.node.getAttr("value"))&&this.writeDefault(e),this.write(e)))}read(){return this.element.value}write(e){let t=e==null?"":String(e);this.element.value!==t&&(this.element.value=t)}writeDefault(e){let t=e==null?"":String(e);this.element.localName==="textarea"?this.#n.text.data!==t&&(this.#n.text.data=t):this.element.defaultValue!==t&&(this.element.defaultValue=t)}same(e,t){return Object.is(e,t)}commit(e,t=this.read()){if(!this.binding.closed){this.#o=!0;try{this.binding.runtime.renderer.html.writeParameter(this.node,"value",t)}finally{this.#o=!1}}}attach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.addEventListener(e,this)}detach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.removeEventListener(e,this);this.#s=!1}refresh(){}handleEvent(e){if(!this.binding.closed){if(e.type==="compositionstart"){this.#i=!0;return}if(e.type==="compositionend"){this.#i=!1,this.writeEvent==="input"&&this.commit(e),this.#s&&(this.#s=!1,this.binding.runtime.renderer.project(this.node));return}this.#i||e.isComposing||e.type===this.writeEvent&&this.commit(e)}}},Al=class extends ve{#e;form=null;static writesDefault=!1;static preservesUnchangedValue=!0;get eventElement(){return this.element.control}attach(){this.form=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null,this.element.setPageContext($l(this)),this.form&&this.node.pointerType(this.node.getAttr("value"))==="^"&&(this.#e=this.form.register(this)),super.attach()}refresh(){let e=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null;e!==this.form&&(this.#e?.(),this.form=e,this.element.setPageContext($l(this)),this.#e=e?e.register(this):null)}project(e,t){this.element.shouldProjectControlValue(e)&&super.project(e,t)}same(e,t){return this.element.sameControlValue(e,t)}detach(){this.element.releaseControl(),this.#e?.(),super.detach()}commit(e){if(this.binding.closed||this.element.control.disabled||this.element.control.readOnly)return;let t=this.element.acceptControlValue();this.form||bf(this.element,t,r=>super.commit(e,r.value))}get writeEvent(){return this.element.commitOnChange?"change":(this.resolved.live??this.element.parameters.live)&&this.element.liveWrites?"input":"change"}read(){return this.element.readControlValue()}write(e){this.element.writeControlValue(e)}handleEvent(e){if(e.type==="input"&&this.form&&!this.binding.closed&&!this.element.control.disabled&&!this.element.control.readOnly&&this.form.draft(this.node,this.element.control.value??""),super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.element.ownerDocument.defaultView.Event;this.element.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}},ft=class extends ve{static liveWrites=!0},Il=class extends ve{static liveWrites=!0;read(){return this.element.value===""?null:Number(this.element.value)}commit(e){this.element.validity.badInput||super.commit(e)}},Cl=class extends ve{static liveWrites=!0;read(){return Number(this.element.value)}},fo=class extends ve{static writesDefault=!1;read(){return this.element.multiple?[...this.element.selectedOptions].map(e=>e.value):this.element.selectedIndex===-1?null:this.element.value}write(e){let t=this.element;if(t.multiple){if(e!=null&&!Array.isArray(e))throw new TypeError(`${this.node.nodeTag} '${this.node.label}': a multiple select requires an array`);let r=new Set((e??[]).map(String));for(let n of t.options){let i=r.has(n.value);n.selected!==i&&(n.selected=i)}}else e==null?t.selectedIndex!==-1&&(t.selectedIndex=-1):(t.selectedIndex===-1||t.value!==String(e))&&(t.value=String(e))}same(e,t){return Array.isArray(e)?Array.isArray(t)&&t.length===e.length&&t.every((r,n)=>Object.is(r,e[n])):super.same(e,t)}},Ar=class extends ve{read(){return this.element.value===""?null:this.element.value}},Dl=class extends ve{},Xi=class extends ve{static writesDefault=!1;read(){return this.element.checked}write(e){let t=!!e;this.element.checked!==t&&(this.element.checked=t)}same(e,t){return e===!!t}attach(){let e=this.node;if(e.getAttr("checked")!=null&&e.pointerType(e.getAttr("value"))==="^")throw new TypeError(`${e.nodeTag} '${e.label}': checked and a ^ value are two sources`);super.attach()}},dn=class extends Xi{#e=null;#t=!1;get groups(){return this.binding.runtime.renderer.radioGroups}attach(){let e=this.node,t=this.resolved.group??null,r=Ol(e);if(t!=null){if(e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);this.#r(t,r)}super.attach(),t!=null&&(this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}detach(){this.#e!==null&&(this.groups.leave(this),this.element.removeAttribute("name"),this.#e=null),super.detach()}refresh(e=this.resolved.group){let t=this.resolved.group??null,r=Ol(this.node);if(!Object.is(e??null,t)){let n=new Set([this,...this.groups.peers(this),...t===null?[]:this.groups.peersOf(t,r)]);this.groups.leave(this),this.#e=t===null?null:this.groups.join(this,t,r),this.#e===null?this.element.removeAttribute("name"):this.element.setAttribute("name",this.#e);for(let i of n){if(this.binding.closed||!this.binding.runtime.renderer.attached(this.node))return;i.binding.closed||!i.binding.runtime.renderer.attached(i.node)||i.binding.runtime.renderer.html.writeParameter(i.node,"value",!1)}return}this.#e!==null&&this.groups.nameOf(t,r)!==this.#e&&(this.#r(t,r),this.groups.leave(this),this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}#r(e,t){let r=this.node;if(mf(this,"value")&&this.groups.peersOf(e,t).some(n=>!n.binding.closed&&n.read()))throw new Error(`${r.nodeTag} '${r.label}': several true values in radio group '${e}'`)}project(e,t){let r=!this.#t;this.#t=!0;let n=this.read();super.project(e,t),!r&&!n&&this.read()&&this.turnOffPeers()}commit(e){let t=this.read();super.commit(e),t&&!this.binding.closed&&this.turnOffPeers()}turnOffPeers(){if(this.#e!==null)for(let e of this.groups.peers(this)){if(this.binding.closed)return;e.binding.closed||(e.element.checked&&(e.element.checked=!1),mf(e,"value")&&e.commit(null))}}},Nl=class extends dn{static writesDefault=!1;get host(){return super.element}get element(){return this.host.control}project(e,t){this.host.shouldProjectControlValue(e)&&super.project(e,t)}commit(e){this.binding.closed||this.element.disabled||this.element.readOnly||bf(this.host,this.host.acceptControlValue(),()=>super.commit(e))}read(){return this.host.readControlValue()}write(e){this.host.writeControlValue(e)}attach(){this.host.setPageContext($l(this)),super.attach(),this.element.addEventListener("keydown",this)}detach(){this.host.releaseControl(),this.element.removeEventListener("keydown",this),super.detach()}handleEvent(e){if(!this.binding.closed){if(e.type==="keydown"){if(this.resolved.group==null||!["ArrowLeft","ArrowUp","ArrowRight","ArrowDown"].includes(e.key))return;let t=this.groups.peersOf(this.resolved.group,Ol(this.node)).filter(s=>!s.binding.closed&&!s.element.disabled),r=t.indexOf(this);if(r<0)return;e.preventDefault();let n=["ArrowLeft","ArrowUp"].includes(e.key)?-1:1,i=t[(r+n+t.length)%t.length];i.element.focus(),i.element.click();return}if(super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.host.ownerDocument.defaultView.Event;this.host.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}}},Yi=class{#e;#t=new Map;#r=new Map;#n=new WeakMap;#o=0;constructor(e){this.#e=e}join(e,t,r){let n=this.nameOf(t,r);return this.#t.has(n)||this.#t.set(n,new Set),this.#t.get(n).add(e),this.#r.set(e,n),n}leave(e){let t=this.#r.get(e);this.#r.delete(e);let r=this.#t.get(t);r?.delete(e),r?.size===0&&this.#t.delete(t)}peers(e){let t=this.#r.get(e);return[...this.#t.get(t)??[]].filter(r=>r!==e)}peersOf(e,t){return[...this.#t.get(this.nameOf(e,t))??[]]}nameOf(e,t){t!==null&&!this.#n.has(t)&&this.#n.set(t,this.#o++);let r=t===null?"page":`form${this.#n.get(t)}`;return`gramlot-${this.#e.instanceId}-${r}-${e}`}};function Ol(o){for(let e=o;e;e=e.parentNode){let t=e.getAttr()??{};if(t.formId!=null||t.form===!0)return e}return null}var gf={text:ft,password:ft,email:ft,url:ft,tel:ft,search:ft,number:Il,range:Cl,color:Dl,date:Ar,time:Ar,month:Ar,week:Ar,"datetime-local":Ar,checkbox:Xi,radio:dn,hidden:null,file:null,button:null,submit:null,reset:null,image:null};function $l(o){let{binding:e,node:t}=o,r=e.runtime.gramlot;return{locale:r.locale,timeZone:r.timeZone,createDecimal:Ye,isDecimal:U,getDecimalLibrary:Zr,form:o.form,formCancelValidation:()=>o.form?.cancelValidation(t),formValidateCandidate:(n,i)=>o.form.validateCandidate(t,n,i),formValidate:()=>o.form?.scheduleValidation(o),formSelectionPending:n=>o.form?.pendingPart(t,"selection",n?"active":null),formSelectionError:n=>o.form?.issue(t,"selection",n),formParseError:n=>o.form?.parseError(t,n),formClearDraft:()=>o.form?.clearDraft(t),publish:(n,i)=>t.publish(n,i),isActive:()=>!e.closed,reportError:(n,i)=>{e.closed||e.runtime.reportError(n,i)},callLogic:(n,i)=>Tt(e.runtime,t,n,i),format:(n,i)=>r.format(n,i),...Wi(e),selectionDisplay:(n,i)=>{if(e.closed)return;let s=t.getAttr("value");if(t.pointerType(s)!=="^"||s.includes("?")||!Object.is(t.getRelativeData(s),i))return;let a=s.slice(1)+"?_displayedValue";t.getRelativeData(a)!==n&&t.setRelativeData(a,n)},periodOutput:(n,i)=>t.setRelativeData(n,i),selectionOutputs:({selectedCaption:n,selectedRecord:i,fields:s},a)=>{if(!e.closed){n&&t.setRelativeData(n,a?.caption??null),i&&t.setRelativeData(i,a?new x(a.record):null);for(let[l,c]of Object.entries(s))t.setRelativeData(c,a?.record[l.slice(9)]??null)}}}}function bf(o,e,t){let r=o.pageContext,n=i=>{i.ok&&i.isCurrent()&&(t(i),o.finishValidation(i))};if(e instanceof Promise)e.then(n).catch(i=>r.reportError(i,"Field update failed"));else try{n(e)}catch(i){r.reportError(i,"Field update failed")}}var Rl=Symbol("source text"),wf={xmlns:"http://www.w3.org/2000/xmlns/",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},tb=new Set(["allowFullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formNoValidate","hidden","inert","isMap","itemscope","loop","multiple","muted","noModule","noValidate","open","playsInline","readOnly","required","reversed","selected"]),rb=new Set(["checked","muted","selected","value"]),nb=new Map([["allowfullscreen","allowFullscreen"],["formnovalidate","formNoValidate"],["ismap","isMap"],["nomodule","noModule"],["novalidate","noValidate"],["playsinline","playsInline"],["readonly","readOnly"]]);function ob(o){let e=o.replace(/-([a-z])/g,(t,r)=>r.toUpperCase());return nb.get(e.toLowerCase())??e}var Zi=class{constructor({format:e,metadataAttributes:t=[],invokeScript:r=null,callLogic:n=null,reportError:i=null,uploadContext:s=null}={}){this.format=e,this.uploadContext=s,this.invokeScript=r,this.callLogic=n,this.reportError=i,this.metadataAttributes=new Set([...lt,"_text",...t])}definition(e){let t=e.builder,n={...t.schema[t.schemaTag(e.nodeTag)]._meta,...e.getAttr("_meta")},i=e.nodeTag==="webcomponent"?xt(e.getAttr()):nn(e.nodeTag,{renderTag:n.render_tag,ns:e.getAttr("ns"),dialectName:t.constructor._name}),s=i==="foreignObject"?kt:n.render_attributes?.xmlns??e.getAttr("xmlns")??(t instanceof vt?kt:be);return{meta:n,namespace:s,tag:i}}validate(e,t=e.builder){this.validateLabelbox(e);let r=e.value instanceof N,n=r?e.getAttr("_text"):e.value;if(n!=null&&!["string","number","boolean"].includes(typeof n))throw new TypeError("HTML text must be scalar");let i=this.definition(e).meta.gramlot_component;for(let[l,c]of Object.entries(e.attr))if(!(i&&Object.hasOwn(i.parameters,l))&&!(e.nodeTag==="menuline"&&l==="parameters")&&!(this.metadataAttributes.has(l)||["ask","_ask"].includes(l)||c&&typeof c=="object"&&Object.hasOwn(c,"$gramlotRef"))&&c!=null&&!["string","number","boolean"].includes(typeof c))throw new TypeError(`HTML attribute ${l} must be scalar`);let s=Object.fromEntries(Object.entries(e.attr).filter(([l])=>!this.metadataAttributes.has(l))),a=r?e.value.getNodes().map(l=>l.nodeTag).filter(Boolean):[];t.validateNode(e,{value:n,attrs:s,childTags:a})}hasLabelbox(e){let t=this.definition(e).meta.gramlot_component;return t?.labelbox?!0:t?.presentationDefaults.length?Object.hasOwn(e.attr,"lbl"):Object.keys(e.attr).some(r=>r==="lbl"||r.startsWith("lbl_")||r.startsWith("box_"))}validateLabelbox(e){if(!this.hasLabelbox(e))return;let{tag:t,namespace:r}=this.definition(e);if(r!==be&&t!=="svg"||["html","head","body","style","script","link","meta","title","base","tr","td","th","thead","tbody","tfoot","col","colgroup","caption","option","optgroup","li","dt","dd","source","track","param","area"].includes(t))throw new TypeError("Labelbox requires content that can be placed in an HTML flow container");let n=e.parentNode;if(n?.nodeTag){let i=this.definition(n);if(i.namespace!==be&&i.tag!=="foreignObject"||["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","ul","ol","dl","p","button","label"].includes(i.tag))throw new TypeError("Labelbox requires an HTML flow container")}}create(e,t,r=null,n=e.attr,i=null){let{tag:s,namespace:a,meta:l}=this.definition(e);r??=s;let c=a===be?t.createElement(r):t.createElementNS(a,r);if(l.gramlot_component&&c.constructor.gramlotComponent?.tag!==r)throw new Error(`Component collection must be activated before rendering ${r}`);l.gramlot_component?.dataScope&&(c.readDataScope=()=>{if(!e.getAttr("datapath"))throw new Error("Data scope requires an explicit datapath");return e.getRelativeData(".")}),l.gramlot_component?.sourceContext&&c.setSourceContext({sourceNode:e,frameRecipient:()=>Hi(Sl(e)),locale:e.rootBuilder.binding.gramlot.locale,timeZone:e.rootBuilder.binding.gramlot.timeZone,collectionView:(f,h)=>e.rootBuilder.binding.collectionView(e,f,h),format:this.format,upload:()=>this.uploadContext(),reportError:(f,h)=>this.reportError(e,f,h),publish:(f,h)=>e.publish(f,h),writeParameter:(f,h)=>this.writeParameter(e,f,h),callLogic:(f,h)=>this.callLogic(e,f,h)});let u=t.createTextNode(this.text(e));(a!==be||!l.void)&&c.append(u);let d={element:c,text:u,tag:r,presentation:c};if(this.hasLabelbox(e)){this.validateLabelbox(e);let f=t.createElement("div");f.append(c),d.labelbox=sl(t,f),d.labelbox.choose=p=>{e.pointerType(e.getAttr("lbl_value"))?this.writeParameter(e,"lbl_value",p):e.setAttr({lbl_value:p})},d.presentation=d.labelbox.box,d.labelId=`gramlot-label-${G()}`,d.controlId=`gramlot-control-${G()}`;let h=t.createElement("style");h.textContent=il,d.presentation.prepend(h),l.gramlot_component?.labelbox&&c.setLabelbox(d.labelbox)}return this.update(d,e,n,Rl,i),d}matches(e,t){let{tag:r,namespace:n}=this.definition(t);return(n===be?e.tag.toLowerCase()===r.toLowerCase():e.tag===r)&&e.element.namespaceURI===n}writeParameter(e,t,r){let n=e.getAttr(t);e.pointerType(n)==="^"&&!H(n)&&!Object.is(e.getRelativeData(n.slice(1)),r)&&e.setRelativeData(n.slice(1),r)}compose(e,t,r){e.text.data=t??"";for(let n of r)e.element.append(n)}update(e,t,r=t.attr,n=Rl,i=null,s=null){if(t.nodeTag==="script"){for(let[w,_]of t.codeAttributes())if(t.activatedCode(w)!==_)throw new Error(`script '${t.label}': '${w}' runs only as received with the Source`)}let{element:a,text:l}=e;if(this.hasLabelbox(t)&&!e.labelbox)throw new TypeError("Declare lbl or box_* when creating an experimental HTML labelbox");let c=a.namespaceURI===be,u=this.definition(t).meta.render_attributes??{},d=e.attrs??{},f=w=>(vr(t,w,t.builder.constructor.dialectPrefixes),yr(t,w,t.builder.constructor.dialectPrefixes),t.builder.renderer_html.adaptAttrs(w)),h=t.parentNode;if(h?._getMeta("gramlot_component")?.childParameters&&(r=a.ownerDocument.defaultView.customElements.get(h._getMeta("render_tag")).projectChild(e.presentation,r,{label:t.label,adapt:f,invoke:(_,v,E)=>this.invokeScript(t,_,v,E),reportError:(_,v)=>this.reportError(t,_,v),publish:(_,v)=>t.publish(_,v),publishParent:(_,v)=>h.publish(_,v),writeParameter:(_,v)=>this.writeParameter(t,_,v),remove:()=>t.parentBag.popNode(t.label)})),e.labelbox){e.labelbox.box.style.visibility="";let w=this.definition(t).meta.gramlot_component?.parameters??{},_=Object.fromEntries(Object.entries(w).filter(([v,E])=>v.startsWith("lbl_")&&Object.hasOwn(E,"default")).map(([v,E])=>[v,E.default]));r.lbl_variant==="card"&&r.lbl_position==null&&delete _.lbl_position,al(e.labelbox,{..._,...r},f)}if(this.definition(t).meta.gramlot_component){if(this.definition(t).meta.gramlot_component.bagStore)if(t.nodeTag==="tree")a.setStoreBag(t.rootBuilder.binding.treeStore(t));else{let w=t.absDatapath(t.getAttr("storepath"));(!s||s.path===w||s.path.startsWith(`${w}.`)||w.startsWith(`${s.path}.`))&&a.setStoreBag(t.getRelativeData(t.getAttr("storepath")))}if(this.definition(t).meta.gramlot_component.bagStruct){let w=t.absDatapath(t.getAttr("structpath"));(!s||s.path===w||s.path.startsWith(`${w}.`)||w.startsWith(`${s.path}.`))&&a.setStructBag(t.getRelativeData(t.getAttr("structpath")))}r=a.projectAttributes(r,f)}e.labelbox&&(r=Object.fromEntries(Object.entries(r).filter(([w])=>w!=="lbl"&&!w.startsWith("lbl_")&&!w.startsWith("box_"))),r.slot!=null?e.presentation.setAttribute("slot",r.slot):e.presentationSlot!=null&&e.presentation.removeAttribute("slot"),e.presentationSlot=r.slot,delete r.slot),r=Object.fromEntries(ge({...r,...u}));let p=ve.classFor(a,r)!==null;n===Rl&&(n=this.text(t));let m=n==null?"":String(n);l.data!==m&&(l.data=m);let b=[...new Set([...Object.keys(d),...Object.keys(r)])];b.sort((w,_)=>(_==="sandbox")-(w==="sandbox")||(c&&a.localName==="input"?(_==="type")-(w==="type"):0));for(let w of b){if(this.metadataAttributes.has(w)||["ask","_ask"].includes(w)||p&&w==="value")continue;let _=r[w];if(c&&w==="multiple"&&["input","select"].includes(a.localName)){a.multiple!==!!_&&(a.multiple=!!_);continue}if(c&&a.localName==="input"&&w==="type"){Object.is(d.type,_)||(_==null?a.removeAttribute("type"):a.type=String(_));continue}let v=w,E=ob(v),D=c&&tb.has(E)&&typeof a[E]=="boolean",k=v==="xmlns"?"xmlns":v.includes(":")?v.split(":")[0]:"",C=Object.hasOwn(wf,k)?wf[k]:null;if(Object.is(d[w],_)||(_==null||D&&!_?C?a.removeAttributeNS(C,v.split(":").at(-1)):a.removeAttribute(v):C?a.setAttributeNS(C,v,String(_)):a.setAttribute(v,D?"":String(_))),c&&(D||rb.has(E))&&E in a){let O=E==="value"?_==null?"":String(_):!!_;a[E]!==O&&(a[E]=O)}}if(i===!1?a.style.visibility!=="hidden"&&(a.style.visibility="hidden"):e.visible===!1&&(r.style==null?a.removeAttribute("style"):a.setAttribute("style",String(r.style))),e.visible=i,e.labelbox){let{fieldLabel:w,labelBox:_,box:v}=e.labelbox;["input","textarea","select","button","output","meter","progress"].includes(e.tag)?(a.id||(a.id=e.controlId),w.htmlFor=a.id):(w.id=e.labelId,this.definition(t).meta.gramlot_component?.labelbox||(v.setAttribute("role","group"),_.hidden?v.removeAttribute("aria-labelledby"):v.setAttribute("aria-labelledby",w.id))),v.hidden=!!r.hidden,i===!1&&(v.style.visibility="hidden")}e.attrs=r}text(e){return e.value instanceof N?e.getAttr("_text")==null?"":String(e.attr._text):e.value==null?"":String(e.value)}};var Ki=class o{#e;#t;#r=null;#n=0;#o=new Set;#i=null;static for(e,t){return t.element?.constructor.gramlotComponent?.command?new o(e,t):null}constructor(e,t){this.#e=e,this.#t=t}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get controllers(){let e=this.node.value;return e?.getNodes?e.getNodes().filter(t=>t.nodeTag==="dataController"||t.nodeTag==="dataRpc"):[]}get mechanism(){let e=this.node,t=this.controllers;if(t.length>1)throw new Error(`${e.nodeTag} '${e.label}': several dataController or dataRpc children; a button has one click mechanism`);let r=e.getAttr()??{},n=[];if(t.length&&n.push("controller"),r.action!=null&&n.push("action"),e.nodeTag==="menuline"&&r.command!=null&&n.push("registered"),_f(r).length&&n.push("fire"),e.nodeTag==="menuline"&&e.value instanceof N&&e.value.getNodes().some(i=>i.nodeTag==="menu")&&n.length)throw new Error(`menuline '${e.label}': a submenu cannot also execute a command`);if(e.nodeTag==="menuline"&&r.group&&n.length)throw new Error(`menuline '${e.label}': a group cannot execute a command`);if(n.length>1)throw new Error(`${e.nodeTag} '${e.label}': ${n.join(" and ")} together; a button has one click mechanism`);return n[0]??null}attach(){this.refresh(),this.element.activateCommand=e=>this.onClick(e),this.element.attachCommand(),this.element.addEventListener("click",this)}refresh(){if(this.node.nodeTag==="menuline"){let t=this.node.getAttr("command"),r=t?this.binding.runtime.gramlot.commands.get(t):null;this.element.setCommandDefinition(r,this.node.label),t&&!r&&this.#i!==t&&(console.warn(`Unknown command '${t}' in menu '${this.node.parentNode?.label}', entry '${this.node.label}'`),this.#i=t)}for(let t of this.#o)t.current()||t.cancel();this.mechanism&&this.node.getAttr("type")==null&&this.element.getAttribute("type")!=="button"&&this.element.setAttribute("type","button")}detach(){this.element.removeEventListener("click",this),this.element.releaseCommand(),delete this.element.activateCommand,this.#r?.();for(let e of this.#o)e.cancel(),e.release();this.#o.clear()}handleEvent(e){this.onClick(e)}onClick(e){if(this.binding.closed||this.element.disabled)return;let t=this.element.commandTarget(e);if(t===null)return;if(t!==this.element)return e.stopPropagation(),t.activateCommand(e);let r=this.element.closest("gramlot-row-actions"),n=r?r.getRowContext():null;if(r&&n===null||!this.element.prepareCommand(e))return;let i=this.mechanism;if(!i||(e.stopPropagation(),this.element.disabled))return;let s=i==="registered"?pf(this.binding,e):null;if(i==="registered"&&!s)return;s&&this.#o.add(s);let a=this.binding.countClick(),l=this.node;for(;l&&l.getAttr("_delay")==null;)l=l.parentNode;let c=l?l.rootBuilder.runtimeValues(l)[1]._delay:0;if(c>0){let u=this.#n+1;this.#r?.(),this.#n=u;let d=setTimeout(()=>{f(),this.#r=null,this.#n=0,this.#a(e,u,s,n)},c),f=this.binding.track(()=>this.#r?.());this.#r=()=>{clearTimeout(d),s&&(s.cancel(),s.release(),this.#o.delete(s)),f(),this.#r=null,this.#n=0};return}return this.#r?.(),this.#a(e,a,s,n)}async#s(e){try{if(!e.current())return;let t=this.node.getAttr("ask"),r=this.binding.runtime.askDialog,n={...e.message.parameters};if(t&&r.required(this.binding,t,n,"ask")&&await r.show(this.binding,t,n)===null)return;e.deliver()}finally{e.release(),this.#o.delete(e)}}#a(e,t,r=null,n=null){if(r)return this.#s(r);if(this.binding.closed||this.element.disabled)return;let i=this.mechanism;if(!i)return;let s=this.node,a=ib(e);if(i==="controller")this.binding.runtime.bindingFor(this.controllers[0])?.providers[0]?.invoke({kind:"click",event:e,counter:t,rowContext:n});else if(i==="action"){let l=()=>{let[,f]=s.rootBuilder.runtimeValues(s),h=Object.fromEntries(Object.entries(f).filter(([p])=>p!=="ask"));return{...this.binding.runtime.renderer.references.resolveArguments(h),...n,event:e,_counter:t,modifiers:a}},c=f=>{if(this.binding.closed||this.element.disabled||f===null)return;let h={...l(),...f};f&&(h._askResult=f),dt(this.binding.runtime,s,"action",s.getAttr("action"),h)},u=s.getAttr("ask"),d=this.binding.runtime.askDialog;if(u&&d.required(this.binding,u,l(),"ask"))return d.show(this.binding,u,l()).then(c);c(void 0)}else{let l={modifier:a,_counter:t},c=s.getAttr("fire");if(c!=null){s.FIRE(c,a||!0,l);return}for(let[u,d]of _f(s.getAttr())){if(this.binding.closed)return;s.FIRE(d,u.slice(5),l)}}}};function _f(o){return Object.entries(o??{}).filter(([e,t])=>t!=null&&(e==="fire"||e.startsWith("fire_")))}function ib(o){return["shift","ctrl","alt","meta"].filter(e=>o[`${e}Key`]).map(e=>e[0].toUpperCase()+e.slice(1)).join("")}var et=class extends Y{static classKwargs={...Y.classKwargs,asBag:!1};constructor({cacheTime:e,onError:t}){super({cacheTime:e??-1}),this.onError=t,this.loading=null,this.loaded=!1,this.writing=!1}resolve({static:e=!1}={}){return!e&&!this.closed&&!this.loading&&!this.writing&&this.expired&&this.refresh(),this.cachedValue}refresh(){if(this.closed)return null;let e=this.startLoad(r=>this.#e(r));if(e===null)return null;let t=()=>{this.loading===e&&(this.loading=null)};return e.then(t,t),this.loading=e,e.catch(r=>{r?.name!=="AbortError"&&this.onError(r)}),e}resolveSync(e){return super.resolve(e)}prepareValue(e){return e}async#e(e){if(this.closed)return;let t=this._computeEffectiveFingerprint(this._buildEffectiveKw()),r=await this.loadAsync(e);if(this.closed||e.ignored)return;let n=this.prepareValue(r);this._lastUpdate=Date.now(),this._lastEffectiveFingerprint=t,this.loaded=!0,this.writing=!0;try{this.node?this.node.setValue(n,this.cacheTime!==0):this.cachedValue=n}finally{this.writing=!1}return n}};var fn=class extends et{static internalParams=new Set([...et.internalParams,"binding","method","params","onCalling","onError","sync"]);constructor({binding:e,method:t,params:r,cacheTime:n,onCalling:i=null,onError:s,sync:a=!1}){super({cacheTime:n,onError:s}),this.binding=e,this.sync=a,this.method=t,this.params=r,this.onCalling=i}get closed(){return this.binding.closed}resolve(e={}){return this.sync?e.static||this.loading||this.writing?this.cachedValue:this.expired&&!this.binding.node.requests.calling(this.onCalling)?this.cachedValue:super.resolveSync(e):super.resolve(e)}load(){let e;try{e=this.binding.callSync("data",this.method,this.params)}catch(t){this.onError(t)}return this.loaded=!0,e}startLoad(e){let t=this.binding.node.requests;return t.calling(this.onCalling)?t.submit(this.method,this.params,e):null}loadAsync(e){return this.binding.call("data",e)}};var yf=new Set(["kind","command","caption","icon","iconSrc","tooltip","disabled","hidden","checked","favorite","parameters","resolver","cacheTime","sync"]);function vf(o,e=new Set){if(!(o instanceof x)||e.has(o))throw new TypeError("Menu resolver must return an acyclic Bag");let t=new Set([...e,o]);return o.getNodes().map(r=>{let n=r.attr,i=n.kind,s=r.staticValue;if(Object.keys(n).some(l=>!yf.has(l)&&!l.startsWith("resolver_")))throw new TypeError(`Unsupported menu record field: ${r.label}`);if(!["command","separator","submenu"].includes(i))throw new TypeError(`Invalid menu kind: ${r.label}`);for(let l of["disabled","hidden","checked"])if(n[l]!=null&&typeof n[l]!="boolean"&&!(typeof n[l]=="string"&&n[l].startsWith("^")))throw new TypeError(`Invalid menu ${l}`);if(n.favorite!=null&&typeof n.favorite!="boolean")throw new TypeError("favorite must be boolean");if(n.caption!=null&&typeof n.caption!="string")throw new TypeError("Menu caption must be text");if(n.parameters!=null&&(typeof n.parameters!="object"||Array.isArray(n.parameters)))throw new TypeError("Menu parameters must be a mapping");if(i==="command"&&(typeof n.command!="string"||!n.command||s!=null||n.resolver!=null))throw new TypeError("Command record requires a command and no children/resolver");if(i==="separator"&&(s!=null||Object.keys(n).length!==1))throw new TypeError("Separator record accepts kind only");if(i==="submenu"&&(typeof n.caption!="string"||n.command!=null||s instanceof x==(n.resolver!=null)||!(s instanceof x)&&s!=null))throw new TypeError("Submenu requires caption and exactly one content source");let a=s instanceof x?vf(s,t):null;return{label:r.label,attrs:{...n},children:a}})}function xf(o,e){let t=o.builder.wrapSource(o),r=o.value instanceof N?o.value.getNodes():[],n=new Set(e.map(i=>i.label));for(let i of r)n.has(i.label)||o.value.popNode(i.label);for(let[i,s]of e.entries()){let{kind:a,...l}=s.attrs,c=Object.fromEntries(Object.entries(l).filter(([p])=>p==="resolver"||p==="cacheTime"||p==="sync"||p.startsWith("resolver_")));for(let p of Object.keys(c))delete l[p];let u=a==="separator"?"-":null,d=o.value instanceof N?o.value.getNodes().find(p=>p.label===s.label):null,f=d?.value instanceof N;if(d&&(f!==(a==="submenu")||d.value==="-"!=(a==="separator"))&&(o.value.popNode(d.label),d=null),!d)d=Z(t.menuline(u,{...l,node_label:s.label}));else{let p=Object.keys(d.attr).filter(m=>yf.has(m)&&!Object.hasOwn(l,m));d.setAttr({...Object.fromEntries(p.map(m=>[m,null])),...l})}if(a==="submenu"){let p=d.value instanceof N?d.value.getNodes().find(m=>m.nodeTag==="menu"):null;p?p.setAttr({...Object.fromEntries(Object.keys(p.attr).filter(m=>m==="resolver"||m==="cacheTime"||m==="sync"||m.startsWith("resolver_")).map(m=>[m,null])),...c}):p=Z(d.builder.wrapSource(d).menu({...c,node_label:"menu"})),s.children&&xf(p,s.children)}let h=o.value.getNodes().indexOf(d);h!==i&&o.value.move(h,i)}}var Ji=class{#e=null;#t=null;#r=0;#n=!1;#o=null;constructor(e,t){this.binding=e,this.element=t}get node(){return this.binding.node}attach(){this.element.menuBinding=this,this.refresh()}detach(){this.#n=!0,this.#r++,this.node.requests.inflight?.cancel(),delete this.element.menuBinding,this.element.close(!1)}refresh(){let[,e]=this.node.rootBuilder.runtimeValues(this.node),t=Object.fromEntries(Object.entries(e).filter(([n])=>n.startsWith("resolver_")).map(([n,i])=>[n.slice(9),i])),r=R([e.resolver,t,e.cacheTime,e.sync]);r!==this.#e&&(this.#e=r,this.#r++,this.#o=null,this.#t=e.resolver?new fn({binding:this.binding,method:e.resolver,params:t,cacheTime:e.cacheTime??-1,sync:e.sync??!1,onError:()=>{}}):null,this.#t?(this.element.setStatus("loading"),this.element.opened&&this.element.isConnected&&this.load()):this.element.setStatus(null))}async load(e=!1){if(this.#n||!this.#t)return;let t=this.#t,r=this.#r;try{if(e?t.refresh():t.resolve(),t.loading&&(this.element.setStatus("loading"),await t.loading),this.#n||r!==this.#r)return;let n=t.cachedValue,i=vf(n),s=R(n);this.#o!==s&&(xf(this.node,i),this.#o=s),this.element.setStatus(i.length?null:"empty")}catch(n){if(this.#n||r!==this.#r)return;this.element.setStatus("error"),console.warn(`Menu '${this.node.label}' failed to load`,n)}}};var Qi=class{#e=!1;#t=!1;constructor(e,t){this.binding=e,this.element=t}attach(){this.element.cardActions=this}detach(){this.#e=!0,delete this.element.cardActions}async clear(){let{binding:e,element:t}=this,r=()=>!this.#e&&!e.closed&&t.isConnected&&t.parameters.delitem===!0;if(this.#t||!r())return;let n=e.node,i=n.value,s=n.absDatapath(".");if(!(s===null||!(i instanceof N))){this.#t=!0;try{if(await e.runtime.askDialog.show(e,{title:"Clear card fields",msg:`Clear the fields of \u201C${t.parameters.title}\u201D? This cannot be undone.`},{})===null||!r()||n.value!==i||n.absDatapath(".")!==s)return;let l=new Map,c=new Set,u=f=>{for(let h of["collapsed","checkbox"]){let p=f.getAttr(h);f.pointerType(p)&&c.add(f.absDatapath(p))}};u(n);let d=f=>{for(let h of f.getNodes()){h.nodeTag==="groupletCard"&&u(h);let p=h.getAttr("value");if(!h._getMeta("data_element")&&h.pointerType(p)==="^"&&!H(p)){let m=h.absDatapath(p);m!==null&&(s===""||m.startsWith(`${s}.`))&&l.set(m,{child:h,pointer:p})}h.staticValue instanceof N&&d(h.staticValue)}};d(i);for(let[f,{child:h,pointer:p}]of l){if(!r()||n.value!==i||n.absDatapath(".")!==s)break;c.has(f)||h.getAttr("value")!==p||h.absDatapath(p)!==f||e.runtime.renderer.html.writeParameter(h,"value",null)}}finally{this.#t=!1}}}};var es="connect_on",ho=class{#e;#t;#r;#n;#o;static declared(e){return Object.entries(e.getAttr()??{}).filter(([t,r])=>t.startsWith(es)&&t.length>es.length&&r!=null).map(([t,r])=>[t,t.slice(es.length).toLowerCase(),r])}constructor(e,t,r,n,i=`${es}${r}`){this.#e=e,this.#t=t,this.#r=r,this.#n=n,this.#o=i}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get eventName(){return this.#r}get handler(){return this.#n}get attribute(){return this.#o}attach(){this.element.addEventListener(this.eventName,this)}detach(){this.element.removeEventListener(this.eventName,this)}handleEvent(e){if(this.binding.closed)return;let t=this.node,r=this.binding.runtime;if(ao(this.handler))return Tt(r,t,this.handler,e);r.inlineCompiler.compile(t,this.attribute,this.handler,["event"])({event:e})}};var Xl={};ee(Xl,{BagCollectionView:()=>vo,parseSort:()=>Hl});var Bl={};ee(Bl,{columnDateMatches:()=>po,columnDateRange:()=>Pl,columnSelection:()=>jl,columnValue:()=>ts,columnValueKey:()=>Qt});function ts(o){if(o==null||o==="")return null;if(typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||o instanceof Date&&Number.isFinite(o.getTime())||U(o)&&o.isFinite())return o;throw new TypeError("Column filters require loaded scalar values")}function Qt(o){return R(ts(o))}function jl(o){if(!Array.isArray(o))throw new TypeError("Column selection requires an array or null");return Object.freeze([...new Map(o.map(e=>{let t=Qt(e);return[t,j(t)]})).values()])}function Pl(o){if(o===null)return null;let{from:e,to:t,dtype:r,timeZone:n}=o;if(!["D","DH","DHZ"].includes(r))throw new TypeError("Date range requires a date column");for(let i of[e,t])if(i!==null&&(!(i instanceof Date)||!Number.isFinite(i.getTime())||i.getUTCHours()||i.getUTCMinutes()||i.getUTCSeconds()||i.getUTCMilliseconds()))throw new TypeError("Date bounds require civil dates");if(e&&t&&e>t)throw new RangeError("From must not be after To.");if(r==="DHZ"&&!n)throw new TypeError("DHZ requires a timeZone");return e||t?Object.freeze({from:e?.toISOString().slice(0,10)??null,to:t?.toISOString().slice(0,10)??null,dtype:r,timeZone:n}):null}function po(o,e){if(!e)return!0;if(o==null||o==="")return!1;if(!(o instanceof Date)||!Number.isFinite(o.getTime()))throw new TypeError("Date range requires date values");let t;if(e.dtype==="DHZ"){let r=new Intl.DateTimeFormat("en",{timeZone:e.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(o),n=i=>r.find(s=>s.type===i).value;t=`${n("year")}-${n("month")}-${n("day")}`}else t=o.toISOString().slice(0,10);return(!e.from||t>=e.from)&&(!e.to||t<=e.to)}var zl={};ee(zl,{compileFilter:()=>Fl});var Ll={};ee(Ll,{parseDateExpression:()=>wo});function Ir(o,e){return e===2?o%4===0&&(o%100!==0||o%400===0)?29:28:[4,6,9,11].includes(e)?30:31}function Fe(o,e,t){if(![o,e,t].every(Number.isInteger)||o<1||o>9999||e<1||e>12||t<1||t>Ir(o,e))throw new RangeError("Date must exist in Gregorian years 0001\u20139999.");return`${String(o).padStart(4,"0")}-${String(e).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function Cr(o){if(typeof o!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(o))throw new RangeError("Expected a civil date in YYYY-MM-DD format.");let e=o.split("-").map(Number);return Fe(...e),e}function mo(o,e,t){let r=o-1,n=365*r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400)+t-1;for(let i=1;i<e;i++)n+=Ir(o,i);return n}function go(o,e){let t=mo(...Cr(o))+e;if(!Number.isSafeInteger(t)||t<0||t>mo(9999,12,31))throw new RangeError("Date offset exceeds Gregorian years 0001\u20139999.");let r=1,n=1e4;for(;n-r>1;){let s=Math.floor((r+n)/2);mo(s,1,1)<=t?r=s:n=s}t-=mo(r,1,1);let i=1;for(;t>=Ir(r,i);)t-=Ir(r,i++);return Fe(r,i,t+1)}function Ml(o){return go(o,-(mo(...Cr(o))%7))}function kf(o,e,t=0,r=1){let n=o*12+e-1+t,i=Math.floor(n/12),s=(n%12+12)%12+1,a=n+r-1,l=Math.floor(a/12),c=(a%12+12)%12+1;return{start:Fe(i,s,1),end:Fe(l,c,Ir(l,c))}}var rs={en:{months:{january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12,jan:1,feb:2,mar:3,apr:4,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12},weekdays:{monday:0,tuesday:1,wednesday:2,thursday:3,friday:4,saturday:5,sunday:6,mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6},quarters:{"1st quarter":1,"2nd quarter":2,"3rd quarter":3,"4th quarter":4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["today"],yesterday:["yesterday"],tomorrow:["tomorrow"],this_week:["this week","week"],last_week:["last week"],next_week:["next week"],this_month:["this month","month"],last_month:["last month"],next_month:["next month"],last:["last"],next:["next"],articles:["the"],from:["from","between"],to:["to","and"],no_period:["no period","always"]},date_order:{default:"MDY",GB:"DMY",AU:"DMY",IE:"DMY",NZ:"DMY",IN:"DMY"}},it:{months:{gennaio:1,febbraio:2,marzo:3,aprile:4,maggio:5,giugno:6,luglio:7,agosto:8,settembre:9,ottobre:10,novembre:11,dicembre:12,gen:1,feb:2,mar:3,apr:4,mag:5,giu:6,lug:7,ago:8,set:9,ott:10,nov:11,dic:12},weekdays:{luned\u00EC:0,marted\u00EC:1,mercoled\u00EC:2,gioved\u00EC:3,venerd\u00EC:4,sabato:5,domenica:6,lun:0,mar:1,mer:2,gio:3,ven:4,sab:5,dom:6},quarters:{"1\xBA trimestre":1,"2\xBA trimestre":2,"3\xBA trimestre":3,"4\xBA trimestre":4,"1\xB0 trimestre":1,"2\xB0 trimestre":2,"3\xB0 trimestre":3,"4\xB0 trimestre":4,t1:1,t2:2,t3:3,t4:4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["oggi"],yesterday:["ieri"],tomorrow:["domani"],this_week:["questa settimana","settimana"],last_week:["settimana scorsa"],next_week:["settimana prossima"],this_month:["questo mese","mese"],last_month:["mese scorso"],next_month:["mese prossimo"],last:["scorso","scorsa"],next:["prossimo","prossima"],articles:["il","lo","la"],from:["da","dal","dalla","tra","fra"],to:["a","al","alla","e"],no_period:["-","senza periodo","sempre"]},date_order:{default:"DMY"}}};function Ef(o){if(typeof o!="string")throw new RangeError("A supported locale is required.");let e=o.replaceAll("-","_"),t=e.indexOf("_"),r=(t<0?e:e.slice(0,t)).toLowerCase(),n=(t<0?"":e.slice(t+1)).toUpperCase();if(!Object.hasOwn(rs,r))throw new RangeError(`Unsupported locale: ${o}`);let i=rs[r];return{dictionary:i,phrases:a=>[...new Set([...i.keywords[a],...rs.en.keywords[a]])],order:i.date_order[n]??i.date_order.default}}var Dr=/^(?:\d{4}|\d{2})$/,Tf=/^\d{1,2}$/,bo=(o,e)=>({ok:!1,error:{code:o,message:e}}),Or=(o="UNRECOGNIZED_EXPRESSION",e="Text is not a supported date expression.")=>{throw Object.assign(new SyntaxError(e),{code:o})},If=(o,e)=>Object.hasOwn(o,e);function Nr(o,e){if(o.length===4)return Number(o);let t=e.year+e.twoDigitYearAhead-100;return t+((Number(o)-t)%100+100)%100}function sb(o,e){if(o.includes(";")){let n=o.split(";").map(i=>i.trim());return n.length!==2?Or("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:n,range:!0}}if(e.phrases("no_period").includes(o))return{bounds:["",""],range:!0};let t=e.phrases("to"),r=e.phrases("from");for(let n of t)if(o.startsWith(`${n} `))return{bounds:["",o.slice(n.length+1).trim()],range:!0};for(let n of t){let i=` ${n} `;if(!o.includes(i))continue;for(let a of r)if(o.startsWith(`${a} `)){o=o.slice(a.length+1);break}let s=o.split(i).map(a=>a.trim());return s.length!==2?Or("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:s,range:!0}}for(let n of r)if(o.startsWith(`${n} `))return{bounds:[o.slice(n.length+1).trim(),""],range:!0};return{bounds:[o,o],range:!1}}function ab(o,e,t){let r=[[o,0]],n=/^(.+?)\s*([+-])\s*(\d+)$/.exec(o);n&&r.push([n[1],Number(n[2]+n[3])]);let i={today:0,yesterday:-1,tomorrow:1,this_week:0,last_week:-1,next_week:1,this_month:0,last_month:-1,next_month:1};for(let[s,a]of r)for(let[l,c]of Object.entries(i))if(e.phrases(l).includes(s)){if(l.endsWith("_week"))return go(Ml(e.workdate),(c+a)*7+(t?6:0));if(l.endsWith("_month")){let u=kf(e.year,e.month,c+a);return t?u.end:u.start}return go(e.workdate,c+a)}return null}function lb(o,e,t){let r=Object.entries(e.dictionary.quarters).sort((n,i)=>i[0].length-n[0].length);for(let[n,i]of r){let s;if(o===n)s=null;else if(o.startsWith(n)&&Dr.test(o.slice(n.length).trim()))s=Nr(o.slice(n.length).trim(),e);else if(o.endsWith(n)&&Dr.test(o.slice(0,-n.length).trim()))s=Nr(o.slice(0,-n.length).trim(),e);else continue;return{year:s,month:t?i*3:i*3-2}}return null}function Sf(o,e){if(If(e.months,o))return e.months[o];let t=/^m(\d{1,2})$/.exec(o);return t&&Number(t[1])>=1&&Number(t[1])<=12?Number(t[1]):null}function cb(o,e){let t=o.split(/\s+/),r=t.map((c,u)=>Sf(c,e.dictionary)?u:-1).filter(c=>c>=0);if(!r.length)return null;if(r.length!==1)return Or();let n=r[0],i=Sf(t[n],e.dictionary),s=t.slice(0,n),a=t.slice(n+1),l=[...s,...a];if(l.length===1&&e.phrases("last").includes(l[0]))return{year:e.year-(i>e.month?1:0),month:i};if(l.length===1&&e.phrases("next").includes(l[0]))return{year:e.year+(i<e.month?1:0),month:i};if(!l.length)return{year:null,month:i};if(!s.length&&a.length===1&&Dr.test(a[0]))return{year:Nr(a[0],e),month:i};if(s.length===1&&Tf.test(s[0])){if(!a.length)return Fe(e.year,i,Number(s[0]));if(a.length===1&&Dr.test(a[0]))return Fe(Nr(a[0],e),i,Number(s[0]))}return!s.length&&a.length===2&&Tf.test(a[0])&&Dr.test(a[1])?Fe(Nr(a[1],e),i,Number(a[0])):Or()}function ub(o,e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(t)return Fe(...t.slice(1).map(Number));let r=/^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(o),n={};if(r)e.order.split("").forEach((a,l)=>{n[a]=r[l+1]});else if(/^(?:\d{6}|\d{8})$/.test(o)){let a=o.length===8?4:2;for(let l of e.order){let c=l==="Y"?a:2;n[l]=o.slice(0,c),o=o.slice(c)}}else return null;if(!Dr.test(n.Y)||n.D.length>2||n.M.length>2)return Or();let i=Number(n.D),s=Number(n.M);return r&&s>12&&i<=12&&([i,s]=[s,i]),Fe(Nr(n.Y,e),s,i)}function Af(o,e,t){if(!o)return null;let r=e.phrases("articles");if(o=o.split(/\s+/).filter(i=>!r.includes(i)).join(" "),!o)return Or();if(Dr.test(o))return Fe(Nr(o,e),t?12:1,t?31:1);let n=ab(o,e,t)??lb(o,e,t)??cb(o,e);return n!==null?n:If(e.dictionary.weekdays,o)?go(Ml(e.workdate),e.dictionary.weekdays[o]):ub(o,e)??Or()}function db(o,e,t){if(o===null||typeof o=="string")return o;let r=o.year??t.year,n=typeof e=="string"?Cr(e)[0]:e?.year,i=typeof e=="string"?Cr(e)[1]:e?.month;return n&&(r>n&&(r=n),r===n&&o.month>i&&r--),Fe(r,o.month,1)}function fb(o,e,t){if(o===null||typeof o=="string")return o;let r=o.year??t.year;if(e!==null){let[n,i]=Cr(e);r<n&&(r=n),r===n&&i>o.month&&r++}return Fe(r,o.month,Ir(r,o.month))}function wo(o,e={}){if(!e||typeof e!="object"||Array.isArray(e))return bo("INVALID_CONTEXT","Options must provide a civil workdate and supported locale.");let t;try{let{locale:r="it-IT",workdate:n,twoDigitYearAhead:i=20}=e,[s,a]=Cr(n);if(!Number.isInteger(i)||i<0||i>99)throw new RangeError("twoDigitYearAhead must be an integer from 0 to 99.");t={...Ef(r),workdate:n,year:s,month:a,twoDigitYearAhead:i}}catch(r){return bo("INVALID_CONTEXT",r.message)}if(typeof o!="string")return bo("INVALID_INPUT","Expression must be a string.");try{let r=o.toLowerCase().trim().replaceAll(",",""),{bounds:n,range:i}=sb(r,t),s=Af(n[1],t,!0),a=Af(n[0],t,!1),l=db(a,s,t),c=fb(s,l,t);return!i&&typeof a=="string"&&l===c?{ok:!0,kind:"date",date:l}:{ok:!0,kind:"period",start:l,end:c}}catch(r){if(r instanceof RangeError)return bo("INVALID_DATE",r.message);if(r instanceof SyntaxError)return bo(r.code,r.message);throw r}}function Fl(o){if(o===null)return null;let{value:e,columns:t,dtype:r,locale:n}=o;if(typeof e!="string"||!Array.isArray(t)||!t.length||t.some(c=>typeof c!="string"||!c||c==="rowidx")||!["T","L","R","N","D"].includes(r))throw new TypeError("Invalid collection filter");if(!e.trim())return null;if(r==="T"){let c=o.literal===!0?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e,u=new RegExp(c,"i");return d=>u.test(t.map(f=>hb(d(f),n,o.timeZone)).join(" "))}if(t.length!==1)throw new TypeError("Typed filters require one column");let i=/^\s*(<=|>=|==|!=|[<>=!#])\s*(.+?)\s*$/.exec(e);if(!i)throw new Error("Enter a comparison, for example > 100 or = 12.");let[,s,a]=i,l;if(r==="D"){let c=new Date,u=`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")}`,d=wo(a,{locale:n,workdate:u});if(!d.ok||d.kind!=="date")throw new Error("Enter one complete date after the comparison.");l=new Date(`${d.date}T00:00:00Z`)}else l=pb(a,n);return c=>{let u=c(t[0]);if(u==null)return!1;if(r==="D"?!(u instanceof Date)||!Number.isFinite(u.getTime()):!(typeof u=="number"&&Number.isFinite(u)||U(u)&&u.isFinite()))throw new TypeError(`Filter value does not match ${r}`);let d=U(l)?-l.comparedTo(u):u<l?-1:u>l?1:0;switch(s){case"=":case"==":return d===0;case"!":case"#":case"!=":return d!==0;case"<":return d<0;case">":return d>0;case"<=":return d<=0;case">=":return d>=0}}}function hb(o,e,t){return o==null?"":typeof o=="string"||typeof o=="boolean"?String(o):oo(o,{pattern:o instanceof Date?"short":"#,##0.####################"},{locale:e,timeZone:t})}function pb(o,e){let t=new Intl.NumberFormat(e).formatToParts(-12345.6),r=t.find(l=>l.type==="decimal").value,n=t.find(l=>l.type==="group")?.value,i=t.find(l=>l.type==="minusSign").value,s=o.replaceAll(i,"-");if(n&&s.includes(n)){let c=s.split(r)[0].replace(/^[+-]/,"").split(n),u=new Intl.NumberFormat(e).formatToParts(1234567890123).filter(h=>h.type==="integer").map(h=>h.value.length),d=u.at(-1),f=u.at(-2);if(s.split(r).slice(1).some(h=>h.includes(n))||!/^\d+$/.test(c[0])||c[0].length>f||c.slice(1).some((h,p)=>!/^\d+$/.test(h)||h.length!==(p===c.length-2?d:f)))throw new Error("Invalid numeric grouping.");s=s.replaceAll(n,"")}if(s=s.replace(r,"."),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(s))throw new Error("Enter a complete number.");let a=Ye(s);if(!U(a)||!a.isFinite())throw new Error("A finite Decimal backend is required.");return a}var Wl={};ee(Wl,{containsId:()=>ql,requireId:()=>Vl,requireIdSet:()=>Ul});function ql(o,e){return(","+o+",").includes(","+e+",")}function Ul(o){if(typeof o!="string")throw new TypeError("grid checked must refer to a string (empty string for an empty set)");return o}function Vl(o){if(typeof o!="string"||!o||o.includes(","))throw new TypeError("grid checkedField requires nonempty text IDs without commas");return o}var Gl={};ee(Gl,{BagCollectionStore:()=>_o,publishCollection:()=>yo});var _o=class{#e=new Set;constructor(e,t){if(!(e instanceof x))throw new TypeError("collection store requires a Bag");if(!["values","attributes"].includes(t))throw new TypeError("collection store rowMode must explicitly be values or attributes");if(!e.parentNode)throw new TypeError("collection store requires a Bag attached to Data");this.bag=e,this.rowMode=t}subscribe(e){return this.#e.add(e),()=>this.#e.delete(e)}receiveData(e,t=null,r=null){yo(this.#e,{full:t===null,rows:t?[t]:[],event:e,field:r})}getRows(){let e=this.bag.getNodes();for(let t of e){if(t.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="values"&&!(t.staticValue instanceof x))throw new TypeError(`collection store row ${t.label} must contain a Bag`)}return e}value(e,t){if(e.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="attributes")return e.getAttr(t);let r=e.staticValue;if(!(r instanceof x))throw new TypeError(`collection store row ${e.label} must contain a Bag`);let n=r.getNode(t);if(n?.resolver)throw new TypeError("collection store requires loaded cells");return n?.staticValue}};function yo(o,e){let t=[],r=Object.freeze({full:e.full,rows:Object.freeze([...e.rows]),event:e.event??null,field:e.field??null});for(let n of[...o])if(o.has(n))try{n(r)}catch(i){t.push(i)}if(t.length)throw new AggregateError(t,"Collection notification failed")}var vo=class{#e;#t=null;#r=new Set;#n=new Map;#o="";#i=new Map;#s=null;constructor(e){this.bindStore(e)}get bag(){return this.#e.bag}get rowMode(){return this.#e.rowMode}get sortedBy(){return this.#o}get criteria(){return Hl(this.#o)}get filter(){return this.#i.get("search")?.definition??null}get filterSignature(){return JSON.stringify([...this.#i].map(([e,{definition:t}])=>[e,t]))}get filterContributions(){return Object.freeze([...this.#i].map(([e,t])=>Object.freeze([e,Object.freeze({...t})])))}copyFiltersFrom(e){this.filterSignature!==e.filterSignature&&this.#c(this.#a(),this.#o,new Map(e.filterContributions))}get filtered(){return this.#s===null?null:[...this.#s]}isFiltered(){return this.#s!==null}value(e,t){return this.#e.value(e,t)}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}connect(){this.#t||(this.synchronize(),this.#t=this.#e.subscribe(e=>this.synchronize(e)))}disconnect(){this.#t?.(),this.#t=null}bindStore(e){if(this.#e===e)return;let t=this.#t!==null;this.disconnect(),this.#e=e,this.#n.clear(),t?this.connect():this.synchronize()}getRows(e=!0){let t=this.#a();return e&&this.#s!==null?this.#s.map(r=>t[r]):t}#a(){return this.#e.getRows().toSorted((e,t)=>(this.#n.get(e)??1/0)-(this.#n.get(t)??1/0))}synchronize(e={full:!0,rows:[]}){if(!e.full&&!this.#o&&!this.#i.size){yo(this.#r,{full:e.full,rows:e.rows});return}this.#c(this.#u(this.#a(),this.criteria),this.#o,this.#i,e)}sort(e){let t=this.#u(this.#a(),Hl(e));this.#c(t,e,this.#i)}moveRow(e,t,r=!1){if(e===t||e.parentBag!==this.bag||t.parentBag!==this.bag)return;let n=this.getRows(!1);n.splice(n.indexOf(e),1),n.splice(n.indexOf(t)+Number(r),0,e),this.#c(n,"",this.#i)}applyFilter(e,t="search"){if(!["base","search"].includes(t))throw new TypeError("Unknown collection filter contribution");let r=e===null?null:Object.freeze({...e,columns:Object.freeze([...e.columns])});this.#l(t,r,Fl(r))}applySetFilter(e){let t=e===null?null:Object.freeze(e.map(({field:n,value:i})=>{if(typeof n!="string"||!n)throw new TypeError("Set filter requires an identity field");return Ul(i),Object.freeze({field:n,value:i})})),r=t===null?null:n=>t.every(({field:i,value:s})=>ql(s,Vl(n(i))));this.#l("sets",t,r)}columnFilter(e){return this.#i.get(`column:${e}`)?.definition.values??null}columnRange(e){let t=this.#i.get(`column:${e}`)?.definition.range;return t?{...t,from:t.from&&new Date(t.from+"T00:00:00Z"),to:t.to&&new Date(t.to+"T00:00:00Z")}:null}applyColumnFilter(e,t,r=this.columnRange(e)){if(r=Pl(r),typeof e!="string"||!e)throw new TypeError("Column filter requires a field");let n=t===null?null:jl(t),i=n?.map(Qt),s=n===null&&r===null?null:Object.freeze({field:e,values:n,keys:i&&Object.freeze(i),range:r}),a=s===null?null:l=>po(l(e),r)&&(i===void 0||i.includes(Qt(l(e))));this.#l(`column:${e}`,s,a)}columnFacets(e){let t=new Map,r=this.#i.get(`column:${e}`)?.definition.range??null,n=this.columnFilter(e),i=n?.map(Qt),s=[...this.#i].filter(([a])=>a!==`column:${e}`).map(([,a])=>a.predicate).filter(a=>a!==null);for(let a of this.#a()){let l=ts(this.value(a,e)),c=Qt(l);t.has(c)||t.set(c,{key:c,value:l,count:0,selected:po(l,r)&&(i===void 0||i.includes(c))}),s.every(u=>u(d=>this.value(a,d)))&&t.get(c).count++}for(let a of n??[]){let l=Qt(a);t.has(l)||t.set(l,{key:l,value:a,count:0,selected:!0})}return[...t.values()].filter(a=>po(a.value,r))}#l(e,t,r){if(JSON.stringify(this.#i.get(e)?.definition??null)===JSON.stringify(t))return;let n=new Map(this.#i);t===null?n.delete(e):n.set(e,{definition:t,predicate:r}),this.#c(this.#a(),this.#o,n)}#c(e,t,r,n={full:!1,rows:[]}){let i=[...r.values()].map(u=>u.predicate).filter(u=>u!==null),s=i.length?e.flatMap((u,d)=>i.every(f=>f(h=>this.value(u,h)))?[d]:[]):null,a=n.full||t!==this.#o||r!==this.#i||e.length!==this.#n.size||e.some((u,d)=>this.#n.get(u)!==d)||JSON.stringify(s)!==JSON.stringify(this.#s);this.#n=new Map(e.map((u,d)=>[u,d])),this.#o=t,this.#i=r,this.#s=s;let l=s===null?null:new Set(s),c=a?[]:n.rows.filter(u=>this.#n.has(u)&&(l===null||l.has(this.#n.get(u))));(a||c.length||n.rows.length)&&yo(this.#r,{full:a,rows:c})}#u(e,t){if(!t.length)return e;let r=e.map(n=>({node:n,keys:t.map(({field:i})=>this.value(n,i))}));for(let n=0;n<t.length;n++)if(new Set(r.map(s=>mb(s.keys[n])).filter(s=>s!==null)).size>1)throw new TypeError(`collection view cannot compare mixed types in ${t[n].field}`);return r.sort((n,i)=>{for(let[s,{direction:a}]of t.entries()){let l=gb(n.keys[s],i.keys[s]);if(l)return a==="a"?l:-l}return 0}).map(n=>n.node)}};function Hl(o){if(typeof o!="string")throw new TypeError("collection view sortedBy must be a string");if(o==="")return[];let e=new Set;return o.split(",").map(t=>{let r=/^([^,:]+):([ad])$/.exec(t);if(!r||e.has(r[1]))throw new TypeError(`Invalid collection view sort criterion: ${t}`);return e.add(r[1]),{field:r[1],direction:r[2]}})}function mb(o){if(o==null)return null;if(typeof o=="number"&&Number.isFinite(o)||U(o)&&o.isFinite())return"number";if(o instanceof Date&&Number.isFinite(o.getTime()))return"date";if(typeof o=="string"||typeof o=="boolean")return typeof o;throw new TypeError("collection view sort requires loaded finite scalar values")}function gb(o,e){return o==null||e==null?o==null?e==null?0:-1:1:U(o)?o.comparedTo(e):U(e)?-e.comparedTo(o):o<e?-1:o>e?1:0}var ns=class{constructor(e=null,t=null){this.parent=e,this.segment=t,this.children=new Map,this.registrations=new Set}},Yl=class{#e;#t;#r;#n;#o;#i=!0;#s;constructor(e,{path:t,attr:r,recipient:n,order:i,subtree:s=!1}){this.#e=e,this.#t=t,this.#r=r,this.#n=n,this.#o=i,this.#s=s}get router(){return this.#e}get path(){return this.#t}get attr(){return this.#r}get recipient(){return this.#n}get subtree(){return this.#s}get active(){return this.#i}get order(){return this.#o}close(){this.active&&(this.#i=!1,this.router.unregister(this))}},Zl=class{constructor({evt:e,node:t,path:r,oldvalue:n,attrsDiff:i,reason:s,fired:a,level:l,registration:c,index:u}){this.evt=e,this.node=t,this.path=r,this.oldvalue=n,this.attrsDiff=i,this.reason=s,this.fired=a,this.level=l,this.registration=c,this.index=u}},os=class{#e;#t=new ns;#r=new Map;#n=0;#o=0;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return this.#n}register({path:e,attr:t=null,recipient:r,subtree:n=!1}){if(typeof e!="string"||e==="")throw new TypeError(`A Data registration requires a path: ${e}`);let i=this.#t;for(let a of e.split(".")){let l=i.children.get(a);l||(l=new ns(i,a),i.children.set(a,l)),i=l}this.#o+=1;let s=new Yl(this,{path:e,attr:t,recipient:r,order:this.#o,subtree:n});return i.registrations.add(s),this.#r.set(s,i),this.#n+=1,s}unregister(e){let t=this.#r.get(e);if(t)for(this.#r.delete(e),t.registrations.delete(e),this.#n-=1;t.parent&&!t.children.size&&!t.registrations.size;)t.parent.children.delete(t.segment),t=t.parent}deliver(e){let{pathlist:t}=e;if(!t?.length||t[0]!==an||e.reason==="autocreate")return;let r=t.slice(1),n=e.evt==="ins"||e.evt==="del";for(let i of Array.isArray(e.node)?e.node:[e.node]){let s=n?[...r,i.label]:r,a=s.join(".");for(let[l,c]of this.#i(s,e))l.active&&l.recipient.receive(new Zl({evt:e.evt,node:i,path:a,oldvalue:e.oldvalue??null,attrsDiff:e.attrs_diff??null,reason:e.reason??null,fired:e.fired??!1,level:c,registration:l,index:e.ind??null}))}}#i(e,t){let r=[],n=this.#t;for(let s of e){for(let a of n.registrations)n!==this.#t&&this.#s(a,"child",t)&&r.push([a,"child"]);if(n=n.children.get(s),!n)return r.sort(([a],[l])=>a.order-l.order)}for(let s of n.registrations)this.#s(s,"node",t)&&r.push([s,"node"]);let i=[...n.children.values()];for(;i.length;){let s=i.pop();for(let a of s.registrations)this.#s(a,"container",t)&&r.push([a,"container"]);i.push(...s.children.values())}return r.sort(([s],[a])=>s.order-a.order)}#s(e,t,r){let{evt:n}=r;return e.subtree?t!=="container"||n!=="upd_attrs":e.attr===null?n==="upd_attrs"?!1:!(t==="child"&&r.fired):t==="child"?!1:t==="container"?n!=="upd_attrs":n==="ins"||n==="del"?!0:Object.hasOwn(r.attrs_diff??{},e.attr)}};var tc={};ee(tc,{GridStructure:()=>hn});var Ql={};ee(Ql,{GridFormulas:()=>Jl,addNumeric:()=>Kl,formulaDefinitions:()=>ko,parseArithmetic:()=>Cf,sameValue:()=>Nf});var bb="#",wb=/[A-Za-z_$][\w$]*/g;function ko(o){let e=new Map;for(let c of o){if(c.formula==null)continue;let u=c.formula.trim(),d=u===bb?{kind:"index",field:null}:u.startsWith("+=")?{kind:"running",field:u.slice(2).trim()}:u.startsWith("%=")?{kind:"percent",field:u.slice(2).trim()}:null;if(d&&d.kind!=="index"&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(d.field))throw new TypeError(`grid formula '${u}' requires a field`);let f=new Map;for(let[m,b]of Object.entries(c))m.startsWith("formula_")&&f.set(m.slice(8),b);let h=null;if(!d)try{h=Cf(u)}catch{}let p=d?new Set(d.field?[d.field]:[]):new Set(u.match(wb)??[]);e.set(c.field,{field:c.field,formula:c.formula,special:d,arithmetic:h,parameters:f,references:p,calculated:c.calculated===!0,column:c})}let t=new Map;for(let c of e.values())for(let u of c.references)t.has(u)||t.set(u,new Set),t.get(u).add(c.field);let r=new Set,n=new Set,i=[],s=c=>{if(!n.has(c)){if(r.has(c))throw new TypeError(`grid formula dependency cycle at '${c}'`);r.add(c);for(let u of e.get(c).references)e.has(u)&&s(u);r.delete(c),n.add(c),i.push(c)}};for(let c of e.keys())s(c);let a=new Set;for(let c of i){let u=e.get(c);(["index","running"].includes(u.special?.kind)||[...u.references].some(d=>a.has(d)))&&a.add(c)}let l=new Map([...e].map(([c,u])=>[c,Object.freeze({...u,view:a.has(c)})]));return Object.freeze({definitions:l,triggered:t,order:Object.freeze(i),viewFields:a})}function Cf(o){let e=_b(o),t=0,r=()=>e[t],n=c=>{if(r().value!==c)throw new SyntaxError(`expected '${c}' in arithmetic formula`);return e[t++]},i={"+":1,"-":1,"*":2,"/":2,"%":2,"**":3},s=()=>{let c=r();if(c.type==="number")return t++,{kind:"number",value:c.value};if(c.type==="name")return t++,{kind:"name",value:c.value};if(c.value==="("){t++;let u=a(0);return n(")"),u}if(c.value==="+"||c.value==="-")return t++,{kind:"unary",operator:c.value,child:s()};throw new SyntaxError(`unexpected '${c.value||"end"}' in arithmetic formula`)},a=c=>{let u=s();for(;i[r().value]>=c;){let d=e[t++].value,f=a(i[d]+(d==="**"?0:1));u={kind:"binary",operator:d,left:u,right:f}}return u},l=a(0);if(r().type!=="eof")throw new SyntaxError(`unexpected '${r().value}' in arithmetic formula`);return l}function _b(o){let e=[],t=0;for(;t<o.length;){let r=o.slice(t),n=/^\s+/.exec(r);if(n){t+=n[0].length;continue}let i=/^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(r);if(i){e.push({type:"number",value:i[0]}),t+=i[0].length;continue}let s=/^[A-Za-z_$][\w$]*/.exec(r);if(s){e.push({type:"name",value:s[0]}),t+=s[0].length;continue}let a=/^(?:\*\*|[()+\-*/%])/.exec(r);if(a){e.push({type:"operator",value:a[0]}),t+=a[0].length;continue}throw new SyntaxError(`unsupported arithmetic formula token at ${t}`)}return e.push({type:"eof",value:""}),e}function Df(){if(Zr()==="number")throw new Error("A Decimal backend is required for exact grid formulas")}function Eo(o,e){if(U(o))return o;if(o==null||o==="")return null;if(typeof o!="number"&&typeof o!="string")throw new TypeError("Decimal arithmetic requires numeric values");return new e(String(o))}var yb={"+":(o,e)=>o+e,"-":(o,e)=>o-e,"*":(o,e)=>o*e,"/":(o,e)=>o/e,"%":(o,e)=>o%e,"**":(o,e)=>o**e};function xo(o,e){if(o.kind==="number")return Number(o.value);if(o.kind==="name"){if(!Object.hasOwn(e,o.value))throw new ReferenceError(`${o.value} is not defined`);return e[o.value]}return o.kind==="unary"?o.operator==="-"?-xo(o.child,e):+xo(o.child,e):yb[o.operator](xo(o.left,e),xo(o.right,e))}function is(o,e,t){if(o.kind==="number")return new t(o.value);if(o.kind==="name"){if(!Object.hasOwn(e,o.value))throw new ReferenceError(`${o.value} is not defined`);return Eo(e[o.value],t)}if(o.kind==="unary"){let s=is(o.child,e,t);return s==null?null:o.operator==="-"?s.neg():s}let r=is(o.left,e,t),n=is(o.right,e,t);if(r==null||n==null)return null;if(o.operator==="**")return r.pow(Number(n.toString()));let i={"+":"plus","-":"minus","*":"times","/":"div","%":"mod"}[o.operator];return r[i](n)}function Nf(o,e){return Object.is(o,e)?!0:U(o)&&U(e)&&o.eq(e)}function Kl(o,e){if(e==null||e==="")return o;if(U(o)||U(e)){Df();let t=U(o)?o.constructor:e.constructor;return Eo(o,t).plus(Eo(e,t))}if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("Grid aggregate formulas require numeric values");return o+e}function vb(o,e){let t=U(e)?e.eq(0):Object.is(e,0);if(o==null||o===""||e==null||t)return null;if(U(o)||U(e)){let r=U(o)?o.constructor:e.constructor;return Eo(o,r).div(Eo(e,r)).times(new r(100))}if(typeof o!="number"||typeof e!="number")throw new TypeError("Percentage formulas require numeric values");return o/e*100}var Jl=class{#e;#t=ko([]);#r=new Set;#n=null;#o=null;#i=[];#s=[];#a=!1;#l=new Map;#c=null;constructor(e){this.#e=e}get source(){return this.#e}get runtime(){return this.source.rootBuilder.binding}get errors(){return new Map(this.#l)}get formulas(){return this.#t}get dataFields(){return new Set(this.formulas.order.filter(e=>!this.viewFields.has(e)))}get viewFields(){return this.formulas.viewFields}configure(e,t,r){if(!(e.formulas===this.#t&&r===this.#n&&t===this.#o&&this.#i.length)&&(this.disconnect(),this.#t=e.formulas,this.#r=new Set(e.fields),this.#n=r,this.#o=t,this.#l.clear(),!!this.formulas.definitions.size)){this.#i=[r.subscribe(n=>this.#f(n)),t.subscribe(()=>{this.#c=null})];for(let n of this.formulas.definitions.values())for(let i of n.parameters.values()){if(typeof i!="string"||!i.startsWith("^"))continue;let[s,a=null]=this.source.absDatapath(i).split("?");this.#s.push(this.runtime.router.register({path:s,attr:a,recipient:{receive:()=>{this.#c=null,this.recalculate(this.#d([n.field]))}}}))}this.recalculate(this.#d(this.#u(n=>n.calculated)))}}disconnect(){for(let e of this.#i)e();for(let e of this.#s)e.close();this.#i=[],this.#s=[],this.#n=null,this.#o=null,this.#c=null,this.#t=ko([])}value(e,t){if(!this.viewFields.has(t))return this.#n.value(e,t);let r=this.#b().get(e);return r===void 0?null:r[t]}#u(e){return[...this.formulas.definitions.values()].filter(e).map(t=>t.field)}#d(e){let t=new Set(e),r=[...e];for(;r.length;)for(let n of this.formulas.triggered.get(r.shift())??[])t.has(n)||(t.add(n),r.push(n));return t}#f({full:e,rows:t,event:r,field:n}){if(this.#c=null,this.#a)return;if(e){this.recalculate(this.#d(this.#u(u=>u.calculated||u.special)));return}let[i]=t,s;n!==null?s=[n]:r.node===i?s=r.evt==="upd_attrs"?Object.keys(r.attrs_diff):[...this.formulas.triggered.keys()]:s=(Array.isArray(r.node)?r.node:[r.node]).map(u=>u.label);let a=new Set;for(let u of s)for(let d of this.formulas.triggered.get(u)??[])a.add(d);let l=this.#d(a),c=[...l].some(u=>this.formulas.definitions.get(u).special?.kind==="percent");this.recalculate(l,c?null:[i])}#p(e){let t={};for(let[r,n]of e.parameters)t[r]=typeof n=="string"&&(n.startsWith("^")||n.startsWith("="))?this.source.getRelativeData(n):n;return t}#h(e,t,r,n,i){if(e.special?.kind==="index")return r;if(e.special?.kind==="running")return Kl(n,i(t,e.special.field));if(e.special?.kind==="percent")return vb(i(t,e.special.field),n);let s=this.#p(e),a={};for(let d of e.references)Object.hasOwn(s,d)?a[d]=s[d]:(this.#r.has(d)||this.#m(t).has(d))&&(a[d]=i(t,d)??null);if(Object.values(a).some(d=>d==null))return null;let l=Object.values(a).find(U);if(e.arithmetic)return l===void 0?xo(e.arithmetic,a):(Df(),is(e.arithmetic,a,l.constructor));if(l!==void 0)throw new Error("Decimal grid formulas support arithmetic expressions only");let c=[...Object.keys(a),"_currcell","_rowNode"];return this.runtime.inlineCompiler.compile(this.source,`struct.${e.field}.formula`,e.formula,c,`return (${e.formula}
222
- );`)({...a,_currcell:e.column,_rowNode:t})}#m(e){return this.#n.rowMode==="attributes"?new Set(Object.keys(e.getAttr())):new Set(e.staticValue.keys())}#g(e,t,r){Nf(this.#n.value(e,t),r)||(this.#n.rowMode==="attributes"?e.setAttr({[t]:r}):e.staticValue.setItem(t,r))}recalculate(e,t=null){if(this.#a||!e.size||this.#n===null)return;this.#a=!0;let r=(n,i)=>this.#n.value(n,i);try{let n=this.#n.getRows();for(let i of this.formulas.order){let s=this.formulas.definitions.get(i);if(!e.has(i)||s.view)continue;let a=null,l=null;if(s.special?.kind==="percent")try{a=0;for(let c of n)a=Kl(a,r(c,s.special.field))}catch(c){a=null,l=c}for(let c of t??n){let u=null;try{u=this.#h(s,c,null,a,r)}catch(d){l=d}this.#g(c,i,u)}l?this.#l.set(i,l):this.#l.delete(i)}}finally{this.#a=!1}}#b(){if(this.#c!==null)return this.#c;let e=this.#o.getRows(),t=new Map(e.map(n=>[n,{}])),r=(n,i)=>this.viewFields.has(i)?t.get(n)[i]:this.#n.value(n,i);for(let n of this.formulas.order){let i=this.formulas.definitions.get(n);if(!i.view)continue;let s=0,a=null;for(let[l,c]of e.entries()){let u=null;try{u=this.#h(i,c,l+1,s,r),i.special?.kind==="running"&&(s=u)}catch(d){a=d}t.get(c)[n]=u}a?this.#l.set(n,a):this.#l.delete(n)}return this.#c=t,t}};var xb=new Set(["T","B","L","R","N","D","H","DHZ"]),kb=new Set(["tag","field","name","title","dtype","width","align","format","columnset","white_space","max_height","edit","check","checked","checkedField","formula","calculated","hidden","totalize","footer_value","footer_format"]),Eb=/^formula_[A-Za-z_$][\w$]*$/,Tb=new Set(["tag","code","name","background","color"]),hn=class{#e=new Map;constructor(e){if(!(e instanceof x))throw new TypeError("grid structpath must resolve to a Bag");let t=ss(e,"view_0"),r=ss(e,"info"),n=ss(t,"rows_0"),i=ss(r,"columnsets"),s=new Set,a=new Map;for(let c of i.getNodes()){let u=c.getAttr();if(Of(u,Tb),ec(u.code,"colgroup code"),u.tag!=="columnset"||c.resolver||c.staticValue!=null||c.label!==u.code)throw new TypeError("grid columnset requires a scalar definition labelled by code");if(a.has(u.code))throw new TypeError(`Duplicate grid colgroup: ${u.code}`);if(u.name!=null&&typeof u.name!="string")throw new TypeError("grid group name must be text");for(let d of["background","color"])if(u[d]!=null&&typeof u[d]!="string")throw new TypeError(`grid ${d} must be text`);a.set(u.code,{...u,name:u.name??u.code})}this.columns=[],this.groups=[];let l=[];for(let c of n.getNodes()){let u=c.getAttr();if(Of(u,kb,Eb),u.tag!=="cell"||c.staticValue!=null||c.resolver)throw new TypeError("grid cell must be a scalar declaration");if(ec(u.field,"field"),s.has(u.field))throw new TypeError(`Duplicate grid field: ${u.field}`);if(s.add(u.field),this.#e.set(u.field,c),u.columnset!=null&&!a.has(u.columnset))throw new TypeError(`Unknown grid columnset: ${u.columnset}`);if(u.dtype!=null&&!xb.has(u.dtype))throw new TypeError(`Unsupported grid dtype: ${u.dtype}`);if(u.align!=null&&!["start","center","end"].includes(u.align))throw new TypeError("grid align requires start, center or end");if(u.width!=null&&(typeof u.width!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem|ch|%)$/.test(u.width)))throw new TypeError("grid width requires a nonnegative CSS length (px, em, rem, ch or %)");if(u.max_height!=null&&(typeof u.max_height!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem)$/.test(u.max_height)))throw new TypeError("grid max_height requires a nonnegative CSS length (px, em or rem)");if(u.white_space!=null&&!["normal","nowrap","pre-wrap"].includes(u.white_space))throw new TypeError("grid white_space requires normal, nowrap or pre-wrap");for(let p of["name","title","format"])if(u[p]!=null&&typeof u[p]!="string")throw new TypeError(`grid ${p} must be text`);if(u.edit!=null&&typeof u.edit!="boolean"&&(typeof u.edit!="object"||Array.isArray(u.edit)))throw new TypeError("grid edit requires a boolean or editor options");if(u.check!=null||u.checked!=null||u.checkedField!=null){if(!["multiple","single"].includes(u.check)||typeof u.checked!="string"||!u.checked.startsWith("^")||u.checked.length<2||u.checked.includes("?"))throw new TypeError("grid check requires single or multiple and checked=^DataPath");if(ec(u.checkedField,"checkedField"),u.edit)throw new TypeError("external check sets cannot edit row fields")}Sb(u);let d=Object.freeze({...u,name:u.name??u.field,align:u.align??(["L","R","N"].includes(u.dtype)?"end":"start")});if(l.push(d),u.hidden)continue;this.columns.push(d);let f=u.columnset??null,h=this.groups.at(-1);(!h||h.code!==f)&&(h={code:f,...f===null?{name:null}:a.get(f),columns:[]},this.groups.push(h)),h.columns.push(d)}if(!this.columns.length)throw new TypeError("grid struct requires at least one column");this.fields=Object.freeze([...s]),this.formulas=ko(l);for(let c of this.groups)Object.freeze(c.columns),Object.freeze(c);Object.freeze(this.columns),Object.freeze(this.groups),Object.freeze(this)}columnNode(e){return this.#e.get(e)}moveColumn(e,t,r=!1){let n=this.#e.get(e),i=this.#e.get(t);if(!n||!i||n===i)return;let s=n.parentBag,a=s.getNodes(),l=a.indexOf(n),c=a.indexOf(i),u=c+Number(r)-+(l<c);u!==l&&s.move(l,u)}setColumnWidth(e,t){if(!Number.isFinite(t)||t<=0)throw new TypeError("grid resized width must be positive pixels");this.#e.get(e).setAttr({width:`${Math.round(t)}px`})}};function ss(o,e){let t=o.getNode(e);if(!t||t.resolver||!(t.staticValue instanceof x))throw new TypeError(`grid struct requires Bag ${e}`);return t.staticValue}function Of(o,e,t=null){for(let r of Object.keys(o))if(!e.has(r)&&!t?.test(r))throw new TypeError(`Unsupported grid struct attribute: ${r}`)}function Sb(o){if(o.formula!=null&&(typeof o.formula!="string"||!o.formula.trim()))throw new TypeError("grid formula must be nonempty text");if(o.formula==null&&(o.calculated!=null||Object.keys(o).some(e=>e.startsWith("formula_"))))throw new TypeError(`grid ${o.field}: calculated and formula_<name> require a formula`);for(let e of["calculated","hidden"])if(o[e]!=null&&typeof o[e]!="boolean")throw new TypeError(`grid ${e} must be a boolean`);if(o.totalize!=null&&typeof o.totalize!="boolean"&&(typeof o.totalize!="string"||!o.totalize))throw new TypeError("grid totalize requires a boolean or a Data path");for(let e of["footer_value","footer_format"])if(o[e]!=null&&typeof o[e]!="string")throw new TypeError(`grid ${e} must be text`)}function ec(o,e){if(typeof o!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new TypeError(`grid ${e} requires a simple field identifier`)}function $f(o){let e=new x,t=new x,r=new x;e.setItem("view_0",new x,{tag:"view"}),e.getItem("view_0").setItem("rows_0",t,{tag:"rows"}),e.setItem("info",new x),e.getItem("info").setItem("columnsets",r);let n=(i,s=null)=>{if(i.builder.validateNode(i),i.nodeTag!=="column"||i.staticValue!=null)throw new TypeError("grid column must be a scalar declaration");let a={tag:"cell"},l=["field","name","title","dtype","width","align","format","white_space","max_height","edit","check","checked","checkedField","formula","calculated","hidden","totalize","footer_value","footer_format",...Object.keys(i.getAttr()).filter(u=>u.startsWith("formula_"))];for(let u of l)i.getAttr(u)!=null&&(a[u]=i.getAttr(u));let c=`cell_${a.field}`;if(t.getNode(c))throw new TypeError(`Duplicate grid field: ${a.field}`);s!==null&&(a.columnset=s),t.setItem(c,null,a)};for(let i of o.getNodes())if(i.nodeTag==="column")n(i);else if(i.nodeTag==="colgroup"){if(i.builder.validateNode(i),!(i.staticValue instanceof N))throw new TypeError("grid colgroup requires column declarations");let s=i.getAttr("code");if(r.getNode(s))throw new TypeError(`Duplicate grid colgroup: ${s}`);let a={tag:"columnset",code:s,name:i.getAttr("name")??s};for(let l of["background","color"])i.getAttr(l)!=null&&(a[l]=i.getAttr(l));r.setItem(s,null,a);for(let l of i.staticValue.getNodes())n(l,s)}else throw new TypeError("grid struct accepts column and colgroup only");return e}function Rf(o){if(o._getMeta("gramlot_component")?.bagStruct){let e=o.staticValue instanceof N?o.staticValue.getNodes():[];if(e.some(t=>!t._getMeta("gridStruct"))||e.length>1)throw new TypeError("grid accepts one struct declaration");if(e.length&&o.getAttr("structpath")!=null)throw new TypeError("grid requires structpath or nested struct, not both");if(!e.length&&!o.getAttr("structpath"))throw new TypeError("grid requires structpath or nested struct");if(!["values","attributes"].includes(o.getAttr("rowMode")))throw new TypeError("grid rowMode must explicitly be values or attributes")}if(o._getMeta("gridStruct")){if(!o.parentNode?._getMeta("gramlot_component")?.bagStruct)throw new TypeError("struct requires a grid parent");if(!(o.staticValue instanceof N))throw new TypeError("grid struct requires column declarations");new hn($f(o.staticValue))}}function jf(o,e){let t=$f(o.staticValue);new hn(t);let r=`_gramlot.grid.${crypto.randomUUID().replaceAll("-","")}.struct`;e.setItem(r,t,null,">",!1,!0,o),o.parentNode.setAttr({structpath:r},!1),o.setValue(null,!1)}var as=class{#e;constructor(e){this.#e=e}get runtime(){return this.#e}install(e){let t=To(e),r=this.setterNodes(e);nc(e);for(let n of r)n._getMeta("gridStruct")?jf(n,this.runtime.data):this.applySetter(n),this.runtime.closeBranch(n),n.parentBag&&n.parentBag.popNode(n.label);this.applyDefaults(t.filter(n=>n.nodeTag&&!n._getMeta("data_element")))}setterNodes(e){return To(e).filter(t=>t.nodeTag==="dataSetter"||t._getMeta("gridStruct"))}applySetter(e){let t=e.absDatapath(e.pathAttribute("destination_path"));if(t===null)return;let r=e.getAttr("value")??null,n=Ib(e.getAttr()),i=this.runtime.data;if(r!==null)i.setItem(t,r,n,">",!1,!0,e),r instanceof x&&e.setAttr({value:null},!1);else{let s=i.getNode(t);s?n&&s.setAttr(n,!0):i.setItem(t,null,n,">",!1,!0,e)}}applyDefaults(e){for(let t of e){let r=t.getAttr();for(let[n,i]of Object.entries(r)){if(!Ab(t,n,i))continue;let s=n==="value"?r.default_value??r.default:r[`default_${n}`];s!=null&&this.#t(t,i,s)}this.#r(t,r)}}#t(e,t,r){let n=e.absDatapath(t);if(n===null)return;let[i,s=null]=n.split("?",2),a=this.runtime.data,l=a.getNode(i);if(s===null){if(l&&l.value!==null&&l.value!==void 0)return;a.setItem(i,r,null,">",!1,!0,e)}else if(l){let c=l.getAttr(s);c==null&&l.setAttr({[s]:r},!0)}else a.setItem(i,null,{[s]:r},">",!1,!0,e)}#r(e,t){let r={};for(let[s,a]of Object.entries(t))s.startsWith("attr_")&&(r[s.slice(5)]=H(a)?Jt(e,s):e.pointerType(a)?e.getRelativeData(a):a);if(!Object.keys(r).length)return;let n=[t.value,t.src].find(s=>e.pointerType(s));if(!n)return;let i=e.absDatapath(n);i!==null&&this.runtime.data.getNode(i.split("?",1)[0])?.setAttr(r,!0,!0,!1)}};function Ab(o,e,t){return e==="_meta"||lt.has(e)||e==="default"||e.startsWith("default_")||e.startsWith("attr_")||e.endsWith("_path")?!1:o.pointerType(t)!==null}function Ib(o){let e={};for(let[t,r]of Object.entries(Et(o??{})))lt.has(t)||t.startsWith("_")||t==="destination_path"||t==="value"||r!=null&&(e[t]=r);return Object.keys(e).length?e:null}function Cb(o){let e=o.builder;if(!(e instanceof me))throw new Error(`dataSetter '${o.label}': dataSetter is not supported inside ${e.constructor._name}`)}function nc(o){for(let e of To(o))Rf(e),e.nodeTag==="dataSetter"&&Cb(e),Rb(e)}var Db=["_init","_onStart","_onBuilt","_delay","_timing","_userChanges"],Nb=new Set(["dataFormula","dataController","dataRpc","dataRemote"]),Ob=["_onCalling","_onResult","_onError"],$b=["_delay","_timing","_userChanges"],rc=["_init","_onBuilt","_onStart"];function Rb(o){let e=i=>o.getAttr(i)!==null&&o.getAttr(i)!==void 0,t=!o._getMeta("data_element")&&typeof o.getAttr("remote")=="string";if(o.nodeTag!=="dataRpc"){let i=Ob.find(s=>e(s)&&!(s==="_onCalling"&&(o.nodeTag==="dataRemote"||t)));if(i){let s=i==="_onCalling"?"dataRpc, dataRemote and remote":"dataRpc";throw new Error(`${o.nodeTag??"fragment"} '${o.label}': '${i}' is allowed only on ${s}`)}}if(Nb.has(o.nodeTag)){let i=Object.entries(o.getAttr()).find(([,a])=>Le(a));if(i)throw new Error(`${o.nodeTag} '${o.label}': '${i[0]}' is a == expression, not accepted on ${o.nodeTag}`);let s=o.nodeTag==="dataRemote"?rc.find(e):null;if(s)throw new Error(`dataRemote '${o.label}': '${s}' is not accepted on dataRemote, its resolver loads when the Data is read`);for(let a of rc){let l=o.getAttr(a);if(!(l==null||typeof l=="boolean"||typeof l=="number"))throw new Error(`${o.nodeTag} '${o.label}': '${a}' accepts true, false, null or a number, not ${JSON.stringify(l)}`)}return}let r=Db.find(i=>e(i)&&!(i==="_delay"&&!o._getMeta("data_element")&&o.nodeTag!=="html_button")&&!(t&&$b.includes(i)));if(!r)return;let n=rc.includes(r)?"dataFormula, dataController and dataRpc":"dataFormula, dataController, dataRpc and dataRemote";throw new Error(`${o.nodeTag??"fragment"} '${o.label}': '${r}' is allowed only on ${n}`)}function To(o){if(o instanceof N)return o.getNodes().flatMap(t=>To(t));let e=[o];return o.value instanceof N&&e.push(...To(o.value)),e}var jb=new Set(["destination_path","result_path","func","formula","script","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","_ask","_ask_if","_ask_title","_ask_onCancel","method","timeout","_onCalling","_onResult","_onError","cacheTime","sync"]),So=class{#e;#t=null;#r=null;constructor(e){this.#e=e}get binding(){return this.#e}debounce(e,t){this.#r?.();let r=null,n=setTimeout(()=>{r(),this.#r=null,t()},e);r=this.binding.track(()=>clearTimeout(n)),this.#r=()=>{clearTimeout(n),r(),this.#r=null}}startTiming(e,t){if(this.#t?.(),!(e>0))return;let r=setInterval(t,e*1e3),n=this.binding.track(()=>clearInterval(r));this.#t=()=>{clearInterval(r),n(),this.#t=null}}cancel(){this.#r?.(),this.#t?.()}},pn=class{#e;#t=[];#r=new Set;#n;#o=null;#i=!1;constructor(e){this.#e=e,this.#n=new So(e),e.track(()=>{this.cancel(),this.#p(),this.#f()})}get binding(){return this.#e}get node(){return this.binding.node}get kind(){throw new Error("Provider.kind is defined by FormulaProvider, ControllerProvider, RpcProvider and RemoteProvider")}register(){let e=this.node,t=e.getAttr("_onStart");if(typeof t=="number"&&!(Number.isFinite(t)&&t>=0))throw new Error(`${e.nodeTag} '${e.label}': _onStart must be true or a delay in ms not below 0: ${t}`);this.#p();let r=this.binding.runtime.router,n=Ze(e,e.getAttr("_timing"));for(let[i,s]of e.pointers()){if(i==="datapath")continue;let a=e.absDatapath(s);if(a===null)continue;let[l,c=null]=a.split("?",2),u=r.register({path:l,attr:c,recipient:this});this.#t.push(u),(i==="_timing"||n.has(i))&&this.#r.add(u)}this.#t.push(...this.binding.runtime.subscriptions.subscribeNode(e,(i,s,a)=>(l,c)=>{let u={kind:"subscription",topic:a,payload:l,metadata:c};if(this.#a("_userChanges")&&a!=="node")return;let d=this.#a("_delay");d>0?this.#n.debounce(d,()=>this.invoke(u)):this.invoke(u)})),this.#s(),this.kind==="remote"&&this.invoke({kind:"install",change:null})}receive(e){if(this.#r.has(e.registration)){this.#s();return}if(this.#a("_userChanges")&&e.level!=="node")return;let t={kind:"data",change:e},r=this.#a("_delay");r>0?this.#n.debounce(r,()=>this.invoke(t)):this.invoke(t)}invoke(e){if(this.binding.closed)return;let t=this.node,r=this.kind==="formula",n=this.kind==="rpc",i=this.kind==="remote",s=this.readArguments(e);e.askResult&&(Object.assign(s,e.askResult),s._askResult=e.askResult);let a=t.getAttr("_ask"),l=this.binding.runtime.askDialog;if(a&&!e.askDone&&l.required(this.binding,a,s,"_ask"))return l.show(this.binding,a,s,t.getAttr("_ask_title")??"Warning").then(p=>{if(!this.binding.closed){if(p===null){let m=t.getAttr("_ask_onCancel");m&&this.#l("_ask_onCancel",m,m,s,!0);return}return this.invoke({...e,askDone:!0,askResult:p})}});let[c,u]=[r?"formula":"script",t.getAttr(r?"formula":"script")],d=t.getAttr("_if");if(d&&!this.#l("_if",d,`return (${d})`,s,!1)){if(i&&this.#f(),[c,u]=["_else",t.getAttr("_else")],!u)return;if(n||i){this.#l(c,u,u,s,!0);return}}if(n)return this.#c(s);if(i)return this.#d(s);let f=t.getAttr("func"),h;if(u)h=this.#l(c,u,r?`return ${u}`:u,s,!0);else if(f==null){if(!r)return;h=new x(ls(s))}else{let{group:p,method:m}=this.binding.runtime.logicRegistry.resolve(f,t);h=r?m.call(p,s):m.call(p,t,s)}r&&t.setRelativeData(t.pathAttribute("result_path"),h)}readArguments(e){let t=this.node,[,r]=t.rootBuilder.runtimeValues(t),n=Object.fromEntries(Object.entries(r).filter(([l])=>!jb.has(l)&&!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),i={...e.kind==="subscription"?e.payload:{},...this.binding.runtime.renderer.references.resolveArguments(n)};e.kind==="subscription"&&(i._subscription_kwargs=e.payload,i._subscription_metadata=e.metadata);let s=e.change??null,a=s?s.level:e.kind==="subscription"?e.topic:e.kind;return i._node=s?s.node:null,i._triggerpars={kw:s,trigger_reason:a},i._reason=a,e.kind==="click"&&(Object.assign(i,Pb(e)),e.rowContext&&Object.assign(i,e.rowContext,{event:e.event})),i}cancel(){this.#n.cancel()}#s(){this.#n.startTiming(this.#a("_timing"),()=>this.invoke({kind:"timing",change:null}))}#a(e){let t=this.node,r=t.getAttr(e);return H(r)?Jt(t,e):t.pointerType(r)?t.getRelativeData(r):r??null}#l(e,t,r,n,i){let s=[...i?["_kwargs"]:[],...Pf,...Bf,...Object.keys(ls(n))];return["_onCalling","_onResult","_onError","_ask_onCancel"].includes(e)?dt(this.binding.runtime,this.node,e,t,{...n,_kwargs:n},s):this.binding.runtime.inlineCompiler.compile(this.node,e,t,s,r)({...n,_kwargs:n})}async#c(e){let t=this.node,[r,n,i]=["_onCalling","_onResult","_onError"].map(a=>t.getAttr(a)),s=t.requests;if(s.calling(r?()=>this.#l("_onCalling",r,r,e,!0):null))return s.submit(this.#a("method"),ls(e),a=>this.#u(a,e,n,i))}async#u(e,t,r,n){if(this.binding.closed)return;let i=this.node,s=this.#a("timeout"),a=s>0?setTimeout(()=>{let u=new Error(`${i.nodeTag} '${i.label}': no answer within ${s} ms`);u.name="TimeoutError",e.controller.abort(u)},s):null,l;try{l={result:await this.binding.call("data",e)}}catch(u){l={error:u}}if(clearTimeout(a),this.binding.closed||e.ignored)return;if("error"in l){if(!n)throw l.error;this.#l("_onError",n,n,{...t,error:l.error},!0);return}let{result:c}=l;i.getAttr("result_path")!=null&&i.setRelativeData(i.pathAttribute("result_path"),c),r&&this.#l("_onResult",r,r,{...t,result:c},!0)}#d(e){this.#f();let t=this.#i;this.#i=!1;let r=this.node,n=r.absDatapath(r.pathAttribute("destination_path"));if(n===null)return;let i=r.getAttr("_onCalling"),s=new fn({binding:this.binding,method:this.#a("method"),params:ls(e),cacheTime:this.#a("cacheTime"),sync:this.#a("sync")!==!1&&this.binding.runtime.gramlot.rpc.supportsCallSync,onCalling:i?()=>this.#l("_onCalling",i,i,e,!0):null,onError:a=>{throw new Error(`${r.nodeTag} '${r.label}': dataRemote '${s.method}' failed: ${a.message}`,{cause:a})}});this.binding.runtime.data.setResolver(n,s),this.#o={path:n,resolver:s},t&&s.refresh()}#f(){if(!this.#o)return;let{path:e,resolver:t}=this.#o;this.#o=null,this.#i=t.loaded||t.loading!==null;let r=this.binding.runtime.data.getNode(e);r?.resolver===t&&(r.resolver=null)}#p(){for(let e of this.#t.splice(0))e.close();this.#r.clear()}},cs=class extends pn{get kind(){return"formula"}},us=class extends pn{get kind(){return"controller"}},ds=class extends pn{get kind(){return"rpc"}},fs=class extends pn{get kind(){return"remote"}},Pf=["_node","_triggerpars","_reason","_subscription_kwargs","_subscription_metadata","_askResult"],Bf=["_evt","button_counter","button_shift","button_ctrl","button_alt","button_meta"];function ls(o){let e={...o};for(let t of[...Pf,...Bf])delete e[t];return e}function Pb({event:o,counter:e}){return{_evt:o,button_counter:e,button_shift:!!o.shiftKey,button_ctrl:!!o.ctrlKey,button_alt:!!o.altKey,button_meta:!!o.metaKey}}var Bb=[[null,/(\W|^)GET (?:\s*)(\^?[\w.#@$?-]+)/g,"$1this.GET('$2')"],[/;SET/g,/(\W|^)SET (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.SET('$2', $3)$4 "],[/;PUT/g,/(\W|^)PUT (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.PUT('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE_AFTER('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE_AFTER('$2')$3 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE('$2', $3)$4 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE('$2')$3 "]],Mb=/(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/,Lb=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),hs=class{#e;#t=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return[...this.#t.values()].reduce((e,t)=>e+t.size,0)}preprocess(e,t,r){let n=r.trim();if(Mb.test(n))throw new Error(`${Ao(e,t)}: the PUBLISH macro is excluded from Gramlot`);let i=n.replace(/\$(\d+)/g,(s,a)=>`arguments[${parseInt(a,10)-1}]`);for(let[s,a,l]of Bb)s&&(i=i.replace(s,`; ${s.source.slice(1)}`)),i=i.replace(a,l);return i!==n&&console.warn(`${Ao(e,t)}: legacy macros are deprecated; write this.GET(path), this.SET(path, value), this.PUT(path, value), this.FIRE(path, value), this.FIRE_AFTER(path, value) and arguments[n] in place of GET, SET, PUT, FIRE, FIRE_AFTER and $n`),i}compile(e,t,r,n,i=r){if(e.activatedCode(t)!==r)throw new Error(`${Ao(e,t)}: inline code runs only as received with the Source (main or a remote Source); a text written later is not run: use named logic`);let s=this.#t.get(e);s||(s=new Map,this.#t.set(e,s),this.runtime.bindingFor(e).track(()=>this.release(e)));let a=s.get(t);a?.source!==i&&(a={source:i,text:this.preprocess(e,t,i),key:null,run:null},s.set(t,a));let l=n.filter(Fb),c=l.join(",");if(a.key!==c){let u=zb(e,t,a.text,l);a.key=c,a.run=d=>u.apply(e,l.map(f=>d[f]))}return a.run}compileExpression(e,t,r){let n=r.slice(2).trim(),i=ge(e.getAttr()).filter(([,a])=>!Le(a)),s=this.compile(e,t,r,[...i.map(([a])=>a).filter(a=>a!=="_F"),"_F"],`return ${n}`);return a=>{let l={};for(let[c,u]of i)Object.hasOwn(a,c)?l[c]=a[c]:l[c]=e.pointerType(u)?e.getRelativeData(u):u;return s({...l,_F:(c,u)=>this.runtime.gramlot.format(c,u)})}}compilePointerExpression(e,t,r,n){let i=this.compile(e,t,r,["_pointerValues","_F"],`return (${n}
223
- )`);return s=>i({_pointerValues:s,_F:(a,l)=>this.runtime.gramlot.format(a,l)})}release(e,t=null){if(t===null){this.#t.delete(e);return}let r=this.#t.get(e);if(r)for(let n of t){r.delete(n);for(let[i]of ge({[n]:null}))r.delete(i)}}};function Fb(o){return/^[A-Za-z_$][\w$]*$/.test(o)&&!Lb.has(o)}function Ao(o,e){return`${o.nodeTag} '${o.label}' ${e?`'${e}'`:"node value"}`}function zb(o,e,t,r){try{return t.startsWith("function")?new Function(`return (${t}
218
+ `,this.shadowRoot.append(t),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.refreshIconOnly())}connectedCallback(){super.connectedCallback();let e={childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["hidden","slot"]};this.#t.observe(this,e),this.#t.observe(this.control,e),this.refreshIconOnly()}disconnectedCallback(){this.#t.disconnect()}releaseControl(){this.#t.disconnect(),super.releaseControl()}refreshIconOnly(){let e=n=>n.nodeType===3?!!n.textContent.trim():n.nodeType===1&&!n.hidden&&n.getAttribute("slot")!=="menu",t=!this.caption.hidden&&this.caption.assignedNodes().some(e),r=[...this.control.children].some(n=>n!==this.icon&&n!==this.caption&&!n.hidden&&!n.matches(".led,.menu-check,.menu-arrow")&&!(n.matches(".menu-caption")&&this.control.classList.contains("toolbar-tooltip"))&&!!n.textContent.trim());this.control.classList.toggle("icon-only",!this.control.classList.contains("menu-row")&&!!(this.icon.textContent||this.icon.firstElementChild)&&!t&&!r)}get disabled(){return this.control.disabled}set disabled(e){this.control.disabled=!!e}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly,this.renderIcon(this.parameters.icon,this.parameters.iconSrc),e["aria-label"]!=null?this.control.setAttribute("aria-label",e["aria-label"]):this.control.removeAttribute("aria-label"),this.#e&&this.setActionPresentation(this.#e),r}renderIcon(e,t){if(!t){this.icon.textContent=e??"",this.refreshIconOnly();return}let r=this.icon.firstElementChild;r||(r=this.ownerDocument.createElement("img"),r.alt="",r.draggable=!1,this.icon.replaceChildren(r)),r.getAttribute("src")!==t&&r.setAttribute("src",t),this.refreshIconOnly()}get entryIcon(){return this.parameters.icon}get entryIconSrc(){return this.parameters.iconSrc}setActionPresentation(e){this.#e=e,this.hidden=e.hidden,this.icon.textContent=e.icon,this.title=e.title,this.control.setAttribute("aria-label",e.title),this.refreshIconOnly()}attachCommand(){}releaseCommand(){}commandTarget(){return this}prepareCommand(){return!this.disabled}}}ao.parameters={action:{dtype:"T",nullable:!0},disabled:{dtype:"B",default:!1,binding:"read"},icon:{dtype:"T",default:"",binding:"read"},iconSrc:{dtype:"T",default:"",binding:"read"}};var Ng=Yt({name:"button",tag:"gramlot-button",base:ao,command:!0,subTags:"*",implementation:o=>class extends o{}}),Og=Yt({name:"toggleButton",tag:"gramlot-toggle-button",base:ao,command:!0,subTags:"*",parameters:{value:{dtype:"B",default:!1,binding:"twoWay"},readonly:{dtype:"B",default:!1,binding:"read"}},implementation:o=>class extends o{#e=!1;constructor(){super();let e=this.ownerDocument.createElement("span");e.className="led",e.setAttribute("aria-hidden","true"),this.control.prepend(e),this.writeControlValue(!1)}get commitOnChange(){return!0}readControlValue(){return this.#e}writeControlValue(e){this.#e=e,this.control.setAttribute("aria-pressed",String(e))}prepareCommand(e){return!super.prepareCommand(e)||this.control.readOnly?!1:(this.writeControlValue(!this.#e),this.control.dispatchEvent(new this.ownerDocument.defaultView.Event("change")),!0)}}}),$g=Yt({name:"menu",tag:"gramlot-menu",base:tf,subTags:"menuline,spacer,contentPane",parameters:{presentation:{dtype:"T",default:"popup",enum:["popup","bar"]},orientation:{dtype:"T",default:"horizontal",enum:["horizontal","vertical"]},modifiers:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",default:"beside",enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",default:24},resolver:{dtype:"T",nullable:!0},cacheTime:{dtype:"R",default:-1},sync:{dtype:"B",default:!1}},implementation:o=>class extends o{}}),Rg=Yt({name:"menuline",tag:"gramlot-menu-line",base:ao,command:!0,subTags:"*",parameters:{command:{dtype:"T",nullable:!0},caption:{dtype:"T",nullable:!0},code:{dtype:"T",nullable:!0},checked:{dtype:"B",nullable:!0,binding:"read"},tooltip:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",nullable:!0,enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",nullable:!0},group:{dtype:"B",default:!1},parameters:{annotation:{kind:"type",module:"builtins",name:"dict"},nullable:!0},favorite:{dtype:"B",default:!1}},implementation:rf}),jg=Yt({name:"spacer",tag:"gramlot-spacer",base:o=>class extends o{projectAttributes(e){let t=br(this,e),{size:r,flex:n}=this.parameters;if(r!=null&&n!=null)throw new TypeError("spacer accepts size or flex, not both");if(r!=null&&(!Number.isFinite(r)||r<0)||n!=null&&(!Number.isFinite(n)||n<=0))throw new TypeError("Invalid spacer size/flex");return this.style.flex=n!=null?`${n} 1 0px`:`0 0 ${r??0}px`,this.setAttribute("aria-hidden","true"),t}},parameters:{size:{dtype:"R",nullable:!0},flex:{dtype:"R",nullable:!0}},implementation:o=>class extends o{}}),Pg=Yt({name:"dropDownButton",tag:"gramlot-drop-down-button",base:ao,command:!0,subTags:"*",parameters:{persist:{dtype:"B",default:!1}},implementation:o=>class extends o{#e=null;#t;#r=null;#n;#o;constructor(){super();let e=this.ownerDocument;this.control.classList.add("split"),this.controlBox.classList.add("choice-field");let t=e.createElement("style");t.textContent=ul+".split{border-radius:var(--gramlot-radius-sm,4px);padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .5em)}",this.shadowRoot.append(t),this.#o=e.createElement("span"),this.#o.hidden=!0,this.control.append(this.#o),this.#n=e.createElement("button"),this.#n.type="button",this.#n.className="arrow choice-toggle",this.#n.setAttribute("aria-label","Open menu"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.controlBox.append(this.#n);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.#n.addEventListener("click",n=>{n.stopPropagation(),this.menu.opened?this.closeMenu():this.openMenu()}),this.#n.addEventListener("keydown",n=>{["ArrowDown","ArrowUp"].includes(n.key)&&(n.preventDefault(),this.openMenu(n.key==="ArrowUp"))})}get menu(){return[...this.children].map(Ie).find(e=>e.localName==="gramlot-menu")}get menuItems(){return this.menu?.items??[]}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.#n.disabled=this.disabled,this.disabled&&this.menu?.close(!1),this.#i(),r}attachCommand(){if(this.parameters.persist){if(!this.id)throw new TypeError("dropDownButton persist requires an explicit id");this.#r=`gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;try{this.#e=this.ownerDocument.defaultView.localStorage.getItem(this.#r)}catch{}}this.#i(),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.#i()),this.#t.observe(this,{childList:!0,subtree:!0,characterData:!0})}releaseCommand(){this.#t?.disconnect(),this.menu?.close(!1)}commandTarget(e){return e?.composedPath().includes(this.menu)?null:this.menuItems.find(t=>t.occurrence===this.#e)??this}selectCommand(e,t){if(t){if(this.#e=e.occurrence,this.#r)try{this.ownerDocument.defaultView.localStorage.setItem(this.#r,this.#e)}catch{}this.#i()}this.closeMenu()}#i(){let e=this.menuItems.map(n=>n.occurrence).filter(Boolean);if(new Set(e).size!==e.length)throw new TypeError("Dropdown menu codes must be unique");let t=this.commandTarget(),r=t!==this;this.caption.hidden=r,this.#o.hidden=!r,this.#o.textContent=r?t.entryCaption:"",this.renderIcon(t.entryIcon,t.entryIconSrc)}openMenu(e=!1){this.disabled||this.menu?.open(this.#n,e)}closeMenu(){this.menu?.close()}}}),Wi=hl({name:"buttons",components:[Ng,Og,Pg,$g,Rg,jg]});var El={};ee(El,{ValidationRun:()=>kr});var kr=class{epoch=0;controller=null;cancel(){this.epoch++,this.controller?.abort(),this.controller=null}start(e,t,r,n,i,s=()=>{}){this.cancel();let a=new AbortController,l=this.epoch;this.controller=a;let c=r.validationCurrent(),u=()=>l===this.epoch&&!a.signal.aborted&&c(),d=m=>({value:e,modified:!1,error:m.message,warnings:[],issues:[],datachanges:[]}),f=!1,h=m=>{if(f||!u())return{ok:!1};f=!0,this.controller=null;let b={ok:!m.error,value:m.value,result:m,rules:t,isCurrent:u};return i(b),b},p;try{if(t.validate_timeout!=null&&(!Number.isInteger(t.validate_timeout)||t.validate_timeout<=0))throw new TypeError("validate_timeout must be a positive integer in milliseconds.");p=n(e,t,{...r,signal:a.signal})}catch(m){return h(d(m))}return p instanceof Promise?(s(),new Promise(m=>{let b,w=()=>{clearTimeout(b),m({ok:!1})};a.signal.addEventListener("abort",w,{once:!0});let _=v=>{clearTimeout(b),a.signal.removeEventListener("abort",w);try{m(h(v))}catch(E){r.reportError(E,"Validation completion failed"),m({ok:!1})}};t.validate_timeout!=null&&(b=setTimeout(()=>{_(d(new Error("Validation timed out."))),a.abort()},t.validate_timeout)),p.then(_,v=>_(d(v)))})):h(p)}};function lo(o){return typeof o=="string"&&!["null","true","false"].includes(o)&&/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(o)}function Tt(o,e,t,r){let{group:n,method:i}=o.logicRegistry.resolve(t,e);return i.call(n,e,r)}function dt(o,e,t,r,n,i=Object.keys(n)){return lo(r)?Tt(o,e,r,n):o.inlineCompiler.compile(e,t,r,i)(n)}function Gi(o){let e=o.node,t=o.runtime.gramlot,r=(n,i,s,a=!1)=>a?o.runtime.inlineCompiler.compile(e,n,i,Object.keys(s),`return (${i});`)(s):dt(o.runtime,e,n,i,s);return{isDecimal:q,invoke:r,callLogic:(n,i)=>Tt(o.runtime,e,n,i),remote:(n,i,s)=>t.rpc.call("data",n,i,{signal:s}),reportError:(n,i)=>{o.closed||o.runtime.reportError(n,i)},validationCurrent:()=>{let n=e.getAttr("value"),i=e.pointerType(n)?e.absDatapath(n):null;return()=>!o.closed&&e.getAttr("value")===n&&(i===null||e.absDatapath(n)===i)},finishValidation:({ok:n,result:i,rules:s})=>{if(o.closed)return;if(n)for(let l of i.datachanges)e.getRelativeData(".").update(l);let a=n?"validate_onAccept":"validate_onReject";if(s[a]){let l=c=>{o.closed||o.runtime.reportError(c,"Validation callback failed")};try{let c=Object.fromEntries(Object.entries(s).map(([d,f])=>[d.slice(9),f])),u=r(a,s[a],{value:i.value,result:i,validations:c,userChange:!0});u instanceof Promise&&u.catch(l)}catch(c){l(c)}}},checkDataPatch:n=>{if(!(n instanceof x))throw new TypeError("Validation data changes must be a Bag.");if(!(e.getRelativeData(".")instanceof x))throw new TypeError("Validation data changes require a Bag datapath.")}}}var Zt=o=>j(R(o)),Er=(o,e)=>R(o)===R(e),co=o=>o.absDatapath(o.getAttr("value")),qe=o=>encodeURIComponent(o).replaceAll(".","%2E"),Kt=o=>qe(co(o)),nf=(o,e)=>qe(o.fullpath)+":"+e,uo=class{constructor(e,t,r=e.absDatapath(".")){if(this.node=e,this.runtime=t,this.registers=new x,this.validationQueue=new Set,this.fields=new Map,this.validations=new Map,this.disposed=!1,this.scheduled=!1,this.writing=0,this.path=r,this.retainedFields=new Map,this.listeners=new Set,this.navigators=new Set,this.validationSources=new Set,this.validationDependencies=new Map,this.validationRevision=0,this.validatedRevision=-1,this.fullValidation=null,this.derived=new Set,!(this.data instanceof x))throw new TypeError("A form requires a Bag at its datapath.");this.registers.setItem("baseline",Zt(this.data));for(let n of["changes","errors","pending","drafts"])this.registers.setItem(n,new x);this.subscription=t.router.register({path:this.path,recipient:this,subtree:!0}),t.bindingFor(e).track(()=>this.dispose())}rebind(){let e=this.node.absDatapath(".");if(e!==this.path){if(!(this.data instanceof x))throw new TypeError("A form requires a Bag at its datapath.");this.subscription.close();for(let t of["errors","pending","drafts"])this.registers.setItem(t,new x);this.path=e,this.subscription=this.runtime.router.register({path:e,recipient:this,subtree:!0}),this.updateChanges();for(let t of this.fields.values())t.element.cancelValidation(),this.clearDraft(t.node),this.scheduleValidation(t)}}get data(){return this.runtime.gramlot.data.getItem(this.path)}registerDerived(e){return this.derived.add(e),this.updateChanges(),()=>{this.derived.delete(e)}}isDerived(e){for(let t of this.derived)if(t(e))return!0;return!1}ownAttributes(e,t){return Object.fromEntries(Object.entries(e.attr).filter(([r])=>!this.isDerived(`${t}?${r}`)))}onlyDerived(e,t){return e?Object.keys(this.ownAttributes(e,t)).length?!1:e.value instanceof x?e.value.getNodes().every(r=>this.onlyDerived(r,t?`${t}.${r.label}`:r.label)):this.isDerived(t):!0}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get errorEntries(){return this.registers.getItem("errors").getNodes().map(e=>({path:decodeURIComponent(e.label),message:e.value.getNodes().map(t=>t.value).join(`
219
+ `)}))}get changeEntries(){let e=[];for(let t of this.registers.getItem("changes").getNodes()){let r=t.value,n=[this.path,r.getItem("path")].filter(Boolean).join("."),i=r.getItem("existed"),s=r.getItem("exists"),a=r.getItem("previous"),l=r.getItem("current");if((!i||!s||!Er(a,l))&&e.push({path:n,previous:a,current:l,existed:i,exists:s}),i&&s){let c=r.getItem("previousAttributes"),u=r.getItem("currentAttributes");for(let d of new Set([...c.getNodes(),...u.getNodes()].map(f=>f.label))){let f=c.getNode(d)!==null,h=u.getNode(d)!==null;(f!==h||!Er(c.getItem(d),u.getItem(d)))&&e.push({path:n+"?"+d,previous:c.getItem(d),current:u.getItem(d),existed:f,exists:h})}}}return e}registerNavigator(e){return this.navigators.add(e),()=>this.navigators.delete(e)}focusField(e){if(this.disposed)return!1;for(let t of this.fields.values())if(co(t.node)===e&&t.element.isConnected)return t.element.control.focus(),!0;for(let t of this.navigators)if(t(e))return!0;return!1}retainField(e){this.retainedFields.set(e,(this.retainedFields.get(e)??0)+1)}releaseField(e){let t=this.retainedFields.get(e);if(t>1){this.retainedFields.set(e,t-1);return}if(this.retainedFields.delete(e),![...this.validations.values()].some(r=>r.path===e)){for(let r of["errors","pending","drafts"]){let n=this.registers.getItem(r),i=qe(e);n.getNode(i)&&n.popNode(i)}this.notify()}}fieldStatus(e){let t=qe(e);return{error:this.registers.getItem("errors").getItem(t),pending:this.registers.getItem("pending").getItem(t),draft:this.registers.getItem("drafts").getItem(t)}}get status(){let e=this.registers.getItem("changes").length>0,t=this.fullValidation!==null||this.registers.getItem("pending").length>0,r=this.registers.getItem("errors").length>0,n=this.registers.getItem("drafts").length>0;return{dirty:e,pending:t,valid:!r&&!n,canSave:e&&!r&&!n&&!t,status:r?"error":t||n?"pending":e?"changed":"ok"}}register(e){let t=e.node;this.fields.set(t,e);let r=this.registerField(t,e.element.constructor);return r.selection=e.element.validationSelection(),this.schedule(()=>{if(this.fields.get(t)!==e)return;let n=this.registers.getItem("drafts").getNode(Kt(t));n&&(t.formDraft=n.value,e.element.restoreFormDraft(n.value)),r.result&&e.element.presentValidation(r.result);let i=this.registers.getItem("errors").getItem(Kt(t));i&&e.element.error(i.getNodes().map(s=>s.value).join(`
220
+ `)),e.element.setFieldState({invalid:!!i,pending:!!this.fieldStatus(r.path).pending})}),()=>{this.fields.delete(t)}}registerField(e,t,r=!0){let n=this.validations.get(e);if(n)return n;if(!t.validationExecutor)throw new TypeError("Grid editors require shared input validation.");let i=this.runtime.bindingFor(e),s=Gi(i);return n={node:e,binding:i,context:s,component:t,run:new kr,execute:t.validationExecutor,checkValue:t.validationValueCheck(s),path:co(e),rules:null,value:void 0,target:null,result:null,selection:null},this.validations.set(e,n),i.editingSession=this,n.release=i.track(()=>this.forgetField(e)),this.refreshField(e,r),n}registerValidationSource(e){return this.validationSources.add(e),this.invalidateValidation(),()=>{this.validationSources.delete(e),this.invalidateValidation()}}invalidateValidation(){if(this.validationRevision++,this.fullValidation)for(let e of this.fullValidation.active)this.cancelValidation(e)}trackValidationDependency(e){if(e===null||this.validationDependencies.has(e))return;let[t,r=null]=e.split("?",2);this.validationDependencies.set(e,this.runtime.router.register({path:t,attr:r,subtree:!0,recipient:{receive:()=>this.invalidateValidation()}}))}clearValidationDependencies(){for(let e of this.validationDependencies.values())e.close();this.validationDependencies.clear()}validate(){if(this.disposed)return Promise.resolve(!1);if(this.fullValidation)return this.fullValidation.promise;for(let s of this.fields.values())Object.hasOwn(s.node,"formDraft")&&s.commit();this.clearValidationDependencies();let e={revision:this.validationRevision,promise:null,active:new Set,failed:!1,complete:!0};this.fullValidation=e,this.notify();let t=this.validationFields(),r=()=>!this.disposed&&!e.failed&&e.revision===this.validationRevision,n=new WeakSet,i=async()=>{let s=0;for(;r();){let a=t.next();if(a.done)return;let{node:l,release:c}=a.value;try{if(n.has(l))continue;n.add(l);for(let[d,f]of l.pointers())d!=="value"&&this.trackValidationDependency((d==="datapath"?l.parentNode:l).absDatapath(f));e.active.add(l),(await this.validateField(l))?.ok||(e.complete=!1)}finally{e.active.delete(l),c()}++s%20===0&&await new Promise(u=>setTimeout(u,0))}};return e.promise=Promise.resolve().then(async()=>{let a=(await Promise.allSettled(Array.from({length:8},()=>i().catch(c=>{e.failed=!0;for(let u of e.active)this.cancelValidation(u);throw c})))).find(c=>c.status==="rejected");if(a)throw a.reason;if(!r())return!1;let l=e.complete&&this.status.valid&&this.registers.getItem("pending").length===0;return l&&(this.validatedRevision=this.validationRevision),l}).finally(()=>{t.return(),this.fullValidation=null,this.notify()}),e.promise}*validationFields(){let e=[...this.validations.keys()];for(let t of this.validationSources)yield*t();for(let t of e)this.validations.has(t)&&(yield{node:t,release:()=>{}})}forgetField(e){let t=this.validations.get(e);if(t){t.run.cancel(),t.release(),t.binding.editingSession===this&&(t.binding.editingSession=null),this.validations.delete(e),this.validationQueue.delete(e);for(let r of["errors","pending"]){let n=this.registers.getItem(r).getItem(qe(t.path));if(n){for(let i of[...n.getNodes()])i.label.startsWith(qe(e.fullpath)+":")&&n.popNode(i.label);n.length||this.registers.getItem(r).popNode(qe(t.path))}}if(![...this.validations.values()].some(r=>r.path===t.path)){let r=this.registers.getItem("drafts");r.getNode(qe(t.path))&&r.popNode(qe(t.path))}delete e.formDraft,this.notify()}}refreshField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||this.writing)return;let[,n]=e.rootBuilder.runtimeValues(e),i=r.component.validationParameters(this.runtime.renderer.evaluateExpressions(e,n)),s=Object.fromEntries(Object.entries(i).filter(([f])=>f.startsWith("validate_"))),a=R(Object.fromEntries(Object.entries(i).filter(([f])=>f!=="value"))),l=co(e),c=this.runtime.gramlot.data.getNode(l.split("?")[0]),u=e.getRelativeData(e.getAttr("value")),d=r.path!==l||r.target!==c||!Er(r.value,u);if(!(!d&&r.configuration===a)){if(r.rules!==null&&this.invalidateValidation(),this.cancelValidation(e),r.path!==l)for(let f of["errors","pending","drafts"]){let h=this.registers.getItem(f);h.getNode(qe(r.path))&&h.popNode(qe(r.path))}Object.assign(r,{path:l,target:c,value:u,rules:s,configuration:a,result:null,selection:r.component.validationSelection(i,r.context)}),d&&this.clearDraft(e),t&&this.scheduleField(e)}}cancelValidation(e){this.validations.get(e)?.run.cancel(),this.validationQueue.delete(e),this.pendingPart(e,"validation",null)}writeCandidate(e,t){this.clearDraft(e),this.writing++;try{this.runtime.renderer.html.writeParameter(e,"value",t)}finally{this.writing--}let r=this.validations.get(e);r&&(r.value=e.getRelativeData(e.getAttr("value")),r.target=this.runtime.gramlot.data.getNode(r.path.split("?")[0]));for(let n of this.validations.keys())n!==e&&this.refreshField(n)}validateCandidate(e,t,r){this.invalidateValidation(),this.cancelValidation(e),this.writeCandidate(e,t);let n=this.validations.get(e);return n.selection=r,this.validateField(e,!1)}scheduleField(e){this.disposed||!this.validations.has(e)||this.validationQueue.has(e)||this.registers.getItem("drafts").getNode(Kt(e))||(this.validationQueue.add(e),this.pendingPart(e,"validation","scheduled"),this.schedule(()=>{this.validationQueue.delete(e)&&this.validateField(e)}))}scheduleValidation(e){this.refreshField(e.node);let t=this.validations.get(e.node);t&&!t.result&&!t.run.controller&&this.scheduleField(e.node)}validateField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||r.binding.closed||(this.validationQueue.delete(e),this.registers.getItem("drafts").getNode(Kt(e)))||this.registers.getItem("pending").getItem(Kt(e))?.getItem(nf(e,"selection")))return;let n=e.getRelativeData(e.getAttr("value")),i=this.fields.get(e);t&&i&&(r.selection=i.element.validationSelection());let s=r.selection,a=r.target,l=r.context.validationCurrent();return r.run.start(n,r.rules,{...r.context,validationCurrent:()=>()=>!this.disposed&&l()&&this.validations.get(e)===r&&this.runtime.gramlot.data.getNode(r.path.split("?")[0])===a,selection:s},r.execute,c=>{if(c.ok)try{r.checkValue(c.value,n)}catch(d){c.ok=!1,c.result.error=d.message}this.result(e,c.result),r.result=c.result,c.ok&&this.writeCandidate(e,c.value);let u=this.fields.get(e);u&&u.element.presentValidation(c.result),r.context.finishValidation(c)},()=>{this.pendingPart(e,"validation","active"),this.fields.get(e)?.element.setFieldState({pending:!0})})}remove(e,t){let r=this.registers.getItem(e),n=Kt(t);r.getNode(n)&&r.popNode(n)}set(e,t,r){r==null?this.remove(e,t):this.registers.getItem(e).setItem(Kt(t),r),this.notify()}draft(e,t){this.invalidateValidation(),this.cancelValidation(e),e.formDraft=t,this.set("drafts",e,t)}clearDraft(e){delete e.formDraft,this.set("drafts",e,null),this.issue(e,"parse",null)}result(e,t){this.pendingPart(e,"validation",null),this.issue(e,"validation",t.error||null)}part(e,t,r,n){r=nf(t,r);let i=this.registers.getItem(e),s=Kt(t),a=i.getItem(s);!a&&n!=null&&(a=new x,i.setItem(s,a)),a&&(n==null?a.getNode(r)&&a.popNode(r):a.setItem(r,n),a.length||this.remove(e,t)),this.notify()}issue(e,t,r){this.part("errors",e,t,r||null)}pendingPart(e,t,r){this.part("pending",e,t,r)}parseError(e,t){this.issue(e,"parse",t)}schedule(e){queueMicrotask(()=>{this.disposed||e()})}receive(e){if(!this.disposed&&(this.updateChanges(e.path),!this.writing)){this.invalidateValidation();for(let t of this.validations.keys())this.refreshField(t)}}updateChanges(e=null){let t=this.registers.getItem("changes"),r=e===this.path?"":e?.startsWith(this.path+".")?e.slice(this.path.length+1).split("?")[0]:"",n=(l,c,u)=>{if(u&&this.isDerived(u))return;let d=l&&this.ownAttributes(l,u),f=c&&this.ownAttributes(c,u);if(l&&c&&l.value instanceof x&&c.value instanceof x&&Er(d,f)){let h=new Set([...l.value.getNodes(),...c.value.getNodes()].map(p=>p.label));for(let p of h)n(l.value.getNode(p),c.value.getNode(p),u?u+"."+p:p)}else(l&&c?!Er([l.value,d],[c.value,f]):!(this.onlyDerived(l,u)&&this.onlyDerived(c,u)))&&t.setItem(qe(u),new x({path:u,existed:!!l,exists:!!c,previous:l?Zt(l.value):null,current:c?Zt(c.value):null,previousAttributes:l?Zt(d):null,currentAttributes:c?Zt(f):null}))},i=this.registers.getItem("baseline"),s=r;for(let l of t.getNodes()){let c=l.value.getItem("path");s.startsWith(c+".")&&(s=c)}let a=s;for(;a.includes(".");){a=a.slice(0,a.lastIndexOf("."));let l=i.getNode(a),c=this.data.getNode(a);(!l||!c||!Er(l.attr,c.attr))&&(s=a)}for(let l of[...t.getNodes()]){let c=l.value.getItem("path");(!s||c===s||c.startsWith(s+"."))&&t.popNode(l.label)}s?n(i.getNode(s),this.data.getNode(s),s):n({value:i,attr:{}},{value:this.data,attr:{}},""),this.notify()}notify(){this.disposed||this.scheduled||(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1;let e=this.status,t=this.registers.getItem("status");(!t||!Er(t,new x(e)))&&(this.registers.setItem("status",new x(e)),this.node.publish("formStatus",e));for(let r of this.listeners)r()}))}commitField(e){for(let t of this.fields.values())co(t.node)===e&&Object.hasOwn(t.node,"formDraft")&&t.commit()}accept(){if(this.disposed)return!1;for(let e of this.fields.values())Object.hasOwn(e.node,"formDraft")&&e.commit();return!this.status.valid||this.status.pending||this.validationSources.size&&this.validatedRevision!==this.validationRevision?!1:(this.registers.setItem("baseline",Zt(this.data)),this.updateChanges(),!0)}load(e){if(!(e instanceof x))throw new TypeError("Editing load requires a Bag.");this.disposed||(this.registers.setItem("baseline",Zt(e)),this.restore())}restore(){if(!this.disposed){this.invalidateValidation();for(let e of this.validations.keys())this.cancelValidation(e);for(let e of this.fields.values())e.element.cancelValidation(),this.clearDraft(e.node),e.element.restoreFormValue(this.registers.getItem("baseline").getItem(e.node.absDatapath(e.node.getAttr("value")).slice(this.path?this.path.length+1:0)));this.runtime.gramlot.data.setItem(this.path,Zt(this.registers.getItem("baseline")));for(let e of["errors","pending","drafts"])this.registers.setItem(e,new x);this.updateChanges();for(let e of this.validations.keys())this.scheduleField(e)}}dispose(){if(!this.disposed){this.disposed=!0,this.subscription.close();for(let e of this.validations.keys())this.forgetField(e);this.fields.clear(),this.validationQueue.clear(),this.retainedFields.clear(),this.listeners.clear(),this.navigators.clear(),this.validationSources.clear(),this.clearValidationDependencies()}}};function Bg(o,e,t=o){let r=new Map,n=new Set,i=new Map;for(let[a,l]of e){if(typeof a!="string")continue;let c=H(l)?.pointer??l;i.set(a,c instanceof Y?c.resolve():o.pointerType(c)?t.getRelativeData(c):Le(c)?null:c)}let s=a=>{if(r.has(a))return r.get(a);if(!e.has(a))throw new Error(`Source attribute '${a}' does not exist`);if(n.has(a))throw new Error(`cyclic attribute dependency: ${[...n,a].join(" -> ")}`);n.add(a);let l=e.get(a),c=H(l),u=c?i.get(a):null,d,f=h=>h?s(h):u;try{if(c)if(c.expression){let h=Jr(c.body),p=h.slots.map(f);d=o.rootBuilder.evaluatePointerExpression(o,a,l,h,p)}else d=zt(c.body,f),u==null&&(d=null);else d=i.get(a);return r.set(a,d),d}finally{n.delete(a)}};return{resolve:s}}function Jt(o,e,t=o){let r=new Map([...Object.entries(o.getAttr()),...ge(o.getAttr())]);return Bg(o,r,t).resolve(e)}var Mg={dataFormula:["formula","_if","_else","_ask_if","_ask_onCancel"],dataController:["script","_if","_else","_ask_if","_ask_onCancel"],dataRpc:["_ask_if","_ask_onCancel","_if","_else","_onCalling","_onResult","_onError"],dataRemote:["_if","_else","_onCalling"]},Tl=["_cachedRemote","_if","_else","_onRemote","_onCalling","_delay","_timing","_userChanges"],Lg=["_if","_else","_onRemote","_onCalling"],Sl=class{#e;#t=null;#r=null;#n=!1;constructor(e){this.#e=e}get inflight(){return this.#t?.view??null}get pending(){let e=this.#r;return e?Object.freeze({method:e.method,get params(){return j(e.text)}}):null}calling(e){if(!e)return!0;let t=!1,r=this.#n;this.#n=!0;try{t=e()!==!1}finally{this.#n=r,!t&&!this.#t&&this.#o()}return t}submit(e,t,r){try{let n=R(t);return this.#t?this.#r?Promise.resolve(void 0):new Promise((i,s)=>{this.#r={method:e,text:n,perform:r,resolve:i,reject:s}}):(this.#r?.resolve(void 0),this.#r=null,this.#i(e,t,n,r))}catch(n){return Promise.reject(n)}}submitSync(e,t){if(this.#t)throw new Error("A synchronous call cannot start while a request of the node is in flight");if(!this.#e.matches(e))throw new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`);return t()}#o(){let e=this.#r;if(!e)return;this.#r=null;let t;try{t=this.#i(e.method,j(e.text),e.text,e.perform)}catch(r){t=Promise.reject(r)}t.then(e.resolve,e.reject)}#i(e,t,r,n){if(!this.#e.matches(e))return Promise.reject(new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`));let i=new AbortController,s={method:e,params:t,text:r,controller:i,ignored:!1};s.view=Object.freeze({method:e,get params(){return j(r)},sentAt:Date.now(),cancel:()=>this.#a(s)}),this.#t=s,i.signal.addEventListener("abort",()=>this.#s(s),{once:!0});let a;try{a=Promise.resolve(n(s))}catch(l){a=Promise.reject(l)}return a.then(()=>this.#s(s),()=>this.#s(s)),a}#s(e){this.#t===e&&(this.#t=null,this.#o())}#a(e){this.#t===e&&(e.ignored=!0,this.#t=null,this.#n||this.#o())}};function of(o){return typeof o=="string"&&o.startsWith("==")}function Fg(o){let e=[],t=r=>{for(let n of r.getNodes())n.nodeTag==="column"&&typeof n.getAttr("formula")=="string"?e.push([`struct.${n.getAttr("field")}.formula`,n.getAttr("formula")]):(n._getMeta("gridStruct")||n.nodeTag==="colgroup")&&n.staticValue instanceof N&&t(n.staticValue)};return o.staticValue instanceof N&&t(o.staticValue),e}var Tr=class extends Se{#e=null;#t=null;get treeStore(){return this.#t}setTreeStore(e){if(this.nodeTag!=="tree")throw new TypeError("setTreeStore requires a tree Source node");if(e!==null&&!(e instanceof x))throw new TypeError("setTreeStore requires a Bag or null");if(e===this.#t)return;this.#t=e;let t=this.rootBuilder.binding,r=t?.bindingFor(this);r&&!r.closed&&(r.rebind(),t.renderer.attached(this)&&t.renderer.project(this))}get formState(){for(let e=this;e;e=e.parentNode){if(e.#e&&e._getMeta("gramlot_component")?.bagStore)return e.#e;if(e.getAttr("formId")!=null||e.getAttr("form")===!0){let t=e.#e??=new uo(e,this.rootBuilder.binding);return t.rebind(),t}}return null}editCollection(e){let t=this.parentNode?.formState;if(t){if(e!==t.path&&!e.startsWith(t.path+"."))throw new Error("An edited grid in a form must use data within that form.");return t}if(this.#e&&this.#e.path!==e)throw new Error("An active grid editing session cannot change its storepath.");return this.#e??=new uo(this,this.rootBuilder.binding,e)}get frame(){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("frame accessor requires a window");let e=this.value instanceof N?this.value.getNodes():[];if(e.length){if(e.length!==1||e[0].nodeTag!=="framePane")throw new TypeError("A window requires exactly one framePane");return this.builder.wrapSource(e[0])}return this.builder.wrapSource(this.builder.commandOnNode(this,"framePane",null,{node_label:"frame"}))}requestClose(e="application"){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("requestClose requires a window");return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(e)}get grid(){if(this.nodeTag==="framePane"){let e=this.staticValue instanceof N?this.staticValue.getNode("center.grid"):null;if(!e||e.nodeTag!=="grid")throw new TypeError("This frame has no central grid");return this.builder.wrapSource(e)}return(e={})=>this.builder.wrapSource(this.builder.commandOnNode(this,"grid",null,e))}get toolbar(){if(this.nodeTag!=="framePane")throw new TypeError("toolbar accessor requires framePane");let e=this.staticValue instanceof N?this.staticValue.getNode("top.bar"):null;if(!e||e.nodeTag!=="menu")throw new TypeError("This frame has no toolbar");return this.builder.wrapSource(e)}get top(){return this.frameRegion("top")}get bottom(){return this.frameRegion("bottom")}get left(){return this.frameRegion("left")}get right(){return this.frameRegion("right")}get center(){return this.frameRegion("center")}frameRegion(e){if(this.nodeTag!=="framePane")throw new TypeError("Region accessors require framePane");let t=this.value instanceof N?this.value.getNodes().find(n=>n.getAttr("region")===e):null;if(t)return this.builder.wrapSource(t);let r={region:e,node_label:e};return e!=="center"&&Object.assign(r,{display:"flex",flex_direction:["top","bottom"].includes(e)?"column":"row"}),this.builder.wrapSource(this.builder.commandOnNode(this,"contentPane",null,r))}#r=new Set;#n=null;#o=null;get requests(){return this.#o??=new Sl(this.rootBuilder.nameSyntax)}codeAttributes(){let e=[...Mg[this.nodeTag]??[],...Object.entries(this.parentNode?._getMeta("gramlot_component")?.childParameters??{}).filter(([,r])=>r.inline).map(([r])=>r),...this._getMeta("gramlot_component")?.command?["action","_ask_if"]:[],...typeof this.getAttr("remote")=="string"?Lg:[]],t=[];for(let[r,n]of Object.entries(this.getAttr()??{}))typeof n=="string"&&(e.includes(r)||r==="validate_call"||r==="validate__onResult"||r==="validate_onAccept"||r==="validate_onReject"||/^validate_\w+_if$/.test(r)||r.startsWith("connect_on")||r.startsWith("subscribe_")||r.startsWith("selfsubscribe_"))&&t.push([r,n]);for(let r of["ask","_ask"]){let n=this.getAttr(r);if(n&&typeof n=="object")for(let i of["_if","askIf"])typeof n[i]=="string"&&t.push([`${r}.${i}`,n[i]])}for(let[r,n]of ge(this.getAttr()))if(of(n)&&t.push([r,n]),this.nodeTag==="script"&&typeof n=="string"){let i=this.builder.constructor.dialectPrefixes.find(s=>r.startsWith(s))??"";["src","href","xlink:href","xlink_href","_text"].includes(r.slice(i.length).toLowerCase())&&t.push([r,n])}return(of(this.staticValue)||this.nodeTag==="script"&&typeof this.staticValue=="string")&&t.push(["",this.staticValue]),this._getMeta("gramlot_component")?.bagStruct&&t.push(...Fg(this)),t}activateCode(){let e=new Map;for(let[t,r]of this.codeAttributes()){if(this.pointerType(r))throw new Error(`${this.nodeTag} '${this.label}': '${t}' is inline code and cannot be the pointer '${r}'; inline code is never read from Data`);e.set(t,r)}for(let[t,r]of[...ge(this.getAttr()),["datapath",this.getAttr("datapath")]])H(r)?.expression&&e.set(t,r);this.#n=e}activatedCode(e){return this.#n?.get(e)??null}remote(e,t={}){let r=this.rootBuilder.nameSyntax;if(typeof e!="string"||!(this.pointerType(e)||r.matches(e)))throw new TypeError(`${this.nodeTag} '${this.label}': remote name must be a pointer or match ${r.pattern}, not ${JSON.stringify(e)}`);let n=Object.keys(t).find(s=>s.startsWith("_")&&!Tl.includes(s));if(n)throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${n}' is not accepted; the control attributes are ${Tl.join(", ")}`);let i={remote:e};for(let[s,a]of Object.entries(t))i[Tl.includes(s)?s:`remote_${s}`]=a;return this.setAttr(i),on(this)}publish(e,t={}){return this.rootBuilder.binding.subscriptions.publishNode(this,e,t)}pointers(){let e=this.getAttr("datapath"),t=H(e)?Ze(this,e):new Set,r=super.pointers().filter(([n,i])=>!(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(n))&&!t.has(n)&&!this.#a(n,i)).map(([n,i])=>[n,H(i)?.pointer??i]);for(let n of t){let i=this.getAttr(n);this.pointerType(i)==="^"&&r.push(["datapath",H(i)?.pointer??i])}return r}runtimeToEvaluate(){let e=super.runtimeToEvaluate();for(let[t,r]of e){if(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(t)){e.set(t,new _t(()=>r));continue}if(this.pointerType(r)){if(H(r)){if(typeof t!="string")throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);this.absDatapath(r)===null&&e.set(t,new _t(()=>Jt(this,t)));continue}this.#a(t,r)?e.set(t,r.slice(1)):this.absDatapath(r)===null&&e.set(t,null)}}return e}pathAttribute(e){let t=this.getAttr(e);return H(t)?Jt(this,e):this.pointerType(t)&&this.#a(e,t)?t.slice(1):t}getRelativeData(e,t=null,r={}){return this.absDatapath(e)===null?null:super.getRelativeData(e,t,r)}setRelativeData(e,t,r={}){this.#l(e),super.setRelativeData(e,t,r)}PUT(e,t){this.#l(e),this.data.setItem(this.absDatapath(e),t,null,">",!1,!0,this,!1,!1)}FIRE(e,t=!0,r=null){t===null&&(t=!0),this.#l(e);let n=this.absDatapath(e);if(n.includes("?")){this.#i(n,t);return}this.data.getNode(n)?.setValue(null,!1);try{this.fireEvent(e,t,{attributes:r})}finally{this.data.getNode(n)?.setValue(null,!1)}}#i(e,t){let[r,n]=e.split("?",2),i=this.data;i.getNode(r)?.setAttr({[n]:null},!1);try{let s=i.getNode(r);s?s.setValue(s.staticValue,!0,{[n]:t},!0,!0,!0,!0):i.setItem(r,null,{[n]:t},">",!0,!0,!0,!0)}finally{i.getNode(r)?.setAttr({[n]:null},!1)}}FIRE_AFTER(e,t=!0,r=10){this.#l(e);let n=this.rootBuilder?.binding?.bindingFor(this)??null,i=null,s=setTimeout(()=>{i?.(),this.FIRE(e,t)},r);return i=n?.track(()=>clearTimeout(s))??null,()=>{clearTimeout(s),i?.()}}absDatapath(e){e=H(e)?.pointer??e;let t=this.pointerType(e)?e.slice(1):e;if(t.startsWith("#")&&t.includes("?")){let[r,n]=t.split("?",2),i=super.absDatapath(r);return i===null?null:`${i}?${n}`}return super.absDatapath(e)}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let n=r.getAttr("datapath");if(this.pointerType(n)&&(n=this.#s(r,n),n===null))return null;if(n!=null&&(e=e==="."?n:n+e),e.startsWith("#"))return r.parentNode._resolveSymbolicDatapath(e,t);r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_finalizeAbsPath(e,t){return e===null?null:super._finalizeAbsPath(e,t)}_resolveSymbolicDatapath(e,t){let r=e.slice(1).split(".",1)[0];if(r==="FORM"||r==="ANCHOR")return super._resolveSymbolicDatapath(e,t);let n=this.rootBuilder?.binding;if(!n)return super._resolveSymbolicDatapath(e,t);let i=n.nodeIds.get(r);if(!i)throw new Error(`#<id>: cannot resolve ${t}`);let s=e.slice(r.length+2);return i.absDatapath(s?`.${s}`:".")}#s(e,t){if(H(t)){let i=Jt(e,"datapath",e.parentNode);return i==null||i===""?null:i}let r=e.parentNode.absDatapath(t);if(r===null)return null;let n=this.data.getItem(r);return n==null||n===""?null:n}#a(e,t){return H(t)||typeof e!="string"||!e.endsWith("_path")?!1:(this.#r.has(e)||(this.#r.add(e),console.warn(`${this.nodeTag} '${this.label}': '${e}' holds a bare Data path; the pointer symbol of '${t}' is removed`)),!0)}#l(e){if(this.absDatapath(e)===null)throw new Error(`${this.nodeTag} '${this.label}': write on a null path: '${e}'`)}},de=class o extends N{get nodeClass(){return Tr}authorizedCopy(e){let t=new this.constructor;for(let r of this.getNodes()){let n=r.getAttr("auth")??null;if(n!==null){if(typeof n!="string")throw new TypeError(`${r.nodeTag} '${r.label}': 'auth' must be a string rule, not ${typeof n}`);if(e(n)!==null)continue}let i=r.staticValue;i instanceof o&&(i=i.authorizedCopy(e));let{auth:s,...a}=r.getAttr(),l=t.setItem(r.label,i,a,">",!1,!1,null,!1,!0,null,r.nodeTag);l.xmlTag=r.xmlTag}return t}activateCode(){for(let e of this.getNodes())e.activateCode(),e.staticValue instanceof o&&e.staticValue.activateCode();return this}};if((Pe(de.tytxSuffix).GramlotBuilderBag??de)!==de)throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");wt(de.tytxSuffix,{...Pe(de.tytxSuffix),GramlotBuilderBag:de});var zg=new Set(["animate","animateMotion","animateTransform","circle","ellipse","feBlend","feColorMatrix","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feGaussianBlur","feImage","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","image","line","metadata","path","polygon","polyline","rect","set","stop","use"]),fo=class extends Gt{constructor(e,t){super(e),this._owner=t}get owner(){return this._owner}_handleMeta(e,t){let r=this.owner.evaluateExpressions(e,t);vr(e,r);let[n,i]=super._handleMeta(e,r);return yr(e,i),e._getMeta("subbuilder")?[n,Jn(so(i))]:[n,i]}adaptAttrs(e){let{_meta:t,...r}=e;return cn(super.adaptAttrs(xr(Et(r))))}renderedItem(e,t,r,n={}){if(this.owner.renderType==="object")return this.owner.renderedItem(e,t,r,n);let{_text:i,...s}=r;return t=this.owner.expressionValue(e,t),Array.isArray(t)&&i!=null&&(t=[this._escapeText(_r(i)),...t]),zg.has(n.tag)?`${n.pretty?" ".repeat(this._nodeDepth(e,n.depthOffset??0)):""}<${n.tag}${this._formatAttrs(s)} />${n.pretty?`
221
+ `:""}`:super.renderedItem(e,t,s,n)}};var Sr=class extends Wt{#e=new WeakMap;#t=new WeakMap;get inlineCompiler(){return null}getRender(e){return this.renders.has(e)||(e instanceof Je?this.addRender(e,this):e instanceof vt&&this.addRender(e,new fo(e,this))),super.getRender(e)}render(e,t={}){if(e._getMeta("data_element"))return null;let[r,n]=e.rootBuilder.runtimeValues(e),i=this.getRender(e.builder),[s,a]=i._handleMeta(e,n);return e._getMeta("subbuilder")||(a=i.adaptAttrs(a)),i.renderedItem(e,e.value instanceof N?this.renderChildren(e.value,t):r,a,{tag:s,...t})}_handleMeta(e,t){let r=this.builder.constructor.dialectPrefixes,n=this.evaluateExpressions(e,t);vr(e,n,r);let[i,s]=super._handleMeta(e,vl(e,n,r));if(yr(e,s,r),e.nodeTag==="webcomponent"){i=xt(e.getAttr());let{code:c,...u}=s;s=u}if(e._getMeta("subbuilder")){let c=so(s);return e._getMeta("subbuilder")==="html"&&(c.xmlns=kt),[i,c]}let[a,l]=xl(i,s);return Object.keys(l).length&&this.#e.set(e,l),[i,a]}evaluateExpressions(e,t){let r=this.inlineCompiler,n=(s,a)=>r?r.compileExpression(e,s,a)(t):null,i={...t};for(let[s,a]of ge(e.getAttr()))e.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(s)||Le(a)&&Object.hasOwn(i,s)&&(i[s]=n(s,a));return Le(e.value)&&this.#t.set(e,n("",e.value)),i}expressionValue(e,t){return Le(e.value)?this.#t.get(e)??null:t}restoreNativeAttributes(e,t){let r=this.#e.get(e);return r?(this.#e.delete(e),{...t,...xr(r)}):t}adaptAttrs(e){let{_meta:t,...r}=e,n=`${this.builder.constructor._name}_`,i=this.builder.constructor.dialectPrefixes,s={},a={};for(let[l,c]of Object.entries(Et(r))){if(c==null)continue;if(l.startsWith(n))throw new Error(`${l}: the attribute prefix '${n}' is not accepted; use the prefix '${i[0]}'`);let u=i.find(d=>l.startsWith(d));u?s[l.slice(u.length)]=c:a[l]=c}return cn({...super.adaptAttrs(a),...s})}renderedItem(e,t,r,n={}){let i;[t,i]=un(this.expressionValue(e,t),this.restoreNativeAttributes(e,r));let{_text:s,...a}=i;Array.isArray(t)&&s!=null&&(t=[this._escapeText(_r(s)),...t]);let l=e.parentNode?._getMeta("subbuilder")==="html"?{xmlns:be,...a}:a;return super.renderedItem(e,t,l,n)}finalize(e,t=null,r={}){if(!r.doctype)return super.finalize(e,t,r);let n=this._composeStringFragments(e),i=this.builder.source.getNodes().filter(s=>!s._getMeta("data_element"));return i.length===1&&i[0].nodeTag==="html"||(n=`<html>${n}</html>`),super.finalize(`<!doctype html>${n}`,t,r)}};var sf={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"binding",version:null,title:"Gramlot binding",description:"Gramlot Data declarations and the plain HTML button; loaded after the HTML grammar."},abstracts:{},elements:{dataBinder:{doc:"Bidirectional subscription between a client Data branch and its page's server store.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"server_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataSetter:{doc:"Initial Data value, written literally at destination_path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!0,default:null},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:"Computed Data value written at result_path; formula is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"formula",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:"Side effects on Data; script is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"script",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRpc:{doc:"Server endpoint called through gramlot.rpc; the value is written at result_path when given.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"timeout",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRemote:{doc:"Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires; with sync (default) the read waits for the answer when the transport supports it.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"cacheTime",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"sync",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"bool"},has_default:!0,default:!0},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},html_button:{doc:"Plain native HTML button without Gramlot click mechanisms.",sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"button"}},html_dialog:{doc:"Native HTML dialog, distinct from the layout window component.",sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"dialog"}}}};var af={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"webcomponent",version:null,title:"Gramlot webcomponent",description:"An explicitly loaded autonomous custom element."},abstracts:{},elements:{webcomponent:{doc:"Create the custom-element tag named by literal code.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"code",kind:"keyword_only",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null}}};var Vg="data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element",Wg=new Set,Gg=new Set(["serverpath","dbenv","shared_id"]),Hg=["formsubscribe_"],Xg={dataSetter:"destination_path",dataFormula:"result_path",dataRpc:"result_path",dataRemote:"destination_path"},Yg={dataFormula:"formula",dataController:"script"},ff=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]),Hi={csv:"CSV",json:"JSON",tytx:"TYTX",xml:"XML",xlsx:"Excel"},lf=new Set(["node_label","frameTarget","nodeId"]),Zg=new Set(["storepath","rowMode","structpath"]);function cf(o,e){let t=o?._meta?.keywordPattern;if(!t)return null;let r=new Set(o.attributes.parameters.filter(i=>!i.kind.startsWith("var_")).map(i=>i.name)),n=Object.keys(e).find(i=>!r.has(i)&&!ff.has(i)&&!new RegExp(t).test(i));return n===void 0?null:`unknown attribute '${n}'`}function Kg(o){if(typeof o=="boolean")return o?Object.keys(Hi):[];if(typeof o!="string"||!o.trim())throw new TypeError("frameGrid export requires a boolean or a list of formats");let e=o.split(",").map(r=>r.trim()),t=e.find(r=>!Object.hasOwn(Hi,r));if(t!==void 0)throw new TypeError(`frameGrid export format '${t}' is not one of ${Object.keys(Hi).join(", ")}`);return e}function uf(o,e){if(["input","textarea","select","webcomponent"].includes(o)&&H(e.value))return"'value' does not accept pointer suffixes; use an ordinary value pointer";if(o==="html_button"&&Object.keys(e).some(n=>["action","ask","_delay","fire"].includes(n)||n.startsWith("fire_")))return"plain HTML button: use button for action, ask, fire or _delay";if(Object.hasOwn(e,"ask")&&!["button","toggleButton","dropDownButton","menuline"].includes(o))return"'ask' is supported on buttons";if(Object.hasOwn(e,"_ask")&&!["dataController","dataFormula","dataRpc"].includes(o))return"'_ask' requires a controller, formula or RPC";if(["dataSetter","dataRemote"].includes(o)&&Object.keys(e).some(n=>n.startsWith("subscribe_")||n.startsWith("selfsubscribe_")))return"topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";let t=Xg[o];if(t&&String(e[t]??"").includes("?"))return`'${t}' does not accept '?attr': '${e[t]}'`;let r=Yg[o];return r&&e[r]!=null&&e.func!=null?`'func' and '${r}' cannot be declared on the same node`:r&&e._if!=null&&e.func!=null?"'_if' is inline and cannot be declared with 'func': write the condition in the method":null}function df(o){return Object.keys(o).find(e=>Gg.has(e)||Hg.some(t=>e.startsWith(t)))}var me=class o extends Je{static _name="gramlot";static containers=["frameGrid"];static _sourceClass=de;static{this.defineGrammar(sf)}static{this.defineGrammar(af)}static{this.defineGrammar(Wi.toDocument())}frameGrid(e,{storepath:t,rowMode:r,structpath:n,searchOn:i=!1,searchHelp:s=!1,chart:a=!1,export:l=!1,printRows:c=!1,advancedTools:u=!1,addrow:d=!1,addrow_defaults:f=null,duprow:h=!1,delrow:p=!1,gridsemaphore:m=!1,...b}={}){for(let z of["framePane","grid"])if(!this.schemaTag(z))throw new TypeError(`frameGrid requires the ${z} collection`);let w={};for(let z of Object.keys(b))z.startsWith("chart_")&&(w[z.slice(6)]=b[z],delete b[z]);let[_,v]=this.frameGridRoute(b),E=Object.keys(v).find(z=>["storepath","rowMode"].includes(z)||z==="structpath"&&n!=null);if(E!==void 0)throw new TypeError(`frameGrid: '${E}' is given twice`);if(a!==!1){if(a!==!0&&(typeof a!="string"||!a))throw new TypeError("chart requires a boolean or chart type");if(!_.datapath)throw new TypeError("A chart frameGrid requires its own datapath");if(!this.schemaTag("chartPane"))throw new TypeError("frameGrid requires the chartPane collection");typeof a=="string"&&(w.chartType=a)}else if(Object.keys(w).length)throw new TypeError("chart_* options require chart");let D=Kg(l);for(let[z,V]of Object.entries({printRows:c,advancedTools:u,addrow:d,duprow:h,delrow:p,gridsemaphore:m}))if(typeof V!="boolean")throw new TypeError(`frameGrid ${z} requires a boolean`);if(f!==null&&(!d||typeof f!="object"||Array.isArray(f)))throw new TypeError("addrow_defaults requires addrow and a mapping");if(m){if(!_.datapath)throw new TypeError("A gridsemaphore frameGrid requires its own datapath");if(!this.schemaTag("editingStatus"))throw new TypeError("frameGrid requires the editingStatus collection");_.form=!0}let k={storepath:t,rowMode:r,...n==null?{}:{structpath:n},node_label:"grid",frameTarget:!0,height:"100%",width:"100%",..._.datapath?{selectedId:"^.selectedId"}:{},...v};a!==!1&&(k.nodeId=G()),this.validateNodeValues("grid",null,k),i!==!1&&this.validateNodeValues("searchBox",null,{searchOn:i,searchHelp:s});let C=e.framePane(_);C.center.grid(k);let O=C.top.menu({presentation:"bar",node_label:"bar",aria_label:"Grid toolbar",class:"gramlot-grid-toolbar"});i!==!1&&O.menuline({group:!0,node_label:"search",class:"gramlot-grid-search"}).searchBox({searchOn:i,searchHelp:s}),d&&O.menuline({command:"grid:addrow",node_label:"addrow",...f===null?{}:{parameters:{defaults:f}}}),h&&O.menuline({command:"grid:duprow",node_label:"duprow"}),p&&O.menuline({command:"grid:delrow",node_label:"delrow"});let L=z=>{let V=z.menuline({caption:"Export",icon:"\u21E9",labelPosition:"tooltip",node_label:"export"}).menu();for(let le of D)V.menuline({command:"grid:export",caption:Hi[le],parameters:{format:le},node_label:le})};if(D.length&&L(O),c&&O.menuline({command:"grid:printRows",node_label:"printRows"}),u){let z=O.menuline({caption:"Advanced tools",icon:"\u2026",labelPosition:"tooltip",node_label:"advancedTools"}).menu();z.menuline({command:"grid:lineNumbers",node_label:"lineNumbers"}),D.length&&L(z),c&&z.menuline({command:"grid:printRows",node_label:"printRows"})}return m&&O.menuline({group:!0,node_label:"semaphore"}).editingStatus(),a!==!1&&(O.menuline({caption:"Chart",icon:"\u25A5",labelPosition:"tooltip",node_label:"chart",action:"this.SET('._chart.open',true)"}),C.center.floatingPane({title:"Chart",open:"^._chart.open",width:"820px",height:"560px",movable:!0,resizable:!0,maximizable:!0,node_label:"chartWindow"}).frame.center.chartPane({storepath:t,rowMode:r,gridId:k.nodeId,configpath:"._chart",configDefaults:new x(w),height:"100%"})),C}frameGridRoute(e){let t=u=>new Set(this.schema[u].attributes.parameters.filter(d=>!d.kind.startsWith("var_")).map(d=>d.name)),r=new Set([...ff,...lt]),n=t("grid"),i=t("framePane"),s=new RegExp(this.schema.grid._meta.parameterPattern),a=u=>(n.has(u)||s.test(u))&&!i.has(u)&&!r.has(u)&&!lf.has(u)&&!Zg.has(u),l={},c={};for(let[u,d]of Object.entries(e)){let f,h;if(u.startsWith("grid_")){if(f=u.slice(5),h=c,lf.has(f))throw new TypeError(`frameGrid: '${u}' is composed by frameGrid`)}else u.startsWith("frame_")?(f=u.slice(6),h=l):(f=u,h=a(u)?c:l);if(Object.hasOwn(h,f))throw new TypeError(`frameGrid: '${f}' is given twice`);h[f]=d}return[l,c]}static get dialectPrefixes(){let e=[];for(let t=Object.getPrototypeOf(o);t&&t!==Function.prototype;t=Object.getPrototypeOf(t))Object.hasOwn(t,"_name")&&t._name&&e.push(`${t._name}_`);return e}constructor(e=null,{collections:t=[],auth:r=null,nameSyntax:n=to}={}){if(!(n instanceof mr))throw new TypeError(`nameSyntax must be a NameSyntax, not ${n}`);super(e),this._binding=null,this._auth=r,this._nameSyntax=n;for(let i of t)this.loadCollection(i)}get auth(){return this._auth}get nameSyntax(){return this._nameSyntax}get binding(){return this._binding}set binding(e){this._binding=e}evaluatePointerExpression(e,t,r,n,i){return this.binding?this.binding.inlineCompiler.compilePointerExpression(e,t,r,n.text)(i):null}nodeById(e){if(!this.binding)return super.nodeById(e);let t=this.binding.nodeIds.get(e);if(!t)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}loadCollection(e){return this.loadGrammar(e instanceof Xt?e.toDocument():e),this}schemaTag(e){let t=e.toLowerCase(),r=o.dialectPrefixes;if(t.startsWith(`${o._name}_`))throw new Error(`${e}: the tag prefix '${o._name}_' is not accepted; use the prefix '${r[0]}'`);if(Wg.has(t))throw new Error(`${e}: excluded from Gramlot`);let n=this.schemaTagNames[t];if(n)return n;for(let i of r)if(t.startsWith(i)&&this.schemaTagNames[t.slice(i.length)])return t;return null}bagCall(e,t,r,n){return t=this.#e(t),[r,n]=this.menuArguments(t,r,n),super.bagCall(e,t,r,n)}commandOnNode(e,t,r,n){return t=this.#e(t),[r,n]=this.menuArguments(t,r,n),super.commandOnNode(e,t,r,n)}menuArguments(e,t,r={}){if(e==="menu"&&t==null)return[new de(null,this),r];if(e==="menuline"&&t!=null&&t!=="-"){if(Object.hasOwn(r,"command"))throw new TypeError("menuline command must be declared once");return[null,{...r,command:t}]}return[t,r]}validateNodeValues(e,t,r={}){if(this.schema[e]?._meta?.gramlot_component&&H(r.value))throw new Error("'value' does not accept pointer suffixes");e==="webcomponent"&&xt(r);let n=df(r);if(n)throw new Error(`${e}: attribute '${n}' is excluded from Gramlot`);let i=uf(e,r)??cf(this.schema[e],r);if(i)throw new Error(`${e}: ${i}`);return super.validateNodeValues(e,t,r)}validateNode(e,t={}){if(e._getMeta("gramlot_component")&&H((t.attrs??e.getAttr()).value))throw new Error("'value' does not accept pointer suffixes");e.nodeTag==="webcomponent"&&xt(t.attrs??e.getAttr());let r=df(t.attrs??e.getAttr());if(r)throw new Error(`${e.nodeTag} '${e.label}': attribute '${r}' is excluded from Gramlot`);let n=uf(e.nodeTag,t.attrs??e.getAttr())??cf(this.schema[e.nodeTag],t.attrs??e.getAttr());if(n)throw new Error(`${e.nodeTag} '${e.label}': ${n}`);return super.validateNode(e,t)}_validateChildren(e,t,r,n){return super._validateChildren(e,t,r.map(i=>i==="html_button"?"button":i==="html_dialog"?"dialog":i),n)}_countsForGrammar(e){return e===this.schema.button||!e?._meta?.gramlot_component&&e!==this.schema.webcomponent&&super._countsForGrammar(e)}setChild(e,t,r,n,i=null){n=Object.fromEntries(Object.entries(n??{}).map(([l,c])=>[l,Z(c)instanceof Se?this.reference(c):c]));let a=t==="dataSetter"&&n?.value!==null&&typeof n?.value=="object"&&Object.getPrototypeOf(n.value)===Object.prototype?{...n,value:new x(n.value)}:n;return super.setChild(e,t,r,a,i)}#e(e){if(e==="data")throw new Error(Vg);if(this.schemaTagNames[e.toLowerCase()]===e)return e;let t=o.dialectPrefixes.find(r=>e.startsWith(r));return this.schemaTagNames[e.slice(t.length)]}get renderer_html(){return new Sr(this)}create(){this.setup(this.data),this.main(this.root)}computeLogic(){}promoteNodeValue(e,t,r){let n=t!=null?{_text:t}:null;e.setValue(r,!0,n,!0)}reference(e,t="node"){if(e=Z(e),!(e instanceof Se)||!["node","dom"].includes(t))throw new TypeError("Reference requires an element and node/dom kind");let r=e.getAttr("__ref");return r==null&&(r=G(),e.setAttr({__ref:r})),{$gramlotRef:r,kind:t}}toTytx(){return R(this.auth===null?this.source:this.source.authorizedCopy(this.auth))}};function Al(o){for(let e=o.parentNode;e;e=e.parentNode)if(e.nodeTag==="framePane")return e;return null}function Xi(o){if(!o||!(o.value instanceof N))return null;let e=o.value.getNodes().find(n=>n.getAttr("region")==="center"),t=[];function r(n){if(n.nodeTag!=="framePane"&&(n.getAttr("frameTarget")===!0&&t.push(n),n.value instanceof N))for(let i of n.value.getNodes())r(i)}return e&&r(e),t.length===1?t[0]:null}function Jg(o){if(o.closed||!o.runtime.renderer.attached(o.node))return!1;for(let e=o.node;e;e=e.parentNode){let[,t]=e.rootBuilder.runtimeValues(e);if(t.hidden===!0||t.disabled===!0)return!1}return!0}function hf(o){if(o&&typeof o=="object"){for(let e of Object.values(o))hf(e);Object.freeze(o)}return o}function pf(o,e){let t=o.node,r=t.getAttr("command"),n=o.runtime.gramlot.commands.get(r),i=Al(t),s=Xi(i);if(!n||!s)return console.warn(`Cannot dispatch command '${r}' at '${t.label}': missing or duplicate frame recipient`),null;let a=t.getAttr("parameters")??{};if(typeof a!="object"||Array.isArray(a))throw new TypeError("Command parameters require a mapping");let l=Object.fromEntries(Object.entries(a).map(([m,b])=>[m,t.pointerType(b)?t.getRelativeData(b):b])),c=hf(j(R(l))),u=Object.freeze(Object.fromEntries(["shift","ctrl","alt","meta"].map(m=>[m,!!e[`${m}Key`]]))),d=Object.freeze({sender:t,target:s,command:r,parameters:c,modifiers:u}),f=!1,h=o.runtime.bindingFor(s).track(()=>{f=!0}),p=()=>!f&&Jg(o)&&Xi(i)===s&&o.runtime.renderer.attached(s)&&t.getAttr("command")===r;return{message:d,current:p,release:h,cancel(){f=!0},deliver(){p()&&s.publish(n.publish,d)}}}var Qg=new Set(["input","select","textarea"]),eb=["type","multiple"];function mf(o,e){let t=o.node,r=t.getAttr(e);return t.pointerType(r)?t.getRelativeData(r):o.resolved[e]}var ve=class o{static liveWrites=!1;static writesDefault=!0;static preservesUnchangedValue=!1;#e;#t=!1;#r;#n;#o=!1;#i=!1;#s=!1;static for(e,t){let r=o.classFor(t.element,t.attrs);return r?new r(e,t):null}static classFor(e,t){if(e.namespaceURI!==be)return null;if(e.constructor.gramlotComponent)return e.constructor.gramlotComponent.parameters.value?.binding!=="twoWay"?null:e.control.type==="radio"?Ol:Il;if(e.localName==="textarea")return ft;if(e.localName==="select")return ho;if(e.localName!=="input")return null;let r=t.type==null?"text":String(t.type).toLowerCase();return Object.hasOwn(gf,r)?gf[r]:ft}static shape(e,t){return e?.constructor.gramlotComponent?.parameters.value?.binding==="twoWay"&&e.control.type==="radio"?JSON.stringify([]):e?.namespaceURI!==be||!Qg.has(e.localName)?null:JSON.stringify(eb.filter(r=>(r!=="type"||e.localName!=="input")&&(r!=="multiple"||!["input","select"].includes(e.localName))).map(r=>t[r]??null))}constructor(e,t){this.#r=e,this.#n=t}get binding(){return this.#r}get element(){return this.#n.element}get node(){return this.binding.node}get eventElement(){return this.element}get resolved(){return this.#n.resolved}get live(){return!!this.resolved.live}get writeEvent(){return this.constructor.liveWrites&&this.live?"input":"change"}project(e,t){if(this.#i){this.#s=!0;return}this.constructor.preservesUnchangedValue&&this.#t&&this.same(this.#e,e)&&(!this.#o||this.same(this.read(),e))||(this.#e=e,this.#t=!0,!(this.#o&&this.same(this.read(),e))&&(this.constructor.writesDefault&&!this.node.pointerType(this.node.getAttr("value"))&&this.writeDefault(e),this.write(e)))}read(){return this.element.value}write(e){let t=e==null?"":String(e);this.element.value!==t&&(this.element.value=t)}writeDefault(e){let t=e==null?"":String(e);this.element.localName==="textarea"?this.#n.text.data!==t&&(this.#n.text.data=t):this.element.defaultValue!==t&&(this.element.defaultValue=t)}same(e,t){return Object.is(e,t)}commit(e,t=this.read()){if(!this.binding.closed){this.#o=!0;try{this.binding.runtime.renderer.html.writeParameter(this.node,"value",t)}finally{this.#o=!1}}}attach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.addEventListener(e,this)}detach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.removeEventListener(e,this);this.#s=!1}refresh(){}handleEvent(e){if(!this.binding.closed){if(e.type==="compositionstart"){this.#i=!0;return}if(e.type==="compositionend"){this.#i=!1,this.writeEvent==="input"&&this.commit(e),this.#s&&(this.#s=!1,this.binding.runtime.renderer.project(this.node));return}this.#i||e.isComposing||e.type===this.writeEvent&&this.commit(e)}}},Il=class extends ve{#e;form=null;static writesDefault=!1;static preservesUnchangedValue=!0;get eventElement(){return this.element.control}attach(){this.form=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null,this.element.setPageContext(Rl(this)),this.form&&this.node.pointerType(this.node.getAttr("value"))==="^"&&(this.#e=this.form.register(this)),super.attach()}refresh(){let e=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null;e!==this.form&&(this.#e?.(),this.form=e,this.element.setPageContext(Rl(this)),this.#e=e?e.register(this):null)}project(e,t){this.element.shouldProjectControlValue(e)&&super.project(e,t)}same(e,t){return this.element.sameControlValue(e,t)}detach(){this.element.releaseControl(),this.#e?.(),super.detach()}commit(e){if(this.binding.closed||this.element.control.disabled||this.element.control.readOnly)return;let t=this.element.acceptControlValue();this.form||bf(this.element,t,r=>super.commit(e,r.value))}get writeEvent(){return this.element.commitOnChange?"change":(this.resolved.live??this.element.parameters.live)&&this.element.liveWrites?"input":"change"}read(){return this.element.readControlValue()}write(e){this.element.writeControlValue(e)}handleEvent(e){if(e.type==="input"&&this.form&&!this.binding.closed&&!this.element.control.disabled&&!this.element.control.readOnly&&this.form.draft(this.node,this.element.control.value??""),super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.element.ownerDocument.defaultView.Event;this.element.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}},ft=class extends ve{static liveWrites=!0},Cl=class extends ve{static liveWrites=!0;read(){return this.element.value===""?null:Number(this.element.value)}commit(e){this.element.validity.badInput||super.commit(e)}},Dl=class extends ve{static liveWrites=!0;read(){return Number(this.element.value)}},ho=class extends ve{static writesDefault=!1;read(){return this.element.multiple?[...this.element.selectedOptions].map(e=>e.value):this.element.selectedIndex===-1?null:this.element.value}write(e){let t=this.element;if(t.multiple){if(e!=null&&!Array.isArray(e))throw new TypeError(`${this.node.nodeTag} '${this.node.label}': a multiple select requires an array`);let r=new Set((e??[]).map(String));for(let n of t.options){let i=r.has(n.value);n.selected!==i&&(n.selected=i)}}else e==null?t.selectedIndex!==-1&&(t.selectedIndex=-1):(t.selectedIndex===-1||t.value!==String(e))&&(t.value=String(e))}same(e,t){return Array.isArray(e)?Array.isArray(t)&&t.length===e.length&&t.every((r,n)=>Object.is(r,e[n])):super.same(e,t)}},Ar=class extends ve{read(){return this.element.value===""?null:this.element.value}},Nl=class extends ve{},Yi=class extends ve{static writesDefault=!1;read(){return this.element.checked}write(e){let t=!!e;this.element.checked!==t&&(this.element.checked=t)}same(e,t){return e===!!t}attach(){let e=this.node;if(e.getAttr("checked")!=null&&e.pointerType(e.getAttr("value"))==="^")throw new TypeError(`${e.nodeTag} '${e.label}': checked and a ^ value are two sources`);super.attach()}},dn=class extends Yi{#e=null;#t=!1;get groups(){return this.binding.runtime.renderer.radioGroups}attach(){let e=this.node,t=this.resolved.group??null,r=$l(e);if(t!=null){if(e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);this.#r(t,r)}super.attach(),t!=null&&(this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}detach(){this.#e!==null&&(this.groups.leave(this),this.element.removeAttribute("name"),this.#e=null),super.detach()}refresh(e=this.resolved.group){let t=this.resolved.group??null,r=$l(this.node);if(!Object.is(e??null,t)){let n=new Set([this,...this.groups.peers(this),...t===null?[]:this.groups.peersOf(t,r)]);this.groups.leave(this),this.#e=t===null?null:this.groups.join(this,t,r),this.#e===null?this.element.removeAttribute("name"):this.element.setAttribute("name",this.#e);for(let i of n){if(this.binding.closed||!this.binding.runtime.renderer.attached(this.node))return;i.binding.closed||!i.binding.runtime.renderer.attached(i.node)||i.binding.runtime.renderer.html.writeParameter(i.node,"value",!1)}return}this.#e!==null&&this.groups.nameOf(t,r)!==this.#e&&(this.#r(t,r),this.groups.leave(this),this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}#r(e,t){let r=this.node;if(mf(this,"value")&&this.groups.peersOf(e,t).some(n=>!n.binding.closed&&n.read()))throw new Error(`${r.nodeTag} '${r.label}': several true values in radio group '${e}'`)}project(e,t){let r=!this.#t;this.#t=!0;let n=this.read();super.project(e,t),!r&&!n&&this.read()&&this.turnOffPeers()}commit(e){let t=this.read();super.commit(e),t&&!this.binding.closed&&this.turnOffPeers()}turnOffPeers(){if(this.#e!==null)for(let e of this.groups.peers(this)){if(this.binding.closed)return;e.binding.closed||(e.element.checked&&(e.element.checked=!1),mf(e,"value")&&e.commit(null))}}},Ol=class extends dn{static writesDefault=!1;get host(){return super.element}get element(){return this.host.control}project(e,t){this.host.shouldProjectControlValue(e)&&super.project(e,t)}commit(e){this.binding.closed||this.element.disabled||this.element.readOnly||bf(this.host,this.host.acceptControlValue(),()=>super.commit(e))}read(){return this.host.readControlValue()}write(e){this.host.writeControlValue(e)}attach(){this.host.setPageContext(Rl(this)),super.attach(),this.element.addEventListener("keydown",this)}detach(){this.host.releaseControl(),this.element.removeEventListener("keydown",this),super.detach()}handleEvent(e){if(!this.binding.closed){if(e.type==="keydown"){if(this.resolved.group==null||!["ArrowLeft","ArrowUp","ArrowRight","ArrowDown"].includes(e.key))return;let t=this.groups.peersOf(this.resolved.group,$l(this.node)).filter(s=>!s.binding.closed&&!s.element.disabled),r=t.indexOf(this);if(r<0)return;e.preventDefault();let n=["ArrowLeft","ArrowUp"].includes(e.key)?-1:1,i=t[(r+n+t.length)%t.length];i.element.focus(),i.element.click();return}if(super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.host.ownerDocument.defaultView.Event;this.host.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}}},Zi=class{#e;#t=new Map;#r=new Map;#n=new WeakMap;#o=0;constructor(e){this.#e=e}join(e,t,r){let n=this.nameOf(t,r);return this.#t.has(n)||this.#t.set(n,new Set),this.#t.get(n).add(e),this.#r.set(e,n),n}leave(e){let t=this.#r.get(e);this.#r.delete(e);let r=this.#t.get(t);r?.delete(e),r?.size===0&&this.#t.delete(t)}peers(e){let t=this.#r.get(e);return[...this.#t.get(t)??[]].filter(r=>r!==e)}peersOf(e,t){return[...this.#t.get(this.nameOf(e,t))??[]]}nameOf(e,t){t!==null&&!this.#n.has(t)&&this.#n.set(t,this.#o++);let r=t===null?"page":`form${this.#n.get(t)}`;return`gramlot-${this.#e.instanceId}-${r}-${e}`}};function $l(o){for(let e=o;e;e=e.parentNode){let t=e.getAttr()??{};if(t.formId!=null||t.form===!0)return e}return null}var gf={text:ft,password:ft,email:ft,url:ft,tel:ft,search:ft,number:Cl,range:Dl,color:Nl,date:Ar,time:Ar,month:Ar,week:Ar,"datetime-local":Ar,checkbox:Yi,radio:dn,hidden:null,file:null,button:null,submit:null,reset:null,image:null};function Rl(o){let{binding:e,node:t}=o,r=e.runtime.gramlot;return{locale:r.locale,timeZone:r.timeZone,createDecimal:Ye,isDecimal:q,getDecimalLibrary:Zr,form:o.form,formCancelValidation:()=>o.form?.cancelValidation(t),formValidateCandidate:(n,i)=>o.form.validateCandidate(t,n,i),formValidate:()=>o.form?.scheduleValidation(o),formSelectionPending:n=>o.form?.pendingPart(t,"selection",n?"active":null),formSelectionError:n=>o.form?.issue(t,"selection",n),formParseError:n=>o.form?.parseError(t,n),formClearDraft:()=>o.form?.clearDraft(t),publish:(n,i)=>t.publish(n,i),isActive:()=>!e.closed,reportError:(n,i)=>{e.closed||e.runtime.reportError(n,i)},callLogic:(n,i)=>Tt(e.runtime,t,n,i),format:(n,i)=>r.format(n,i),...Gi(e),selectionDisplay:(n,i)=>{if(e.closed)return;let s=t.getAttr("value");if(t.pointerType(s)!=="^"||s.includes("?")||!Object.is(t.getRelativeData(s),i))return;let a=s.slice(1)+"?_displayedValue";t.getRelativeData(a)!==n&&t.setRelativeData(a,n)},periodOutput:(n,i)=>t.setRelativeData(n,i),selectionOutputs:({selectedCaption:n,selectedRecord:i,fields:s},a)=>{if(!e.closed){n&&t.setRelativeData(n,a?.caption??null),i&&t.setRelativeData(i,a?new x(a.record):null);for(let[l,c]of Object.entries(s))t.setRelativeData(c,a?.record[l.slice(9)]??null)}}}}function bf(o,e,t){let r=o.pageContext,n=i=>{i.ok&&i.isCurrent()&&(t(i),o.finishValidation(i))};if(e instanceof Promise)e.then(n).catch(i=>r.reportError(i,"Field update failed"));else try{n(e)}catch(i){r.reportError(i,"Field update failed")}}var jl=Symbol("source text"),wf={xmlns:"http://www.w3.org/2000/xmlns/",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},tb=new Set(["allowFullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formNoValidate","hidden","inert","isMap","itemscope","loop","multiple","muted","noModule","noValidate","open","playsInline","readOnly","required","reversed","selected"]),rb=new Set(["checked","muted","selected","value"]),nb=new Map([["allowfullscreen","allowFullscreen"],["formnovalidate","formNoValidate"],["ismap","isMap"],["nomodule","noModule"],["novalidate","noValidate"],["playsinline","playsInline"],["readonly","readOnly"]]);function ob(o){let e=o.replace(/-([a-z])/g,(t,r)=>r.toUpperCase());return nb.get(e.toLowerCase())??e}var Ki=class{constructor({format:e,metadataAttributes:t=[],invokeScript:r=null,callLogic:n=null,reportError:i=null,uploadContext:s=null}={}){this.format=e,this.uploadContext=s,this.invokeScript=r,this.callLogic=n,this.reportError=i,this.metadataAttributes=new Set([...lt,"_text",...t])}definition(e){let t=e.builder,n={...t.schema[t.schemaTag(e.nodeTag)]._meta,...e.getAttr("_meta")},i=e.nodeTag==="webcomponent"?xt(e.getAttr()):nn(e.nodeTag,{renderTag:n.render_tag,ns:e.getAttr("ns"),dialectName:t.constructor._name}),s=i==="foreignObject"?kt:n.render_attributes?.xmlns??e.getAttr("xmlns")??(t instanceof vt?kt:be);return{meta:n,namespace:s,tag:i}}validate(e,t=e.builder){this.validateLabelbox(e);let r=e.value instanceof N,n=r?e.getAttr("_text"):e.value;if(n!=null&&!["string","number","boolean"].includes(typeof n))throw new TypeError("HTML text must be scalar");let i=this.definition(e).meta.gramlot_component;for(let[l,c]of Object.entries(e.attr))if(!(i&&Object.hasOwn(i.parameters,l))&&!(e.nodeTag==="menuline"&&l==="parameters")&&!(this.metadataAttributes.has(l)||["ask","_ask"].includes(l)||c&&typeof c=="object"&&Object.hasOwn(c,"$gramlotRef"))&&c!=null&&!["string","number","boolean"].includes(typeof c))throw new TypeError(`HTML attribute ${l} must be scalar`);let s=Object.fromEntries(Object.entries(e.attr).filter(([l])=>!this.metadataAttributes.has(l))),a=r?e.value.getNodes().map(l=>l.nodeTag).filter(Boolean):[];t.validateNode(e,{value:n,attrs:s,childTags:a})}hasLabelbox(e){let t=this.definition(e).meta.gramlot_component;return t?.labelbox?!0:t?.presentationDefaults.length?Object.hasOwn(e.attr,"lbl"):Object.keys(e.attr).some(r=>r==="lbl"||r.startsWith("lbl_")||r.startsWith("box_"))}validateLabelbox(e){if(!this.hasLabelbox(e))return;let{tag:t,namespace:r}=this.definition(e);if(r!==be&&t!=="svg"||["html","head","body","style","script","link","meta","title","base","tr","td","th","thead","tbody","tfoot","col","colgroup","caption","option","optgroup","li","dt","dd","source","track","param","area"].includes(t))throw new TypeError("Labelbox requires content that can be placed in an HTML flow container");let n=e.parentNode;if(n?.nodeTag){let i=this.definition(n);if(i.namespace!==be&&i.tag!=="foreignObject"||["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","ul","ol","dl","p","button","label"].includes(i.tag))throw new TypeError("Labelbox requires an HTML flow container")}}create(e,t,r=null,n=e.attr,i=null){let{tag:s,namespace:a,meta:l}=this.definition(e);r??=s;let c=a===be?t.createElement(r):t.createElementNS(a,r);if(l.gramlot_component&&c.constructor.gramlotComponent?.tag!==r)throw new Error(`Component collection must be activated before rendering ${r}`);l.gramlot_component?.dataScope&&(c.readDataScope=()=>{if(!e.getAttr("datapath"))throw new Error("Data scope requires an explicit datapath");return e.getRelativeData(".")}),l.gramlot_component?.sourceContext&&c.setSourceContext({sourceNode:e,frameRecipient:()=>Xi(Al(e)),locale:e.rootBuilder.binding.gramlot.locale,timeZone:e.rootBuilder.binding.gramlot.timeZone,collectionView:(f,h)=>e.rootBuilder.binding.collectionView(e,f,h),format:this.format,upload:()=>this.uploadContext(),terminalUrl:f=>{let h=e.rootBuilder.binding.gramlot._pageStore;if(!h)throw new Error("A terminal requires a server with a PageStore channel (websocket)");return h.terminalUrl(f)},reportError:(f,h)=>this.reportError(e,f,h),publish:(f,h)=>e.publish(f,h),writeParameter:(f,h)=>this.writeParameter(e,f,h),callLogic:(f,h)=>this.callLogic(e,f,h)});let u=t.createTextNode(this.text(e));(a!==be||!l.void)&&c.append(u);let d={element:c,text:u,tag:r,presentation:c};if(this.hasLabelbox(e)){this.validateLabelbox(e);let f=t.createElement("div");f.append(c),d.labelbox=al(t,f),d.labelbox.choose=p=>{e.pointerType(e.getAttr("lbl_value"))?this.writeParameter(e,"lbl_value",p):e.setAttr({lbl_value:p})},d.presentation=d.labelbox.box,d.labelId=`gramlot-label-${G()}`,d.controlId=`gramlot-control-${G()}`;let h=t.createElement("style");h.textContent=sl,d.presentation.prepend(h),l.gramlot_component?.labelbox&&c.setLabelbox(d.labelbox)}return this.update(d,e,n,jl,i),d}matches(e,t){let{tag:r,namespace:n}=this.definition(t);return(n===be?e.tag.toLowerCase()===r.toLowerCase():e.tag===r)&&e.element.namespaceURI===n}writeParameter(e,t,r){let n=e.getAttr(t);e.pointerType(n)==="^"&&!H(n)&&!Object.is(e.getRelativeData(n.slice(1)),r)&&e.setRelativeData(n.slice(1),r)}compose(e,t,r){e.text.data=t??"";for(let n of r)e.element.append(n)}update(e,t,r=t.attr,n=jl,i=null,s=null){if(t.nodeTag==="script"){for(let[w,_]of t.codeAttributes())if(t.activatedCode(w)!==_)throw new Error(`script '${t.label}': '${w}' runs only as received with the Source`)}let{element:a,text:l}=e;if(this.hasLabelbox(t)&&!e.labelbox)throw new TypeError("Declare lbl or box_* when creating an experimental HTML labelbox");let c=a.namespaceURI===be,u=this.definition(t).meta.render_attributes??{},d=e.attrs??{},f=w=>(vr(t,w,t.builder.constructor.dialectPrefixes),yr(t,w,t.builder.constructor.dialectPrefixes),t.builder.renderer_html.adaptAttrs(w)),h=t.parentNode;if(h?._getMeta("gramlot_component")?.childParameters&&(r=a.ownerDocument.defaultView.customElements.get(h._getMeta("render_tag")).projectChild(e.presentation,r,{label:t.label,adapt:f,invoke:(_,v,E)=>this.invokeScript(t,_,v,E),reportError:(_,v)=>this.reportError(t,_,v),publish:(_,v)=>t.publish(_,v),publishParent:(_,v)=>h.publish(_,v),writeParameter:(_,v)=>this.writeParameter(t,_,v),remove:()=>t.parentBag.popNode(t.label)})),e.labelbox){e.labelbox.box.style.visibility="";let w=this.definition(t).meta.gramlot_component?.parameters??{},_=Object.fromEntries(Object.entries(w).filter(([v,E])=>v.startsWith("lbl_")&&Object.hasOwn(E,"default")).map(([v,E])=>[v,E.default]));r.lbl_variant==="card"&&r.lbl_position==null&&delete _.lbl_position,ll(e.labelbox,{..._,...r},f)}if(this.definition(t).meta.gramlot_component){if(this.definition(t).meta.gramlot_component.bagStore)if(t.nodeTag==="tree")a.setStoreBag(t.rootBuilder.binding.treeStore(t));else{let w=t.absDatapath(t.getAttr("storepath"));(!s||s.path===w||s.path.startsWith(`${w}.`)||w.startsWith(`${s.path}.`))&&a.setStoreBag(t.getRelativeData(t.getAttr("storepath")))}if(this.definition(t).meta.gramlot_component.bagStruct){let w=t.absDatapath(t.getAttr("structpath"));(!s||s.path===w||s.path.startsWith(`${w}.`)||w.startsWith(`${s.path}.`))&&a.setStructBag(t.getRelativeData(t.getAttr("structpath")))}r=a.projectAttributes(r,f)}e.labelbox&&(r=Object.fromEntries(Object.entries(r).filter(([w])=>w!=="lbl"&&!w.startsWith("lbl_")&&!w.startsWith("box_"))),r.slot!=null?e.presentation.setAttribute("slot",r.slot):e.presentationSlot!=null&&e.presentation.removeAttribute("slot"),e.presentationSlot=r.slot,delete r.slot),r=Object.fromEntries(ge({...r,...u}));let p=ve.classFor(a,r)!==null;n===jl&&(n=this.text(t));let m=n==null?"":String(n);l.data!==m&&(l.data=m);let b=[...new Set([...Object.keys(d),...Object.keys(r)])];b.sort((w,_)=>(_==="sandbox")-(w==="sandbox")||(c&&a.localName==="input"?(_==="type")-(w==="type"):0));for(let w of b){if(this.metadataAttributes.has(w)||["ask","_ask"].includes(w)||p&&w==="value")continue;let _=r[w];if(c&&w==="multiple"&&["input","select"].includes(a.localName)){a.multiple!==!!_&&(a.multiple=!!_);continue}if(c&&a.localName==="input"&&w==="type"){Object.is(d.type,_)||(_==null?a.removeAttribute("type"):a.type=String(_));continue}let v=w,E=ob(v),D=c&&tb.has(E)&&typeof a[E]=="boolean",k=v==="xmlns"?"xmlns":v.includes(":")?v.split(":")[0]:"",C=Object.hasOwn(wf,k)?wf[k]:null;if(Object.is(d[w],_)||(_==null||D&&!_?C?a.removeAttributeNS(C,v.split(":").at(-1)):a.removeAttribute(v):C?a.setAttributeNS(C,v,String(_)):a.setAttribute(v,D?"":String(_))),c&&(D||rb.has(E))&&E in a){let O=E==="value"?_==null?"":String(_):!!_;a[E]!==O&&(a[E]=O)}}if(i===!1?a.style.visibility!=="hidden"&&(a.style.visibility="hidden"):e.visible===!1&&(r.style==null?a.removeAttribute("style"):a.setAttribute("style",String(r.style))),e.visible=i,e.labelbox){let{fieldLabel:w,labelBox:_,box:v}=e.labelbox;["input","textarea","select","button","output","meter","progress"].includes(e.tag)?(a.id||(a.id=e.controlId),w.htmlFor=a.id):(w.id=e.labelId,this.definition(t).meta.gramlot_component?.labelbox||(v.setAttribute("role","group"),_.hidden?v.removeAttribute("aria-labelledby"):v.setAttribute("aria-labelledby",w.id))),v.hidden=!!r.hidden,i===!1&&(v.style.visibility="hidden")}e.attrs=r}text(e){return e.value instanceof N?e.getAttr("_text")==null?"":String(e.attr._text):e.value==null?"":String(e.value)}};var Ji=class o{#e;#t;#r=null;#n=0;#o=new Set;#i=null;static for(e,t){return t.element?.constructor.gramlotComponent?.command?new o(e,t):null}constructor(e,t){this.#e=e,this.#t=t}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get controllers(){let e=this.node.value;return e?.getNodes?e.getNodes().filter(t=>t.nodeTag==="dataController"||t.nodeTag==="dataRpc"):[]}get mechanism(){let e=this.node,t=this.controllers;if(t.length>1)throw new Error(`${e.nodeTag} '${e.label}': several dataController or dataRpc children; a button has one click mechanism`);let r=e.getAttr()??{},n=[];if(t.length&&n.push("controller"),r.action!=null&&n.push("action"),e.nodeTag==="menuline"&&r.command!=null&&n.push("registered"),_f(r).length&&n.push("fire"),e.nodeTag==="menuline"&&e.value instanceof N&&e.value.getNodes().some(i=>i.nodeTag==="menu")&&n.length)throw new Error(`menuline '${e.label}': a submenu cannot also execute a command`);if(e.nodeTag==="menuline"&&r.group&&n.length)throw new Error(`menuline '${e.label}': a group cannot execute a command`);if(n.length>1)throw new Error(`${e.nodeTag} '${e.label}': ${n.join(" and ")} together; a button has one click mechanism`);return n[0]??null}attach(){this.refresh(),this.element.activateCommand=e=>this.onClick(e),this.element.attachCommand(),this.element.addEventListener("click",this)}refresh(){if(this.node.nodeTag==="menuline"){let t=this.node.getAttr("command"),r=t?this.binding.runtime.gramlot.commands.get(t):null;this.element.setCommandDefinition(r,this.node.label),t&&!r&&this.#i!==t&&(console.warn(`Unknown command '${t}' in menu '${this.node.parentNode?.label}', entry '${this.node.label}'`),this.#i=t)}for(let t of this.#o)t.current()||t.cancel();this.mechanism&&this.node.getAttr("type")==null&&this.element.getAttribute("type")!=="button"&&this.element.setAttribute("type","button")}detach(){this.element.removeEventListener("click",this),this.element.releaseCommand(),delete this.element.activateCommand,this.#r?.();for(let e of this.#o)e.cancel(),e.release();this.#o.clear()}handleEvent(e){this.onClick(e)}onClick(e){if(this.binding.closed||this.element.disabled)return;let t=this.element.commandTarget(e);if(t===null)return;if(t!==this.element)return e.stopPropagation(),t.activateCommand(e);let r=this.element.closest("gramlot-row-actions"),n=r?r.getRowContext():null;if(r&&n===null||!this.element.prepareCommand(e))return;let i=this.mechanism;if(!i||(e.stopPropagation(),this.element.disabled))return;let s=i==="registered"?pf(this.binding,e):null;if(i==="registered"&&!s)return;s&&this.#o.add(s);let a=this.binding.countClick(),l=this.node;for(;l&&l.getAttr("_delay")==null;)l=l.parentNode;let c=l?l.rootBuilder.runtimeValues(l)[1]._delay:0;if(c>0){let u=this.#n+1;this.#r?.(),this.#n=u;let d=setTimeout(()=>{f(),this.#r=null,this.#n=0,this.#a(e,u,s,n)},c),f=this.binding.track(()=>this.#r?.());this.#r=()=>{clearTimeout(d),s&&(s.cancel(),s.release(),this.#o.delete(s)),f(),this.#r=null,this.#n=0};return}return this.#r?.(),this.#a(e,a,s,n)}async#s(e){try{if(!e.current())return;let t=this.node.getAttr("ask"),r=this.binding.runtime.askDialog,n={...e.message.parameters};if(t&&r.required(this.binding,t,n,"ask")&&await r.show(this.binding,t,n)===null)return;e.deliver()}finally{e.release(),this.#o.delete(e)}}#a(e,t,r=null,n=null){if(r)return this.#s(r);if(this.binding.closed||this.element.disabled)return;let i=this.mechanism;if(!i)return;let s=this.node,a=ib(e);if(i==="controller")this.binding.runtime.bindingFor(this.controllers[0])?.providers[0]?.invoke({kind:"click",event:e,counter:t,rowContext:n});else if(i==="action"){let l=()=>{let[,f]=s.rootBuilder.runtimeValues(s),h=Object.fromEntries(Object.entries(f).filter(([p])=>p!=="ask"));return{...this.binding.runtime.renderer.references.resolveArguments(h),...n,event:e,_counter:t,modifiers:a}},c=f=>{if(this.binding.closed||this.element.disabled||f===null)return;let h={...l(),...f};f&&(h._askResult=f),dt(this.binding.runtime,s,"action",s.getAttr("action"),h)},u=s.getAttr("ask"),d=this.binding.runtime.askDialog;if(u&&d.required(this.binding,u,l(),"ask"))return d.show(this.binding,u,l()).then(c);c(void 0)}else{let l={modifier:a,_counter:t},c=s.getAttr("fire");if(c!=null){s.FIRE(c,a||!0,l);return}for(let[u,d]of _f(s.getAttr())){if(this.binding.closed)return;s.FIRE(d,u.slice(5),l)}}}};function _f(o){return Object.entries(o??{}).filter(([e,t])=>t!=null&&(e==="fire"||e.startsWith("fire_")))}function ib(o){return["shift","ctrl","alt","meta"].filter(e=>o[`${e}Key`]).map(e=>e[0].toUpperCase()+e.slice(1)).join("")}var et=class extends Y{static classKwargs={...Y.classKwargs,asBag:!1};constructor({cacheTime:e,onError:t}){super({cacheTime:e??-1}),this.onError=t,this.loading=null,this.loaded=!1,this.writing=!1}resolve({static:e=!1}={}){return!e&&!this.closed&&!this.loading&&!this.writing&&this.expired&&this.refresh(),this.cachedValue}refresh(){if(this.closed)return null;let e=this.startLoad(r=>this.#e(r));if(e===null)return null;let t=()=>{this.loading===e&&(this.loading=null)};return e.then(t,t),this.loading=e,e.catch(r=>{r?.name!=="AbortError"&&this.onError(r)}),e}resolveSync(e){return super.resolve(e)}prepareValue(e){return e}async#e(e){if(this.closed)return;let t=this._computeEffectiveFingerprint(this._buildEffectiveKw()),r=await this.loadAsync(e);if(this.closed||e.ignored)return;let n=this.prepareValue(r);this._lastUpdate=Date.now(),this._lastEffectiveFingerprint=t,this.loaded=!0,this.writing=!0;try{this.node?this.node.setValue(n,this.cacheTime!==0):this.cachedValue=n}finally{this.writing=!1}return n}};var fn=class extends et{static internalParams=new Set([...et.internalParams,"binding","method","params","onCalling","onError","sync"]);constructor({binding:e,method:t,params:r,cacheTime:n,onCalling:i=null,onError:s,sync:a=!1}){super({cacheTime:n,onError:s}),this.binding=e,this.sync=a,this.method=t,this.params=r,this.onCalling=i}get closed(){return this.binding.closed}resolve(e={}){return this.sync?e.static||this.loading||this.writing?this.cachedValue:this.expired&&!this.binding.node.requests.calling(this.onCalling)?this.cachedValue:super.resolveSync(e):super.resolve(e)}load(){let e;try{e=this.binding.callSync("data",this.method,this.params)}catch(t){this.onError(t)}return this.loaded=!0,e}startLoad(e){let t=this.binding.node.requests;return t.calling(this.onCalling)?t.submit(this.method,this.params,e):null}loadAsync(e){return this.binding.call("data",e)}};var yf=new Set(["kind","command","caption","icon","iconSrc","tooltip","disabled","hidden","checked","favorite","parameters","resolver","cacheTime","sync"]);function vf(o,e=new Set){if(!(o instanceof x)||e.has(o))throw new TypeError("Menu resolver must return an acyclic Bag");let t=new Set([...e,o]);return o.getNodes().map(r=>{let n=r.attr,i=n.kind,s=r.staticValue;if(Object.keys(n).some(l=>!yf.has(l)&&!l.startsWith("resolver_")))throw new TypeError(`Unsupported menu record field: ${r.label}`);if(!["command","separator","submenu"].includes(i))throw new TypeError(`Invalid menu kind: ${r.label}`);for(let l of["disabled","hidden","checked"])if(n[l]!=null&&typeof n[l]!="boolean"&&!(typeof n[l]=="string"&&n[l].startsWith("^")))throw new TypeError(`Invalid menu ${l}`);if(n.favorite!=null&&typeof n.favorite!="boolean")throw new TypeError("favorite must be boolean");if(n.caption!=null&&typeof n.caption!="string")throw new TypeError("Menu caption must be text");if(n.parameters!=null&&(typeof n.parameters!="object"||Array.isArray(n.parameters)))throw new TypeError("Menu parameters must be a mapping");if(i==="command"&&(typeof n.command!="string"||!n.command||s!=null||n.resolver!=null))throw new TypeError("Command record requires a command and no children/resolver");if(i==="separator"&&(s!=null||Object.keys(n).length!==1))throw new TypeError("Separator record accepts kind only");if(i==="submenu"&&(typeof n.caption!="string"||n.command!=null||s instanceof x==(n.resolver!=null)||!(s instanceof x)&&s!=null))throw new TypeError("Submenu requires caption and exactly one content source");let a=s instanceof x?vf(s,t):null;return{label:r.label,attrs:{...n},children:a}})}function xf(o,e){let t=o.builder.wrapSource(o),r=o.value instanceof N?o.value.getNodes():[],n=new Set(e.map(i=>i.label));for(let i of r)n.has(i.label)||o.value.popNode(i.label);for(let[i,s]of e.entries()){let{kind:a,...l}=s.attrs,c=Object.fromEntries(Object.entries(l).filter(([p])=>p==="resolver"||p==="cacheTime"||p==="sync"||p.startsWith("resolver_")));for(let p of Object.keys(c))delete l[p];let u=a==="separator"?"-":null,d=o.value instanceof N?o.value.getNodes().find(p=>p.label===s.label):null,f=d?.value instanceof N;if(d&&(f!==(a==="submenu")||d.value==="-"!=(a==="separator"))&&(o.value.popNode(d.label),d=null),!d)d=Z(t.menuline(u,{...l,node_label:s.label}));else{let p=Object.keys(d.attr).filter(m=>yf.has(m)&&!Object.hasOwn(l,m));d.setAttr({...Object.fromEntries(p.map(m=>[m,null])),...l})}if(a==="submenu"){let p=d.value instanceof N?d.value.getNodes().find(m=>m.nodeTag==="menu"):null;p?p.setAttr({...Object.fromEntries(Object.keys(p.attr).filter(m=>m==="resolver"||m==="cacheTime"||m==="sync"||m.startsWith("resolver_")).map(m=>[m,null])),...c}):p=Z(d.builder.wrapSource(d).menu({...c,node_label:"menu"})),s.children&&xf(p,s.children)}let h=o.value.getNodes().indexOf(d);h!==i&&o.value.move(h,i)}}var Qi=class{#e=null;#t=null;#r=0;#n=!1;#o=null;constructor(e,t){this.binding=e,this.element=t}get node(){return this.binding.node}attach(){this.element.menuBinding=this,this.refresh()}detach(){this.#n=!0,this.#r++,this.node.requests.inflight?.cancel(),delete this.element.menuBinding,this.element.close(!1)}refresh(){let[,e]=this.node.rootBuilder.runtimeValues(this.node),t=Object.fromEntries(Object.entries(e).filter(([n])=>n.startsWith("resolver_")).map(([n,i])=>[n.slice(9),i])),r=R([e.resolver,t,e.cacheTime,e.sync]);r!==this.#e&&(this.#e=r,this.#r++,this.#o=null,this.#t=e.resolver?new fn({binding:this.binding,method:e.resolver,params:t,cacheTime:e.cacheTime??-1,sync:e.sync??!1,onError:()=>{}}):null,this.#t?(this.element.setStatus("loading"),this.element.opened&&this.element.isConnected&&this.load()):this.element.setStatus(null))}async load(e=!1){if(this.#n||!this.#t)return;let t=this.#t,r=this.#r;try{if(e?t.refresh():t.resolve(),t.loading&&(this.element.setStatus("loading"),await t.loading),this.#n||r!==this.#r)return;let n=t.cachedValue,i=vf(n),s=R(n);this.#o!==s&&(xf(this.node,i),this.#o=s),this.element.setStatus(i.length?null:"empty")}catch(n){if(this.#n||r!==this.#r)return;this.element.setStatus("error"),console.warn(`Menu '${this.node.label}' failed to load`,n)}}};var es=class{#e=!1;#t=!1;constructor(e,t){this.binding=e,this.element=t}attach(){this.element.cardActions=this}detach(){this.#e=!0,delete this.element.cardActions}async clear(){let{binding:e,element:t}=this,r=()=>!this.#e&&!e.closed&&t.isConnected&&t.parameters.delitem===!0;if(this.#t||!r())return;let n=e.node,i=n.value,s=n.absDatapath(".");if(!(s===null||!(i instanceof N))){this.#t=!0;try{if(await e.runtime.askDialog.show(e,{title:"Clear card fields",msg:`Clear the fields of \u201C${t.parameters.title}\u201D? This cannot be undone.`},{})===null||!r()||n.value!==i||n.absDatapath(".")!==s)return;let l=new Map,c=new Set,u=f=>{for(let h of["collapsed","checkbox"]){let p=f.getAttr(h);f.pointerType(p)&&c.add(f.absDatapath(p))}};u(n);let d=f=>{for(let h of f.getNodes()){h.nodeTag==="groupletCard"&&u(h);let p=h.getAttr("value");if(!h._getMeta("data_element")&&h.pointerType(p)==="^"&&!H(p)){let m=h.absDatapath(p);m!==null&&(s===""||m.startsWith(`${s}.`))&&l.set(m,{child:h,pointer:p})}h.staticValue instanceof N&&d(h.staticValue)}};d(i);for(let[f,{child:h,pointer:p}]of l){if(!r()||n.value!==i||n.absDatapath(".")!==s)break;c.has(f)||h.getAttr("value")!==p||h.absDatapath(p)!==f||e.runtime.renderer.html.writeParameter(h,"value",null)}}finally{this.#t=!1}}}};var ts="connect_on",po=class{#e;#t;#r;#n;#o;static declared(e){return Object.entries(e.getAttr()??{}).filter(([t,r])=>t.startsWith(ts)&&t.length>ts.length&&r!=null).map(([t,r])=>[t,t.slice(ts.length).toLowerCase(),r])}constructor(e,t,r,n,i=`${ts}${r}`){this.#e=e,this.#t=t,this.#r=r,this.#n=n,this.#o=i}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get eventName(){return this.#r}get handler(){return this.#n}get attribute(){return this.#o}attach(){this.element.addEventListener(this.eventName,this)}detach(){this.element.removeEventListener(this.eventName,this)}handleEvent(e){if(this.binding.closed)return;let t=this.node,r=this.binding.runtime;if(lo(this.handler))return Tt(r,t,this.handler,e);r.inlineCompiler.compile(t,this.attribute,this.handler,["event"])({event:e})}};var Yl={};ee(Yl,{BagCollectionView:()=>xo,parseSort:()=>Xl});var Ml={};ee(Ml,{columnDateMatches:()=>mo,columnDateRange:()=>Bl,columnSelection:()=>Pl,columnValue:()=>rs,columnValueKey:()=>Qt});function rs(o){if(o==null||o==="")return null;if(typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||o instanceof Date&&Number.isFinite(o.getTime())||q(o)&&o.isFinite())return o;throw new TypeError("Column filters require loaded scalar values")}function Qt(o){return R(rs(o))}function Pl(o){if(!Array.isArray(o))throw new TypeError("Column selection requires an array or null");return Object.freeze([...new Map(o.map(e=>{let t=Qt(e);return[t,j(t)]})).values()])}function Bl(o){if(o===null)return null;let{from:e,to:t,dtype:r,timeZone:n}=o;if(!["D","DH","DHZ"].includes(r))throw new TypeError("Date range requires a date column");for(let i of[e,t])if(i!==null&&(!(i instanceof Date)||!Number.isFinite(i.getTime())||i.getUTCHours()||i.getUTCMinutes()||i.getUTCSeconds()||i.getUTCMilliseconds()))throw new TypeError("Date bounds require civil dates");if(e&&t&&e>t)throw new RangeError("From must not be after To.");if(r==="DHZ"&&!n)throw new TypeError("DHZ requires a timeZone");return e||t?Object.freeze({from:e?.toISOString().slice(0,10)??null,to:t?.toISOString().slice(0,10)??null,dtype:r,timeZone:n}):null}function mo(o,e){if(!e)return!0;if(o==null||o==="")return!1;if(!(o instanceof Date)||!Number.isFinite(o.getTime()))throw new TypeError("Date range requires date values");let t;if(e.dtype==="DHZ"){let r=new Intl.DateTimeFormat("en",{timeZone:e.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(o),n=i=>r.find(s=>s.type===i).value;t=`${n("year")}-${n("month")}-${n("day")}`}else t=o.toISOString().slice(0,10);return(!e.from||t>=e.from)&&(!e.to||t<=e.to)}var Ul={};ee(Ul,{compileFilter:()=>zl});var Fl={};ee(Fl,{parseDateExpression:()=>_o});function Ir(o,e){return e===2?o%4===0&&(o%100!==0||o%400===0)?29:28:[4,6,9,11].includes(e)?30:31}function Fe(o,e,t){if(![o,e,t].every(Number.isInteger)||o<1||o>9999||e<1||e>12||t<1||t>Ir(o,e))throw new RangeError("Date must exist in Gregorian years 0001\u20139999.");return`${String(o).padStart(4,"0")}-${String(e).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function Cr(o){if(typeof o!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(o))throw new RangeError("Expected a civil date in YYYY-MM-DD format.");let e=o.split("-").map(Number);return Fe(...e),e}function go(o,e,t){let r=o-1,n=365*r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400)+t-1;for(let i=1;i<e;i++)n+=Ir(o,i);return n}function bo(o,e){let t=go(...Cr(o))+e;if(!Number.isSafeInteger(t)||t<0||t>go(9999,12,31))throw new RangeError("Date offset exceeds Gregorian years 0001\u20139999.");let r=1,n=1e4;for(;n-r>1;){let s=Math.floor((r+n)/2);go(s,1,1)<=t?r=s:n=s}t-=go(r,1,1);let i=1;for(;t>=Ir(r,i);)t-=Ir(r,i++);return Fe(r,i,t+1)}function Ll(o){return bo(o,-(go(...Cr(o))%7))}function kf(o,e,t=0,r=1){let n=o*12+e-1+t,i=Math.floor(n/12),s=(n%12+12)%12+1,a=n+r-1,l=Math.floor(a/12),c=(a%12+12)%12+1;return{start:Fe(i,s,1),end:Fe(l,c,Ir(l,c))}}var ns={en:{months:{january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12,jan:1,feb:2,mar:3,apr:4,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12},weekdays:{monday:0,tuesday:1,wednesday:2,thursday:3,friday:4,saturday:5,sunday:6,mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6},quarters:{"1st quarter":1,"2nd quarter":2,"3rd quarter":3,"4th quarter":4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["today"],yesterday:["yesterday"],tomorrow:["tomorrow"],this_week:["this week","week"],last_week:["last week"],next_week:["next week"],this_month:["this month","month"],last_month:["last month"],next_month:["next month"],last:["last"],next:["next"],articles:["the"],from:["from","between"],to:["to","and"],no_period:["no period","always"]},date_order:{default:"MDY",GB:"DMY",AU:"DMY",IE:"DMY",NZ:"DMY",IN:"DMY"}},it:{months:{gennaio:1,febbraio:2,marzo:3,aprile:4,maggio:5,giugno:6,luglio:7,agosto:8,settembre:9,ottobre:10,novembre:11,dicembre:12,gen:1,feb:2,mar:3,apr:4,mag:5,giu:6,lug:7,ago:8,set:9,ott:10,nov:11,dic:12},weekdays:{luned\u00EC:0,marted\u00EC:1,mercoled\u00EC:2,gioved\u00EC:3,venerd\u00EC:4,sabato:5,domenica:6,lun:0,mar:1,mer:2,gio:3,ven:4,sab:5,dom:6},quarters:{"1\xBA trimestre":1,"2\xBA trimestre":2,"3\xBA trimestre":3,"4\xBA trimestre":4,"1\xB0 trimestre":1,"2\xB0 trimestre":2,"3\xB0 trimestre":3,"4\xB0 trimestre":4,t1:1,t2:2,t3:3,t4:4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["oggi"],yesterday:["ieri"],tomorrow:["domani"],this_week:["questa settimana","settimana"],last_week:["settimana scorsa"],next_week:["settimana prossima"],this_month:["questo mese","mese"],last_month:["mese scorso"],next_month:["mese prossimo"],last:["scorso","scorsa"],next:["prossimo","prossima"],articles:["il","lo","la"],from:["da","dal","dalla","tra","fra"],to:["a","al","alla","e"],no_period:["-","senza periodo","sempre"]},date_order:{default:"DMY"}}};function Ef(o){if(typeof o!="string")throw new RangeError("A supported locale is required.");let e=o.replaceAll("-","_"),t=e.indexOf("_"),r=(t<0?e:e.slice(0,t)).toLowerCase(),n=(t<0?"":e.slice(t+1)).toUpperCase();if(!Object.hasOwn(ns,r))throw new RangeError(`Unsupported locale: ${o}`);let i=ns[r];return{dictionary:i,phrases:a=>[...new Set([...i.keywords[a],...ns.en.keywords[a]])],order:i.date_order[n]??i.date_order.default}}var Dr=/^(?:\d{4}|\d{2})$/,Tf=/^\d{1,2}$/,wo=(o,e)=>({ok:!1,error:{code:o,message:e}}),Or=(o="UNRECOGNIZED_EXPRESSION",e="Text is not a supported date expression.")=>{throw Object.assign(new SyntaxError(e),{code:o})},If=(o,e)=>Object.hasOwn(o,e);function Nr(o,e){if(o.length===4)return Number(o);let t=e.year+e.twoDigitYearAhead-100;return t+((Number(o)-t)%100+100)%100}function sb(o,e){if(o.includes(";")){let n=o.split(";").map(i=>i.trim());return n.length!==2?Or("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:n,range:!0}}if(e.phrases("no_period").includes(o))return{bounds:["",""],range:!0};let t=e.phrases("to"),r=e.phrases("from");for(let n of t)if(o.startsWith(`${n} `))return{bounds:["",o.slice(n.length+1).trim()],range:!0};for(let n of t){let i=` ${n} `;if(!o.includes(i))continue;for(let a of r)if(o.startsWith(`${a} `)){o=o.slice(a.length+1);break}let s=o.split(i).map(a=>a.trim());return s.length!==2?Or("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:s,range:!0}}for(let n of r)if(o.startsWith(`${n} `))return{bounds:[o.slice(n.length+1).trim(),""],range:!0};return{bounds:[o,o],range:!1}}function ab(o,e,t){let r=[[o,0]],n=/^(.+?)\s*([+-])\s*(\d+)$/.exec(o);n&&r.push([n[1],Number(n[2]+n[3])]);let i={today:0,yesterday:-1,tomorrow:1,this_week:0,last_week:-1,next_week:1,this_month:0,last_month:-1,next_month:1};for(let[s,a]of r)for(let[l,c]of Object.entries(i))if(e.phrases(l).includes(s)){if(l.endsWith("_week"))return bo(Ll(e.workdate),(c+a)*7+(t?6:0));if(l.endsWith("_month")){let u=kf(e.year,e.month,c+a);return t?u.end:u.start}return bo(e.workdate,c+a)}return null}function lb(o,e,t){let r=Object.entries(e.dictionary.quarters).sort((n,i)=>i[0].length-n[0].length);for(let[n,i]of r){let s;if(o===n)s=null;else if(o.startsWith(n)&&Dr.test(o.slice(n.length).trim()))s=Nr(o.slice(n.length).trim(),e);else if(o.endsWith(n)&&Dr.test(o.slice(0,-n.length).trim()))s=Nr(o.slice(0,-n.length).trim(),e);else continue;return{year:s,month:t?i*3:i*3-2}}return null}function Sf(o,e){if(If(e.months,o))return e.months[o];let t=/^m(\d{1,2})$/.exec(o);return t&&Number(t[1])>=1&&Number(t[1])<=12?Number(t[1]):null}function cb(o,e){let t=o.split(/\s+/),r=t.map((c,u)=>Sf(c,e.dictionary)?u:-1).filter(c=>c>=0);if(!r.length)return null;if(r.length!==1)return Or();let n=r[0],i=Sf(t[n],e.dictionary),s=t.slice(0,n),a=t.slice(n+1),l=[...s,...a];if(l.length===1&&e.phrases("last").includes(l[0]))return{year:e.year-(i>e.month?1:0),month:i};if(l.length===1&&e.phrases("next").includes(l[0]))return{year:e.year+(i<e.month?1:0),month:i};if(!l.length)return{year:null,month:i};if(!s.length&&a.length===1&&Dr.test(a[0]))return{year:Nr(a[0],e),month:i};if(s.length===1&&Tf.test(s[0])){if(!a.length)return Fe(e.year,i,Number(s[0]));if(a.length===1&&Dr.test(a[0]))return Fe(Nr(a[0],e),i,Number(s[0]))}return!s.length&&a.length===2&&Tf.test(a[0])&&Dr.test(a[1])?Fe(Nr(a[1],e),i,Number(a[0])):Or()}function ub(o,e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(t)return Fe(...t.slice(1).map(Number));let r=/^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(o),n={};if(r)e.order.split("").forEach((a,l)=>{n[a]=r[l+1]});else if(/^(?:\d{6}|\d{8})$/.test(o)){let a=o.length===8?4:2;for(let l of e.order){let c=l==="Y"?a:2;n[l]=o.slice(0,c),o=o.slice(c)}}else return null;if(!Dr.test(n.Y)||n.D.length>2||n.M.length>2)return Or();let i=Number(n.D),s=Number(n.M);return r&&s>12&&i<=12&&([i,s]=[s,i]),Fe(Nr(n.Y,e),s,i)}function Af(o,e,t){if(!o)return null;let r=e.phrases("articles");if(o=o.split(/\s+/).filter(i=>!r.includes(i)).join(" "),!o)return Or();if(Dr.test(o))return Fe(Nr(o,e),t?12:1,t?31:1);let n=ab(o,e,t)??lb(o,e,t)??cb(o,e);return n!==null?n:If(e.dictionary.weekdays,o)?bo(Ll(e.workdate),e.dictionary.weekdays[o]):ub(o,e)??Or()}function db(o,e,t){if(o===null||typeof o=="string")return o;let r=o.year??t.year,n=typeof e=="string"?Cr(e)[0]:e?.year,i=typeof e=="string"?Cr(e)[1]:e?.month;return n&&(r>n&&(r=n),r===n&&o.month>i&&r--),Fe(r,o.month,1)}function fb(o,e,t){if(o===null||typeof o=="string")return o;let r=o.year??t.year;if(e!==null){let[n,i]=Cr(e);r<n&&(r=n),r===n&&i>o.month&&r++}return Fe(r,o.month,Ir(r,o.month))}function _o(o,e={}){if(!e||typeof e!="object"||Array.isArray(e))return wo("INVALID_CONTEXT","Options must provide a civil workdate and supported locale.");let t;try{let{locale:r="it-IT",workdate:n,twoDigitYearAhead:i=20}=e,[s,a]=Cr(n);if(!Number.isInteger(i)||i<0||i>99)throw new RangeError("twoDigitYearAhead must be an integer from 0 to 99.");t={...Ef(r),workdate:n,year:s,month:a,twoDigitYearAhead:i}}catch(r){return wo("INVALID_CONTEXT",r.message)}if(typeof o!="string")return wo("INVALID_INPUT","Expression must be a string.");try{let r=o.toLowerCase().trim().replaceAll(",",""),{bounds:n,range:i}=sb(r,t),s=Af(n[1],t,!0),a=Af(n[0],t,!1),l=db(a,s,t),c=fb(s,l,t);return!i&&typeof a=="string"&&l===c?{ok:!0,kind:"date",date:l}:{ok:!0,kind:"period",start:l,end:c}}catch(r){if(r instanceof RangeError)return wo("INVALID_DATE",r.message);if(r instanceof SyntaxError)return wo(r.code,r.message);throw r}}function zl(o){if(o===null)return null;let{value:e,columns:t,dtype:r,locale:n}=o;if(typeof e!="string"||!Array.isArray(t)||!t.length||t.some(c=>typeof c!="string"||!c||c==="rowidx")||!["T","L","R","N","D"].includes(r))throw new TypeError("Invalid collection filter");if(!e.trim())return null;if(r==="T"){let c=o.literal===!0?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e,u=new RegExp(c,"i");return d=>u.test(t.map(f=>hb(d(f),n,o.timeZone)).join(" "))}if(t.length!==1)throw new TypeError("Typed filters require one column");let i=/^\s*(<=|>=|==|!=|[<>=!#])\s*(.+?)\s*$/.exec(e);if(!i)throw new Error("Enter a comparison, for example > 100 or = 12.");let[,s,a]=i,l;if(r==="D"){let c=new Date,u=`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")}`,d=_o(a,{locale:n,workdate:u});if(!d.ok||d.kind!=="date")throw new Error("Enter one complete date after the comparison.");l=new Date(`${d.date}T00:00:00Z`)}else l=pb(a,n);return c=>{let u=c(t[0]);if(u==null)return!1;if(r==="D"?!(u instanceof Date)||!Number.isFinite(u.getTime()):!(typeof u=="number"&&Number.isFinite(u)||q(u)&&u.isFinite()))throw new TypeError(`Filter value does not match ${r}`);let d=q(l)?-l.comparedTo(u):u<l?-1:u>l?1:0;switch(s){case"=":case"==":return d===0;case"!":case"#":case"!=":return d!==0;case"<":return d<0;case">":return d>0;case"<=":return d<=0;case">=":return d>=0}}}function hb(o,e,t){return o==null?"":typeof o=="string"||typeof o=="boolean"?String(o):io(o,{pattern:o instanceof Date?"short":"#,##0.####################"},{locale:e,timeZone:t})}function pb(o,e){let t=new Intl.NumberFormat(e).formatToParts(-12345.6),r=t.find(l=>l.type==="decimal").value,n=t.find(l=>l.type==="group")?.value,i=t.find(l=>l.type==="minusSign").value,s=o.replaceAll(i,"-");if(n&&s.includes(n)){let c=s.split(r)[0].replace(/^[+-]/,"").split(n),u=new Intl.NumberFormat(e).formatToParts(1234567890123).filter(h=>h.type==="integer").map(h=>h.value.length),d=u.at(-1),f=u.at(-2);if(s.split(r).slice(1).some(h=>h.includes(n))||!/^\d+$/.test(c[0])||c[0].length>f||c.slice(1).some((h,p)=>!/^\d+$/.test(h)||h.length!==(p===c.length-2?d:f)))throw new Error("Invalid numeric grouping.");s=s.replaceAll(n,"")}if(s=s.replace(r,"."),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(s))throw new Error("Enter a complete number.");let a=Ye(s);if(!q(a)||!a.isFinite())throw new Error("A finite Decimal backend is required.");return a}var Gl={};ee(Gl,{containsId:()=>ql,requireId:()=>Wl,requireIdSet:()=>Vl});function ql(o,e){return(","+o+",").includes(","+e+",")}function Vl(o){if(typeof o!="string")throw new TypeError("grid checked must refer to a string (empty string for an empty set)");return o}function Wl(o){if(typeof o!="string"||!o||o.includes(","))throw new TypeError("grid checkedField requires nonempty text IDs without commas");return o}var Hl={};ee(Hl,{BagCollectionStore:()=>yo,publishCollection:()=>vo});var yo=class{#e=new Set;constructor(e,t){if(!(e instanceof x))throw new TypeError("collection store requires a Bag");if(!["values","attributes"].includes(t))throw new TypeError("collection store rowMode must explicitly be values or attributes");if(!e.parentNode)throw new TypeError("collection store requires a Bag attached to Data");this.bag=e,this.rowMode=t}subscribe(e){return this.#e.add(e),()=>this.#e.delete(e)}receiveData(e,t=null,r=null){vo(this.#e,{full:t===null,rows:t?[t]:[],event:e,field:r})}getRows(){let e=this.bag.getNodes();for(let t of e){if(t.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="values"&&!(t.staticValue instanceof x))throw new TypeError(`collection store row ${t.label} must contain a Bag`)}return e}value(e,t){if(e.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="attributes")return e.getAttr(t);let r=e.staticValue;if(!(r instanceof x))throw new TypeError(`collection store row ${e.label} must contain a Bag`);let n=r.getNode(t);if(n?.resolver)throw new TypeError("collection store requires loaded cells");return n?.staticValue}};function vo(o,e){let t=[],r=Object.freeze({full:e.full,rows:Object.freeze([...e.rows]),event:e.event??null,field:e.field??null});for(let n of[...o])if(o.has(n))try{n(r)}catch(i){t.push(i)}if(t.length)throw new AggregateError(t,"Collection notification failed")}var xo=class{#e;#t=null;#r=new Set;#n=new Map;#o="";#i=new Map;#s=null;constructor(e){this.bindStore(e)}get bag(){return this.#e.bag}get rowMode(){return this.#e.rowMode}get sortedBy(){return this.#o}get criteria(){return Xl(this.#o)}get filter(){return this.#i.get("search")?.definition??null}get filterSignature(){return JSON.stringify([...this.#i].map(([e,{definition:t}])=>[e,t]))}get filterContributions(){return Object.freeze([...this.#i].map(([e,t])=>Object.freeze([e,Object.freeze({...t})])))}copyFiltersFrom(e){this.filterSignature!==e.filterSignature&&this.#c(this.#a(),this.#o,new Map(e.filterContributions))}get filtered(){return this.#s===null?null:[...this.#s]}isFiltered(){return this.#s!==null}value(e,t){return this.#e.value(e,t)}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}connect(){this.#t||(this.synchronize(),this.#t=this.#e.subscribe(e=>this.synchronize(e)))}disconnect(){this.#t?.(),this.#t=null}bindStore(e){if(this.#e===e)return;let t=this.#t!==null;this.disconnect(),this.#e=e,this.#n.clear(),t?this.connect():this.synchronize()}getRows(e=!0){let t=this.#a();return e&&this.#s!==null?this.#s.map(r=>t[r]):t}#a(){return this.#e.getRows().toSorted((e,t)=>(this.#n.get(e)??1/0)-(this.#n.get(t)??1/0))}synchronize(e={full:!0,rows:[]}){if(!e.full&&!this.#o&&!this.#i.size){vo(this.#r,{full:e.full,rows:e.rows});return}this.#c(this.#u(this.#a(),this.criteria),this.#o,this.#i,e)}sort(e){let t=this.#u(this.#a(),Xl(e));this.#c(t,e,this.#i)}moveRow(e,t,r=!1){if(e===t||e.parentBag!==this.bag||t.parentBag!==this.bag)return;let n=this.getRows(!1);n.splice(n.indexOf(e),1),n.splice(n.indexOf(t)+Number(r),0,e),this.#c(n,"",this.#i)}applyFilter(e,t="search"){if(!["base","search"].includes(t))throw new TypeError("Unknown collection filter contribution");let r=e===null?null:Object.freeze({...e,columns:Object.freeze([...e.columns])});this.#l(t,r,zl(r))}applySetFilter(e){let t=e===null?null:Object.freeze(e.map(({field:n,value:i})=>{if(typeof n!="string"||!n)throw new TypeError("Set filter requires an identity field");return Vl(i),Object.freeze({field:n,value:i})})),r=t===null?null:n=>t.every(({field:i,value:s})=>ql(s,Wl(n(i))));this.#l("sets",t,r)}columnFilter(e){return this.#i.get(`column:${e}`)?.definition.values??null}columnRange(e){let t=this.#i.get(`column:${e}`)?.definition.range;return t?{...t,from:t.from&&new Date(t.from+"T00:00:00Z"),to:t.to&&new Date(t.to+"T00:00:00Z")}:null}applyColumnFilter(e,t,r=this.columnRange(e)){if(r=Bl(r),typeof e!="string"||!e)throw new TypeError("Column filter requires a field");let n=t===null?null:Pl(t),i=n?.map(Qt),s=n===null&&r===null?null:Object.freeze({field:e,values:n,keys:i&&Object.freeze(i),range:r}),a=s===null?null:l=>mo(l(e),r)&&(i===void 0||i.includes(Qt(l(e))));this.#l(`column:${e}`,s,a)}columnFacets(e){let t=new Map,r=this.#i.get(`column:${e}`)?.definition.range??null,n=this.columnFilter(e),i=n?.map(Qt),s=[...this.#i].filter(([a])=>a!==`column:${e}`).map(([,a])=>a.predicate).filter(a=>a!==null);for(let a of this.#a()){let l=rs(this.value(a,e)),c=Qt(l);t.has(c)||t.set(c,{key:c,value:l,count:0,selected:mo(l,r)&&(i===void 0||i.includes(c))}),s.every(u=>u(d=>this.value(a,d)))&&t.get(c).count++}for(let a of n??[]){let l=Qt(a);t.has(l)||t.set(l,{key:l,value:a,count:0,selected:!0})}return[...t.values()].filter(a=>mo(a.value,r))}#l(e,t,r){if(JSON.stringify(this.#i.get(e)?.definition??null)===JSON.stringify(t))return;let n=new Map(this.#i);t===null?n.delete(e):n.set(e,{definition:t,predicate:r}),this.#c(this.#a(),this.#o,n)}#c(e,t,r,n={full:!1,rows:[]}){let i=[...r.values()].map(u=>u.predicate).filter(u=>u!==null),s=i.length?e.flatMap((u,d)=>i.every(f=>f(h=>this.value(u,h)))?[d]:[]):null,a=n.full||t!==this.#o||r!==this.#i||e.length!==this.#n.size||e.some((u,d)=>this.#n.get(u)!==d)||JSON.stringify(s)!==JSON.stringify(this.#s);this.#n=new Map(e.map((u,d)=>[u,d])),this.#o=t,this.#i=r,this.#s=s;let l=s===null?null:new Set(s),c=a?[]:n.rows.filter(u=>this.#n.has(u)&&(l===null||l.has(this.#n.get(u))));(a||c.length||n.rows.length)&&vo(this.#r,{full:a,rows:c})}#u(e,t){if(!t.length)return e;let r=e.map(n=>({node:n,keys:t.map(({field:i})=>this.value(n,i))}));for(let n=0;n<t.length;n++)if(new Set(r.map(s=>mb(s.keys[n])).filter(s=>s!==null)).size>1)throw new TypeError(`collection view cannot compare mixed types in ${t[n].field}`);return r.sort((n,i)=>{for(let[s,{direction:a}]of t.entries()){let l=gb(n.keys[s],i.keys[s]);if(l)return a==="a"?l:-l}return 0}).map(n=>n.node)}};function Xl(o){if(typeof o!="string")throw new TypeError("collection view sortedBy must be a string");if(o==="")return[];let e=new Set;return o.split(",").map(t=>{let r=/^([^,:]+):([ad])$/.exec(t);if(!r||e.has(r[1]))throw new TypeError(`Invalid collection view sort criterion: ${t}`);return e.add(r[1]),{field:r[1],direction:r[2]}})}function mb(o){if(o==null)return null;if(typeof o=="number"&&Number.isFinite(o)||q(o)&&o.isFinite())return"number";if(o instanceof Date&&Number.isFinite(o.getTime()))return"date";if(typeof o=="string"||typeof o=="boolean")return typeof o;throw new TypeError("collection view sort requires loaded finite scalar values")}function gb(o,e){return o==null||e==null?o==null?e==null?0:-1:1:q(o)?o.comparedTo(e):q(e)?-e.comparedTo(o):o<e?-1:o>e?1:0}var os=class{constructor(e=null,t=null){this.parent=e,this.segment=t,this.children=new Map,this.registrations=new Set}},Zl=class{#e;#t;#r;#n;#o;#i=!0;#s;constructor(e,{path:t,attr:r,recipient:n,order:i,subtree:s=!1}){this.#e=e,this.#t=t,this.#r=r,this.#n=n,this.#o=i,this.#s=s}get router(){return this.#e}get path(){return this.#t}get attr(){return this.#r}get recipient(){return this.#n}get subtree(){return this.#s}get active(){return this.#i}get order(){return this.#o}close(){this.active&&(this.#i=!1,this.router.unregister(this))}},Kl=class{constructor({evt:e,node:t,path:r,oldvalue:n,attrsDiff:i,reason:s,fired:a,level:l,registration:c,index:u}){this.evt=e,this.node=t,this.path=r,this.oldvalue=n,this.attrsDiff=i,this.reason=s,this.fired=a,this.level=l,this.registration=c,this.index=u}},is=class{#e;#t=new os;#r=new Map;#n=0;#o=0;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return this.#n}register({path:e,attr:t=null,recipient:r,subtree:n=!1}){if(typeof e!="string"||e==="")throw new TypeError(`A Data registration requires a path: ${e}`);let i=this.#t;for(let a of e.split(".")){let l=i.children.get(a);l||(l=new os(i,a),i.children.set(a,l)),i=l}this.#o+=1;let s=new Zl(this,{path:e,attr:t,recipient:r,order:this.#o,subtree:n});return i.registrations.add(s),this.#r.set(s,i),this.#n+=1,s}unregister(e){let t=this.#r.get(e);if(t)for(this.#r.delete(e),t.registrations.delete(e),this.#n-=1;t.parent&&!t.children.size&&!t.registrations.size;)t.parent.children.delete(t.segment),t=t.parent}deliver(e){let{pathlist:t}=e;if(!t?.length||t[0]!==an||e.reason==="autocreate")return;let r=t.slice(1),n=e.evt==="ins"||e.evt==="del";for(let i of Array.isArray(e.node)?e.node:[e.node]){let s=n?[...r,i.label]:r,a=s.join(".");for(let[l,c]of this.#i(s,e))l.active&&l.recipient.receive(new Kl({evt:e.evt,node:i,path:a,oldvalue:e.oldvalue??null,attrsDiff:e.attrs_diff??null,reason:e.reason??null,fired:e.fired??!1,level:c,registration:l,index:e.ind??null}))}}#i(e,t){let r=[],n=this.#t;for(let s of e){for(let a of n.registrations)n!==this.#t&&this.#s(a,"child",t)&&r.push([a,"child"]);if(n=n.children.get(s),!n)return r.sort(([a],[l])=>a.order-l.order)}for(let s of n.registrations)this.#s(s,"node",t)&&r.push([s,"node"]);let i=[...n.children.values()];for(;i.length;){let s=i.pop();for(let a of s.registrations)this.#s(a,"container",t)&&r.push([a,"container"]);i.push(...s.children.values())}return r.sort(([s],[a])=>s.order-a.order)}#s(e,t,r){let{evt:n}=r;return e.subtree?t!=="container"||n!=="upd_attrs":e.attr===null?n==="upd_attrs"?!1:!(t==="child"&&r.fired):t==="child"?!1:t==="container"?n!=="upd_attrs":n==="ins"||n==="del"?!0:Object.hasOwn(r.attrs_diff??{},e.attr)}};var rc={};ee(rc,{GridStructure:()=>hn});var ec={};ee(ec,{GridFormulas:()=>Ql,addNumeric:()=>Jl,formulaDefinitions:()=>Eo,parseArithmetic:()=>Cf,sameValue:()=>Nf});var bb="#",wb=/[A-Za-z_$][\w$]*/g;function Eo(o){let e=new Map;for(let c of o){if(c.formula==null)continue;let u=c.formula.trim(),d=u===bb?{kind:"index",field:null}:u.startsWith("+=")?{kind:"running",field:u.slice(2).trim()}:u.startsWith("%=")?{kind:"percent",field:u.slice(2).trim()}:null;if(d&&d.kind!=="index"&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(d.field))throw new TypeError(`grid formula '${u}' requires a field`);let f=new Map;for(let[m,b]of Object.entries(c))m.startsWith("formula_")&&f.set(m.slice(8),b);let h=null;if(!d)try{h=Cf(u)}catch{}let p=d?new Set(d.field?[d.field]:[]):new Set(u.match(wb)??[]);e.set(c.field,{field:c.field,formula:c.formula,special:d,arithmetic:h,parameters:f,references:p,calculated:c.calculated===!0,column:c})}let t=new Map;for(let c of e.values())for(let u of c.references)t.has(u)||t.set(u,new Set),t.get(u).add(c.field);let r=new Set,n=new Set,i=[],s=c=>{if(!n.has(c)){if(r.has(c))throw new TypeError(`grid formula dependency cycle at '${c}'`);r.add(c);for(let u of e.get(c).references)e.has(u)&&s(u);r.delete(c),n.add(c),i.push(c)}};for(let c of e.keys())s(c);let a=new Set;for(let c of i){let u=e.get(c);(["index","running"].includes(u.special?.kind)||[...u.references].some(d=>a.has(d)))&&a.add(c)}let l=new Map([...e].map(([c,u])=>[c,Object.freeze({...u,view:a.has(c)})]));return Object.freeze({definitions:l,triggered:t,order:Object.freeze(i),viewFields:a})}function Cf(o){let e=_b(o),t=0,r=()=>e[t],n=c=>{if(r().value!==c)throw new SyntaxError(`expected '${c}' in arithmetic formula`);return e[t++]},i={"+":1,"-":1,"*":2,"/":2,"%":2,"**":3},s=()=>{let c=r();if(c.type==="number")return t++,{kind:"number",value:c.value};if(c.type==="name")return t++,{kind:"name",value:c.value};if(c.value==="("){t++;let u=a(0);return n(")"),u}if(c.value==="+"||c.value==="-")return t++,{kind:"unary",operator:c.value,child:s()};throw new SyntaxError(`unexpected '${c.value||"end"}' in arithmetic formula`)},a=c=>{let u=s();for(;i[r().value]>=c;){let d=e[t++].value,f=a(i[d]+(d==="**"?0:1));u={kind:"binary",operator:d,left:u,right:f}}return u},l=a(0);if(r().type!=="eof")throw new SyntaxError(`unexpected '${r().value}' in arithmetic formula`);return l}function _b(o){let e=[],t=0;for(;t<o.length;){let r=o.slice(t),n=/^\s+/.exec(r);if(n){t+=n[0].length;continue}let i=/^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(r);if(i){e.push({type:"number",value:i[0]}),t+=i[0].length;continue}let s=/^[A-Za-z_$][\w$]*/.exec(r);if(s){e.push({type:"name",value:s[0]}),t+=s[0].length;continue}let a=/^(?:\*\*|[()+\-*/%])/.exec(r);if(a){e.push({type:"operator",value:a[0]}),t+=a[0].length;continue}throw new SyntaxError(`unsupported arithmetic formula token at ${t}`)}return e.push({type:"eof",value:""}),e}function Df(){if(Zr()==="number")throw new Error("A Decimal backend is required for exact grid formulas")}function To(o,e){if(q(o))return o;if(o==null||o==="")return null;if(typeof o!="number"&&typeof o!="string")throw new TypeError("Decimal arithmetic requires numeric values");return new e(String(o))}var yb={"+":(o,e)=>o+e,"-":(o,e)=>o-e,"*":(o,e)=>o*e,"/":(o,e)=>o/e,"%":(o,e)=>o%e,"**":(o,e)=>o**e};function ko(o,e){if(o.kind==="number")return Number(o.value);if(o.kind==="name"){if(!Object.hasOwn(e,o.value))throw new ReferenceError(`${o.value} is not defined`);return e[o.value]}return o.kind==="unary"?o.operator==="-"?-ko(o.child,e):+ko(o.child,e):yb[o.operator](ko(o.left,e),ko(o.right,e))}function ss(o,e,t){if(o.kind==="number")return new t(o.value);if(o.kind==="name"){if(!Object.hasOwn(e,o.value))throw new ReferenceError(`${o.value} is not defined`);return To(e[o.value],t)}if(o.kind==="unary"){let s=ss(o.child,e,t);return s==null?null:o.operator==="-"?s.neg():s}let r=ss(o.left,e,t),n=ss(o.right,e,t);if(r==null||n==null)return null;if(o.operator==="**")return r.pow(Number(n.toString()));let i={"+":"plus","-":"minus","*":"times","/":"div","%":"mod"}[o.operator];return r[i](n)}function Nf(o,e){return Object.is(o,e)?!0:q(o)&&q(e)&&o.eq(e)}function Jl(o,e){if(e==null||e==="")return o;if(q(o)||q(e)){Df();let t=q(o)?o.constructor:e.constructor;return To(o,t).plus(To(e,t))}if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("Grid aggregate formulas require numeric values");return o+e}function vb(o,e){let t=q(e)?e.eq(0):Object.is(e,0);if(o==null||o===""||e==null||t)return null;if(q(o)||q(e)){let r=q(o)?o.constructor:e.constructor;return To(o,r).div(To(e,r)).times(new r(100))}if(typeof o!="number"||typeof e!="number")throw new TypeError("Percentage formulas require numeric values");return o/e*100}var Ql=class{#e;#t=Eo([]);#r=new Set;#n=null;#o=null;#i=[];#s=[];#a=!1;#l=new Map;#c=null;constructor(e){this.#e=e}get source(){return this.#e}get runtime(){return this.source.rootBuilder.binding}get errors(){return new Map(this.#l)}get formulas(){return this.#t}get dataFields(){return new Set(this.formulas.order.filter(e=>!this.viewFields.has(e)))}get viewFields(){return this.formulas.viewFields}configure(e,t,r){if(!(e.formulas===this.#t&&r===this.#n&&t===this.#o&&this.#i.length)&&(this.disconnect(),this.#t=e.formulas,this.#r=new Set(e.fields),this.#n=r,this.#o=t,this.#l.clear(),!!this.formulas.definitions.size)){this.#i=[r.subscribe(n=>this.#f(n)),t.subscribe(()=>{this.#c=null})];for(let n of this.formulas.definitions.values())for(let i of n.parameters.values()){if(typeof i!="string"||!i.startsWith("^"))continue;let[s,a=null]=this.source.absDatapath(i).split("?");this.#s.push(this.runtime.router.register({path:s,attr:a,recipient:{receive:()=>{this.#c=null,this.recalculate(this.#d([n.field]))}}}))}this.recalculate(this.#d(this.#u(n=>n.calculated)))}}disconnect(){for(let e of this.#i)e();for(let e of this.#s)e.close();this.#i=[],this.#s=[],this.#n=null,this.#o=null,this.#c=null,this.#t=Eo([])}value(e,t){if(!this.viewFields.has(t))return this.#n.value(e,t);let r=this.#b().get(e);return r===void 0?null:r[t]}#u(e){return[...this.formulas.definitions.values()].filter(e).map(t=>t.field)}#d(e){let t=new Set(e),r=[...e];for(;r.length;)for(let n of this.formulas.triggered.get(r.shift())??[])t.has(n)||(t.add(n),r.push(n));return t}#f({full:e,rows:t,event:r,field:n}){if(this.#c=null,this.#a)return;if(e){this.recalculate(this.#d(this.#u(u=>u.calculated||u.special)));return}let[i]=t,s;n!==null?s=[n]:r.node===i?s=r.evt==="upd_attrs"?Object.keys(r.attrs_diff):[...this.formulas.triggered.keys()]:s=(Array.isArray(r.node)?r.node:[r.node]).map(u=>u.label);let a=new Set;for(let u of s)for(let d of this.formulas.triggered.get(u)??[])a.add(d);let l=this.#d(a),c=[...l].some(u=>this.formulas.definitions.get(u).special?.kind==="percent");this.recalculate(l,c?null:[i])}#p(e){let t={};for(let[r,n]of e.parameters)t[r]=typeof n=="string"&&(n.startsWith("^")||n.startsWith("="))?this.source.getRelativeData(n):n;return t}#h(e,t,r,n,i){if(e.special?.kind==="index")return r;if(e.special?.kind==="running")return Jl(n,i(t,e.special.field));if(e.special?.kind==="percent")return vb(i(t,e.special.field),n);let s=this.#p(e),a={};for(let d of e.references)Object.hasOwn(s,d)?a[d]=s[d]:(this.#r.has(d)||this.#m(t).has(d))&&(a[d]=i(t,d)??null);if(Object.values(a).some(d=>d==null))return null;let l=Object.values(a).find(q);if(e.arithmetic)return l===void 0?ko(e.arithmetic,a):(Df(),ss(e.arithmetic,a,l.constructor));if(l!==void 0)throw new Error("Decimal grid formulas support arithmetic expressions only");let c=[...Object.keys(a),"_currcell","_rowNode"];return this.runtime.inlineCompiler.compile(this.source,`struct.${e.field}.formula`,e.formula,c,`return (${e.formula}
222
+ );`)({...a,_currcell:e.column,_rowNode:t})}#m(e){return this.#n.rowMode==="attributes"?new Set(Object.keys(e.getAttr())):new Set(e.staticValue.keys())}#g(e,t,r){Nf(this.#n.value(e,t),r)||(this.#n.rowMode==="attributes"?e.setAttr({[t]:r}):e.staticValue.setItem(t,r))}recalculate(e,t=null){if(this.#a||!e.size||this.#n===null)return;this.#a=!0;let r=(n,i)=>this.#n.value(n,i);try{let n=this.#n.getRows();for(let i of this.formulas.order){let s=this.formulas.definitions.get(i);if(!e.has(i)||s.view)continue;let a=null,l=null;if(s.special?.kind==="percent")try{a=0;for(let c of n)a=Jl(a,r(c,s.special.field))}catch(c){a=null,l=c}for(let c of t??n){let u=null;try{u=this.#h(s,c,null,a,r)}catch(d){l=d}this.#g(c,i,u)}l?this.#l.set(i,l):this.#l.delete(i)}}finally{this.#a=!1}}#b(){if(this.#c!==null)return this.#c;let e=this.#o.getRows(),t=new Map(e.map(n=>[n,{}])),r=(n,i)=>this.viewFields.has(i)?t.get(n)[i]:this.#n.value(n,i);for(let n of this.formulas.order){let i=this.formulas.definitions.get(n);if(!i.view)continue;let s=0,a=null;for(let[l,c]of e.entries()){let u=null;try{u=this.#h(i,c,l+1,s,r),i.special?.kind==="running"&&(s=u)}catch(d){a=d}t.get(c)[n]=u}a?this.#l.set(n,a):this.#l.delete(n)}return this.#c=t,t}};var xb=new Set(["T","B","L","R","N","D","H","DHZ"]),kb=new Set(["tag","field","name","title","dtype","width","align","format","columnset","white_space","max_height","edit","check","checked","checkedField","formula","calculated","hidden","totalize","footer_value","footer_format"]),Eb=/^formula_[A-Za-z_$][\w$]*$/,Tb=new Set(["tag","code","name","background","color"]),hn=class{#e=new Map;constructor(e){if(!(e instanceof x))throw new TypeError("grid structpath must resolve to a Bag");let t=as(e,"view_0"),r=as(e,"info"),n=as(t,"rows_0"),i=as(r,"columnsets"),s=new Set,a=new Map;for(let c of i.getNodes()){let u=c.getAttr();if(Of(u,Tb),tc(u.code,"colgroup code"),u.tag!=="columnset"||c.resolver||c.staticValue!=null||c.label!==u.code)throw new TypeError("grid columnset requires a scalar definition labelled by code");if(a.has(u.code))throw new TypeError(`Duplicate grid colgroup: ${u.code}`);if(u.name!=null&&typeof u.name!="string")throw new TypeError("grid group name must be text");for(let d of["background","color"])if(u[d]!=null&&typeof u[d]!="string")throw new TypeError(`grid ${d} must be text`);a.set(u.code,{...u,name:u.name??u.code})}this.columns=[],this.groups=[];let l=[];for(let c of n.getNodes()){let u=c.getAttr();if(Of(u,kb,Eb),u.tag!=="cell"||c.staticValue!=null||c.resolver)throw new TypeError("grid cell must be a scalar declaration");if(tc(u.field,"field"),s.has(u.field))throw new TypeError(`Duplicate grid field: ${u.field}`);if(s.add(u.field),this.#e.set(u.field,c),u.columnset!=null&&!a.has(u.columnset))throw new TypeError(`Unknown grid columnset: ${u.columnset}`);if(u.dtype!=null&&!xb.has(u.dtype))throw new TypeError(`Unsupported grid dtype: ${u.dtype}`);if(u.align!=null&&!["start","center","end"].includes(u.align))throw new TypeError("grid align requires start, center or end");if(u.width!=null&&(typeof u.width!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem|ch|%)$/.test(u.width)))throw new TypeError("grid width requires a nonnegative CSS length (px, em, rem, ch or %)");if(u.max_height!=null&&(typeof u.max_height!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem)$/.test(u.max_height)))throw new TypeError("grid max_height requires a nonnegative CSS length (px, em or rem)");if(u.white_space!=null&&!["normal","nowrap","pre-wrap"].includes(u.white_space))throw new TypeError("grid white_space requires normal, nowrap or pre-wrap");for(let p of["name","title","format"])if(u[p]!=null&&typeof u[p]!="string")throw new TypeError(`grid ${p} must be text`);if(u.edit!=null&&typeof u.edit!="boolean"&&(typeof u.edit!="object"||Array.isArray(u.edit)))throw new TypeError("grid edit requires a boolean or editor options");if(u.check!=null||u.checked!=null||u.checkedField!=null){if(!["multiple","single"].includes(u.check)||typeof u.checked!="string"||!u.checked.startsWith("^")||u.checked.length<2||u.checked.includes("?"))throw new TypeError("grid check requires single or multiple and checked=^DataPath");if(tc(u.checkedField,"checkedField"),u.edit)throw new TypeError("external check sets cannot edit row fields")}Sb(u);let d=Object.freeze({...u,name:u.name??u.field,align:u.align??(["L","R","N"].includes(u.dtype)?"end":"start")});if(l.push(d),u.hidden)continue;this.columns.push(d);let f=u.columnset??null,h=this.groups.at(-1);(!h||h.code!==f)&&(h={code:f,...f===null?{name:null}:a.get(f),columns:[]},this.groups.push(h)),h.columns.push(d)}if(!this.columns.length)throw new TypeError("grid struct requires at least one column");this.fields=Object.freeze([...s]),this.formulas=Eo(l);for(let c of this.groups)Object.freeze(c.columns),Object.freeze(c);Object.freeze(this.columns),Object.freeze(this.groups),Object.freeze(this)}columnNode(e){return this.#e.get(e)}moveColumn(e,t,r=!1){let n=this.#e.get(e),i=this.#e.get(t);if(!n||!i||n===i)return;let s=n.parentBag,a=s.getNodes(),l=a.indexOf(n),c=a.indexOf(i),u=c+Number(r)-+(l<c);u!==l&&s.move(l,u)}setColumnWidth(e,t){if(!Number.isFinite(t)||t<=0)throw new TypeError("grid resized width must be positive pixels");this.#e.get(e).setAttr({width:`${Math.round(t)}px`})}};function as(o,e){let t=o.getNode(e);if(!t||t.resolver||!(t.staticValue instanceof x))throw new TypeError(`grid struct requires Bag ${e}`);return t.staticValue}function Of(o,e,t=null){for(let r of Object.keys(o))if(!e.has(r)&&!t?.test(r))throw new TypeError(`Unsupported grid struct attribute: ${r}`)}function Sb(o){if(o.formula!=null&&(typeof o.formula!="string"||!o.formula.trim()))throw new TypeError("grid formula must be nonempty text");if(o.formula==null&&(o.calculated!=null||Object.keys(o).some(e=>e.startsWith("formula_"))))throw new TypeError(`grid ${o.field}: calculated and formula_<name> require a formula`);for(let e of["calculated","hidden"])if(o[e]!=null&&typeof o[e]!="boolean")throw new TypeError(`grid ${e} must be a boolean`);if(o.totalize!=null&&typeof o.totalize!="boolean"&&(typeof o.totalize!="string"||!o.totalize))throw new TypeError("grid totalize requires a boolean or a Data path");for(let e of["footer_value","footer_format"])if(o[e]!=null&&typeof o[e]!="string")throw new TypeError(`grid ${e} must be text`)}function tc(o,e){if(typeof o!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new TypeError(`grid ${e} requires a simple field identifier`)}function $f(o){let e=new x,t=new x,r=new x;e.setItem("view_0",new x,{tag:"view"}),e.getItem("view_0").setItem("rows_0",t,{tag:"rows"}),e.setItem("info",new x),e.getItem("info").setItem("columnsets",r);let n=(i,s=null)=>{if(i.builder.validateNode(i),i.nodeTag!=="column"||i.staticValue!=null)throw new TypeError("grid column must be a scalar declaration");let a={tag:"cell"},l=["field","name","title","dtype","width","align","format","white_space","max_height","edit","check","checked","checkedField","formula","calculated","hidden","totalize","footer_value","footer_format",...Object.keys(i.getAttr()).filter(u=>u.startsWith("formula_"))];for(let u of l)i.getAttr(u)!=null&&(a[u]=i.getAttr(u));let c=`cell_${a.field}`;if(t.getNode(c))throw new TypeError(`Duplicate grid field: ${a.field}`);s!==null&&(a.columnset=s),t.setItem(c,null,a)};for(let i of o.getNodes())if(i.nodeTag==="column")n(i);else if(i.nodeTag==="colgroup"){if(i.builder.validateNode(i),!(i.staticValue instanceof N))throw new TypeError("grid colgroup requires column declarations");let s=i.getAttr("code");if(r.getNode(s))throw new TypeError(`Duplicate grid colgroup: ${s}`);let a={tag:"columnset",code:s,name:i.getAttr("name")??s};for(let l of["background","color"])i.getAttr(l)!=null&&(a[l]=i.getAttr(l));r.setItem(s,null,a);for(let l of i.staticValue.getNodes())n(l,s)}else throw new TypeError("grid struct accepts column and colgroup only");return e}function Rf(o){if(o._getMeta("gramlot_component")?.bagStruct){let e=o.staticValue instanceof N?o.staticValue.getNodes():[];if(e.some(t=>!t._getMeta("gridStruct"))||e.length>1)throw new TypeError("grid accepts one struct declaration");if(e.length&&o.getAttr("structpath")!=null)throw new TypeError("grid requires structpath or nested struct, not both");if(!e.length&&!o.getAttr("structpath"))throw new TypeError("grid requires structpath or nested struct");if(!["values","attributes"].includes(o.getAttr("rowMode")))throw new TypeError("grid rowMode must explicitly be values or attributes")}if(o._getMeta("gridStruct")){if(!o.parentNode?._getMeta("gramlot_component")?.bagStruct)throw new TypeError("struct requires a grid parent");if(!(o.staticValue instanceof N))throw new TypeError("grid struct requires column declarations");new hn($f(o.staticValue))}}function jf(o,e){let t=$f(o.staticValue);new hn(t);let r=`_gramlot.grid.${crypto.randomUUID().replaceAll("-","")}.struct`;e.setItem(r,t,null,">",!1,!0,o),o.parentNode.setAttr({structpath:r},!1),o.setValue(null,!1)}var ls=class{#e;constructor(e){this.#e=e}get runtime(){return this.#e}install(e){let t=So(e),r=this.setterNodes(e);oc(e);for(let n of r)n._getMeta("gridStruct")?jf(n,this.runtime.data):this.applySetter(n),this.runtime.closeBranch(n),n.parentBag&&n.parentBag.popNode(n.label);this.applyDefaults(t.filter(n=>n.nodeTag&&!n._getMeta("data_element")))}setterNodes(e){return So(e).filter(t=>t.nodeTag==="dataSetter"||t._getMeta("gridStruct"))}applySetter(e){let t=e.absDatapath(e.pathAttribute("destination_path"));if(t===null)return;let r=e.getAttr("value")??null,n=Ib(e.getAttr()),i=this.runtime.data;if(r!==null)i.setItem(t,r,n,">",!1,!0,e),r instanceof x&&e.setAttr({value:null},!1);else{let s=i.getNode(t);s?n&&s.setAttr(n,!0):i.setItem(t,null,n,">",!1,!0,e)}}applyDefaults(e){for(let t of e){let r=t.getAttr();for(let[n,i]of Object.entries(r)){if(!Ab(t,n,i))continue;let s=n==="value"?r.default_value??r.default:r[`default_${n}`];s!=null&&this.#t(t,i,s)}this.#r(t,r)}}#t(e,t,r){let n=e.absDatapath(t);if(n===null)return;let[i,s=null]=n.split("?",2),a=this.runtime.data,l=a.getNode(i);if(s===null){if(l&&l.value!==null&&l.value!==void 0)return;a.setItem(i,r,null,">",!1,!0,e)}else if(l){let c=l.getAttr(s);c==null&&l.setAttr({[s]:r},!0)}else a.setItem(i,null,{[s]:r},">",!1,!0,e)}#r(e,t){let r={};for(let[s,a]of Object.entries(t))s.startsWith("attr_")&&(r[s.slice(5)]=H(a)?Jt(e,s):e.pointerType(a)?e.getRelativeData(a):a);if(!Object.keys(r).length)return;let n=[t.value,t.src].find(s=>e.pointerType(s));if(!n)return;let i=e.absDatapath(n);i!==null&&this.runtime.data.getNode(i.split("?",1)[0])?.setAttr(r,!0,!0,!1)}};function Ab(o,e,t){return e==="_meta"||lt.has(e)||e==="default"||e.startsWith("default_")||e.startsWith("attr_")||e.endsWith("_path")?!1:o.pointerType(t)!==null}function Ib(o){let e={};for(let[t,r]of Object.entries(Et(o??{})))lt.has(t)||t.startsWith("_")||t==="destination_path"||t==="value"||r!=null&&(e[t]=r);return Object.keys(e).length?e:null}function Cb(o){let e=o.builder;if(!(e instanceof me))throw new Error(`dataSetter '${o.label}': dataSetter is not supported inside ${e.constructor._name}`)}function oc(o){for(let e of So(o))Rf(e),e.nodeTag==="dataSetter"&&Cb(e),Rb(e)}var Db=["_init","_onStart","_onBuilt","_delay","_timing","_userChanges"],Nb=new Set(["dataFormula","dataController","dataRpc","dataRemote"]),Ob=["_onCalling","_onResult","_onError"],$b=["_delay","_timing","_userChanges"],nc=["_init","_onBuilt","_onStart"];function Rb(o){let e=i=>o.getAttr(i)!==null&&o.getAttr(i)!==void 0,t=!o._getMeta("data_element")&&typeof o.getAttr("remote")=="string";if(o.nodeTag!=="dataRpc"){let i=Ob.find(s=>e(s)&&!(s==="_onCalling"&&(o.nodeTag==="dataRemote"||t)));if(i){let s=i==="_onCalling"?"dataRpc, dataRemote and remote":"dataRpc";throw new Error(`${o.nodeTag??"fragment"} '${o.label}': '${i}' is allowed only on ${s}`)}}if(Nb.has(o.nodeTag)){let i=Object.entries(o.getAttr()).find(([,a])=>Le(a));if(i)throw new Error(`${o.nodeTag} '${o.label}': '${i[0]}' is a == expression, not accepted on ${o.nodeTag}`);let s=o.nodeTag==="dataRemote"?nc.find(e):null;if(s)throw new Error(`dataRemote '${o.label}': '${s}' is not accepted on dataRemote, its resolver loads when the Data is read`);for(let a of nc){let l=o.getAttr(a);if(!(l==null||typeof l=="boolean"||typeof l=="number"))throw new Error(`${o.nodeTag} '${o.label}': '${a}' accepts true, false, null or a number, not ${JSON.stringify(l)}`)}return}let r=Db.find(i=>e(i)&&!(i==="_delay"&&!o._getMeta("data_element")&&o.nodeTag!=="html_button")&&!(t&&$b.includes(i)));if(!r)return;let n=nc.includes(r)?"dataFormula, dataController and dataRpc":"dataFormula, dataController, dataRpc and dataRemote";throw new Error(`${o.nodeTag??"fragment"} '${o.label}': '${r}' is allowed only on ${n}`)}function So(o){if(o instanceof N)return o.getNodes().flatMap(t=>So(t));let e=[o];return o.value instanceof N&&e.push(...So(o.value)),e}var jb=new Set(["destination_path","result_path","func","formula","script","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","_ask","_ask_if","_ask_title","_ask_onCancel","method","timeout","_onCalling","_onResult","_onError","cacheTime","sync"]),Ao=class{#e;#t=null;#r=null;constructor(e){this.#e=e}get binding(){return this.#e}debounce(e,t){this.#r?.();let r=null,n=setTimeout(()=>{r(),this.#r=null,t()},e);r=this.binding.track(()=>clearTimeout(n)),this.#r=()=>{clearTimeout(n),r(),this.#r=null}}startTiming(e,t){if(this.#t?.(),!(e>0))return;let r=setInterval(t,e*1e3),n=this.binding.track(()=>clearInterval(r));this.#t=()=>{clearInterval(r),n(),this.#t=null}}cancel(){this.#r?.(),this.#t?.()}},pn=class{#e;#t=[];#r=new Set;#n;#o=null;#i=!1;constructor(e){this.#e=e,this.#n=new Ao(e),e.track(()=>{this.cancel(),this.#p(),this.#f()})}get binding(){return this.#e}get node(){return this.binding.node}get kind(){throw new Error("Provider.kind is defined by FormulaProvider, ControllerProvider, RpcProvider and RemoteProvider")}register(){let e=this.node,t=e.getAttr("_onStart");if(typeof t=="number"&&!(Number.isFinite(t)&&t>=0))throw new Error(`${e.nodeTag} '${e.label}': _onStart must be true or a delay in ms not below 0: ${t}`);this.#p();let r=this.binding.runtime.router,n=Ze(e,e.getAttr("_timing"));for(let[i,s]of e.pointers()){if(i==="datapath")continue;let a=e.absDatapath(s);if(a===null)continue;let[l,c=null]=a.split("?",2),u=r.register({path:l,attr:c,recipient:this});this.#t.push(u),(i==="_timing"||n.has(i))&&this.#r.add(u)}this.#t.push(...this.binding.runtime.subscriptions.subscribeNode(e,(i,s,a)=>(l,c)=>{let u={kind:"subscription",topic:a,payload:l,metadata:c};if(this.#a("_userChanges")&&a!=="node")return;let d=this.#a("_delay");d>0?this.#n.debounce(d,()=>this.invoke(u)):this.invoke(u)})),this.#s(),this.kind==="remote"&&this.invoke({kind:"install",change:null})}receive(e){if(this.#r.has(e.registration)){this.#s();return}if(this.#a("_userChanges")&&e.level!=="node")return;let t={kind:"data",change:e},r=this.#a("_delay");r>0?this.#n.debounce(r,()=>this.invoke(t)):this.invoke(t)}invoke(e){if(this.binding.closed)return;let t=this.node,r=this.kind==="formula",n=this.kind==="rpc",i=this.kind==="remote",s=this.readArguments(e);e.askResult&&(Object.assign(s,e.askResult),s._askResult=e.askResult);let a=t.getAttr("_ask"),l=this.binding.runtime.askDialog;if(a&&!e.askDone&&l.required(this.binding,a,s,"_ask"))return l.show(this.binding,a,s,t.getAttr("_ask_title")??"Warning").then(p=>{if(!this.binding.closed){if(p===null){let m=t.getAttr("_ask_onCancel");m&&this.#l("_ask_onCancel",m,m,s,!0);return}return this.invoke({...e,askDone:!0,askResult:p})}});let[c,u]=[r?"formula":"script",t.getAttr(r?"formula":"script")],d=t.getAttr("_if");if(d&&!this.#l("_if",d,`return (${d})`,s,!1)){if(i&&this.#f(),[c,u]=["_else",t.getAttr("_else")],!u)return;if(n||i){this.#l(c,u,u,s,!0);return}}if(n)return this.#c(s);if(i)return this.#d(s);let f=t.getAttr("func"),h;if(u)h=this.#l(c,u,r?`return ${u}`:u,s,!0);else if(f==null){if(!r)return;h=new x(cs(s))}else{let{group:p,method:m}=this.binding.runtime.logicRegistry.resolve(f,t);h=r?m.call(p,s):m.call(p,t,s)}r&&t.setRelativeData(t.pathAttribute("result_path"),h)}readArguments(e){let t=this.node,[,r]=t.rootBuilder.runtimeValues(t),n=Object.fromEntries(Object.entries(r).filter(([l])=>!jb.has(l)&&!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),i={...e.kind==="subscription"?e.payload:{},...this.binding.runtime.renderer.references.resolveArguments(n)};e.kind==="subscription"&&(i._subscription_kwargs=e.payload,i._subscription_metadata=e.metadata);let s=e.change??null,a=s?s.level:e.kind==="subscription"?e.topic:e.kind;return i._node=s?s.node:null,i._triggerpars={kw:s,trigger_reason:a},i._reason=a,e.kind==="click"&&(Object.assign(i,Pb(e)),e.rowContext&&Object.assign(i,e.rowContext,{event:e.event})),i}cancel(){this.#n.cancel()}#s(){this.#n.startTiming(this.#a("_timing"),()=>this.invoke({kind:"timing",change:null}))}#a(e){let t=this.node,r=t.getAttr(e);return H(r)?Jt(t,e):t.pointerType(r)?t.getRelativeData(r):r??null}#l(e,t,r,n,i){let s=[...i?["_kwargs"]:[],...Pf,...Bf,...Object.keys(cs(n))];return["_onCalling","_onResult","_onError","_ask_onCancel"].includes(e)?dt(this.binding.runtime,this.node,e,t,{...n,_kwargs:n},s):this.binding.runtime.inlineCompiler.compile(this.node,e,t,s,r)({...n,_kwargs:n})}async#c(e){let t=this.node,[r,n,i]=["_onCalling","_onResult","_onError"].map(a=>t.getAttr(a)),s=t.requests;if(s.calling(r?()=>this.#l("_onCalling",r,r,e,!0):null))return s.submit(this.#a("method"),cs(e),a=>this.#u(a,e,n,i))}async#u(e,t,r,n){if(this.binding.closed)return;let i=this.node,s=this.#a("timeout"),a=s>0?setTimeout(()=>{let u=new Error(`${i.nodeTag} '${i.label}': no answer within ${s} ms`);u.name="TimeoutError",e.controller.abort(u)},s):null,l;try{l={result:await this.binding.call("data",e)}}catch(u){l={error:u}}if(clearTimeout(a),this.binding.closed||e.ignored)return;if("error"in l){if(!n)throw l.error;this.#l("_onError",n,n,{...t,error:l.error},!0);return}let{result:c}=l;i.getAttr("result_path")!=null&&i.setRelativeData(i.pathAttribute("result_path"),c),r&&this.#l("_onResult",r,r,{...t,result:c},!0)}#d(e){this.#f();let t=this.#i;this.#i=!1;let r=this.node,n=r.absDatapath(r.pathAttribute("destination_path"));if(n===null)return;let i=r.getAttr("_onCalling"),s=new fn({binding:this.binding,method:this.#a("method"),params:cs(e),cacheTime:this.#a("cacheTime"),sync:this.#a("sync")!==!1&&this.binding.runtime.gramlot.rpc.supportsCallSync,onCalling:i?()=>this.#l("_onCalling",i,i,e,!0):null,onError:a=>{throw new Error(`${r.nodeTag} '${r.label}': dataRemote '${s.method}' failed: ${a.message}`,{cause:a})}});this.binding.runtime.data.setResolver(n,s),this.#o={path:n,resolver:s},t&&s.refresh()}#f(){if(!this.#o)return;let{path:e,resolver:t}=this.#o;this.#o=null,this.#i=t.loaded||t.loading!==null;let r=this.binding.runtime.data.getNode(e);r?.resolver===t&&(r.resolver=null)}#p(){for(let e of this.#t.splice(0))e.close();this.#r.clear()}},us=class extends pn{get kind(){return"formula"}},ds=class extends pn{get kind(){return"controller"}},fs=class extends pn{get kind(){return"rpc"}},hs=class extends pn{get kind(){return"remote"}},Pf=["_node","_triggerpars","_reason","_subscription_kwargs","_subscription_metadata","_askResult"],Bf=["_evt","button_counter","button_shift","button_ctrl","button_alt","button_meta"];function cs(o){let e={...o};for(let t of[...Pf,...Bf])delete e[t];return e}function Pb({event:o,counter:e}){return{_evt:o,button_counter:e,button_shift:!!o.shiftKey,button_ctrl:!!o.ctrlKey,button_alt:!!o.altKey,button_meta:!!o.metaKey}}var Bb=[[null,/(\W|^)GET (?:\s*)(\^?[\w.#@$?-]+)/g,"$1this.GET('$2')"],[/;SET/g,/(\W|^)SET (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.SET('$2', $3)$4 "],[/;PUT/g,/(\W|^)PUT (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.PUT('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE_AFTER('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE_AFTER('$2')$3 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE('$2', $3)$4 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE('$2')$3 "]],Mb=/(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/,Lb=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),ps=class{#e;#t=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return[...this.#t.values()].reduce((e,t)=>e+t.size,0)}preprocess(e,t,r){let n=r.trim();if(Mb.test(n))throw new Error(`${Io(e,t)}: the PUBLISH macro is excluded from Gramlot`);let i=n.replace(/\$(\d+)/g,(s,a)=>`arguments[${parseInt(a,10)-1}]`);for(let[s,a,l]of Bb)s&&(i=i.replace(s,`; ${s.source.slice(1)}`)),i=i.replace(a,l);return i!==n&&console.warn(`${Io(e,t)}: legacy macros are deprecated; write this.GET(path), this.SET(path, value), this.PUT(path, value), this.FIRE(path, value), this.FIRE_AFTER(path, value) and arguments[n] in place of GET, SET, PUT, FIRE, FIRE_AFTER and $n`),i}compile(e,t,r,n,i=r){if(e.activatedCode(t)!==r)throw new Error(`${Io(e,t)}: inline code runs only as received with the Source (main or a remote Source); a text written later is not run: use named logic`);let s=this.#t.get(e);s||(s=new Map,this.#t.set(e,s),this.runtime.bindingFor(e).track(()=>this.release(e)));let a=s.get(t);a?.source!==i&&(a={source:i,text:this.preprocess(e,t,i),key:null,run:null},s.set(t,a));let l=n.filter(Fb),c=l.join(",");if(a.key!==c){let u=zb(e,t,a.text,l);a.key=c,a.run=d=>u.apply(e,l.map(f=>d[f]))}return a.run}compileExpression(e,t,r){let n=r.slice(2).trim(),i=ge(e.getAttr()).filter(([,a])=>!Le(a)),s=this.compile(e,t,r,[...i.map(([a])=>a).filter(a=>a!=="_F"),"_F"],`return ${n}`);return a=>{let l={};for(let[c,u]of i)Object.hasOwn(a,c)?l[c]=a[c]:l[c]=e.pointerType(u)?e.getRelativeData(u):u;return s({...l,_F:(c,u)=>this.runtime.gramlot.format(c,u)})}}compilePointerExpression(e,t,r,n){let i=this.compile(e,t,r,["_pointerValues","_F"],`return (${n}
223
+ )`);return s=>i({_pointerValues:s,_F:(a,l)=>this.runtime.gramlot.format(a,l)})}release(e,t=null){if(t===null){this.#t.delete(e);return}let r=this.#t.get(e);if(r)for(let n of t){r.delete(n);for(let[i]of ge({[n]:null}))r.delete(i)}}};function Fb(o){return/^[A-Za-z_$][\w$]*$/.test(o)&&!Lb.has(o)}function Io(o,e){return`${o.nodeTag} '${o.label}' ${e?`'${e}'`:"node value"}`}function zb(o,e,t,r){try{return t.startsWith("function")?new Function(`return (${t}
224
224
  )`)():new Function(...r,`${t}
225
- `)}catch(n){throw n instanceof EvalError?new EvalError(`${Ao(o,e)}: inline code blocked by the Content Security Policy of the page (no 'unsafe-eval'); move the code to named logic (a method of the page's class Logic) or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`,{cause:n}):new SyntaxError(`${Ao(o,e)}: ${n.message} in the inline code:
226
- ${t}`,{cause:n})}}var ps=class{#e;#t;#r=!1;#n=null;#o=null;constructor(e){this.#e=e,this.#t=new So(e)}get binding(){return this.#e}get node(){return this.binding.node}get closed(){return this.#r||this.binding.closed}close(){this.#r=!0,this.#t.cancel()}register(){this.#t.startTiming(this.#s("_timing"),()=>this.trigger())}receive(e){if(this.#s("_userChanges")&&e.level!=="node")return;let t=this.#s("_delay");t>0?this.#t.debounce(t,()=>this.trigger()):this.trigger()}trigger(){this.update().catch(e=>{this.closed||this.binding.runtime.reportError(e,"Content could not be loaded")})}async update(){if(this.closed||!this.binding.hasStamp("start"))return;let e=this.node,[,t]=e.rootBuilder.runtimeValues(e),r=t.remote,n={};for(let[l,c]of Object.entries(t))l.startsWith("remote_")&&(n[l.slice(7)]=c);let i=e.getAttr("_if");if(i&&!this.#a("_if",i,`return (${i})`,n)){let l=e.getAttr("_else");l&&this.#a("_else",l,l,n);return}let s;try{let l=R(n);if(t._cachedRemote&&this.#i(r,l))return;let c=e.getAttr("_onCalling");if(!e.requests.calling(c?()=>this.#a("_onCalling",c,c,n):null))return;s=await this.binding.runtime.gramlot.src.remoteSource(e,r,n)}catch(l){throw new Error(`${e.nodeTag} '${e.label}': remote '${r}' failed: ${l.message}`,{cause:l})}let a=e.getAttr("_onRemote");!this.closed&&s&&a&&await this.#a("_onRemote",a,a,n)}fragmentMounted(e,t){this.#n=e,this.#o=t}#i(e,t){let r=this.node.requests.inflight;return r?r.method===e&&R(r.params)===t:e===this.#n&&t===this.#o}#s(e){let[,t]=this.node.rootBuilder.runtimeValues(this.node);return t[e]??null}#a(e,t,r,n){return e==="_onRemote"?dt(this.binding.runtime,this.node,e,t,n):this.binding.runtime.inlineCompiler.compile(this.node,e,t,Object.keys(n),r)(n)}};var mn="gramlot-page-store-remote",ms=class{constructor(e){this.binding=e,this.registration=null,this.ready=!1}register(){let{runtime:e,node:t}=this.binding;if(this.connection=e.gramlot._pageStore,!this.connection)throw new Error("dataBinder requires a PageStore WebSocket");if(this.clientPath=t.absDatapath(t.pathAttribute("destination_path")),this.serverPath=t.getAttr("server_path"),typeof this.clientPath!="string"||!this.clientPath||this.clientPath.includes("?"))throw new TypeError("dataBinder requires a nonempty client Data path");if(typeof this.serverPath!="string"||!/^[^.?#\[\]!:]+(?:\.[^.?#\[\]!:]+)*$/.test(this.serverPath))throw new TypeError("dataBinder requires a literal server path");this.id=G(),this.ready=!1,this.registration=e.router.register({path:this.clientPath,recipient:this,subtree:!0});try{this.connection.register(this)}catch(r){throw this.registration.close(),this.registration=null,r}}receive(e){if(!this.ready||e.reason===mn)return;if(e.fired)throw new Error("Fired events are outside the first PageStore PoC");let{data:t}=this.binding.runtime,r=e.level==="container",n=r?t.getNode(this.clientPath):e.node;this.connection.send({op:"change",binderId:this.id,path:r||e.path===this.clientPath?"":e.path.slice(this.clientPath.length+1),evt:r?n?"upd_value":"del":e.evt,value:n?.value??null,attr:{...n?.attr},index:e.index,fired:!1})}apply(e){if(!this.registration?.active)return;let{data:t}=this.binding.runtime,r=e.path?this.clientPath+"."+e.path:this.clientPath;if(this.ready=!0,e.op==="snapshot")e.exists?t.setItem(this.clientPath,e.value,e.attr,">",!1,!1,mn):t.popNode(this.clientPath,mn);else if(e.op==="change")e.evt==="del"?t.popNode(r,mn):e.evt==="upd_attrs"?t.getNode(r).setAttr(e.attr,mn,!1,!1):t.setItem(r,e.value,e.attr,e.index??">",!1,!1,mn);else throw new Error("Unknown PageStore delivery")}unregister(){this.ready=!1,this.registration?.close(),this.registration=null,this.connection?.unregister(this)}};var qb=new Set(["title","msg","fields","_if","askIf"]),Ub=new Set(["name","lbl","tag","type","default_value","required","min","max","step","placeholder"]),gs=class{#e;#t=null;#r=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}required(e,t,r,n){let i=(s,a)=>typeof a=="boolean"?a:e.runtime.inlineCompiler.compile(e.node,s,a,Object.keys(r),`return (${a});`)(r);if(typeof t=="string"){let s=e.node.getAttr("_ask_if");return!s||!!i("_ask_if",s)}return t?.askIf&&i(`${n}.askIf`,t.askIf),!t?._if||!!i(`${n}._if`,t._if)}show(e,t,r,n="Parameters"){let i=typeof t=="string"?{msg:t,title:n}:t;if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError("ask requires text or a parameter description");for(let d of Object.keys(i))if(!qb.has(d))throw new Error(`Unsupported ask option: ${d}`);let s=i.fields??[];if(!Array.isArray(s))throw new TypeError("ask fields must be an array");let a=new Set;for(let d of s){if(!d||!/^[A-Za-z_]\w*$/.test(d.name)||a.has(d.name))throw new Error("ask fields require distinct simple names");a.add(d.name);for(let f of Object.keys(d))if(!Ub.has(f))throw new Error(`Unsupported ask field option: ${f}`);if(d.tag&&!["input","textarea"].includes(d.tag))throw new Error(`Unsupported ask widget: ${d.tag}`);if(d.type&&!["text","number","date","checkbox","email","password","url","tel"].includes(d.type))throw new Error(`Unsupported ask input type: ${d.type}`)}let l=this.runtime.gramlot,c=this.#n(),u=this.#r;return new Promise((d,f)=>{let h=`ask_${G()}`,p=!1,m=()=>{},b=(w,_=null)=>{if(p)return;p=!0;let v=w?Object.fromEntries(s.map(E=>[E.name,l.data.getItem(`${h}.${E.name}`)])):null;u.delete(h),m();try{l.src.source.popNode(h),l.data.getNode(h)&&l.data.popNode(h),_?f(_):d(v)}catch(E){f(E)}};u.set(h,{finish:b}),m=e.track(()=>b(!1));try{let w=new me,_=w.root.html_dialog({nodeId:h,datapath:h,request:h,connect_oncancel:`${c}.cancel`,connect_onclose:`${c}.cancel`,class:"gramlot-ask","aria-labelledby":`${h}_title`,style:"border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"});_.h2(i.title??n,{id:`${h}_title`,style:"font-size:1.1em;margin:0 0 12px;"}),i.msg&&_.p(i.msg);let v=_.form({request:h,connect_onsubmit:`${c}.confirm`});for(let k of s){v.dataSetter({destination_path:`.${k.name}`,value:Object.hasOwn(r,k.name)?r[k.name]:k.default_value??(k.type==="checkbox"?!1:"")});let C=v.div({style:"margin:8px 0;"});C.html_label(k.lbl??k.name,{for:`${h}_${k.name}`,style:"display:block;margin-bottom:4px;"});let O={id:`${h}_${k.name}`,value:`^.${k.name}`,live:!0};for(let L of["required","min","max","step","placeholder"])k[L]!==void 0&&(O[L]=k[L]);k.tag==="textarea"?C.textarea(O):C.input({...O,type:k.type??"text"})}let E=v.div({style:"display:flex;justify-content:flex-end;gap:8px;margin-top:16px;"});E.html_button("Cancel",{type:"button",request:h,connect_onclick:`${c}.cancel`}),E.html_button("Confirm",{type:"submit",autofocus:s.length===0}),l.src.source.setItem(h,l.src.prepareSource(w.source));let D=l.src.binding.nodeIds.get(h);l.dom.getDomNode(D).showModal()}catch(w){b(!1,w)}})}#n(){if(this.#t===null){let e=`ask_${G()}`,t=this.#r;class r{confirm(i,s){s.preventDefault(),t.get(i.getAttr("request"))?.finish(!0)}cancel(i,s){s.preventDefault(),t.get(i.getAttr("request"))?.finish(!1)}}this.runtime.logicRegistry.register(r,{group:e,resource:"gramlot:ask"}),this.#t=e}return this.#t}};var bs=class{#e;#t=`errors_${G()}`;#r=null;#n=new Map;#o=new Set;#i=0;constructor(e){this.#e=e}show(e,t){let r=new Set,n=[];for(let s=e;s!==null&&typeof s=="object"&&!r.has(s);s=s.cause){if(s.name==="AbortError")return;r.add(s),n.push(s.stack??s.message)}let i=typeof e?.message=="string"?e.message:String(e);queueMicrotask(()=>{this.#e.disposed||this.#s(i,t,n.join(`
225
+ `)}catch(n){throw n instanceof EvalError?new EvalError(`${Io(o,e)}: inline code blocked by the Content Security Policy of the page (no 'unsafe-eval'); move the code to named logic (a method of the page's class Logic) or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`,{cause:n}):new SyntaxError(`${Io(o,e)}: ${n.message} in the inline code:
226
+ ${t}`,{cause:n})}}var ms=class{#e;#t;#r=!1;#n=null;#o=null;constructor(e){this.#e=e,this.#t=new Ao(e)}get binding(){return this.#e}get node(){return this.binding.node}get closed(){return this.#r||this.binding.closed}close(){this.#r=!0,this.#t.cancel()}register(){this.#t.startTiming(this.#s("_timing"),()=>this.trigger())}receive(e){if(this.#s("_userChanges")&&e.level!=="node")return;let t=this.#s("_delay");t>0?this.#t.debounce(t,()=>this.trigger()):this.trigger()}trigger(){this.update().catch(e=>{this.closed||this.binding.runtime.reportError(e,"Content could not be loaded")})}async update(){if(this.closed||!this.binding.hasStamp("start"))return;let e=this.node,[,t]=e.rootBuilder.runtimeValues(e),r=t.remote,n={};for(let[l,c]of Object.entries(t))l.startsWith("remote_")&&(n[l.slice(7)]=c);let i=e.getAttr("_if");if(i&&!this.#a("_if",i,`return (${i})`,n)){let l=e.getAttr("_else");l&&this.#a("_else",l,l,n);return}let s;try{let l=R(n);if(t._cachedRemote&&this.#i(r,l))return;let c=e.getAttr("_onCalling");if(!e.requests.calling(c?()=>this.#a("_onCalling",c,c,n):null))return;s=await this.binding.runtime.gramlot.src.remoteSource(e,r,n)}catch(l){throw new Error(`${e.nodeTag} '${e.label}': remote '${r}' failed: ${l.message}`,{cause:l})}let a=e.getAttr("_onRemote");!this.closed&&s&&a&&await this.#a("_onRemote",a,a,n)}fragmentMounted(e,t){this.#n=e,this.#o=t}#i(e,t){let r=this.node.requests.inflight;return r?r.method===e&&R(r.params)===t:e===this.#n&&t===this.#o}#s(e){let[,t]=this.node.rootBuilder.runtimeValues(this.node);return t[e]??null}#a(e,t,r,n){return e==="_onRemote"?dt(this.binding.runtime,this.node,e,t,n):this.binding.runtime.inlineCompiler.compile(this.node,e,t,Object.keys(n),r)(n)}};var mn="gramlot-page-store-remote",gs=class{constructor(e){this.binding=e,this.registration=null,this.ready=!1}register(){let{runtime:e,node:t}=this.binding;if(this.connection=e.gramlot._pageStore,!this.connection)throw new Error("dataBinder requires a PageStore WebSocket");if(this.clientPath=t.absDatapath(t.pathAttribute("destination_path")),this.serverPath=t.getAttr("server_path"),typeof this.clientPath!="string"||!this.clientPath||this.clientPath.includes("?"))throw new TypeError("dataBinder requires a nonempty client Data path");if(typeof this.serverPath!="string"||!/^[^.?#\[\]!:]+(?:\.[^.?#\[\]!:]+)*$/.test(this.serverPath))throw new TypeError("dataBinder requires a literal server path");this.id=G(),this.ready=!1,this.registration=e.router.register({path:this.clientPath,recipient:this,subtree:!0});try{this.connection.register(this)}catch(r){throw this.registration.close(),this.registration=null,r}}receive(e){if(!this.ready||e.reason===mn)return;if(e.fired)throw new Error("Fired events are outside the first PageStore PoC");let{data:t}=this.binding.runtime,r=e.level==="container",n=r?t.getNode(this.clientPath):e.node;this.connection.send({op:"change",binderId:this.id,path:r||e.path===this.clientPath?"":e.path.slice(this.clientPath.length+1),evt:r?n?"upd_value":"del":e.evt,value:n?.value??null,attr:{...n?.attr},index:e.index,fired:!1})}apply(e){if(!this.registration?.active)return;let{data:t}=this.binding.runtime,r=e.path?this.clientPath+"."+e.path:this.clientPath;if(this.ready=!0,e.op==="snapshot")e.exists?t.setItem(this.clientPath,e.value,e.attr,">",!1,!1,mn):t.popNode(this.clientPath,mn);else if(e.op==="change")e.evt==="del"?t.popNode(r,mn):e.evt==="upd_attrs"?t.getNode(r).setAttr(e.attr,mn,!1,!1):t.setItem(r,e.value,e.attr,e.index??">",!1,!1,mn);else throw new Error("Unknown PageStore delivery")}unregister(){this.ready=!1,this.registration?.close(),this.registration=null,this.connection?.unregister(this)}};var Ub=new Set(["title","msg","fields","_if","askIf"]),qb=new Set(["name","lbl","tag","type","default_value","required","min","max","step","placeholder"]),bs=class{#e;#t=null;#r=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}required(e,t,r,n){let i=(s,a)=>typeof a=="boolean"?a:e.runtime.inlineCompiler.compile(e.node,s,a,Object.keys(r),`return (${a});`)(r);if(typeof t=="string"){let s=e.node.getAttr("_ask_if");return!s||!!i("_ask_if",s)}return t?.askIf&&i(`${n}.askIf`,t.askIf),!t?._if||!!i(`${n}._if`,t._if)}show(e,t,r,n="Parameters"){let i=typeof t=="string"?{msg:t,title:n}:t;if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError("ask requires text or a parameter description");for(let d of Object.keys(i))if(!Ub.has(d))throw new Error(`Unsupported ask option: ${d}`);let s=i.fields??[];if(!Array.isArray(s))throw new TypeError("ask fields must be an array");let a=new Set;for(let d of s){if(!d||!/^[A-Za-z_]\w*$/.test(d.name)||a.has(d.name))throw new Error("ask fields require distinct simple names");a.add(d.name);for(let f of Object.keys(d))if(!qb.has(f))throw new Error(`Unsupported ask field option: ${f}`);if(d.tag&&!["input","textarea"].includes(d.tag))throw new Error(`Unsupported ask widget: ${d.tag}`);if(d.type&&!["text","number","date","checkbox","email","password","url","tel"].includes(d.type))throw new Error(`Unsupported ask input type: ${d.type}`)}let l=this.runtime.gramlot,c=this.#n(),u=this.#r;return new Promise((d,f)=>{let h=`ask_${G()}`,p=!1,m=()=>{},b=(w,_=null)=>{if(p)return;p=!0;let v=w?Object.fromEntries(s.map(E=>[E.name,l.data.getItem(`${h}.${E.name}`)])):null;u.delete(h),m();try{l.src.source.popNode(h),l.data.getNode(h)&&l.data.popNode(h),_?f(_):d(v)}catch(E){f(E)}};u.set(h,{finish:b}),m=e.track(()=>b(!1));try{let w=new me,_=w.root.html_dialog({nodeId:h,datapath:h,request:h,connect_oncancel:`${c}.cancel`,connect_onclose:`${c}.cancel`,class:"gramlot-ask","aria-labelledby":`${h}_title`,style:"border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"});_.h2(i.title??n,{id:`${h}_title`,style:"font-size:1.1em;margin:0 0 12px;"}),i.msg&&_.p(i.msg);let v=_.form({request:h,connect_onsubmit:`${c}.confirm`});for(let k of s){v.dataSetter({destination_path:`.${k.name}`,value:Object.hasOwn(r,k.name)?r[k.name]:k.default_value??(k.type==="checkbox"?!1:"")});let C=v.div({style:"margin:8px 0;"});C.html_label(k.lbl??k.name,{for:`${h}_${k.name}`,style:"display:block;margin-bottom:4px;"});let O={id:`${h}_${k.name}`,value:`^.${k.name}`,live:!0};for(let L of["required","min","max","step","placeholder"])k[L]!==void 0&&(O[L]=k[L]);k.tag==="textarea"?C.textarea(O):C.input({...O,type:k.type??"text"})}let E=v.div({style:"display:flex;justify-content:flex-end;gap:8px;margin-top:16px;"});E.html_button("Cancel",{type:"button",request:h,connect_onclick:`${c}.cancel`}),E.html_button("Confirm",{type:"submit",autofocus:s.length===0}),l.src.source.setItem(h,l.src.prepareSource(w.source));let D=l.src.binding.nodeIds.get(h);l.dom.getDomNode(D).showModal()}catch(w){b(!1,w)}})}#n(){if(this.#t===null){let e=`ask_${G()}`,t=this.#r;class r{confirm(i,s){s.preventDefault(),t.get(i.getAttr("request"))?.finish(!0)}cancel(i,s){s.preventDefault(),t.get(i.getAttr("request"))?.finish(!1)}}this.runtime.logicRegistry.register(r,{group:e,resource:"gramlot:ask"}),this.#t=e}return this.#t}};var ws=class{#e;#t=`errors_${G()}`;#r=null;#n=new Map;#o=new Set;#i=0;constructor(e){this.#e=e}show(e,t){let r=new Set,n=[];for(let s=e;s!==null&&typeof s=="object"&&!r.has(s);s=s.cause){if(s.name==="AbortError")return;r.add(s),n.push(s.stack??s.message)}let i=typeof e?.message=="string"?e.message:String(e);queueMicrotask(()=>{this.#e.disposed||this.#s(i,t,n.join(`
227
227
  Caused by:
228
- `))})}#s(e,t,r){let n=this.#e.gramlot,i=JSON.stringify([t,e]);if(this.#o.has(i))return;let s=this.#e.nodeIds.get(this.#t);if(!s){if(this.#n.clear(),this.#i=0,this.#r===null){let p=this;class m{close(w){p.#a(w.getAttr("notice"))}}this.#r=`errors_${G()}`,this.#e.logicRegistry.register(m,{group:this.#r,resource:"gramlot:error-notifications"})}let h=new me;h.root.aside({nodeId:this.#t,class:"gramlot-error-notifications",popover:"manual","aria-label":"Error notifications",style:"position:fixed;inset:auto max(12px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) auto;margin:0;width:360px;max-width:calc(100vw - 24px);max-height:50vh;overflow:auto;box-sizing:border-box;padding:0;border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:8px;background:var(--gramlot-surface,#fff);color:var(--gramlot-ink,#222);font:13px/1.4 system-ui;box-shadow:0 6px 24px #0003;"}),n.src.source.setItem(this.#t,n.src.prepareSource(h.source)),s=this.#e.nodeIds.get(this.#t)}if(this.#n.has(i))return;if(this.#n.size===5){let h=`${++this.#i} additional errors`,p=s.value.getNode("overflow");p?p.setValue(h):n.src.builder.wrapSource(s).p(h,{node_label:"overflow",role:"status",style:"margin:0;padding:12px;"});return}let a=`notice_${G()}`,l=new me,c=l.root.article({role:"alert",style:"color:inherit;padding:12px;border-bottom:1px solid var(--gramlot-border,#ddd);"}),u=c.div({style:"display:flex;align-items:start;gap:12px;"});u.strong(`==${JSON.stringify(t)}`,{style:"flex:1;color:var(--gramlot-error,#b13d48);"}),u.html_button("\xD7",{type:"button",notice:a,connect_onclick:`${this.#r}.close`,"aria-label":"Dismiss notification",title:"Dismiss notification",style:"border:0;background:transparent;color:inherit;font:18px/1 system-ui;width:24px;height:24px;flex:0 0 24px;padding:0;cursor:pointer;"}),c.p(`==${JSON.stringify(e)}`,{style:"margin:6px 0;overflow-wrap:anywhere;"});let d=c.details({style:"border:0;padding:0;margin:8px 0 0;background:transparent;"});d.summary("Details",{style:"cursor:pointer;"}),d.pre(`==${JSON.stringify(r)}`,{style:"font:11px/1.4 monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:6px 0 0;padding:8px;border:0;border-radius:4px;background:var(--gramlot-surface-subtle,#f2f4f6);"});let f=n.src.builder.wrapSource(s).div({node_label:a});Z(f).setValue(n.src.prepareSource(l.source)),this.#n.set(i,a),n.dom.getDomNode(s).showPopover()}#a(e){this.#e.nodeIds.get(this.#t).value.popNode(e);for(let[r,n]of this.#n)n===e&&(this.#n.delete(r),this.#o.add(r));this.#n.size||this.#e.gramlot.src.source.popNode(this.#t)}};var Mf={dataFormula:cs,dataController:us,dataRpc:ds,dataRemote:fs},Vb=["datapath","_anchor","nodeId","form","formId"],gn=class{#e;#t=new Map;#r=new Map;#n;#o;#i;#s;#a;#l;#c=`gramlot-data-${G()}`;#u=!1;#d=new Set;#f=new Set;#p=new WeakMap;constructor(e,{subscriptions:t}){this.#e=e,this.#l=t,this.#n=new os(this),this.#o=new as(this),this.#i=new hs(this),this.#s=new gs(this),this.#a=new bs(this)}get gramlot(){return this.#e}reportError(e,t){this.disposed||this.#a.show(e,t)}get subscriptions(){return this.#l}get builder(){return this.gramlot.src.builder}get renderer(){return this.gramlot.src.renderer}get logicRegistry(){return this.gramlot.src.logicRegistry}get data(){return this.builder.data}treeStore(e){if(e.treeStore!==null)return e.treeStore;let t=e.getAttr("storepath");if(t==="*S"||t.startsWith("*S.")){let r=this.renderer.source.getItem("main");return t==="*S"?r:r.getItem(t.slice(3))}return t==="*D"||t.startsWith("*D.")?t==="*D"?this.data:this.data.getItem(t.slice(3)):e.getRelativeData(t)}registerTreeRoot(e,t){let r=t?this.#d:this.#f;return r.add(e),{close:()=>r.delete(e)}}refreshSourceTrees(){for(let e of[...this.#d])!e.closed&&this.renderer.attached(e.node)&&this.renderer.project(e.node)}get root(){return this.data.parent}get size(){return this.#t.size}get disposed(){return this.#u}get router(){return this.#n}get installer(){return this.#o}get inlineCompiler(){return this.#i}get askDialog(){return this.#s}get nodeIds(){return this.#r}collectionStore(e,t){if(this.disposed)throw new Error("BindingRuntime is disposed");let r=this.#p.get(e);if(!r)r=new _o(e,t),this.#p.set(e,r);else if(r.rowMode!==t)throw new TypeError("A shared collection store requires one rowMode");return r}collectionView(e,t,r){let n=this.collectionStore(t,r);return Object.hasOwn(e,"gridCollectionView")?e.gridCollectionView.bindStore(n):Object.defineProperty(e,"gridCollectionView",{value:new vo(n),configurable:!0}),e.gridCollectionView}attach(){this.root.subscribe(this.#c,{any:e=>this.receiveData(e)})}receiveData(e){let t=this.root;for(let[r,n]of(e.pathlist??[]).entries()){let i=t.node(n)?.staticValue;if(!(i instanceof x))break;this.#p.get(i)?.receiveData(e,r+1<e.pathlist.length?i.node(e.pathlist[r+1]):null,e.pathlist[r+2]??null),t=i}this.router.deliver(e);for(let r of[...this.#f])!r.closed&&this.renderer.attached(r.node)&&this.renderer.project(r.node)}bindingFor(e){return this.#t.get(e)??null}openBinding(e){if(this.disposed)throw new Error("BindingRuntime is disposed");let t=this.bindingFor(e);return t||(t=new oc(this,e),this.#t.set(e,t)),t}closeBranch(e){let t=[];if(e.value instanceof N)for(let n of e.value.getNodes())try{this.closeBranch(n)}catch(i){t.push(i)}let r=this.bindingFor(e);if(r){this.#t.delete(e);let n=e.getAttr("nodeId");this.nodeIds.get(n)===e&&this.nodeIds.delete(n);try{r.close()}catch(i){t.push(i)}}if(t.length)throw new AggregateError(t,"Source branch close failed")}rebindBranch(e){let t=this.#_(e);for(let r of t)this.bindingFor(r)?.rebind();for(let r of t)this.renderer.project(r);for(let r of t)this.bindingFor(r)?.remote?.trigger()}handleSourceEvent(e){let{evt:t,node:r}=e,n=[],i=s=>{try{this.closeBranch(s)}catch(a){n.push(a)}};try{if(t==="ins")this.#h(r);else if(t==="del")for(let s of Array.isArray(r)?r:[r])i(s);else if(t==="upd_value"||t==="upd_value_attr"){if(e.oldvalue instanceof N)for(let s of e.oldvalue.getNodes())i(s);this.inlineCompiler.release(r,[""]),t==="upd_value_attr"?this.#b(r,e.attrs_diff):this.#w(r).rebind(),r.value instanceof N&&this.#h(r.value)}else if(t==="upd_attrs")this.#b(r,e.attrs_diff);else throw new Error(`Unsupported Source event: ${t}`)}catch(s){throw n.length?new AggregateError([...n,s],"Source event failed"):s}return n}branchBuilt(e){let t=[];for(let r of this.#_(e)){let n=this.bindingFor(r);!n||n.hasStamp("built")||!this.renderer.attached(r)||(n.stamp("built"),t.push(n))}for(let r of t)this.renderer.attached(r.node)&&this.#g(r,"built","_onBuilt");if(this.gramlot.state==="started")for(let r of t)this.renderer.attached(r.node)&&this.#m(r)}pageStarted(){for(let e of[...this.#t.values()])!e.closed&&e.hasStamp("built")&&this.#m(e)}dispose(){if(this.disposed)return;this.#u=!0,this.root.unsubscribe(this.#c,{any:!0}),this.nodeIds.clear(),this.#p=new WeakMap;let e=[];for(let[t,r]of[...this.#t.entries()].reverse()){this.#t.delete(t);try{r.close()}catch(n){e.push(n)}}if(e.length)throw new AggregateError(e,"Binding cleanup failed")}#h(e){if(!(e instanceof N)&&this.bindingFor(e))return;let t=e instanceof N?e.getNodes().flatMap(i=>this.#_(i)):this.#_(e),r=new Set(t.filter(i=>this.bindingFor(i))),n=new Map;for(let i of t){let s=i.getAttr("nodeId");if(s!=null){if(n.has(s)||this.nodeIds.has(s)&&this.nodeIds.get(s)!==i)throw new Error(`Duplicate nodeId '${s}'`);n.set(s,i)}}for(let[i,s]of n)this.nodeIds.set(i,s);try{for(let i of t)this.openBinding(i);this.installer.install(e);for(let i of t)this.renderer.attached(i)&&this.bindingFor(i).registerPointers()}catch(i){let s=[i];for(let a of t.filter(l=>!r.has(l)).reverse()){let l=a.getAttr("nodeId");n.get(l)===a&&this.nodeIds.get(l)===a&&this.nodeIds.delete(l);let c=this.bindingFor(a);if(c){this.#t.delete(a);try{c.close()}catch(u){s.push(u)}}}throw s.length>1?new AggregateError(s,"Source branch installation failed"):i}for(let i of t){let s=this.bindingFor(i);if(!(!s||s.hasStamp("init")||!this.renderer.attached(i))&&(s.stamp("init"),Lf(i.getAttr("_init"))))for(let a of s.providers)a.invoke({kind:"init",change:null})}}#m(e){e.hasStamp("start")||(e.stamp("start"),this.#g(e,"start","_onStart"),e.remote?.trigger())}#g(e,t,r){let n=e.node.getAttr(r);if(Lf(n))for(let i of e.providers){if(typeof n!="number"||n<=0){i.invoke({kind:t,change:null});continue}let s=null,a=setTimeout(()=>{s(),i.invoke({kind:t,change:null})},n);s=e.track(()=>clearTimeout(a))}}#b(e,t){let r=this.#w(e);if(this.inlineCompiler.release(e,Object.keys(t)),Object.hasOwn(t,"nodeId")){let{old:n,new:i}=t.nodeId;if(i!=null&&this.nodeIds.has(i)&&this.nodeIds.get(i)!==e)throw new Error(`Duplicate nodeId '${i}'`);this.nodeIds.get(n)===e&&this.nodeIds.delete(n),i!=null&&this.nodeIds.set(i,e)}Vb.some(n=>Object.hasOwn(t,n))?this.rebindBranch(e):r.rebind()}#w(e){let t=this.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': the node has no NodeBinding (its installation failed); remove it from the Source and insert it again`);return t}#_(e){let t=[e];if(e.value instanceof N)for(let r of e.value.getNodes())t.push(...this.#_(r));return t}};function Lf(o){return o===!0||typeof o=="number"}var oc=class{#e;#t;#r=!1;#n=[];#o=[];#i=new Set;#s=null;#a=null;#l=null;#c=new Set;#u=new Set;#d=0;#f=new Set;#p=null;editingSession=null;constructor(e,t){this.#e=e,this.#t=t}get runtime(){return this.#e}get node(){return this.#t}get closed(){return this.#r}get registrations(){return[...this.#o]}get providers(){return this.#s?[this.#s]:[]}get remote(){return this.#l}get clickCount(){return this.#d}countClick(){return++this.#d}hasStamp(e){return this.#i.has(e)}stamp(e){this.#i.add(e)}registerPointers(){this.node._getMeta("data_element")&&(this.runtime.renderer.references.remove(this.node),this.runtime.renderer.references.register(this.node,null));let e=this.node,t=e._getMeta("data_element");if(t&&!Mf[e.nodeTag]&&e.nodeTag!=="dataBinder")return;!t&&typeof e.getAttr("remote")=="string"?this.#l??=new ps(this):this.#l&&(this.#l.close(),this.#l=null);let r=new Set,n=e._getMeta("gramlot_component");for(let[s,a]of[["bagStore","storepath"],["bagStruct","structpath"]]){if(!n?.[s])continue;if(s==="bagStore"&&e.nodeTag==="tree"&&e.treeStore!==null){let d=e.treeStore,f=`gramlot-tree-${G()}`;d.subscribe(f,{any:()=>{!this.closed&&this.runtime.renderer.attached(e)&&this.runtime.renderer.project(e)}}),this.#o.push({close:()=>d.unsubscribe(f,{any:!0})});continue}let l=e.getAttr(a);if(typeof l!="string"||!l||/^[\^=]/.test(l)||l.includes("?"))throw new TypeError(`${a} requires a plain Bag data path`);if(s==="bagStore"&&e.nodeTag==="tree"&&(l==="*S"||l.startsWith("*S."))){this.#o.push(this.runtime.registerTreeRoot(this,!0));continue}if(s==="bagStore"&&e.nodeTag==="tree"&&l==="*D"){this.#o.push(this.runtime.registerTreeRoot(this,!1));continue}let c=s==="bagStore"&&e.nodeTag==="tree"&&l.startsWith("*D.")?l.slice(3):e.absDatapath(l),u=this.runtime.router.register({path:c,recipient:this,subtree:!0});this.#o.push(u),s==="bagStore"&&n.bagStruct&&(this.#p=u)}let i=this.remote?Ze(e,e.getAttr("_timing")):new Set;if(this.remote){for(let[s,a]of Object.entries(e.getAttr()))if(s.startsWith("remote_"))for(let l of Ze(e,a))r.add(l)}for(let[s,a]of e.pointers()){if(t&&s!=="datapath")continue;let c=(s==="datapath"?e.parentNode:e).absDatapath(a);if(c===null)continue;let[u,d=null]=c.split("?",2),f=this.runtime.router.register({path:u,attr:d,recipient:this});this.#o.push(f),s==="datapath"&&this.#f.add(f),this.remote&&(s==="remote"||s.startsWith("remote_")||r.has(s))&&this.#c.add(f),this.remote&&(s==="_timing"||i.has(s))&&this.#u.add(f)}if(!t){this.#h(),this.remote?.register();return}if(e.nodeTag==="dataBinder"){this.#a??=new ms(this),this.#a.register();return}this.#s??=new Mf[e.nodeTag](this),this.#s.register()}#h(){let e=this.node;this.#o.push(...this.runtime.subscriptions.subscribeNode(e,(t,r)=>{if(typeof r!="string"||!r)throw new TypeError(`${t} requires a handler`);return n=>{if(this.closed)return;if(ao(r))return Tt(this.runtime,e,r,n);let[,i]=e.rootBuilder.runtimeValues(e),s=Object.fromEntries(Object.entries(i).filter(([l])=>!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),a={...this.runtime.renderer.references.resolveArguments(s),p_0:n};return this.runtime.inlineCompiler.compile(e,t,r,Object.keys(a))(a)}}))}rebind(){this.#m(),this.registerPointers(),this.editingSession?.refreshField(this.node)}receive(e){if(!(e.registration===this.#p&&(e.level==="child"||e.evt==="upd_attrs"))){if(this.#f.has(e.registration)){this.runtime.rebindBranch(this.node);return}this.#c.has(e.registration)&&this.remote.receive(e),this.#u.has(e.registration)&&this.remote.register(),this.editingSession?.refreshField(this.node),this.runtime.renderer.project(this.node,e)}}track(e){if(this.closed)throw new Error(`NodeBinding of '${this.node.label}' is closed`);return this.#n.push(e),()=>{let t=this.#n.indexOf(e);t!==-1&&this.#n.splice(t,1)}}async call(e,t){let{controller:r}=t,n=this.track(()=>r.abort());try{let i=await this.runtime.gramlot.rpc.call(e,t.method,t.params,{signal:r.signal});if(r.signal.aborted)throw r.signal.reason;return i}finally{n()}}callSync(e,t,r){return this.node.requests.submitSync(t,()=>this.runtime.gramlot.rpc.callSync(e,t,r))}close(){if(this.closed)return;this.#r=!0,this.#l?.close(),this.node._getMeta("data_element")&&this.runtime.renderer.references.remove(this.node),this.#m();let e=[];for(let t of this.#n.splice(0).reverse())try{t()}catch(r){e.push(r)}if(e.length)throw new AggregateError(e,`NodeBinding of '${this.node.label}' cleanup failed`)}#m(){this.#a?.unregister();for(let e of this.#o.splice(0))e.close();this.#p=null,this.#f.clear(),this.#c.clear(),this.#u.clear()}};var ws=class{constructor(e){this.renderer=e}prepare(e,t){let r=this.renderer.records.get(e);if(!r||r.resolved.draggable!==!0)return null;let n=e._getMeta("gramlot_component")?.dragSource?r.element.getDragContext(t):{dragValues:{},item:void 0,path:void 0};if(n===null)return null;let{dragValues:i,item:s,path:a}=n;if(r.resolved.onDrag){let c=this.renderer.html.callLogic(e,r.resolved.onDrag,{dragValues:i,item:s,path:a});if(c&&typeof c.then=="function")throw new TypeError("onDrag must run synchronously");if(c===!1)return null}return Qe(i),{dragValues:Object.fromEntries(Object.entries(i).map(([c,u])=>{if(c.startsWith("text/")||c==="dragTags"){if(typeof u!="string")throw new TypeError(`${c} drag data must be text`);return[c,u]}return[c,j(R(u))]})),item:s,path:a}}};var er=class{static isTarget(e){return e.dropTarget===!0||!!e.dropTargetCb||Object.entries(e).some(([t,r])=>t.startsWith("dropTargetCb_")&&!!r)}static acceptedTypes(e,t="",r=[]){let n=t.split(",").map(i=>i.trim()).filter(Boolean).map(i=>{let s=i.split("*").map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return new RegExp(`^${s.join(".*")}$`)});return e.filter(i=>i!=="dragTags"&&(r.includes(i)||n.some(s=>s.test(i))))}static acceptsTags(e="",t=""){if(!t.trim())return!0;let r=new Set(e.split(",").map(n=>n.trim()).filter(Boolean));return r.size?t.split(",").some(n=>n.split(" AND ").every(i=>(i=i.trim(),!i||i==="!"?!1:i.startsWith("!")?!r.has(i.slice(1)):r.has(i)))):!1}static acceptsEffect(e="all",t="move"){let r={all:["copy","move","link"],none:[],copy:["copy"],move:["move"],link:["link"],copyMove:["copy","move"],copyLink:["copy","link"],linkMove:["link","move"]};if(!Object.hasOwn(r,e))throw new TypeError(`Invalid effectAllowed: ${e}`);if(!["copy","move","link"].includes(t))throw new TypeError(`Invalid dropEffect: ${t}`);return r[e].includes(t)}static evaluate(e,t,r,n,i=[]){let s=this.acceptedTypes(e,n.dropTypes,i),a=n.dropEffect??"move",l=this.isTarget(n)&&s.length>0&&this.acceptsTags(t,n.dropTags)&&this.acceptsEffect(r,a);return{accepted:l,types:s,dropEffect:l?a:"none"}}};var Ff=["dragstart","dragover","dragleave","drop","dragend"],_s=class{#e;#t;#r=null;#n=null;#o=null;#i;constructor(e){this.#e=e,this.#t=e.destination.ownerDocument;for(let t of Ff)this.#t.addEventListener(t,this);this.#i=()=>this.#b("none"),this.#t.defaultView.addEventListener("pagehide",this.#i)}handleEvent(e){e.type==="dragstart"?this.#l(e):e.type==="dragend"?this.#b(e.dataTransfer.dropEffect):e.type==="dragleave"?this.#h():e.type==="dragover"?this.#d(e):e.type==="drop"&&this.#f(e)}#s(e,t){for(let r of e.composedPath()){let n=this.#e.elements.get(r);if(n&&t(n.resolved))return n}return null}#a(e,t){return e.node._getMeta("gramlot_component")?.dragSource?e.element.getDragContext(t):{element:e.element,item:void 0,path:void 0}}#l(e){let t=this.#s(e,r=>r.draggable===!0);if(t){this.#b("none");try{let r=this.#e.prepareDrag(t.node,e);if(!r||!t.element.isConnected||this.#e.records.get(t.node)!==t){e.preventDefault();return}let n=this.#a(t,e);if(!n){e.preventDefault();return}let i=new Map(Object.entries(r.dragValues).filter(([c])=>c!=="dragTags").map(([c,u])=>[c,c.startsWith("text/")?u:R(u)]));if(!i.size){e.preventDefault();return}let s=t.resolved.effectAllowed??"all";er.acceptsEffect(s,"move");let a="";for(let c=t;c;c=c.parent)if(c.resolved?.dragTags!=null){a=c.resolved.dragTags;break}let l=this.#r={record:t,wires:i,effectAllowed:s,phase:"active",tags:[a,r.dragValues.dragTags].filter(Boolean).join(","),endTopic:this.#e.binding.subscriptions.topicFor(t.node,"endDrag"),source:{pageId:this.#e.binding.gramlot.pageId??null,sourcePath:t.node.fullpath,itemPath:r.path??null},preview:null,release:null};e.dataTransfer.clearData();for(let[c,u]of i)e.dataTransfer.setData(c,u);e.dataTransfer.effectAllowed=s,this.#o=this.#t.createElement("style"),this.#o.textContent=".canBeDropped{outline:2px solid var(--gramlot-brand-blue,#3766b5);outline-offset:-2px}.cannotBeDropped{outline:2px dashed currentColor;outline-offset:-2px}.draggedItem{opacity:.75}",this.#t.head.append(this.#o),this.#c(l,n.element,e.dataTransfer),l.release=this.#e.onDispose(t.node,()=>this.#b("none"))}catch(r){e.preventDefault(),this.#g(),this.#w(r)}}}#c(e,t,r){let n=t.cloneNode(!0);n.removeAttribute("id");for(let i of n.querySelectorAll("[id]"))i.removeAttribute("id");n.setAttribute("aria-hidden","true"),n.classList.add(...(e.record.resolved.dragClass??"draggedItem").split(/\s+/).filter(Boolean)),Object.assign(n.style,{position:"fixed",left:"-10000px",top:"0",width:`${t.getBoundingClientRect().width}px`,pointerEvents:"none"}),t.parentNode.append(n),e.preview=n,r.setDragImage(n,0,0)}#u(e){let t=this.#r,r=this.#s(e,c=>er.isTarget(c));if(!r)return null;let n=this.#a(r,e);if(!n)return{record:r,element:r.element,accepted:!1};let i=er.evaluate([...t.wires.keys()],t.tags,t.effectAllowed,r.resolved),a={dropValues:Object.fromEntries(i.types.map(c=>[c,c.startsWith("text/")?t.wires.get(c):j(t.wires.get(c))])),item:n.item,path:n.path,source:{...t.source},selfdrop:r===t.record,dropEffect:i.dropEffect,dataAvailable:!0};n.placement!==void 0&&(a.placement=n.placement);let l=i.accepted&&this.#e.checkDropTarget(r.node,a)&&this.#e.records.get(r.node)===r&&n.element.isConnected;return{record:r,element:n.element,accepted:l,context:a}}#d(e){if(!this.#r){this.#s(e,t=>er.isTarget(t))&&(e.preventDefault(),e.dataTransfer.dropEffect="none");return}if(e.preventDefault(),this.#r.phase!=="active"){e.dataTransfer.dropEffect="none";return}try{let t=this.#r,r=this.#u(e);if(this.#r!==t){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r?.accepted?r.context.dropEffect:"none",this.#h(),r&&this.#p(r.element,r.accepted)}catch(t){e.dataTransfer.dropEffect="none",this.#r&&(this.#r.phase="rejected"),this.#m(),this.#w(t)}}async#f(e){if(!this.#r){this.#s(e,n=>er.isTarget(n))&&e.preventDefault();return}if(e.preventDefault(),this.#r.phase!=="active")return;let t=this.#r,r;try{if(r=this.#u(e),this.#r!==t){e.dataTransfer.dropEffect="none";return}if(t.phase="dropped",this.#m(),!r?.accepted){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r.context.dropEffect,r.record.node.publish("onDrop",r.context),await this.#e.invokeDrop(r.record.node,r.context)}catch(n){this.#r===t&&(t.phase="rejected",this.#m()),(!r||this.#e.records.has(r.record.node))&&this.#w(n)}}#p(e,t){let r=t?"canBeDropped":"cannotBeDropped",n=(e.getAttribute("part")??"").split(/\s+/).filter(Boolean);this.#n={element:e,name:r,hadClass:e.classList.contains(r),hadPart:n.includes(r)},e.classList.add(r),n.includes(r)||e.setAttribute("part",[...n,r].join(" "))}#h(){if(!this.#n)return;let{element:e,name:t,hadClass:r,hadPart:n}=this.#n;r||e.classList.remove(t),n||e.setAttribute("part",(e.getAttribute("part")??"").split(/\s+/).filter(i=>i!==t).join(" ")),this.#n=null}#m(){this.#h(),this.#r&&(this.#r.preview?.remove(),this.#r.preview=null,this.#r.wires.clear())}#g(){let e=this.#r;return this.#m(),this.#r=null,e?.release?.(),this.#o?.remove(),this.#o=null,e}#b(e){let t=this.#g();!t||this.#e.disposed||this.#e.endDrag(t.record.node,{source:{...t.source},dropEffect:e},t.endTopic).catch(r=>this.#w(r))}#w(e){this.#e.binding.reportError(e,"Drag and drop failed")}dispose(){this.#g();for(let e of Ff)this.#t.removeEventListener(e,this);this.#t.defaultView.removeEventListener("pagehide",this.#i)}};var Io=class extends Sr{static renderType="object";#e=new Set;#t=new WeakSet;#r=new WeakMap;#n=new WeakMap;#o=new WeakMap;constructor(e,t,r,{binding:n}={}){if(super(e),!(e instanceof Ae)||!(t instanceof de)||r?.nodeType!==1)throw new TypeError("GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination");if(!(n instanceof gn))throw new TypeError("GramlotRenderer requires a BindingRuntime");if(!(t._builder instanceof Ae))throw new TypeError("SourceBag requires builder ownership");this._binding=n,this.source=t,this.destination=r,this.html=new Zi({uploadContext:()=>({gramlot:n.gramlot,window:r.ownerDocument.defaultView}),metadataAttributes:["__ref"],format:(i,s)=>n.gramlot.format(i,s),reportError:(i,s,a)=>{this.records.has(i)&&n.reportError(s,a)},callLogic:(i,s,a)=>{let{group:l,method:c}=n.gramlot.src.logicRegistry.resolve(s,i);return c.call(l,i,a)},invokeScript:(i,s,a,l)=>dt(n,i,s,a,l,i.parentNode._getMeta("gramlot_component").childParameters[s].inline)}),this.records=new Map,this.references=new Jn(t),this.pending=[],this.building=!1,this.disposed=!1,this.elements=new WeakMap,this.dragPreparation=new ws(this),this.instanceId=G(),this.radioGroups=new Yi(this),this.dragDrop=new _s(this),this.subscription=`html-source-renderer-${this.instanceId}`,t.subscribe(this.subscription,{any:i=>this.receive(i)})}get binding(){return this._binding}prepareDrag(e,t){return this.dragPreparation.prepare(e,t)}checkDropTarget(e,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,placement:c}){let u=this.records.get(e);if(!u)return!1;if(!u.resolved.dropTargetCb)return!0;let d=this.html.callLogic(e,u.resolved.dropTargetCb,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,...c===void 0?{}:{placement:c}});if(typeof d!="boolean")throw new TypeError("dropTargetCb must return a boolean synchronously");return d}async invokeDrop(e,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,placement:c}){let u=this.records.get(e);!u||!u.resolved.onDrop||Object.keys(t).length===0||await this.html.callLogic(e,u.resolved.onDrop,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,...c===void 0?{}:{placement:c}})}async endDrag(e,{source:t,dropEffect:r},n){let i={source:t,dropEffect:r},s=[],a=this.records.get(e);try{a&&!a.binding.closed&&a.resolved.onDragEnd&&await this.html.callLogic(e,a.resolved.onDragEnd,i)}catch(l){s.push(l)}try{this.binding.gramlot.publish(n,i)}catch(l){s.push(l)}if(s.length)throw new AggregateError(s,"Drag completion notification failed")}get inlineCompiler(){return this.binding.inlineCompiler}evaluateExpressions(e,t){let r=this.#n.get(e)??super.evaluateExpressions(e,t),n=e._getMeta("gramlot_component");if(n?.presentationDefaults.length){let i=e.getAttr();this.#o.set(e,Object.fromEntries(Object.entries(r).filter(([s])=>Object.hasOwn(i,s)&&n.presentationDefaults.some(a=>s.startsWith(a)))))}if(this.html.hasLabelbox(e)||n?.presentationDefaults.length){let i=[];for(let s=e.parentNode;s;s=s.parentNode)this.#o.has(s)&&i.unshift(this.#o.get(s));r=Object.assign({},...i,r)}return this.#n.delete(e),this.#r.set(e,r),r}render(e,t={}){if(!(e instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(e._getMeta("data_element")||this.#t.has(e)||!this.binding.bindingFor(e)&&this.#l(e))return null;if(e.nodeTag)this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder);else if(!(e.value instanceof N))throw new TypeError("Source fragments must contain child SourceBags");return e.nodeTag?super.render(e,t):this.renderFragment(e,t)}renderFragment(e,{document:t=this.destination.ownerDocument,...r}={}){let n=t.createDocumentFragment(),i={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],start:t.createComment("source-fragment"),end:t.createComment("/source-fragment")};this.records.set(e,i),this.elements.set(n,i),n.append(i.start);for(let s of e.value.getNodes()){let a=this.render(s,{document:t,...r});if(a===null)continue;n.append(a);let l=this.elements.get(a);l&&(l.parent=i,i.children.add(s))}return n.append(i.end),n}renderedItem(e,t,r,{tag:n,document:i=this.destination.ownerDocument}={}){let s=r;t=this.expressionValue(e,t),this.getRender(e.builder)===this&&(s=this.restoreNativeAttributes(e,r),e._getMeta("gramlot_component")||([t,s]=un(t,s,(h,p)=>this._binding.gramlot.format(h,p)))),s=this.componentAttributes(e,s);let a=Array.isArray(t)?t:[],l=Array.isArray(t)?s._text:t,c=this.#r.get(e),u={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],resolved:c,...this.html.create(e,i,n,s,c.visible??null)};this.html.compose(u,l,a),u.labelbox&&u.cleanup.push(()=>u.labelbox.menu?.dispose()),u.shape=ve.shape(u.element,c),this.records.set(e,u),this.elements.set(u.element,u),this.elements.set(u.presentation,u);let d=ve.for(u.binding,u);(d||u.element.namespaceURI===be&&u.element.localName==="input")&&u.cleanup.push(()=>u.control?.detach()),d&&(u.control=d,d.attach(),this.#f(u,e,s,null));let f=Ki.for(u.binding,u);if(f&&(u.button=f,f.attach(),u.cleanup.push(()=>f.detach())),e.nodeTag==="menu"&&(u.menu=new Ji(u.binding,u.element),u.menu.attach(),u.cleanup.push(()=>u.menu.detach())),e.nodeTag==="groupletCard"){let h=new Qi(u.binding,u.element);h.attach(),u.cleanup.push(()=>h.detach())}this.#p(u),this.references?.register(e,u.element);for(let h of a){let p=this.elements.get(h);p&&(p.parent=u,p.container=u.element,u.children.add(p.node))}return u.presentation}validateCandidate(e,{replacingNode:t=null}={}){if(!(e instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");let r=new Set,n=a=>{if(!r.has(a)){r.add(a);for(let l of this.records.get(a)?.children??[])n(l);if(a.value instanceof N)for(let l of a.value.getNodes())n(l)}};for(let a of this.records.get(t)?.children??[])n(a);if(t?.value instanceof N)for(let a of t.value.getNodes())n(a);this.#i(e,t?t.nodeTag:null),nc(e),this.references?.validate(e,r);let i=new Set,s=a=>{for(let l of a.getNodes()){let c=l.getAttr("nodeId");if(c!=null){let u=this.binding.nodeIds.get(c);if(i.has(c)||u&&u!==l&&!r.has(u))throw new Error(`Duplicate nodeId '${c}'`);i.add(c)}l.value instanceof N&&s(l.value)}};return s(e),e}#i(e,t=null){let r=new Set,n=(i,s=null)=>{if(!(i instanceof de)||r.has(i))throw new TypeError("Source values must be unshared, acyclic GramlotBuilderBags");if(!(i._builder instanceof Ae))throw new TypeError("SourceBag requires builder ownership");r.add(i);for(let a of i.getNodes()){if(!(a instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(!(a.builder instanceof Ae))throw new TypeError("SourceBagNode requires builder ownership");if(a.resolver)throw new TypeError("Source resolvers are outside this port");if(a._getMeta("data_element"))a.builder.validateNode(a);else if(a.nodeTag){let l=a._getMeta("subbuilder")?i._builder:a.builder;this.html.validate(a,l),a._getMeta("subbuilder")||a.builder.validateParent(a.nodeTag,s)}else{if(!(a.value instanceof N))throw new TypeError("Source fragments must contain child SourceBags");if(Object.keys(a.attr).some(l=>l!=="_meta"))throw new TypeError("Fragment attributes are unsupported")}a.value instanceof N&&n(a.value,a._getMeta("subbuilder")?null:a.nodeTag??s)}};n(e,t)}freeze(e){e=Z(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Freeze requires a mounted Source node");t.frozen=!0}unfreeze(e){e=Z(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Unfreeze requires a mounted Source node");let r=n=>{delete n.frozen;for(let i of n.children)r(this.records.get(i))};r(t),!this.#s(e)&&(this.attached(e)?this.#g(e):this.remove(e))}#s(e){for(;e;){let t=this.records.get(e);if(t?.frozen)return!0;e=e.parentBag?.parentNode??t?.parent?.node}return!1}receive(e){if(this.disposed)return;let t=r=>this.#e.has(r)||e.evt==="del"&&r.nodeTag==="dataSetter";if(Array.isArray(e.node)){let r=e.node.filter(n=>!t(n));if(!r.length)return;e={...e,node:r}}else if(t(e.node))return;if(this.pending.push(e),!this.building){this.building=!0;try{for(;this.pending.length;){let r=this.pending.shift();if(r.evt!=="del"&&!this.attached(r.node))continue;r.evt!=="del"&&r.evt!=="upd_attrs"&&this.#c(r);let n=this.binding.handleSourceEvent(r);try{this.#a(r,n)}catch(i){if(!n.length)throw i;n.push(i)}if(this.binding.refreshSourceTrees(),n.length)throw n.length===1?n[0]:new AggregateError(n,"Source cleanup failed")}}catch(r){throw this.pending.length=0,r}finally{this.building=!1}}}#a(e,t){if(e.evt==="del"){for(let r of Array.isArray(e.node)?e.node:[e.node]){if(this.#s(r))continue;let n=this.records.get(r)?.parent??null;try{this.remove(r)}catch(i){t.push(i)}this.#h(n)}return}if(!this.#s(e.node))if(e.evt==="ins")this.insert(e.node);else if(e.evt.startsWith("upd_"))this.update(e.node,e.evt);else throw new Error(`Unsupported Source event: ${e.evt}`)}attached(e){let t=e.parentBag;for(;t&&t!==this.source;)t=t.parentNode?.parentBag;return t===this.source}#l(e){let t=new Set(this.pending.flatMap(r=>Array.isArray(r.node)?r.node:[r.node]));for(let r=e;r;r=r.parentBag?.parentNode)if(t.has(r))return!0;return!1}#c(e){let t=r=>{if(!(r instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(r.value instanceof N){if(!(r.value instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");for(let n of r.value.getNodes())t(n)}};t(e.node)}unmountView(e){this.#t.add(e),this.remove(e)}mountView(e){this.#t.delete(e),this.insert(e)}insert(e){if(!this.attached(e)||this.records.has(e))return;for(let s=e;s;s=s.parentNode)if(this.#t.has(s))return;if(e._getMeta("data_element")){this.records.get(e.parentBag?.parentNode)?.button?.refresh(),this.binding.branchBuilt(e);return}let t=this.records.get(e.parentBag?.parentNode),r=t?.element??t?.container??this.destination,n=e.parentBag.getNodes(),i=t?.end??null;for(let s=n.indexOf(e)+1;s<n.length;s++){let a=this.records.get(n[s]);if(a){i=a.presentation??a.start;break}}this.buildNode(e,r,i,t)}buildNode(e,t,r=null,n=null){this.#e.add(e);let i;try{i=this.render(e,{document:t.ownerDocument})}catch(a){this.#u(e,a)}finally{this.#e.delete(e)}let s=this.records.get(e);return t.insertBefore(i,r),s.parent=n,this.assignContainer(s,t),n?.children.add(e),this.#h(n),this.binding.branchBuilt(e),s}#u(e,t){let r=[t],n=[],i=s=>{if(n.push(s),s.value instanceof N)for(let a of s.value.getNodes())i(a)};i(e);for(let s of n.reverse())try{this.remove(s)}catch(a){r.push(a)}throw r.length===1?t:new AggregateError(r,"Source build and cleanup failed")}mountDestination(e,t){let r=this.records.get(e);if(!r?.presentation||t?.nodeType!==1)throw new TypeError("mountDestination requires a mounted element and an HTML destination");if(r.presentation.contains(t))throw new Error("Destination cannot be inside the moved presentation");let n=r.parent;return this.remove(e),this.buildNode(e,t,null,n)}assignContainer(e,t){e.container=t;let r=e.element??t;for(let n of e.children){let i=this.records.get(n);i&&this.assignContainer(i,r)}}update(e,t){let r=this.records.get(e);if(!r){this.insert(e);return}let n=e.value==null||["string","number","boolean"].includes(typeof e.value),i=t==="upd_value"&&n&&r.element&&r.children.size===0&&this.html.matches(r,e);(t==="upd_attrs"||i)&&r.element&&this.html.matches(r,e)?(e.nodeTag&&this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder),this.project(e),t==="upd_attrs"&&this.records.get(e)===r&&(this.references?.remove(e),this.references?.register(e,r.element))):this.#g(e)}project(e,t=null){let r=this.records.get(e);if(!r?.element||!this.attached(e))return;let n=this.getRender(e.builder),i=this.#o.get(e),[s,a]=e.rootBuilder.runtimeValues(e),[,l]=n._handleMeta(e,a),c=this.#r.get(e),u=r.element.namespaceURI===be&&r.element.localName==="input"&&!Object.is(r.resolved.type,c.type),d=r.element.namespaceURI===be&&["input","select"].includes(r.element.localName)&&!!r.resolved.multiple!=!!c.multiple,f=r.resolved.group,h=r.control instanceof dn&&!Object.is(f??null,c.group??null);if((u||d||h)&&this.#s(e))return;if(r.shape!==ve.shape(r.element,c)){if(this.#s(e))return;this.#n.set(e,c);try{this.#g(e)}finally{this.#n.delete(e)}return}let p=u?ve.classFor(r.element,c):null,m=u&&(r.control?.constructor??null)!==p,b=(u||d&&r.element.localName==="input")&&!m&&r.control&&Object.is(r.resolved.value,c.value);if(m&&(r.control?.detach(),r.control=null),h&&!m&&c.group!=null&&e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);r.resolved=c;let w=e._getMeta("subbuilder")?l:n.adaptAttrs(l),_=e.value instanceof N,v=_?[]:this.expressionValue(e,s);if(n===this&&(w=this.restoreNativeAttributes(e,w),e._getMeta("gramlot_component")||([v,w]=un(v,w,(D,k)=>this._binding.gramlot.format(D,k)))),w=this.componentAttributes(e,w),this.html.update(r,e,w,_?w._text:v,c.visible??null,t),m&&p&&(r.control=new p(r.binding,r),r.control.attach()),h&&!m){r.control.refresh(f??null),this.records.get(e)===r&&!r.binding.closed&&this.project(e);return}b||this.#f(r,e,w,t),r.control?.refresh(),r.button?.refresh(),r.menu?.refresh(),this.#p(r);let E=this.#o.get(e);if(E){let D=new Set([...Object.keys(i??{}),...Object.keys(E)].filter(k=>!Object.is(i?.[k],E[k])));D.size&&this.#d(e,D)}(r.element.localName==="option"||r.element.localName==="optgroup")&&this.#h(r.parent)}#d(e,t){if(e.value instanceof N)for(let r of e.value.getNodes()){let n=r._getMeta("gramlot_component"),i=r.getAttr(),s=t;n?.presentationDefaults.length?s=new Set([...t].filter(a=>!Object.hasOwn(i,a))):this.html.hasLabelbox(r)&&[...t].some(a=>!Object.hasOwn(i,a))&&this.project(r),s.size&&this.#d(r,s)}}componentAttributes(e,t){let r=e._getMeta("gramlot_component"),n=e.parentNode?._getMeta("gramlot_component")?.childParameters;if(!r&&!n)return t;let i=this.#r.get(e),s=Object.fromEntries([...new Set([...Object.keys(r?.parameters??{}),...Object.keys(n??{}),...Object.keys(i).filter(a=>a.startsWith("validate_"))])].filter(a=>Object.hasOwn(i,a)).map(a=>[a,i[a]]));return{...t,...s}}#f(e,t,r,n){if(!e.control)return;let i=t.getAttr("value")!=null;(i||e.valueDeclared)&&e.control.project(r.value??null,n),e.valueDeclared=i}#p(e){let t=new Map(ho.declared(e.node).map(r=>[r[0],r]));if(!e.events){if(!t.size)return;e.events=new Map,e.cleanup.push(()=>{for(let r of e.events.values())r.detach();e.events.clear()})}for(let[r,n]of[...e.events])t.get(r)?.[2]!==n.handler&&(n.detach(),e.events.delete(r));for(let[r,[,n,i]]of t){if(e.events.has(r))continue;let s=new ho(e.binding,e,n,i,r);s.attach(),e.events.set(r,s)}}#h(e){for(let t=e;t;t=t.parent){if(t.control instanceof fo){this.project(t.node);return}if(t.element&&t.element.localName!=="optgroup")return}}getDomNode(e){let t=Z(e),r=this.records.get(t);return r&&this.attached(t)?r.element??null:null}getBaseSourceNode(e){for(let t=e;t;t=t.parentNode){let r=t.nodeType===1?this.elements.get(t):null;if(r)return this.attached(r.node)?r.node:null}return null}#m(e){let t=this.binding.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': rendered without an open NodeBinding`);return t}#g(e){let t=this.records.get(e),r=t.presentation?.nextSibling??t.end?.nextSibling??null,n=t.container,i=t.parent,s=null;try{this.remove(e)}catch(a){s=a}try{this.buildNode(e,n,r,i)}catch(a){throw s?new AggregateError([s,a],"Source replacement cleanup and commit failed"):a}if(s)throw s}onDispose(e,t){let r=this.records.get(e);if(!r)throw new Error("Source node is not mounted");return r.cleanup.push(t),()=>{let n=r.cleanup.indexOf(t);n!==-1&&r.cleanup.splice(n,1)}}remove(e){let t=this.records.get(e);if(!t)return;let r=[];for(let n of[...t.children])try{this.remove(n)}catch(i){r.push(i)}for(let n of t.cleanup.splice(0).reverse())try{n()}catch(i){r.push(i)}if(this.references?.remove(e),t.element&&this.elements.delete(t.element),t.presentation&&this.elements.delete(t.presentation),t.presentation?.remove(),t.start?.remove(),t.end?.remove(),t.parent?.children.delete(e),this.records.delete(e),this.#r.delete(e),this.#o.delete(e),r.length)throw new AggregateError(r,"Source cleanup failed")}dispose(){if(this.disposed)return;this.disposed=!0,this.dragDrop.dispose(),this.source.unsubscribe(this.subscription,{any:!0}),this.pending.length=0;let e=[],t=[...this.records.entries()].filter(([,r])=>!r.parent).map(([r])=>r);for(let r of t)try{this.remove(r)}catch(n){e.push(n)}if(e.length)throw new AggregateError(e,"Renderer cleanup failed")}};var Wb=new Set(["page","constructor"]);function zf(o,e){if(o===null)return[];let t=o.split("/");for(let r of t)if(Wb.has(r))throw new Error(`${e}: a logic group cannot be named '${r}' (group '${o}')`);return t}var Gb=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function Hb(o){return/^[\w$]/.test(o)?Gb.has(o):o!==")"&&o!=="]"}function Xb(o,e){let t=!1;for(let r=e+1;r<o.length;r++){let n=o[r];if(n===`
228
+ `))})}#s(e,t,r){let n=this.#e.gramlot,i=JSON.stringify([t,e]);if(this.#o.has(i))return;let s=this.#e.nodeIds.get(this.#t);if(!s){if(this.#n.clear(),this.#i=0,this.#r===null){let p=this;class m{close(w){p.#a(w.getAttr("notice"))}}this.#r=`errors_${G()}`,this.#e.logicRegistry.register(m,{group:this.#r,resource:"gramlot:error-notifications"})}let h=new me;h.root.aside({nodeId:this.#t,class:"gramlot-error-notifications",popover:"manual","aria-label":"Error notifications",style:"position:fixed;inset:auto max(12px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) auto;margin:0;width:360px;max-width:calc(100vw - 24px);max-height:50vh;overflow:auto;box-sizing:border-box;padding:0;border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:8px;background:var(--gramlot-surface,#fff);color:var(--gramlot-ink,#222);font:13px/1.4 system-ui;box-shadow:0 6px 24px #0003;"}),n.src.source.setItem(this.#t,n.src.prepareSource(h.source)),s=this.#e.nodeIds.get(this.#t)}if(this.#n.has(i))return;if(this.#n.size===5){let h=`${++this.#i} additional errors`,p=s.value.getNode("overflow");p?p.setValue(h):n.src.builder.wrapSource(s).p(h,{node_label:"overflow",role:"status",style:"margin:0;padding:12px;"});return}let a=`notice_${G()}`,l=new me,c=l.root.article({role:"alert",style:"color:inherit;padding:12px;border-bottom:1px solid var(--gramlot-border,#ddd);"}),u=c.div({style:"display:flex;align-items:start;gap:12px;"});u.strong(`==${JSON.stringify(t)}`,{style:"flex:1;color:var(--gramlot-error,#b13d48);"}),u.html_button("\xD7",{type:"button",notice:a,connect_onclick:`${this.#r}.close`,"aria-label":"Dismiss notification",title:"Dismiss notification",style:"border:0;background:transparent;color:inherit;font:18px/1 system-ui;width:24px;height:24px;flex:0 0 24px;padding:0;cursor:pointer;"}),c.p(`==${JSON.stringify(e)}`,{style:"margin:6px 0;overflow-wrap:anywhere;"});let d=c.details({style:"border:0;padding:0;margin:8px 0 0;background:transparent;"});d.summary("Details",{style:"cursor:pointer;"}),d.pre(`==${JSON.stringify(r)}`,{style:"font:11px/1.4 monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:6px 0 0;padding:8px;border:0;border-radius:4px;background:var(--gramlot-surface-subtle,#f2f4f6);"});let f=n.src.builder.wrapSource(s).div({node_label:a});Z(f).setValue(n.src.prepareSource(l.source)),this.#n.set(i,a),n.dom.getDomNode(s).showPopover()}#a(e){this.#e.nodeIds.get(this.#t).value.popNode(e);for(let[r,n]of this.#n)n===e&&(this.#n.delete(r),this.#o.add(r));this.#n.size||this.#e.gramlot.src.source.popNode(this.#t)}};var Mf={dataFormula:us,dataController:ds,dataRpc:fs,dataRemote:hs},Vb=["datapath","_anchor","nodeId","form","formId"],gn=class{#e;#t=new Map;#r=new Map;#n;#o;#i;#s;#a;#l;#c=`gramlot-data-${G()}`;#u=!1;#d=new Set;#f=new Set;#p=new WeakMap;constructor(e,{subscriptions:t}){this.#e=e,this.#l=t,this.#n=new is(this),this.#o=new ls(this),this.#i=new ps(this),this.#s=new bs(this),this.#a=new ws(this)}get gramlot(){return this.#e}reportError(e,t){this.disposed||this.#a.show(e,t)}get subscriptions(){return this.#l}get builder(){return this.gramlot.src.builder}get renderer(){return this.gramlot.src.renderer}get logicRegistry(){return this.gramlot.src.logicRegistry}get data(){return this.builder.data}treeStore(e){if(e.treeStore!==null)return e.treeStore;let t=e.getAttr("storepath");if(t==="*S"||t.startsWith("*S.")){let r=this.renderer.source.getItem("main");return t==="*S"?r:r.getItem(t.slice(3))}return t==="*D"||t.startsWith("*D.")?t==="*D"?this.data:this.data.getItem(t.slice(3)):e.getRelativeData(t)}registerTreeRoot(e,t){let r=t?this.#d:this.#f;return r.add(e),{close:()=>r.delete(e)}}refreshSourceTrees(){for(let e of[...this.#d])!e.closed&&this.renderer.attached(e.node)&&this.renderer.project(e.node)}get root(){return this.data.parent}get size(){return this.#t.size}get disposed(){return this.#u}get router(){return this.#n}get installer(){return this.#o}get inlineCompiler(){return this.#i}get askDialog(){return this.#s}get nodeIds(){return this.#r}collectionStore(e,t){if(this.disposed)throw new Error("BindingRuntime is disposed");let r=this.#p.get(e);if(!r)r=new yo(e,t),this.#p.set(e,r);else if(r.rowMode!==t)throw new TypeError("A shared collection store requires one rowMode");return r}collectionView(e,t,r){let n=this.collectionStore(t,r);return Object.hasOwn(e,"gridCollectionView")?e.gridCollectionView.bindStore(n):Object.defineProperty(e,"gridCollectionView",{value:new xo(n),configurable:!0}),e.gridCollectionView}attach(){this.root.subscribe(this.#c,{any:e=>this.receiveData(e)})}receiveData(e){let t=this.root;for(let[r,n]of(e.pathlist??[]).entries()){let i=t.node(n)?.staticValue;if(!(i instanceof x))break;this.#p.get(i)?.receiveData(e,r+1<e.pathlist.length?i.node(e.pathlist[r+1]):null,e.pathlist[r+2]??null),t=i}this.router.deliver(e);for(let r of[...this.#f])!r.closed&&this.renderer.attached(r.node)&&this.renderer.project(r.node)}bindingFor(e){return this.#t.get(e)??null}openBinding(e){if(this.disposed)throw new Error("BindingRuntime is disposed");let t=this.bindingFor(e);return t||(t=new ic(this,e),this.#t.set(e,t)),t}closeBranch(e){let t=[];if(e.value instanceof N)for(let n of e.value.getNodes())try{this.closeBranch(n)}catch(i){t.push(i)}let r=this.bindingFor(e);if(r){this.#t.delete(e);let n=e.getAttr("nodeId");this.nodeIds.get(n)===e&&this.nodeIds.delete(n);try{r.close()}catch(i){t.push(i)}}if(t.length)throw new AggregateError(t,"Source branch close failed")}rebindBranch(e){let t=this.#_(e);for(let r of t)this.bindingFor(r)?.rebind();for(let r of t)this.renderer.project(r);for(let r of t)this.bindingFor(r)?.remote?.trigger()}handleSourceEvent(e){let{evt:t,node:r}=e,n=[],i=s=>{try{this.closeBranch(s)}catch(a){n.push(a)}};try{if(t==="ins")this.#h(r);else if(t==="del")for(let s of Array.isArray(r)?r:[r])i(s);else if(t==="upd_value"||t==="upd_value_attr"){if(e.oldvalue instanceof N)for(let s of e.oldvalue.getNodes())i(s);this.inlineCompiler.release(r,[""]),t==="upd_value_attr"?this.#b(r,e.attrs_diff):this.#w(r).rebind(),r.value instanceof N&&this.#h(r.value)}else if(t==="upd_attrs")this.#b(r,e.attrs_diff);else throw new Error(`Unsupported Source event: ${t}`)}catch(s){throw n.length?new AggregateError([...n,s],"Source event failed"):s}return n}branchBuilt(e){let t=[];for(let r of this.#_(e)){let n=this.bindingFor(r);!n||n.hasStamp("built")||!this.renderer.attached(r)||(n.stamp("built"),t.push(n))}for(let r of t)this.renderer.attached(r.node)&&this.#g(r,"built","_onBuilt");if(this.gramlot.state==="started")for(let r of t)this.renderer.attached(r.node)&&this.#m(r)}pageStarted(){for(let e of[...this.#t.values()])!e.closed&&e.hasStamp("built")&&this.#m(e)}dispose(){if(this.disposed)return;this.#u=!0,this.root.unsubscribe(this.#c,{any:!0}),this.nodeIds.clear(),this.#p=new WeakMap;let e=[];for(let[t,r]of[...this.#t.entries()].reverse()){this.#t.delete(t);try{r.close()}catch(n){e.push(n)}}if(e.length)throw new AggregateError(e,"Binding cleanup failed")}#h(e){if(!(e instanceof N)&&this.bindingFor(e))return;let t=e instanceof N?e.getNodes().flatMap(i=>this.#_(i)):this.#_(e),r=new Set(t.filter(i=>this.bindingFor(i))),n=new Map;for(let i of t){let s=i.getAttr("nodeId");if(s!=null){if(n.has(s)||this.nodeIds.has(s)&&this.nodeIds.get(s)!==i)throw new Error(`Duplicate nodeId '${s}'`);n.set(s,i)}}for(let[i,s]of n)this.nodeIds.set(i,s);try{for(let i of t)this.openBinding(i);this.installer.install(e);for(let i of t)this.renderer.attached(i)&&this.bindingFor(i).registerPointers()}catch(i){let s=[i];for(let a of t.filter(l=>!r.has(l)).reverse()){let l=a.getAttr("nodeId");n.get(l)===a&&this.nodeIds.get(l)===a&&this.nodeIds.delete(l);let c=this.bindingFor(a);if(c){this.#t.delete(a);try{c.close()}catch(u){s.push(u)}}}throw s.length>1?new AggregateError(s,"Source branch installation failed"):i}for(let i of t){let s=this.bindingFor(i);if(!(!s||s.hasStamp("init")||!this.renderer.attached(i))&&(s.stamp("init"),Lf(i.getAttr("_init"))))for(let a of s.providers)a.invoke({kind:"init",change:null})}}#m(e){e.hasStamp("start")||(e.stamp("start"),this.#g(e,"start","_onStart"),e.remote?.trigger())}#g(e,t,r){let n=e.node.getAttr(r);if(Lf(n))for(let i of e.providers){if(typeof n!="number"||n<=0){i.invoke({kind:t,change:null});continue}let s=null,a=setTimeout(()=>{s(),i.invoke({kind:t,change:null})},n);s=e.track(()=>clearTimeout(a))}}#b(e,t){let r=this.#w(e);if(this.inlineCompiler.release(e,Object.keys(t)),Object.hasOwn(t,"nodeId")){let{old:n,new:i}=t.nodeId;if(i!=null&&this.nodeIds.has(i)&&this.nodeIds.get(i)!==e)throw new Error(`Duplicate nodeId '${i}'`);this.nodeIds.get(n)===e&&this.nodeIds.delete(n),i!=null&&this.nodeIds.set(i,e)}Vb.some(n=>Object.hasOwn(t,n))?this.rebindBranch(e):r.rebind()}#w(e){let t=this.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': the node has no NodeBinding (its installation failed); remove it from the Source and insert it again`);return t}#_(e){let t=[e];if(e.value instanceof N)for(let r of e.value.getNodes())t.push(...this.#_(r));return t}};function Lf(o){return o===!0||typeof o=="number"}var ic=class{#e;#t;#r=!1;#n=[];#o=[];#i=new Set;#s=null;#a=null;#l=null;#c=new Set;#u=new Set;#d=0;#f=new Set;#p=null;editingSession=null;constructor(e,t){this.#e=e,this.#t=t}get runtime(){return this.#e}get node(){return this.#t}get closed(){return this.#r}get registrations(){return[...this.#o]}get providers(){return this.#s?[this.#s]:[]}get remote(){return this.#l}get clickCount(){return this.#d}countClick(){return++this.#d}hasStamp(e){return this.#i.has(e)}stamp(e){this.#i.add(e)}registerPointers(){this.node._getMeta("data_element")&&(this.runtime.renderer.references.remove(this.node),this.runtime.renderer.references.register(this.node,null));let e=this.node,t=e._getMeta("data_element");if(t&&!Mf[e.nodeTag]&&e.nodeTag!=="dataBinder")return;!t&&typeof e.getAttr("remote")=="string"?this.#l??=new ms(this):this.#l&&(this.#l.close(),this.#l=null);let r=new Set,n=e._getMeta("gramlot_component");for(let[s,a]of[["bagStore","storepath"],["bagStruct","structpath"]]){if(!n?.[s])continue;if(s==="bagStore"&&e.nodeTag==="tree"&&e.treeStore!==null){let d=e.treeStore,f=`gramlot-tree-${G()}`;d.subscribe(f,{any:()=>{!this.closed&&this.runtime.renderer.attached(e)&&this.runtime.renderer.project(e)}}),this.#o.push({close:()=>d.unsubscribe(f,{any:!0})});continue}let l=e.getAttr(a);if(typeof l!="string"||!l||/^[\^=]/.test(l)||l.includes("?"))throw new TypeError(`${a} requires a plain Bag data path`);if(s==="bagStore"&&e.nodeTag==="tree"&&(l==="*S"||l.startsWith("*S."))){this.#o.push(this.runtime.registerTreeRoot(this,!0));continue}if(s==="bagStore"&&e.nodeTag==="tree"&&l==="*D"){this.#o.push(this.runtime.registerTreeRoot(this,!1));continue}let c=s==="bagStore"&&e.nodeTag==="tree"&&l.startsWith("*D.")?l.slice(3):e.absDatapath(l),u=this.runtime.router.register({path:c,recipient:this,subtree:!0});this.#o.push(u),s==="bagStore"&&n.bagStruct&&(this.#p=u)}let i=this.remote?Ze(e,e.getAttr("_timing")):new Set;if(this.remote){for(let[s,a]of Object.entries(e.getAttr()))if(s.startsWith("remote_"))for(let l of Ze(e,a))r.add(l)}for(let[s,a]of e.pointers()){if(t&&s!=="datapath")continue;let c=(s==="datapath"?e.parentNode:e).absDatapath(a);if(c===null)continue;let[u,d=null]=c.split("?",2),f=this.runtime.router.register({path:u,attr:d,recipient:this});this.#o.push(f),s==="datapath"&&this.#f.add(f),this.remote&&(s==="remote"||s.startsWith("remote_")||r.has(s))&&this.#c.add(f),this.remote&&(s==="_timing"||i.has(s))&&this.#u.add(f)}if(!t){this.#h(),this.remote?.register();return}if(e.nodeTag==="dataBinder"){this.#a??=new gs(this),this.#a.register();return}this.#s??=new Mf[e.nodeTag](this),this.#s.register()}#h(){let e=this.node;this.#o.push(...this.runtime.subscriptions.subscribeNode(e,(t,r)=>{if(typeof r!="string"||!r)throw new TypeError(`${t} requires a handler`);return n=>{if(this.closed)return;if(lo(r))return Tt(this.runtime,e,r,n);let[,i]=e.rootBuilder.runtimeValues(e),s=Object.fromEntries(Object.entries(i).filter(([l])=>!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),a={...this.runtime.renderer.references.resolveArguments(s),p_0:n};return this.runtime.inlineCompiler.compile(e,t,r,Object.keys(a))(a)}}))}rebind(){this.#m(),this.registerPointers(),this.editingSession?.refreshField(this.node)}receive(e){if(!(e.registration===this.#p&&(e.level==="child"||e.evt==="upd_attrs"))){if(this.#f.has(e.registration)){this.runtime.rebindBranch(this.node);return}this.#c.has(e.registration)&&this.remote.receive(e),this.#u.has(e.registration)&&this.remote.register(),this.editingSession?.refreshField(this.node),this.runtime.renderer.project(this.node,e)}}track(e){if(this.closed)throw new Error(`NodeBinding of '${this.node.label}' is closed`);return this.#n.push(e),()=>{let t=this.#n.indexOf(e);t!==-1&&this.#n.splice(t,1)}}async call(e,t){let{controller:r}=t,n=this.track(()=>r.abort());try{let i=await this.runtime.gramlot.rpc.call(e,t.method,t.params,{signal:r.signal});if(r.signal.aborted)throw r.signal.reason;return i}finally{n()}}callSync(e,t,r){return this.node.requests.submitSync(t,()=>this.runtime.gramlot.rpc.callSync(e,t,r))}close(){if(this.closed)return;this.#r=!0,this.#l?.close(),this.node._getMeta("data_element")&&this.runtime.renderer.references.remove(this.node),this.#m();let e=[];for(let t of this.#n.splice(0).reverse())try{t()}catch(r){e.push(r)}if(e.length)throw new AggregateError(e,`NodeBinding of '${this.node.label}' cleanup failed`)}#m(){this.#a?.unregister();for(let e of this.#o.splice(0))e.close();this.#p=null,this.#f.clear(),this.#c.clear(),this.#u.clear()}};var _s=class{constructor(e){this.renderer=e}prepare(e,t){let r=this.renderer.records.get(e);if(!r||r.resolved.draggable!==!0)return null;let n=e._getMeta("gramlot_component")?.dragSource?r.element.getDragContext(t):{dragValues:{},item:void 0,path:void 0};if(n===null)return null;let{dragValues:i,item:s,path:a}=n;if(r.resolved.onDrag){let c=this.renderer.html.callLogic(e,r.resolved.onDrag,{dragValues:i,item:s,path:a});if(c&&typeof c.then=="function")throw new TypeError("onDrag must run synchronously");if(c===!1)return null}return Qe(i),{dragValues:Object.fromEntries(Object.entries(i).map(([c,u])=>{if(c.startsWith("text/")||c==="dragTags"){if(typeof u!="string")throw new TypeError(`${c} drag data must be text`);return[c,u]}return[c,j(R(u))]})),item:s,path:a}}};var er=class{static isTarget(e){return e.dropTarget===!0||!!e.dropTargetCb||Object.entries(e).some(([t,r])=>t.startsWith("dropTargetCb_")&&!!r)}static acceptedTypes(e,t="",r=[]){let n=t.split(",").map(i=>i.trim()).filter(Boolean).map(i=>{let s=i.split("*").map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return new RegExp(`^${s.join(".*")}$`)});return e.filter(i=>i!=="dragTags"&&(r.includes(i)||n.some(s=>s.test(i))))}static acceptsTags(e="",t=""){if(!t.trim())return!0;let r=new Set(e.split(",").map(n=>n.trim()).filter(Boolean));return r.size?t.split(",").some(n=>n.split(" AND ").every(i=>(i=i.trim(),!i||i==="!"?!1:i.startsWith("!")?!r.has(i.slice(1)):r.has(i)))):!1}static acceptsEffect(e="all",t="move"){let r={all:["copy","move","link"],none:[],copy:["copy"],move:["move"],link:["link"],copyMove:["copy","move"],copyLink:["copy","link"],linkMove:["link","move"]};if(!Object.hasOwn(r,e))throw new TypeError(`Invalid effectAllowed: ${e}`);if(!["copy","move","link"].includes(t))throw new TypeError(`Invalid dropEffect: ${t}`);return r[e].includes(t)}static evaluate(e,t,r,n,i=[]){let s=this.acceptedTypes(e,n.dropTypes,i),a=n.dropEffect??"move",l=this.isTarget(n)&&s.length>0&&this.acceptsTags(t,n.dropTags)&&this.acceptsEffect(r,a);return{accepted:l,types:s,dropEffect:l?a:"none"}}};var Ff=["dragstart","dragover","dragleave","drop","dragend"],ys=class{#e;#t;#r=null;#n=null;#o=null;#i;constructor(e){this.#e=e,this.#t=e.destination.ownerDocument;for(let t of Ff)this.#t.addEventListener(t,this);this.#i=()=>this.#b("none"),this.#t.defaultView.addEventListener("pagehide",this.#i)}handleEvent(e){e.type==="dragstart"?this.#l(e):e.type==="dragend"?this.#b(e.dataTransfer.dropEffect):e.type==="dragleave"?this.#h():e.type==="dragover"?this.#d(e):e.type==="drop"&&this.#f(e)}#s(e,t){for(let r of e.composedPath()){let n=this.#e.elements.get(r);if(n&&t(n.resolved))return n}return null}#a(e,t){return e.node._getMeta("gramlot_component")?.dragSource?e.element.getDragContext(t):{element:e.element,item:void 0,path:void 0}}#l(e){let t=this.#s(e,r=>r.draggable===!0);if(t){this.#b("none");try{let r=this.#e.prepareDrag(t.node,e);if(!r||!t.element.isConnected||this.#e.records.get(t.node)!==t){e.preventDefault();return}let n=this.#a(t,e);if(!n){e.preventDefault();return}let i=new Map(Object.entries(r.dragValues).filter(([c])=>c!=="dragTags").map(([c,u])=>[c,c.startsWith("text/")?u:R(u)]));if(!i.size){e.preventDefault();return}let s=t.resolved.effectAllowed??"all";er.acceptsEffect(s,"move");let a="";for(let c=t;c;c=c.parent)if(c.resolved?.dragTags!=null){a=c.resolved.dragTags;break}let l=this.#r={record:t,wires:i,effectAllowed:s,phase:"active",tags:[a,r.dragValues.dragTags].filter(Boolean).join(","),endTopic:this.#e.binding.subscriptions.topicFor(t.node,"endDrag"),source:{pageId:this.#e.binding.gramlot.pageId??null,sourcePath:t.node.fullpath,itemPath:r.path??null},preview:null,release:null};e.dataTransfer.clearData();for(let[c,u]of i)e.dataTransfer.setData(c,u);e.dataTransfer.effectAllowed=s,this.#o=this.#t.createElement("style"),this.#o.textContent=".canBeDropped{outline:2px solid var(--gramlot-brand-blue,#3766b5);outline-offset:-2px}.cannotBeDropped{outline:2px dashed currentColor;outline-offset:-2px}.draggedItem{opacity:.75}",this.#t.head.append(this.#o),this.#c(l,n.element,e.dataTransfer),l.release=this.#e.onDispose(t.node,()=>this.#b("none"))}catch(r){e.preventDefault(),this.#g(),this.#w(r)}}}#c(e,t,r){let n=t.cloneNode(!0);n.removeAttribute("id");for(let i of n.querySelectorAll("[id]"))i.removeAttribute("id");n.setAttribute("aria-hidden","true"),n.classList.add(...(e.record.resolved.dragClass??"draggedItem").split(/\s+/).filter(Boolean)),Object.assign(n.style,{position:"fixed",left:"-10000px",top:"0",width:`${t.getBoundingClientRect().width}px`,pointerEvents:"none"}),t.parentNode.append(n),e.preview=n,r.setDragImage(n,0,0)}#u(e){let t=this.#r,r=this.#s(e,c=>er.isTarget(c));if(!r)return null;let n=this.#a(r,e);if(!n)return{record:r,element:r.element,accepted:!1};let i=er.evaluate([...t.wires.keys()],t.tags,t.effectAllowed,r.resolved),a={dropValues:Object.fromEntries(i.types.map(c=>[c,c.startsWith("text/")?t.wires.get(c):j(t.wires.get(c))])),item:n.item,path:n.path,source:{...t.source},selfdrop:r===t.record,dropEffect:i.dropEffect,dataAvailable:!0};n.placement!==void 0&&(a.placement=n.placement);let l=i.accepted&&this.#e.checkDropTarget(r.node,a)&&this.#e.records.get(r.node)===r&&n.element.isConnected;return{record:r,element:n.element,accepted:l,context:a}}#d(e){if(!this.#r){this.#s(e,t=>er.isTarget(t))&&(e.preventDefault(),e.dataTransfer.dropEffect="none");return}if(e.preventDefault(),this.#r.phase!=="active"){e.dataTransfer.dropEffect="none";return}try{let t=this.#r,r=this.#u(e);if(this.#r!==t){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r?.accepted?r.context.dropEffect:"none",this.#h(),r&&this.#p(r.element,r.accepted)}catch(t){e.dataTransfer.dropEffect="none",this.#r&&(this.#r.phase="rejected"),this.#m(),this.#w(t)}}async#f(e){if(!this.#r){this.#s(e,n=>er.isTarget(n))&&e.preventDefault();return}if(e.preventDefault(),this.#r.phase!=="active")return;let t=this.#r,r;try{if(r=this.#u(e),this.#r!==t){e.dataTransfer.dropEffect="none";return}if(t.phase="dropped",this.#m(),!r?.accepted){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r.context.dropEffect,r.record.node.publish("onDrop",r.context),await this.#e.invokeDrop(r.record.node,r.context)}catch(n){this.#r===t&&(t.phase="rejected",this.#m()),(!r||this.#e.records.has(r.record.node))&&this.#w(n)}}#p(e,t){let r=t?"canBeDropped":"cannotBeDropped",n=(e.getAttribute("part")??"").split(/\s+/).filter(Boolean);this.#n={element:e,name:r,hadClass:e.classList.contains(r),hadPart:n.includes(r)},e.classList.add(r),n.includes(r)||e.setAttribute("part",[...n,r].join(" "))}#h(){if(!this.#n)return;let{element:e,name:t,hadClass:r,hadPart:n}=this.#n;r||e.classList.remove(t),n||e.setAttribute("part",(e.getAttribute("part")??"").split(/\s+/).filter(i=>i!==t).join(" ")),this.#n=null}#m(){this.#h(),this.#r&&(this.#r.preview?.remove(),this.#r.preview=null,this.#r.wires.clear())}#g(){let e=this.#r;return this.#m(),this.#r=null,e?.release?.(),this.#o?.remove(),this.#o=null,e}#b(e){let t=this.#g();!t||this.#e.disposed||this.#e.endDrag(t.record.node,{source:{...t.source},dropEffect:e},t.endTopic).catch(r=>this.#w(r))}#w(e){this.#e.binding.reportError(e,"Drag and drop failed")}dispose(){this.#g();for(let e of Ff)this.#t.removeEventListener(e,this);this.#t.defaultView.removeEventListener("pagehide",this.#i)}};var Co=class extends Sr{static renderType="object";#e=new Set;#t=new WeakSet;#r=new WeakMap;#n=new WeakMap;#o=new WeakMap;constructor(e,t,r,{binding:n}={}){if(super(e),!(e instanceof Ae)||!(t instanceof de)||r?.nodeType!==1)throw new TypeError("GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination");if(!(n instanceof gn))throw new TypeError("GramlotRenderer requires a BindingRuntime");if(!(t._builder instanceof Ae))throw new TypeError("SourceBag requires builder ownership");this._binding=n,this.source=t,this.destination=r,this.html=new Ki({uploadContext:()=>({gramlot:n.gramlot,window:r.ownerDocument.defaultView}),metadataAttributes:["__ref"],format:(i,s)=>n.gramlot.format(i,s),reportError:(i,s,a)=>{this.records.has(i)&&n.reportError(s,a)},callLogic:(i,s,a)=>{let{group:l,method:c}=n.gramlot.src.logicRegistry.resolve(s,i);return c.call(l,i,a)},invokeScript:(i,s,a,l)=>dt(n,i,s,a,l,i.parentNode._getMeta("gramlot_component").childParameters[s].inline)}),this.records=new Map,this.references=new Qn(t),this.pending=[],this.building=!1,this.disposed=!1,this.elements=new WeakMap,this.dragPreparation=new _s(this),this.instanceId=G(),this.radioGroups=new Zi(this),this.dragDrop=new ys(this),this.subscription=`html-source-renderer-${this.instanceId}`,t.subscribe(this.subscription,{any:i=>this.receive(i)})}get binding(){return this._binding}prepareDrag(e,t){return this.dragPreparation.prepare(e,t)}checkDropTarget(e,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,placement:c}){let u=this.records.get(e);if(!u)return!1;if(!u.resolved.dropTargetCb)return!0;let d=this.html.callLogic(e,u.resolved.dropTargetCb,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,...c===void 0?{}:{placement:c}});if(typeof d!="boolean")throw new TypeError("dropTargetCb must return a boolean synchronously");return d}async invokeDrop(e,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,placement:c}){let u=this.records.get(e);!u||!u.resolved.onDrop||Object.keys(t).length===0||await this.html.callLogic(e,u.resolved.onDrop,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,...c===void 0?{}:{placement:c}})}async endDrag(e,{source:t,dropEffect:r},n){let i={source:t,dropEffect:r},s=[],a=this.records.get(e);try{a&&!a.binding.closed&&a.resolved.onDragEnd&&await this.html.callLogic(e,a.resolved.onDragEnd,i)}catch(l){s.push(l)}try{this.binding.gramlot.publish(n,i)}catch(l){s.push(l)}if(s.length)throw new AggregateError(s,"Drag completion notification failed")}get inlineCompiler(){return this.binding.inlineCompiler}evaluateExpressions(e,t){let r=this.#n.get(e)??super.evaluateExpressions(e,t),n=e._getMeta("gramlot_component");if(n?.presentationDefaults.length){let i=e.getAttr();this.#o.set(e,Object.fromEntries(Object.entries(r).filter(([s])=>Object.hasOwn(i,s)&&n.presentationDefaults.some(a=>s.startsWith(a)))))}if(this.html.hasLabelbox(e)||n?.presentationDefaults.length){let i=[];for(let s=e.parentNode;s;s=s.parentNode)this.#o.has(s)&&i.unshift(this.#o.get(s));r=Object.assign({},...i,r)}return this.#n.delete(e),this.#r.set(e,r),r}render(e,t={}){if(!(e instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(e._getMeta("data_element")||this.#t.has(e)||!this.binding.bindingFor(e)&&this.#l(e))return null;if(e.nodeTag)this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder);else if(!(e.value instanceof N))throw new TypeError("Source fragments must contain child SourceBags");return e.nodeTag?super.render(e,t):this.renderFragment(e,t)}renderFragment(e,{document:t=this.destination.ownerDocument,...r}={}){let n=t.createDocumentFragment(),i={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],start:t.createComment("source-fragment"),end:t.createComment("/source-fragment")};this.records.set(e,i),this.elements.set(n,i),n.append(i.start);for(let s of e.value.getNodes()){let a=this.render(s,{document:t,...r});if(a===null)continue;n.append(a);let l=this.elements.get(a);l&&(l.parent=i,i.children.add(s))}return n.append(i.end),n}renderedItem(e,t,r,{tag:n,document:i=this.destination.ownerDocument}={}){let s=r;t=this.expressionValue(e,t),this.getRender(e.builder)===this&&(s=this.restoreNativeAttributes(e,r),e._getMeta("gramlot_component")||([t,s]=un(t,s,(h,p)=>this._binding.gramlot.format(h,p)))),s=this.componentAttributes(e,s);let a=Array.isArray(t)?t:[],l=Array.isArray(t)?s._text:t,c=this.#r.get(e),u={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],resolved:c,...this.html.create(e,i,n,s,c.visible??null)};this.html.compose(u,l,a),u.labelbox&&u.cleanup.push(()=>u.labelbox.menu?.dispose()),u.shape=ve.shape(u.element,c),this.records.set(e,u),this.elements.set(u.element,u),this.elements.set(u.presentation,u);let d=ve.for(u.binding,u);(d||u.element.namespaceURI===be&&u.element.localName==="input")&&u.cleanup.push(()=>u.control?.detach()),d&&(u.control=d,d.attach(),this.#f(u,e,s,null));let f=Ji.for(u.binding,u);if(f&&(u.button=f,f.attach(),u.cleanup.push(()=>f.detach())),e.nodeTag==="menu"&&(u.menu=new Qi(u.binding,u.element),u.menu.attach(),u.cleanup.push(()=>u.menu.detach())),e.nodeTag==="groupletCard"){let h=new es(u.binding,u.element);h.attach(),u.cleanup.push(()=>h.detach())}this.#p(u),this.references?.register(e,u.element);for(let h of a){let p=this.elements.get(h);p&&(p.parent=u,p.container=u.element,u.children.add(p.node))}return u.presentation}validateCandidate(e,{replacingNode:t=null}={}){if(!(e instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");let r=new Set,n=a=>{if(!r.has(a)){r.add(a);for(let l of this.records.get(a)?.children??[])n(l);if(a.value instanceof N)for(let l of a.value.getNodes())n(l)}};for(let a of this.records.get(t)?.children??[])n(a);if(t?.value instanceof N)for(let a of t.value.getNodes())n(a);this.#i(e,t?t.nodeTag:null),oc(e),this.references?.validate(e,r);let i=new Set,s=a=>{for(let l of a.getNodes()){let c=l.getAttr("nodeId");if(c!=null){let u=this.binding.nodeIds.get(c);if(i.has(c)||u&&u!==l&&!r.has(u))throw new Error(`Duplicate nodeId '${c}'`);i.add(c)}l.value instanceof N&&s(l.value)}};return s(e),e}#i(e,t=null){let r=new Set,n=(i,s=null)=>{if(!(i instanceof de)||r.has(i))throw new TypeError("Source values must be unshared, acyclic GramlotBuilderBags");if(!(i._builder instanceof Ae))throw new TypeError("SourceBag requires builder ownership");r.add(i);for(let a of i.getNodes()){if(!(a instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(!(a.builder instanceof Ae))throw new TypeError("SourceBagNode requires builder ownership");if(a.resolver)throw new TypeError("Source resolvers are outside this port");if(a._getMeta("data_element"))a.builder.validateNode(a);else if(a.nodeTag){let l=a._getMeta("subbuilder")?i._builder:a.builder;this.html.validate(a,l),a._getMeta("subbuilder")||a.builder.validateParent(a.nodeTag,s)}else{if(!(a.value instanceof N))throw new TypeError("Source fragments must contain child SourceBags");if(Object.keys(a.attr).some(l=>l!=="_meta"))throw new TypeError("Fragment attributes are unsupported")}a.value instanceof N&&n(a.value,a._getMeta("subbuilder")?null:a.nodeTag??s)}};n(e,t)}freeze(e){e=Z(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Freeze requires a mounted Source node");t.frozen=!0}unfreeze(e){e=Z(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Unfreeze requires a mounted Source node");let r=n=>{delete n.frozen;for(let i of n.children)r(this.records.get(i))};r(t),!this.#s(e)&&(this.attached(e)?this.#g(e):this.remove(e))}#s(e){for(;e;){let t=this.records.get(e);if(t?.frozen)return!0;e=e.parentBag?.parentNode??t?.parent?.node}return!1}receive(e){if(this.disposed)return;let t=r=>this.#e.has(r)||e.evt==="del"&&r.nodeTag==="dataSetter";if(Array.isArray(e.node)){let r=e.node.filter(n=>!t(n));if(!r.length)return;e={...e,node:r}}else if(t(e.node))return;if(this.pending.push(e),!this.building){this.building=!0;try{for(;this.pending.length;){let r=this.pending.shift();if(r.evt!=="del"&&!this.attached(r.node))continue;r.evt!=="del"&&r.evt!=="upd_attrs"&&this.#c(r);let n=this.binding.handleSourceEvent(r);try{this.#a(r,n)}catch(i){if(!n.length)throw i;n.push(i)}if(this.binding.refreshSourceTrees(),n.length)throw n.length===1?n[0]:new AggregateError(n,"Source cleanup failed")}}catch(r){throw this.pending.length=0,r}finally{this.building=!1}}}#a(e,t){if(e.evt==="del"){for(let r of Array.isArray(e.node)?e.node:[e.node]){if(this.#s(r))continue;let n=this.records.get(r)?.parent??null;try{this.remove(r)}catch(i){t.push(i)}this.#h(n)}return}if(!this.#s(e.node))if(e.evt==="ins")this.insert(e.node);else if(e.evt.startsWith("upd_"))this.update(e.node,e.evt);else throw new Error(`Unsupported Source event: ${e.evt}`)}attached(e){let t=e.parentBag;for(;t&&t!==this.source;)t=t.parentNode?.parentBag;return t===this.source}#l(e){let t=new Set(this.pending.flatMap(r=>Array.isArray(r.node)?r.node:[r.node]));for(let r=e;r;r=r.parentBag?.parentNode)if(t.has(r))return!0;return!1}#c(e){let t=r=>{if(!(r instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(r.value instanceof N){if(!(r.value instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");for(let n of r.value.getNodes())t(n)}};t(e.node)}unmountView(e){this.#t.add(e),this.remove(e)}mountView(e){this.#t.delete(e),this.insert(e)}insert(e){if(!this.attached(e)||this.records.has(e))return;for(let s=e;s;s=s.parentNode)if(this.#t.has(s))return;if(e._getMeta("data_element")){this.records.get(e.parentBag?.parentNode)?.button?.refresh(),this.binding.branchBuilt(e);return}let t=this.records.get(e.parentBag?.parentNode),r=t?.element??t?.container??this.destination,n=e.parentBag.getNodes(),i=t?.end??null;for(let s=n.indexOf(e)+1;s<n.length;s++){let a=this.records.get(n[s]);if(a){i=a.presentation??a.start;break}}this.buildNode(e,r,i,t)}buildNode(e,t,r=null,n=null){this.#e.add(e);let i;try{i=this.render(e,{document:t.ownerDocument})}catch(a){this.#u(e,a)}finally{this.#e.delete(e)}let s=this.records.get(e);return t.insertBefore(i,r),s.parent=n,this.assignContainer(s,t),n?.children.add(e),this.#h(n),this.binding.branchBuilt(e),s}#u(e,t){let r=[t],n=[],i=s=>{if(n.push(s),s.value instanceof N)for(let a of s.value.getNodes())i(a)};i(e);for(let s of n.reverse())try{this.remove(s)}catch(a){r.push(a)}throw r.length===1?t:new AggregateError(r,"Source build and cleanup failed")}mountDestination(e,t){let r=this.records.get(e);if(!r?.presentation||t?.nodeType!==1)throw new TypeError("mountDestination requires a mounted element and an HTML destination");if(r.presentation.contains(t))throw new Error("Destination cannot be inside the moved presentation");let n=r.parent;return this.remove(e),this.buildNode(e,t,null,n)}assignContainer(e,t){e.container=t;let r=e.element??t;for(let n of e.children){let i=this.records.get(n);i&&this.assignContainer(i,r)}}update(e,t){let r=this.records.get(e);if(!r){this.insert(e);return}let n=e.value==null||["string","number","boolean"].includes(typeof e.value),i=t==="upd_value"&&n&&r.element&&r.children.size===0&&this.html.matches(r,e);(t==="upd_attrs"||i)&&r.element&&this.html.matches(r,e)?(e.nodeTag&&this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder),this.project(e),t==="upd_attrs"&&this.records.get(e)===r&&(this.references?.remove(e),this.references?.register(e,r.element))):this.#g(e)}project(e,t=null){let r=this.records.get(e);if(!r?.element||!this.attached(e))return;let n=this.getRender(e.builder),i=this.#o.get(e),[s,a]=e.rootBuilder.runtimeValues(e),[,l]=n._handleMeta(e,a),c=this.#r.get(e),u=r.element.namespaceURI===be&&r.element.localName==="input"&&!Object.is(r.resolved.type,c.type),d=r.element.namespaceURI===be&&["input","select"].includes(r.element.localName)&&!!r.resolved.multiple!=!!c.multiple,f=r.resolved.group,h=r.control instanceof dn&&!Object.is(f??null,c.group??null);if((u||d||h)&&this.#s(e))return;if(r.shape!==ve.shape(r.element,c)){if(this.#s(e))return;this.#n.set(e,c);try{this.#g(e)}finally{this.#n.delete(e)}return}let p=u?ve.classFor(r.element,c):null,m=u&&(r.control?.constructor??null)!==p,b=(u||d&&r.element.localName==="input")&&!m&&r.control&&Object.is(r.resolved.value,c.value);if(m&&(r.control?.detach(),r.control=null),h&&!m&&c.group!=null&&e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);r.resolved=c;let w=e._getMeta("subbuilder")?l:n.adaptAttrs(l),_=e.value instanceof N,v=_?[]:this.expressionValue(e,s);if(n===this&&(w=this.restoreNativeAttributes(e,w),e._getMeta("gramlot_component")||([v,w]=un(v,w,(D,k)=>this._binding.gramlot.format(D,k)))),w=this.componentAttributes(e,w),this.html.update(r,e,w,_?w._text:v,c.visible??null,t),m&&p&&(r.control=new p(r.binding,r),r.control.attach()),h&&!m){r.control.refresh(f??null),this.records.get(e)===r&&!r.binding.closed&&this.project(e);return}b||this.#f(r,e,w,t),r.control?.refresh(),r.button?.refresh(),r.menu?.refresh(),this.#p(r);let E=this.#o.get(e);if(E){let D=new Set([...Object.keys(i??{}),...Object.keys(E)].filter(k=>!Object.is(i?.[k],E[k])));D.size&&this.#d(e,D)}(r.element.localName==="option"||r.element.localName==="optgroup")&&this.#h(r.parent)}#d(e,t){if(e.value instanceof N)for(let r of e.value.getNodes()){let n=r._getMeta("gramlot_component"),i=r.getAttr(),s=t;n?.presentationDefaults.length?s=new Set([...t].filter(a=>!Object.hasOwn(i,a))):this.html.hasLabelbox(r)&&[...t].some(a=>!Object.hasOwn(i,a))&&this.project(r),s.size&&this.#d(r,s)}}componentAttributes(e,t){let r=e._getMeta("gramlot_component"),n=e.parentNode?._getMeta("gramlot_component")?.childParameters;if(!r&&!n)return t;let i=this.#r.get(e),s=Object.fromEntries([...new Set([...Object.keys(r?.parameters??{}),...Object.keys(n??{}),...Object.keys(i).filter(a=>a.startsWith("validate_"))])].filter(a=>Object.hasOwn(i,a)).map(a=>[a,i[a]]));return{...t,...s}}#f(e,t,r,n){if(!e.control)return;let i=t.getAttr("value")!=null;(i||e.valueDeclared)&&e.control.project(r.value??null,n),e.valueDeclared=i}#p(e){let t=new Map(po.declared(e.node).map(r=>[r[0],r]));if(!e.events){if(!t.size)return;e.events=new Map,e.cleanup.push(()=>{for(let r of e.events.values())r.detach();e.events.clear()})}for(let[r,n]of[...e.events])t.get(r)?.[2]!==n.handler&&(n.detach(),e.events.delete(r));for(let[r,[,n,i]]of t){if(e.events.has(r))continue;let s=new po(e.binding,e,n,i,r);s.attach(),e.events.set(r,s)}}#h(e){for(let t=e;t;t=t.parent){if(t.control instanceof ho){this.project(t.node);return}if(t.element&&t.element.localName!=="optgroup")return}}getDomNode(e){let t=Z(e),r=this.records.get(t);return r&&this.attached(t)?r.element??null:null}getBaseSourceNode(e){for(let t=e;t;t=t.parentNode){let r=t.nodeType===1?this.elements.get(t):null;if(r)return this.attached(r.node)?r.node:null}return null}#m(e){let t=this.binding.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': rendered without an open NodeBinding`);return t}#g(e){let t=this.records.get(e),r=t.presentation?.nextSibling??t.end?.nextSibling??null,n=t.container,i=t.parent,s=null;try{this.remove(e)}catch(a){s=a}try{this.buildNode(e,n,r,i)}catch(a){throw s?new AggregateError([s,a],"Source replacement cleanup and commit failed"):a}if(s)throw s}onDispose(e,t){let r=this.records.get(e);if(!r)throw new Error("Source node is not mounted");return r.cleanup.push(t),()=>{let n=r.cleanup.indexOf(t);n!==-1&&r.cleanup.splice(n,1)}}remove(e){let t=this.records.get(e);if(!t)return;let r=[];for(let n of[...t.children])try{this.remove(n)}catch(i){r.push(i)}for(let n of t.cleanup.splice(0).reverse())try{n()}catch(i){r.push(i)}if(this.references?.remove(e),t.element&&this.elements.delete(t.element),t.presentation&&this.elements.delete(t.presentation),t.presentation?.remove(),t.start?.remove(),t.end?.remove(),t.parent?.children.delete(e),this.records.delete(e),this.#r.delete(e),this.#o.delete(e),r.length)throw new AggregateError(r,"Source cleanup failed")}dispose(){if(this.disposed)return;this.disposed=!0,this.dragDrop.dispose(),this.source.unsubscribe(this.subscription,{any:!0}),this.pending.length=0;let e=[],t=[...this.records.entries()].filter(([,r])=>!r.parent).map(([r])=>r);for(let r of t)try{this.remove(r)}catch(n){e.push(n)}if(e.length)throw new AggregateError(e,"Renderer cleanup failed")}};var Wb=new Set(["page","constructor"]);function zf(o,e){if(o===null)return[];let t=o.split("/");for(let r of t)if(Wb.has(r))throw new Error(`${e}: a logic group cannot be named '${r}' (group '${o}')`);return t}var Gb=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function Hb(o){return/^[\w$]/.test(o)?Gb.has(o):o!==")"&&o!=="]"}function Xb(o,e){let t=!1;for(let r=e+1;r<o.length;r++){let n=o[r];if(n===`
229
229
  `)return-1;if(n==="\\"){r++;continue}if(n==="[")t=!0;else if(n==="]")t=!1;else if(n==="/"&&!t)return r}return-1}function Yb(o){let e=0,t="",r="";for(let n=o.indexOf("{");n<o.length;n++){let i=o[n];if(i==="/"&&o[n+1]==="/"){if(n=o.indexOf(`
230
- `,n),n<0)break;continue}if(i==="/"&&o[n+1]==="*"){let s=o.indexOf("*/",n+2);if(s>=0){n=s+1;continue}}if(i==="/"&&Hb(r)){let s=Xb(o,n);if(s>=0){n=s,r=")";continue}}if(i==='"'||i==="'"||i==="`"){let s=n+1;for(;s<o.length&&o[s]!==i;)s+=o[s]==="\\"?2:1;e===1&&(t+=o.slice(n+1,s)==="constructor"?" constructor":' ""'),n=s,r=")";continue}if(/[\w$]/.test(i)){let s=n+1;for(;s<o.length&&/[\w$]/.test(o[s]);)s++;e===1&&(t+=o.slice(n,s)),r=o.slice(n,s),n=s-1;continue}if(/\s/.test(i)||(r=i),i==="{"){++e===2&&(t+=" {}");continue}if(i==="}"){e--;continue}e===1&&(t+=i)}return/(?<![\w$.#])(?<!\bstatic\s+)constructor\s*\(/.test(t)}function qf(o,e){if(o===void 0)return[];if(typeof o!="function"||!/^class\b/.test(Function.prototype.toString.call(o)))throw new Error(`${e}: the module exports no class Logic`);if(Object.getPrototypeOf(o)!==Function.prototype||Object.getPrototypeOf(o.prototype)!==Object.prototype)throw new Error(`${e}: class Logic cannot extend another class`);if(Yb(Function.prototype.toString.call(o)))throw new Error(`${e}: class Logic cannot declare a constructor; state lives on the group or the page`);let t=[];for(let r of Reflect.ownKeys(o.prototype)){if(r==="constructor")continue;if(typeof r=="symbol")throw new Error(`${e}: class Logic cannot declare symbol keys (${String(r)})`);let n=Object.getOwnPropertyDescriptor(o.prototype,r);if(n.get||n.set)throw new Error(`${e}: class Logic cannot declare the accessor '${r}'`);if(typeof n.value!="function")throw new Error(`${e}: Logic.prototype.${r} is not a method`);if(r==="page")throw new Error(`${e}: a logic method cannot be named 'page'`);t.push([r,n.value])}return t}function Uf(o,e,t){Object.defineProperty(o,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}var $r=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get page(){return this.#t}},bn=class{#e;#t=new Map;constructor(e){this.#e=e,e.logic=new $r(this,e)}get gramlot(){return this.#e}static check(e){let t=new Map;for(let{group:r,resource:n}of e){let i=zf(r,n);for(let s=0;s<i.length;s++){let a=i.slice(0,s).join("/");t.has(a)||t.set(a,new Set),t.get(a).add(i[s])}}for(let{logicClass:r,group:n,resource:i}of e){let s=t.get(n??"")??new Set;for(let[a]of qf(r,i))if(s.has(a))throw new Error(`${i}: the logic method '${a}' has the name of a child group`)}}register(e,{group:t=null,resource:r}){let n=zf(t,r),i=qf(e,r),s=this.#e.logic;for(let a of n){let l=Object.getOwnPropertyDescriptor(s,a)?.value;if(l===void 0){let c=new $r(this,this.#e);Uf(s,a,c),s=c}else if(l instanceof $r)s=l;else throw new Error(`${r}: the group '${a}' has the name of a logic method`)}for(let[a,l]of i){if(Object.getOwnPropertyDescriptor(s,a)?.value instanceof $r)throw new Error(`${r}: the logic method '${a}' has the name of a child group`);Uf(s,a,l)}this.#t.has(s)||this.#t.set(s,[]),this.#t.get(s).push(r)}resolve(e,t){let r=e.split("."),n=r.pop(),i=this.#e.logic;for(let a=0;a<r.length;a++)if(i=Object.getOwnPropertyDescriptor(i,r[a])?.value,!(i instanceof $r))throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: no resource was registered for the group '${r.slice(0,a+1).join("/")}'`);let s=Object.getOwnPropertyDescriptor(i,n)?.value;if(typeof s!="function"){let a=this.#t.get(i)??[],l=r.length?`the group '${r.join("/")}'`:"the page logic";throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: ${l} has no method '${n}' (resources: ${a.join(", ")||"none"})`)}return{group:i,method:s}}};var Co=class extends Ne{constructor(e,{collections:t,destination:r,subscriptions:n,nameSyntax:i}){super(e),e.src=this,this.logicRegistry=new bn(e),this.builder=new me(null,{collections:t,nameSyntax:i}),this.binding=new gn(e,{subscriptions:n}),this.builder.binding=this.binding,this.binding.attach(),this.source=this.builder.source,this.renderer=new Io(this.builder,this.source,r,{binding:this.binding})}startSource(e){if(!["ready","failed"].includes(this.gramlot.state))throw new Error(`Cannot start embedded Source while Gramlot is ${this.gramlot.state}`);try{return this.mountMainSource(e)}catch(t){throw this.gramlot.state="failed",t}}mountMainSource(e,t=null){let r=this.prepareSource(e);if(this.renderer.validateCandidate(r),t!==null){if(!(t instanceof x)||t instanceof N)throw new TypeError("Initial page data must be a Data Bag");for(let n of t.getNodes())this.builder.data.setItem([n.label],n.getValue(),n.attr,">",!1,!1)}try{this.source.setItem("main",r)}catch(n){throw this.binding.bindingFor(this.source.getNode("main"))||this.source.popNode("main"),n}return this.gramlot.state="started",this.binding.pageStarted(),this.binding.subscriptions.ready(),this.gramlot}prepareSource(e,t=this.builder){if(e instanceof N){if(!(e instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");return e.bindBuilder(t).activateCode()}if(typeof e!="string")throw new TypeError("Source value did not decode to SourceBag");let r=Ri(e,t);if(!(r instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");return r.activateCode()}async remoteSource(e,t,r={}){if(!this.gramlot.rpc.transport?.call)throw new Error("Remote Source is unavailable without a server transport");let i=this.binding.bindingFor(e);if(this.gramlot.state!=="started"||!i)throw new Error("Remote Source target is not mounted");return await e.requests.submit(t,r,s=>this.#e(e,i,s))??!1}async#e(e,t,r){if(t.closed||this.gramlot.state==="disposed")return!1;let n=!1,i=()=>this.gramlot.state!=="disposed"&&!r.ignored&&!t.closed;try{let s=await t.call("source",r);if(!i())return!1;let a=this.prepareSource(s,e.builder);return i()?(this.renderer.validateCandidate(a,{replacingNode:e}),n=!0,e.setValue(a,!0,{_text:null},!0),t.remote?.fragmentMounted(r.method,r.text),!0):!1}catch(s){if(!n&&!i())return!1;throw s}}};var Do=class extends Ne{setTouchMode(e="auto"){if(!["auto","on","off"].includes(e))throw new TypeError(`Invalid touch mode: ${e}`);let t=this.gramlot.src.renderer.destination.ownerDocument.documentElement;e==="auto"?t.removeAttribute("data-gramlot-touch"):t.setAttribute("data-gramlot-touch",e)}navigate(e){if(typeof e!="string"||!e)throw new TypeError("Navigation requires an absolute HTTP(S) URL");let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw new TypeError("Navigation requires an HTTP(S) URL without credentials");this.gramlot.src.renderer.destination.ownerDocument.defaultView.location.assign(t.href)}reference(e){return this.gramlot.src.renderer.references.resolve(e)}getBaseSourceNode(e){return this.gramlot.src.renderer.getBaseSourceNode(e)}getDomNode(e){return this.gramlot.src.renderer.getDomNode(e)}};var ys=class extends Ne{#e=new Map;#t=new WeakSet;#r=new WeakMap;#n=0;#o=!1;ready(){this.gramlot._frames.ready()}subscribe(e,t){if(this.#a(),this.#s(e),typeof t!="function")throw new TypeError("subscribe requires a callback");let r=Object.freeze({});return this.#t.add(r),this.#e.has(e)||this.#e.set(e,new Map),this.#e.get(e).set(r,t),r}unsubscribe(e){if(!this.#t.has(e))throw new TypeError("Unknown subscription registration");for(let[t,r]of this.#e)r.delete(e)&&!r.size&&this.#e.delete(t)}publish(e,t={},r={}){if(this.#a(),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("publish requires one object of named data");if(typeof e=="string")return this.#i(e,t,r);if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("publish requires a topic string or descriptor");if(Object.keys(e).some(s=>!["topic","nodeId","parent","iframe","pageId","server"].includes(s)))throw new Error("This publication route is not implemented yet");if(this.#s(e.topic),e.parent!==void 0&&typeof e.parent!="boolean")throw new TypeError("parent must be boolean");if(e.server!==void 0&&typeof e.server!="boolean")throw new TypeError("server must be boolean");if(e.iframe==="*")throw new Error("Recursive iframe broadcast is not implemented yet");if(e.pageId!==void 0&&(typeof e.pageId!="string"||!e.pageId))throw new TypeError("pageId must be a nonempty string");if((e.parent||e.iframe!==void 0||e.pageId!==void 0)&&Object.hasOwn(e,"nodeId"))throw new Error("Interframe node addressing is not implemented yet");let i=null;if(e.server===!0){if(["parent","iframe","nodeId"].some(s=>Object.hasOwn(e,s)))throw new Error("Server publication cannot combine window or node selectors");if(!this.gramlot._pageStore)throw new Error("Server publication requires a WebSocket channel");i=this.gramlot._pageStore.preparePublish(e,t)}else(e.parent||e.iframe!==void 0||e.pageId!==void 0)&&(i=this.gramlot._frames.prepare(e,t));if(Object.hasOwn(e,"nodeId")){let s=this.gramlot.src.binding.nodeIds.get(e.nodeId);if(!s)throw new Error(`nodeId not found: ${e.nodeId}`);return this.publishNode(s,e.topic,t)}return this.#i(e.topic,t),i?.()}topicFor(e,t){this.#s(t),e=Z(e);let r=this.gramlot.src.binding.bindingFor(e);if(!r||r.closed)throw new Error("Topic target is not an active Source node of this page");let n=e.getAttr("nodeId");return n==null&&(this.#r.has(e)||this.#r.set(e,`gramlot-self-${++this.#n}`),n=this.#r.get(e)),`${n}_${t}`}publishNode(e,t,r={}){return this.publish(this.topicFor(e,t),r)}subscribeNode(e,t){let r=[];for(let[n,i]of Object.entries(e.getAttr())){let s=n.startsWith("selfsubscribe_")?"selfsubscribe_":n.startsWith("subscribe_")?"subscribe_":null;if(!s)continue;let a=s==="selfsubscribe_"?this.topicFor(e,n.slice(s.length)):n.slice(s.length);this.#s(a),r.push([a,t(n,i,a)])}return this.#a(),r.map(([n,i])=>{let s=this.subscribe(n,i);return{close:()=>this.unsubscribe(s)}})}dispose(){this.#o=!0,this.#e.clear()}#i(e,t,r={}){this.#s(e);let n=this.#e.get(e);if(n)for(let[i,s]of[...n]){if(this.#o)break;n.has(i)&&s(t,{...r})}}#s(e){if(typeof e!="string"||!e)throw new TypeError("A topic must be a nonempty string")}#a(){if(this.#o)throw new Error("Gramlot subscriptions are disposed")}};var vs=class extends Y{constructor(e,t,r){super({cacheTime:r}),this.handler=e,this.name=t,this.failed=!1,this.writing=!1,this.request=null,this.revision=0,this.received=0}resolve({static:e=!1}={}){return!e&&!this.handler.disposed&&!this.writing&&!this.request&&!this.failed&&!this._node.attr.watching&&this.expired&&this.handler.refresh(this.name),this.cachedValue}reset(){super.reset(),this.failed=!1,this.revision++}};var Vf=["appinfo","location"],Wf={UNAVAILABLE:"unavailable",PERMISSION_DENIED:"denied",TIMEOUT:"error",FAILED:"error",CANCELLED:"cancelled"};function K(o){let e=Object.hasOwn(Wf,o?.code)?o.code:"FAILED";return{status:Wf[e],error:e==="CANCELLED"?null:{code:e,message:String(o?.message??"Device operation failed")}}}var No=class extends Ne{#e=null;#t=null;#r=null;#n=null;#o=null;#i=null;#s=new Map;#a=new Map;#l=null;#c=null;#u=null;#d=null;#f=null;#p=null;#h=null;constructor(e){super(e),this.provider=null,this.disposed=!1,this.monitor=null,this.retiring=null,this.resolvers=new Map,this.cleanup=Promise.resolve()}installData(){let{gramlot:e}=this;e.data.setItem("_gramlot.device.database",null,{status:"idle",error:null}),e.data.setItem("_gramlot.device.orientation",null,{status:"idle",error:null,listening:!1});for(let m of["gyroscope","accelerometer"])e.data.setItem(`_gramlot.device.${m}`,null,{enabled:!1,watching:!1,status:"idle",error:null}),e.data.getNode(`_gramlot.device.${m}`).setAttr({error:null},!1,!0,!1),this.#a.set(m,{node:e.data.getNode(`_gramlot.device.${m}`),stream:null,cleanup:Promise.resolve()});for(let m of Vf){let b=`_gramlot.device.${m}`,w={status:"idle",error:null,cacheTime:m==="appinfo"?-1:5};m==="location"&&Object.assign(w,{enabled:!1,watching:!1}),e.data.setItem(b,null);let _=e.data.getNode(b);_.setAttr(w,!1,!0,!1);let v=new vs(this,m,w.cacheTime);_.resolver=v,this.resolvers.set(m,v)}e.data.setItem("_gramlot.device.clipboard",null,{status:"idle",error:null,text:"",copy:null,paste:null,operation:null});let t=e.data.getNode("_gramlot.device.clipboard");e.data.setItem("_gramlot.device.camera",null,{status:"idle",error:null,capture:null,choose:null});let r=e.data.getNode("_gramlot.device.camera");e.data.setItem("_gramlot.device.barcode",null,{status:"idle",error:null,scan:null});let n=e.data.getNode("_gramlot.device.barcode");e.data.setItem("_gramlot.device.biometrics",null,{status:"idle",error:null,verify:null});let i=e.data.getNode("_gramlot.device.biometrics"),s=new x;s.setItem("request",new x);for(let m of["scheduled","received","action"])s.setItem(m,null);e.data.setItem("_gramlot.device.notifications",s,{status:"idle",error:null,schedule:null,listening:!1,listenerError:null});let a=e.data.getNode("_gramlot.device.notifications"),l=new x;for(let m of["registration","received","action"])l.setItem(m,null);e.data.setItem("_gramlot.device.push",l,{status:"idle",error:null,register:null,listening:!1,listenerError:null});let c=e.data.getNode("_gramlot.device.push"),u=new x;u.setItem("request",null),e.data.setItem("_gramlot.device.links",u,{listening:!1,listenerError:null});let d=new x;d.setItem("request",null),e.data.setItem("_gramlot.device.shortcuts",d,{listening:!1,listenerError:null}),e.data.setItem("_gramlot.device.network",null,{status:"idle",error:null,listening:!1});let f=new x;f.setItem("active",null),f.setItem("event",null),f.setItem("sequence",0),e.data.setItem("_gramlot.device.lifecycle",f,{status:"idle",error:null,listening:!1}),e.data.setItem("_gramlot.device.haptics",null,{status:"idle",error:null,impact:null,style:"medium",vibrate:null,duration:600});let h=e.data.getNode("_gramlot.device.haptics");e.data.setItem("_gramlot.device.audio",null,{status:"idle",error:null,recording:!1,start:null,stop:null,cancel:null,share:null,shareStatus:"idle",shareError:null,shareActivity:null});let p=e.data.getNode("_gramlot.device.audio");e.data.subscribe("gramlot.device",{update:m=>{if(!this.disposed){for(let[b,w]of this.#a)if(m.node===w.node&&m.attrs_diff?.enabled){if(typeof w.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.#g(b,w)}m.node===t&&m.fired&&(m.attrs_diff?.copy?.new===!0&&this.#v(t,"copy"),m.attrs_diff?.paste?.new===!0&&this.#v(t,"paste")),m.node===p&&m.fired&&(m.attrs_diff?.start?.new===!0&&this.#b(p),m.attrs_diff?.stop?.new===!0&&this.#w(p),m.attrs_diff?.cancel?.new===!0&&this.#y(p),m.attrs_diff?.share?.new===!0&&this.#_(p)),m.node===h&&m.fired&&m.attrs_diff?.impact?.new===!0&&this.#E(h),m.node===h&&m.fired&&m.attrs_diff?.vibrate?.new===!0&&this.#x(h),m.node===n&&m.fired&&m.attrs_diff?.scan?.new===!0&&this.#I(n),m.node===r&&m.fired&&m.attrs_diff?.choose?.new===!0&&this.#T(r,"choose"),m.node===r&&m.fired&&m.attrs_diff?.capture?.new===!0&&this.#T(r,"capture"),m.node===i&&m.fired&&m.attrs_diff?.verify?.new===!0&&this.#C(i),m.node===a&&m.fired&&m.attrs_diff?.schedule?.new===!0&&this.#D(a),m.node===c&&m.fired&&m.attrs_diff?.register?.new===!0&&this.#O(c);for(let b of this.resolvers.values()){if(m.node!==b._node)continue;let{cacheTime:w}=m.node.attr;if(typeof w!="number"||!Number.isFinite(w)||w<0&&w!==-1)throw new TypeError("Device cacheTime must be -1 or a nonnegative number of seconds");if(b.cacheTime=w,b.name==="location"){if(typeof m.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.reconcile()}}}}})}attach(e,{dispose:t=null}={}){if(this.assertLive(),this.provider)throw new Error("A device provider is already attached");if(!Array.isArray(e.capabilities)||e.capabilities.some(r=>![...Vf,"camera","biometrics","notifications","push","shortcuts","barcode","network","lifecycle","haptics","audio","clipboard","links","orientation","gyroscope","accelerometer","database"].includes(r)))throw new TypeError("Unknown device provider capability");if(t!==null&&typeof t!="function")throw new TypeError("Device attachment dispose must be a function");this.releaseProvider=t,this.provider=e,this.installData(),this.reconcile(),this.#m("orientation",(r,n)=>e.startOrientationEvents(r,n),(r,n)=>{if(!["portrait","landscape"].includes(n?.type)||!["primary","secondary"].includes(n.direction)||!Number.isFinite(n.timestamp))throw new TypeError("Invalid screen orientation from device provider");let i=new x;for(let s of["type","direction","timestamp"])i.setItem(s,n[s]);r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("network",(r,n)=>e.startNetworkEvents(r,n),(r,n)=>{if(typeof n?.connected!="boolean"||!["none","unknown","wifi","cellular"].includes(n.type))throw new TypeError("Invalid network state from device provider");let i=new x;i.setItem("connected",n.connected),i.setItem("type",n.type),r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("lifecycle",(r,n)=>e.startLifecycleEvents(r,n),(r,n)=>{if(n?.kind==="state"&&typeof n.active=="boolean")r.staticValue.setItem("active",n.active);else if(n?.kind==="pause"||n?.kind==="resume")r.staticValue.setItem("event",n.kind),r.staticValue.setItem("sequence",r.staticValue.getItem("sequence")+1);else throw new TypeError("Invalid lifecycle event from device provider");r.setAttr({status:"success",error:null},!0,!0,!1)}),e.capabilities.includes("links")&&this.#R(this.gramlot.data.getNode("_gramlot.device.links")),e.capabilities.includes("shortcuts")&&this.#$(this.gramlot.data.getNode("_gramlot.device.shortcuts")),e.capabilities.includes("push")&&this.#A(this.gramlot.data.getNode("_gramlot.device.push")),e.capabilities.includes("notifications")&&this.#S(this.gramlot.data.getNode("_gramlot.device.notifications"))}assertLive(){if(this.disposed)throw new Error("DeviceHandler is disposed")}resolver(e){if(this.assertLive(),!this.resolvers.has(e))throw new TypeError(`Unknown device value: ${e}`);return this.resolvers.get(e)}invalidate(e){this.resolver(e).reset()}refresh(e){let t=this.resolver(e);if(t.request)return;let r={revision:t.revision,received:t.received};t.request=r,this.attributes(t,{status:"pending",error:null}),Promise.resolve().then(()=>{if(!(this.disposed||t.request!==r))return this.requireCapability(e),e==="appinfo"?this.provider.readAppInfo():this.provider.readLocation()}).then(n=>{this.disposed||t.request!==r||(this.accept(t,n),t.revision!==r.revision&&(t._lastUpdate=null))}).catch(n=>{!this.disposed&&t.request===r&&t.received===r.received&&this.failure(t,n)}).finally(()=>{t.request===r&&(t.request=null)})}#m(e,t,r){let n=this.gramlot.data.getNode(`_gramlot.device.${e}`);if(!this.provider.capabilities.includes(e)){n.setAttr(K({code:"UNAVAILABLE",message:`${e} is unavailable`}),!0,!0,!1);return}let i={controller:new AbortController};this.#s.set(e,i),n.setAttr({status:"pending",error:null},!0,!0,!1),i.start=Promise.resolve().then(()=>i.controller.signal.aborted?async()=>{}:t(s=>{if(!i.controller.signal.aborted)try{r(n,s)}catch(a){n.setAttr(K(a),!0,!0,!1)}},i.controller.signal)).then(s=>(i.controller.signal.aborted||n.setAttr({listening:!0},!0,!0,!1),s)),i.start.catch(s=>{let a=i.controller.signal.aborted;i.controller.abort(),a||n.setAttr({...K(s),listening:!1},!0,!0,!1)})}#g(e,t){let{node:r}=t;if(!r.attr.enabled){let i=t.stream;if(!i)return;t.stream=null,i.controller.abort(),t.cleanup=i.start.then(s=>s(),()=>{}).then(()=>{!this.disposed&&!t.stream&&r.setAttr({watching:!1,status:"idle",error:null},!0,!0,!1)}),t.cleanup.catch(s=>{this.disposed||r.setAttr(K(s),!0,!0,!1)});return}if(t.stream)return;let n={controller:new AbortController};t.stream=n,n.start=t.cleanup.then(()=>{if(n.controller.signal.aborted)return async()=>{};this.requireCapability(e);let i=s=>{if(!(this.disposed||n.controller.signal.aborted))try{if(s?.kind==="state"&&typeof s.watching=="boolean")r.setAttr({watching:s.watching,status:s.watching?"pending":"idle",error:null},!0,!0,!1);else if(s?.kind==="sample"){for(let l of["x","y","z","timestamp"])if(!Number.isFinite(s[l]))throw new TypeError(`Invalid ${e}.${l}`);if(!r.attr.watching||r.staticValue&&s.timestamp<r.staticValue.getItem("timestamp"))return;let a=new x;for(let l of["x","y","z","timestamp"])a.setItem(l,s[l]);r.setValue(a,!0,{status:"success",error:null},!0,!1)}else if(s?.kind==="error"&&s.error instanceof Error)r.setAttr({...K(s.error),watching:!1},!0,!0,!1);else throw new TypeError(`Invalid ${e} event`)}catch(a){r.setAttr(K(a),!0,!0,!1)}};return e==="gyroscope"?this.provider.startGyroscopeUpdates(i,n.controller.signal):this.provider.startAccelerometerUpdates(i,n.controller.signal)}),n.start.catch(i=>{!this.disposed&&!n.controller.signal.aborted&&r.setAttr({...K(i),watching:!1},!0,!0,!1)}),r.setAttr({status:"pending",error:null},!0,!0,!1)}#b(e){let t=this.#n;if(t){if(t.phase!=="complete")return;t.phase="replacing",e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),t.close=t.start.then(n=>n.dispose()).then(()=>{this.disposed||t.controller.signal.aborted||this.#n!==t||(this.#n=null,this.#b(e))}).catch(n=>{!this.disposed&&this.#n===t&&(t.phase="failed",e.setAttr(K(n),!0,!0,!1))});return}let r={controller:new AbortController,phase:"starting"};this.#n=r,e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.start=Promise.resolve().then(async()=>r.controller.signal.aborted?null:(this.requireCapability("audio"),this.provider.startAudioRecording(n=>{this.#n===r&&!r.controller.signal.aborted&&this.#y(e,n)},r.controller.signal))),r.start.then(n=>{!n||r.controller.signal.aborted||this.disposed||(r.phase="recording",e.setAttr({status:"recording",error:null,recording:!0},!0,!0,!1))}).catch(n=>{r.controller.signal.aborted||this.disposed||(this.#n===r&&(this.#n=null),e.setAttr({...K(n),recording:!1},!0,!0,!1))})}#w(e){let t=this.#n;!t||t.phase!=="recording"||(t.phase="stopping",e.setAttr({status:"pending",error:null},!0,!0,!1),t.stop=t.start.then(r=>r.stop()).then(r=>{if(t.controller.signal.aborted||this.disposed)return;if(typeof r?.url!="string"||!r.url||typeof r.mimeType!="string"||!r.mimeType.startsWith("audio/")||!Number.isFinite(r.duration)||r.duration<0)throw new TypeError("Invalid audio result from device provider");let n=new x;for(let i of["url","mimeType","duration"])n.setItem(i,r[i]);t.phase="complete",e.setValue(n,!0,{status:"success",error:null,recording:!1},!0,!1)}).catch(r=>{!t.controller.signal.aborted&&!this.disposed&&this.#y(e,r)}))}#_(e){let t=this.#n;if(t?.phase!=="sharing"){if(!t||t.phase!=="complete"){let r=K(new Error("Record and stop audio before sharing"));e.setAttr({shareStatus:r.status,shareError:r.error,shareActivity:null},!0,!0,!1);return}t.phase="sharing",e.setAttr({shareStatus:"pending",shareError:null,shareActivity:null},!0,!0,!1),t.share=t.start.then(r=>r.share(t.controller.signal)).then(r=>{if(!(t.controller.signal.aborted||this.disposed)){if(typeof r?.activity!="string")throw new TypeError("Invalid audio share result from device provider");e.setAttr({shareStatus:"success",shareError:null,shareActivity:r.activity},!0,!0,!1)}}).catch(r=>{if(t.controller.signal.aborted||this.disposed)return;let n=K(r);e.setAttr({shareStatus:n.status,shareError:n.error,shareActivity:null},!0,!0,!1)}).finally(()=>{this.#n===t&&!t.controller.signal.aborted&&(t.phase="complete")})}}#y(e,t={code:"CANCELLED",message:"Audio recording cancelled"}){let r=this.#n;!r||r.phase==="closing"||r.phase==="sharing"||(r.phase="closing",r.controller.abort(),e.setValue(null,!0,{status:"pending",error:null,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.close=r.start.then(n=>n===null?void 0:n.dispose(),n=>{if(n?.code!=="CANCELLED")throw n}).then(()=>{this.disposed||this.#n!==r||(this.#n=null,e.setAttr({...K(t),recording:!1},!0,!0,!1))}).catch(n=>{!this.disposed&&this.#n===r&&(r.phase="failed",e.setAttr(K(n),!0,!0,!1))}))}#v(e,t){if(this.#t)return;let r=new AbortController;this.#t=r;let n=e.attr.text;e.setValue(null,!0,{status:"pending",error:null,operation:t},!0,!1),Promise.resolve().then(async()=>{if(r.signal.aborted)return;this.requireCapability("clipboard");let i;if(t==="copy"){if(typeof n!="string")throw new TypeError("Clipboard text must be a string");await this.provider.copyText(n,r.signal),i={text:n}}else i=await this.provider.pasteText(r.signal);if(r.signal.aborted)return;if(typeof i?.text!="string")throw new TypeError("Invalid clipboard text from device provider");let s=new x;s.setItem("text",i.text),e.setValue(s,!0,{status:"success",error:null},!0,!1)}).catch(i=>{r.signal.aborted||e.setAttr(K(i),!0,!0,!1)}).finally(()=>{this.#t===r&&(this.#t=null)})}#x(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{duration:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!Number.isInteger(r)||r<1||r>5e3)throw new TypeError("Vibration duration must be an integer from 1 to 5000 milliseconds");if(await this.provider.vibrate(r,t.signal),t.signal.aborted)return;let n=new x;n.setItem("duration",r),n.setItem("acknowledged",!0),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(n=>{t.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#E(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{style:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!["light","medium","heavy"].includes(r))throw new TypeError("Invalid haptic style");if(await this.provider.impact(r,t.signal),t.signal.aborted)return;let n=new x;n.setItem("style",r),n.setItem("acknowledged",!0),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(n=>{t.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#I(e){if(this.#o)return;let t=new AbortController;this.#o=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("barcode"),this.provider.scanBarcode(t.signal)}).then(r=>{if(t.signal.aborted)return;if(typeof r?.text!="string"||!r.text||typeof r.format!="string"||!r.format)throw new TypeError("Invalid barcode result from device provider");let n=new x;n.setItem("text",r.text),n.setItem("format",r.format),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setAttr(K(r),!0,!0,!1)}).finally(()=>{this.#o===t&&(this.#o=null)})}#T(e,t){if(this.#r)return;let r=new AbortController;this.#r=r,e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(()=>{if(!r.signal.aborted)return this.requireCapability("camera"),t==="choose"?this.provider.choosePhoto(r.signal):this.provider.takePhoto(r.signal)}).then(n=>{if(r.signal.aborted)return;if(typeof n?.url!="string"||!n.url||typeof n.format!="string"||!n.format)throw new TypeError("Invalid camera photo from device provider");let i=new x;i.setItem("url",n.url),i.setItem("format",n.format),e.setValue(i,!0,{status:"success",error:null},!0,!1)}).catch(n=>{r.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#r===r&&(this.#r=null)})}#C(e){if(this.#l)return;let t=new AbortController;this.#l=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("biometrics"),this.provider.verifyBiometrics(t.signal)}).then(()=>{if(t.signal.aborted)return;let r=new x;r.setItem("verified",!0),e.setValue(r,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setValue(null,!0,K(r),!0,!1)}).finally(()=>{this.#l===t&&(this.#l=null)})}#S(e){if(this.#u)return this.#u.start;let t={controller:new AbortController};return this.#u=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startNotificationEvents(r=>{if(!t.controller.signal.aborted)try{if(!["received","action"].includes(r.kind)||!Number.isInteger(r.id)||typeof r.title!="string"||typeof r.body!="string"||r.kind==="action"&&typeof r.actionId!="string")throw new TypeError("Invalid notification event from device provider");let n=new x;for(let i of["id","title","body"])n.setItem(i,r[i]);r.kind==="action"&&n.setItem("actionId",r.actionId),e.staticValue.setItem(r.kind,n)}catch(n){e.setAttr({listenerError:K(n).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),this.#u===t&&(this.#u=null),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#D(e){if(this.#c)return;let t=new AbortController;this.#c=t;let r=e.staticValue.getItem("request"),n=r instanceof x?Object.fromEntries(["id","title","body","delay"].map(i=>[i,r.getItem(i)])):null;e.staticValue.setItem("scheduled",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{if(!t.signal.aborted){if(this.requireCapability("notifications"),!n||!Number.isInteger(n.id)||n.id<1||n.id>2147483647||typeof n.title!="string"||!n.title.trim()||typeof n.body!="string"||!n.body.trim()||typeof n.delay!="number"||!Number.isFinite(n.delay)||n.delay<=0)throw new TypeError("Notification requires a positive 32-bit id, title, body and positive delay in seconds");if(await this.#S(e),!t.signal.aborted)return this.provider.scheduleNotification(n,t.signal)}}).then(i=>{if(t.signal.aborted)return;if(i?.id!==n.id||typeof i.at!="number"||!Number.isFinite(i.at))throw new TypeError("Invalid notification scheduling acknowledgement");let s=new x;s.setItem("id",i.id),s.setItem("at",i.at),e.staticValue.setItem("scheduled",s),e.setAttr({status:"success",error:null},!0,!0,!1)}).catch(i=>{t.signal.aborted||e.setAttr(K(i),!0,!0,!1)}).finally(()=>{this.#c===t&&(this.#c=null)})}#k(){let e=this.#d;return this.#d=null,e&&clearTimeout(e.timer),e}#N(e,t){if(t.kind==="registration"){if(typeof t.token!="string"||!t.token)throw new TypeError("Invalid push registration token");this.#k();let r=new x;r.setItem("token",t.token),e.staticValue.setItem("registration",r),e.setAttr({status:"success",error:null},!0,!0,!1)}else if(t.kind==="registrationError")this.#k(),e.staticValue.setItem("registration",null),e.setAttr(K(t.error),!0,!0,!1);else{if(!["received","action"].includes(t.kind))throw new TypeError("Invalid push event kind");let r=["id","title","body","messageId","destination"];t.kind==="action"&&r.push("actionId");let n=new x;for(let i of r){if(typeof t[i]!="string")throw new TypeError(`Invalid push event ${i}`);n.setItem(i,t[i])}e.staticValue.setItem(t.kind,n)}}#A(e){if(this.#f)return this.#f.start;let t={controller:new AbortController};return this.#f=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startPushEvents(r=>{if(!t.controller.signal.aborted)try{this.#N(e,r)}catch(n){e.setAttr({listenerError:K(n).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),this.#f===t&&(this.#f=null),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#O(e){if(this.#d)return;let t={controller:new AbortController,timer:null};this.#d=t,t.timer=setTimeout(()=>{this.disposed||this.#d!==t||(this.#k(),t.controller.abort(),e.setAttr(K({code:"TIMEOUT",message:"Push registration has not returned a token"}),!0,!0,!1))},3e4),e.staticValue.setItem("registration",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{t.controller.signal.aborted||(this.requireCapability("push"),await this.#A(e),!(t.controller.signal.aborted||this.#d!==t)&&await this.provider.registerPush(t.controller.signal))}).catch(r=>{this.disposed||this.#d!==t||(this.#k(),t.controller.abort(),e.setAttr(K(r),!0,!0,!1))})}#$(e){let t={controller:new AbortController};this.#p=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startShortcutEvents((r,n=null)=>{if(!t.controller.signal.aborted)try{if(n)throw n;for(let s of["id","destination"])if(typeof r?.[s]!="string"||!r[s])throw new TypeError(`Invalid shortcut request ${s}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new x;i.setItem("id",r.id),i.setItem("destination",r.destination),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:K(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)})}#R(e){let t={controller:new AbortController};this.#h=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startLinkEvents((r,n=null)=>{if(!t.controller.signal.aborted)try{if(n)throw n;for(let s of["id","url"])if(typeof r?.[s]!="string"||!r[s])throw new TypeError(`Invalid link request ${s}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new x;i.setItem("id",r.id),i.setItem("url",r.url),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:K(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)})}requireCapability(e){if(!this.provider||!this.provider.capabilities.includes(e))throw Object.assign(new Error(`${e} is unavailable in this environment`),{code:"UNAVAILABLE"})}attributes(e,t){let r=e.writing;e.writing=!0;try{e._node.setAttr(t,!0,!0,!1)}finally{e.writing=r}}accept(e,t){let r=e.name==="appinfo"?["id","name","version","build"]:["latitude","longitude","accuracy","timestamp"],n=e.name==="appinfo"?"string":"number";for(let l of r)if(typeof t[l]!==n||n==="number"&&!Number.isFinite(t[l]))throw new TypeError(`Invalid ${e.name}.${l} from device provider`);let i=e.cachedValue;if(e.name==="location"&&i&&t.timestamp<i.getItem("timestamp")){this.attributes(e,{status:"success",error:null});return}let s=new x;for(let l of r)s.setItem(l,t[l]);e._lastUpdate=Date.now(),e.failed=!1,e.received++;let a=e.writing;e.writing=!0;try{e._node.setValue(s,!0,{status:"success",error:null},!0,!1)}finally{e.writing=a}}failure(e,t){e.failed=!0,this.attributes(e,K(t))}reconcile(){let e=this.resolvers.get("location");if(e._node.attr.enabled){if(this.monitor)return;let t={stop:null,controller:new AbortController};this.monitor=t,t.start=Promise.resolve(this.cleanup).then(()=>this.disposed||this.monitor!==t?null:(this.requireCapability("location"),this.provider.startLocationUpdates((r,n)=>{if(!(this.disposed||this.monitor!==t))if(n)this.failure(e,n);else try{this.accept(e,r)}catch(i){this.failure(e,i)}},t.controller.signal))),t.start.then(r=>{r===null||this.disposed||this.monitor!==t||(t.stop=r,this.attributes(e,{watching:!0}))}).catch(r=>{!this.disposed&&this.monitor===t&&(this.attributes(e,{watching:!1}),this.failure(e,r))}),this.attributes(e,{status:"pending",error:null})}else if(this.monitor){let t=this.monitor;this.monitor=null,t.controller.abort(),this.retiring=t,this.cleanup=t.start.then(r=>r===null?void 0:r(),()=>{}).then(()=>{if(this.retiring===t&&(this.retiring=null),!this.disposed){let r={watching:!1};!this.monitor&&!e.request&&e._node.attr.status==="pending"&&Object.assign(r,{status:"cancelled",error:null}),this.attributes(e,r)}}),this.cleanup.catch(r=>{this.disposed||this.failure(e,r)})}}async openDatabase(e){if(this.assertLive(),!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(e)||typeof e!="string")throw new TypeError("Invalid database name");if(this.#e)throw new Error("This page already owns a database connection");let t=this.gramlot.data.getNode("_gramlot.device.database"),r=(i,s=null)=>{this.disposed||t.setAttr({status:i,error:s},!0,!0,!1)};if(!this.provider.capabilities.includes("database")){let i=Object.assign(new Error("Native database unavailable"),{code:"UNAVAILABLE"});throw r("unavailable",{code:i.code,message:i.message}),i}let n={controller:new AbortController,close:null,start:null};this.#e=n,r("pending"),n.start=this.provider.openDatabase(e,n.controller.signal);try{let i=await n.start,s=!1,a=null,l=()=>a||(s=!0,a=i.close().then(()=>{r("closed")},u=>{throw r("error",{code:"FAILED",message:u.message}),u}).finally(()=>{this.#e===n&&(this.#e=null)}),a);if(n.close=l,this.disposed||n.controller.signal.aborted)throw await l(),Object.assign(new Error("Page closed"),{code:"CANCELLED"});let c=async(u,d,f)=>{if(this.assertLive(),s)throw new Error("Database connection is closed");r("pending");try{let h=await i[u](d,f);return r("success"),h}catch(h){throw r("error",{code:"FAILED",message:h.message}),h}};return r("success"),{query:(u,d=[])=>c("query",u,d),execute:(u,d=[])=>c("execute",u,d),close:l}}catch(i){throw this.#e===n&&(this.#e=null),this.disposed||t.setAttr(K(i),!0,!0,!1),i}}dispose(){if(this.disposed)return;this.disposed=!0;let e=this.#e;e?.controller.abort(),e&&(this.cleanup=Promise.all([this.cleanup,e.start.then(()=>e.close?.(),()=>{})]).then(()=>{}));let t=[...this.#a.values()].map(u=>{let d=u.stream;return u.stream=null,d?.controller.abort(),d?d.start.then(f=>f(),()=>{}):u.cleanup});this.#t?.abort(),this.#t=null;let r=this.#n;this.#n=null,r?.controller.abort(),this.#i?.abort(),this.#i=null;let n=[...this.#s.values()];this.#s.clear();for(let u of n)u.controller.abort();let i=this.#h;this.#h=null,i?.controller.abort();let s=this.#p;this.#p=null,s?.controller.abort(),this.#k()?.controller.abort();let a=this.#f;this.#f=null,a?.controller.abort(),this.#o?.abort(),this.#o=null,this.#r?.abort(),this.#r=null,this.#l?.abort(),this.#l=null,this.#c?.abort(),this.#c=null;let l=this.#u;this.#u=null,l?.controller.abort(),this.gramlot.data.unsubscribe("gramlot.device",{any:!0});let c=this.monitor;if(this.monitor=null,c?.controller.abort(),c)this.cleanup=c.start.then(u=>u===null?void 0:u(),()=>{});else if(this.retiring?.stop){let u=this.retiring;this.cleanup=this.cleanup.catch(()=>u.stop())}l&&(this.cleanup=Promise.all([this.cleanup,l.start.then(u=>u(),()=>{})]).then(()=>{})),a&&(this.cleanup=Promise.all([this.cleanup,a.start.then(u=>u(),()=>{})]).then(()=>{})),i&&(this.cleanup=Promise.all([this.cleanup,i.start.then(u=>u(),()=>{})]).then(()=>{})),s&&(this.cleanup=Promise.all([this.cleanup,s.start.then(u=>u(),()=>{})]).then(()=>{})),this.cleanup=Promise.all([this.cleanup,...t,...n.map(u=>u.start.then(d=>d(),()=>{}))]).then(()=>{}),r&&(this.cleanup=Promise.all([this.cleanup,r.start.then(u=>u===null?void 0:u.dispose(),u=>{if(u?.code!=="CANCELLED")throw u})]).then(()=>{})),this.cleanup=this.cleanup.finally(()=>this.releaseProvider?.()),this.cleanup.catch(u=>{this.cleanupError=u});for(let u of this.resolvers.values())u.request=null}};var Gf=2e3;function Zb(o){if(!(o instanceof Date))return String(o??"");let e=o.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}var Oo=class{constructor(e,t){this.gramlot=e,this.document=t}branch(e){let t=this.gramlot.data.getItem(e);if(!(t instanceof x))throw new Error(`gramlot.utl.inout: no data Bag at '${e}'`);return t}mailText(e){let t=[],r=(n,i)=>{for(let s of n.getNodes()){let a=i+s.label;s.value instanceof x?r(s.value,`${a}.`):t.push(`${a}: ${Zb(s.value)}`)}};return r(this.branch(e),""),t.join(`
230
+ `,n),n<0)break;continue}if(i==="/"&&o[n+1]==="*"){let s=o.indexOf("*/",n+2);if(s>=0){n=s+1;continue}}if(i==="/"&&Hb(r)){let s=Xb(o,n);if(s>=0){n=s,r=")";continue}}if(i==='"'||i==="'"||i==="`"){let s=n+1;for(;s<o.length&&o[s]!==i;)s+=o[s]==="\\"?2:1;e===1&&(t+=o.slice(n+1,s)==="constructor"?" constructor":' ""'),n=s,r=")";continue}if(/[\w$]/.test(i)){let s=n+1;for(;s<o.length&&/[\w$]/.test(o[s]);)s++;e===1&&(t+=o.slice(n,s)),r=o.slice(n,s),n=s-1;continue}if(/\s/.test(i)||(r=i),i==="{"){++e===2&&(t+=" {}");continue}if(i==="}"){e--;continue}e===1&&(t+=i)}return/(?<![\w$.#])(?<!\bstatic\s+)constructor\s*\(/.test(t)}function Uf(o,e){if(o===void 0)return[];if(typeof o!="function"||!/^class\b/.test(Function.prototype.toString.call(o)))throw new Error(`${e}: the module exports no class Logic`);if(Object.getPrototypeOf(o)!==Function.prototype||Object.getPrototypeOf(o.prototype)!==Object.prototype)throw new Error(`${e}: class Logic cannot extend another class`);if(Yb(Function.prototype.toString.call(o)))throw new Error(`${e}: class Logic cannot declare a constructor; state lives on the group or the page`);let t=[];for(let r of Reflect.ownKeys(o.prototype)){if(r==="constructor")continue;if(typeof r=="symbol")throw new Error(`${e}: class Logic cannot declare symbol keys (${String(r)})`);let n=Object.getOwnPropertyDescriptor(o.prototype,r);if(n.get||n.set)throw new Error(`${e}: class Logic cannot declare the accessor '${r}'`);if(typeof n.value!="function")throw new Error(`${e}: Logic.prototype.${r} is not a method`);if(r==="page")throw new Error(`${e}: a logic method cannot be named 'page'`);t.push([r,n.value])}return t}function qf(o,e,t){Object.defineProperty(o,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}var $r=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get page(){return this.#t}},bn=class{#e;#t=new Map;constructor(e){this.#e=e,e.logic=new $r(this,e)}get gramlot(){return this.#e}static check(e){let t=new Map;for(let{group:r,resource:n}of e){let i=zf(r,n);for(let s=0;s<i.length;s++){let a=i.slice(0,s).join("/");t.has(a)||t.set(a,new Set),t.get(a).add(i[s])}}for(let{logicClass:r,group:n,resource:i}of e){let s=t.get(n??"")??new Set;for(let[a]of Uf(r,i))if(s.has(a))throw new Error(`${i}: the logic method '${a}' has the name of a child group`)}}register(e,{group:t=null,resource:r}){let n=zf(t,r),i=Uf(e,r),s=this.#e.logic;for(let a of n){let l=Object.getOwnPropertyDescriptor(s,a)?.value;if(l===void 0){let c=new $r(this,this.#e);qf(s,a,c),s=c}else if(l instanceof $r)s=l;else throw new Error(`${r}: the group '${a}' has the name of a logic method`)}for(let[a,l]of i){if(Object.getOwnPropertyDescriptor(s,a)?.value instanceof $r)throw new Error(`${r}: the logic method '${a}' has the name of a child group`);qf(s,a,l)}this.#t.has(s)||this.#t.set(s,[]),this.#t.get(s).push(r)}resolve(e,t){let r=e.split("."),n=r.pop(),i=this.#e.logic;for(let a=0;a<r.length;a++)if(i=Object.getOwnPropertyDescriptor(i,r[a])?.value,!(i instanceof $r))throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: no resource was registered for the group '${r.slice(0,a+1).join("/")}'`);let s=Object.getOwnPropertyDescriptor(i,n)?.value;if(typeof s!="function"){let a=this.#t.get(i)??[],l=r.length?`the group '${r.join("/")}'`:"the page logic";throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: ${l} has no method '${n}' (resources: ${a.join(", ")||"none"})`)}return{group:i,method:s}}};var Do=class extends Ne{constructor(e,{collections:t,destination:r,subscriptions:n,nameSyntax:i}){super(e),e.src=this,this.logicRegistry=new bn(e),this.builder=new me(null,{collections:t,nameSyntax:i}),this.binding=new gn(e,{subscriptions:n}),this.builder.binding=this.binding,this.binding.attach(),this.source=this.builder.source,this.renderer=new Co(this.builder,this.source,r,{binding:this.binding})}startSource(e){if(!["ready","failed"].includes(this.gramlot.state))throw new Error(`Cannot start embedded Source while Gramlot is ${this.gramlot.state}`);try{return this.mountMainSource(e)}catch(t){throw this.gramlot.state="failed",t}}mountMainSource(e,t=null){let r=this.prepareSource(e);if(this.renderer.validateCandidate(r),t!==null){if(!(t instanceof x)||t instanceof N)throw new TypeError("Initial page data must be a Data Bag");for(let n of t.getNodes())this.builder.data.setItem([n.label],n.getValue(),n.attr,">",!1,!1)}try{this.source.setItem("main",r)}catch(n){throw this.binding.bindingFor(this.source.getNode("main"))||this.source.popNode("main"),n}return this.gramlot.state="started",this.binding.pageStarted(),this.binding.subscriptions.ready(),this.gramlot}prepareSource(e,t=this.builder){if(e instanceof N){if(!(e instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");return e.bindBuilder(t).activateCode()}if(typeof e!="string")throw new TypeError("Source value did not decode to SourceBag");let r=ji(e,t);if(!(r instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");return r.activateCode()}async remoteSource(e,t,r={}){if(!this.gramlot.rpc.transport?.call)throw new Error("Remote Source is unavailable without a server transport");let i=this.binding.bindingFor(e);if(this.gramlot.state!=="started"||!i)throw new Error("Remote Source target is not mounted");return await e.requests.submit(t,r,s=>this.#e(e,i,s))??!1}async#e(e,t,r){if(t.closed||this.gramlot.state==="disposed")return!1;let n=!1,i=()=>this.gramlot.state!=="disposed"&&!r.ignored&&!t.closed;try{let s=await t.call("source",r);if(!i())return!1;let a=this.prepareSource(s,e.builder);return i()?(this.renderer.validateCandidate(a,{replacingNode:e}),n=!0,e.setValue(a,!0,{_text:null},!0),t.remote?.fragmentMounted(r.method,r.text),!0):!1}catch(s){if(!n&&!i())return!1;throw s}}};var No=class extends Ne{setTouchMode(e="auto"){if(!["auto","on","off"].includes(e))throw new TypeError(`Invalid touch mode: ${e}`);let t=this.gramlot.src.renderer.destination.ownerDocument.documentElement;e==="auto"?t.removeAttribute("data-gramlot-touch"):t.setAttribute("data-gramlot-touch",e)}navigate(e){if(typeof e!="string"||!e)throw new TypeError("Navigation requires an absolute HTTP(S) URL");let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw new TypeError("Navigation requires an HTTP(S) URL without credentials");this.gramlot.src.renderer.destination.ownerDocument.defaultView.location.assign(t.href)}reference(e){return this.gramlot.src.renderer.references.resolve(e)}getBaseSourceNode(e){return this.gramlot.src.renderer.getBaseSourceNode(e)}getDomNode(e){return this.gramlot.src.renderer.getDomNode(e)}};var vs=class extends Ne{#e=new Map;#t=new WeakSet;#r=new WeakMap;#n=0;#o=!1;ready(){this.gramlot._frames.ready()}subscribe(e,t){if(this.#a(),this.#s(e),typeof t!="function")throw new TypeError("subscribe requires a callback");let r=Object.freeze({});return this.#t.add(r),this.#e.has(e)||this.#e.set(e,new Map),this.#e.get(e).set(r,t),r}unsubscribe(e){if(!this.#t.has(e))throw new TypeError("Unknown subscription registration");for(let[t,r]of this.#e)r.delete(e)&&!r.size&&this.#e.delete(t)}publish(e,t={},r={}){if(this.#a(),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("publish requires one object of named data");if(typeof e=="string")return this.#i(e,t,r);if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("publish requires a topic string or descriptor");if(Object.keys(e).some(s=>!["topic","nodeId","parent","iframe","pageId","server"].includes(s)))throw new Error("This publication route is not implemented yet");if(this.#s(e.topic),e.parent!==void 0&&typeof e.parent!="boolean")throw new TypeError("parent must be boolean");if(e.server!==void 0&&typeof e.server!="boolean")throw new TypeError("server must be boolean");if(e.iframe==="*")throw new Error("Recursive iframe broadcast is not implemented yet");if(e.pageId!==void 0&&(typeof e.pageId!="string"||!e.pageId))throw new TypeError("pageId must be a nonempty string");if((e.parent||e.iframe!==void 0||e.pageId!==void 0)&&Object.hasOwn(e,"nodeId"))throw new Error("Interframe node addressing is not implemented yet");let i=null;if(e.server===!0){if(["parent","iframe","nodeId"].some(s=>Object.hasOwn(e,s)))throw new Error("Server publication cannot combine window or node selectors");if(!this.gramlot._pageStore)throw new Error("Server publication requires a WebSocket channel");i=this.gramlot._pageStore.preparePublish(e,t)}else(e.parent||e.iframe!==void 0||e.pageId!==void 0)&&(i=this.gramlot._frames.prepare(e,t));if(Object.hasOwn(e,"nodeId")){let s=this.gramlot.src.binding.nodeIds.get(e.nodeId);if(!s)throw new Error(`nodeId not found: ${e.nodeId}`);return this.publishNode(s,e.topic,t)}return this.#i(e.topic,t),i?.()}topicFor(e,t){this.#s(t),e=Z(e);let r=this.gramlot.src.binding.bindingFor(e);if(!r||r.closed)throw new Error("Topic target is not an active Source node of this page");let n=e.getAttr("nodeId");return n==null&&(this.#r.has(e)||this.#r.set(e,`gramlot-self-${++this.#n}`),n=this.#r.get(e)),`${n}_${t}`}publishNode(e,t,r={}){return this.publish(this.topicFor(e,t),r)}subscribeNode(e,t){let r=[];for(let[n,i]of Object.entries(e.getAttr())){let s=n.startsWith("selfsubscribe_")?"selfsubscribe_":n.startsWith("subscribe_")?"subscribe_":null;if(!s)continue;let a=s==="selfsubscribe_"?this.topicFor(e,n.slice(s.length)):n.slice(s.length);this.#s(a),r.push([a,t(n,i,a)])}return this.#a(),r.map(([n,i])=>{let s=this.subscribe(n,i);return{close:()=>this.unsubscribe(s)}})}dispose(){this.#o=!0,this.#e.clear()}#i(e,t,r={}){this.#s(e);let n=this.#e.get(e);if(n)for(let[i,s]of[...n]){if(this.#o)break;n.has(i)&&s(t,{...r})}}#s(e){if(typeof e!="string"||!e)throw new TypeError("A topic must be a nonempty string")}#a(){if(this.#o)throw new Error("Gramlot subscriptions are disposed")}};var xs=class extends Y{constructor(e,t,r){super({cacheTime:r}),this.handler=e,this.name=t,this.failed=!1,this.writing=!1,this.request=null,this.revision=0,this.received=0}resolve({static:e=!1}={}){return!e&&!this.handler.disposed&&!this.writing&&!this.request&&!this.failed&&!this._node.attr.watching&&this.expired&&this.handler.refresh(this.name),this.cachedValue}reset(){super.reset(),this.failed=!1,this.revision++}};var Vf=["appinfo","location"],Wf={UNAVAILABLE:"unavailable",PERMISSION_DENIED:"denied",TIMEOUT:"error",FAILED:"error",CANCELLED:"cancelled"};function K(o){let e=Object.hasOwn(Wf,o?.code)?o.code:"FAILED";return{status:Wf[e],error:e==="CANCELLED"?null:{code:e,message:String(o?.message??"Device operation failed")}}}var Oo=class extends Ne{#e=null;#t=null;#r=null;#n=null;#o=null;#i=null;#s=new Map;#a=new Map;#l=null;#c=null;#u=null;#d=null;#f=null;#p=null;#h=null;constructor(e){super(e),this.provider=null,this.disposed=!1,this.monitor=null,this.retiring=null,this.resolvers=new Map,this.cleanup=Promise.resolve()}installData(){let{gramlot:e}=this;e.data.setItem("_gramlot.device.database",null,{status:"idle",error:null}),e.data.setItem("_gramlot.device.orientation",null,{status:"idle",error:null,listening:!1});for(let m of["gyroscope","accelerometer"])e.data.setItem(`_gramlot.device.${m}`,null,{enabled:!1,watching:!1,status:"idle",error:null}),e.data.getNode(`_gramlot.device.${m}`).setAttr({error:null},!1,!0,!1),this.#a.set(m,{node:e.data.getNode(`_gramlot.device.${m}`),stream:null,cleanup:Promise.resolve()});for(let m of Vf){let b=`_gramlot.device.${m}`,w={status:"idle",error:null,cacheTime:m==="appinfo"?-1:5};m==="location"&&Object.assign(w,{enabled:!1,watching:!1}),e.data.setItem(b,null);let _=e.data.getNode(b);_.setAttr(w,!1,!0,!1);let v=new xs(this,m,w.cacheTime);_.resolver=v,this.resolvers.set(m,v)}e.data.setItem("_gramlot.device.clipboard",null,{status:"idle",error:null,text:"",copy:null,paste:null,operation:null});let t=e.data.getNode("_gramlot.device.clipboard");e.data.setItem("_gramlot.device.camera",null,{status:"idle",error:null,capture:null,choose:null});let r=e.data.getNode("_gramlot.device.camera");e.data.setItem("_gramlot.device.barcode",null,{status:"idle",error:null,scan:null});let n=e.data.getNode("_gramlot.device.barcode");e.data.setItem("_gramlot.device.biometrics",null,{status:"idle",error:null,verify:null});let i=e.data.getNode("_gramlot.device.biometrics"),s=new x;s.setItem("request",new x);for(let m of["scheduled","received","action"])s.setItem(m,null);e.data.setItem("_gramlot.device.notifications",s,{status:"idle",error:null,schedule:null,listening:!1,listenerError:null});let a=e.data.getNode("_gramlot.device.notifications"),l=new x;for(let m of["registration","received","action"])l.setItem(m,null);e.data.setItem("_gramlot.device.push",l,{status:"idle",error:null,register:null,listening:!1,listenerError:null});let c=e.data.getNode("_gramlot.device.push"),u=new x;u.setItem("request",null),e.data.setItem("_gramlot.device.links",u,{listening:!1,listenerError:null});let d=new x;d.setItem("request",null),e.data.setItem("_gramlot.device.shortcuts",d,{listening:!1,listenerError:null}),e.data.setItem("_gramlot.device.network",null,{status:"idle",error:null,listening:!1});let f=new x;f.setItem("active",null),f.setItem("event",null),f.setItem("sequence",0),e.data.setItem("_gramlot.device.lifecycle",f,{status:"idle",error:null,listening:!1}),e.data.setItem("_gramlot.device.haptics",null,{status:"idle",error:null,impact:null,style:"medium",vibrate:null,duration:600});let h=e.data.getNode("_gramlot.device.haptics");e.data.setItem("_gramlot.device.audio",null,{status:"idle",error:null,recording:!1,start:null,stop:null,cancel:null,share:null,shareStatus:"idle",shareError:null,shareActivity:null});let p=e.data.getNode("_gramlot.device.audio");e.data.subscribe("gramlot.device",{update:m=>{if(!this.disposed){for(let[b,w]of this.#a)if(m.node===w.node&&m.attrs_diff?.enabled){if(typeof w.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.#g(b,w)}m.node===t&&m.fired&&(m.attrs_diff?.copy?.new===!0&&this.#v(t,"copy"),m.attrs_diff?.paste?.new===!0&&this.#v(t,"paste")),m.node===p&&m.fired&&(m.attrs_diff?.start?.new===!0&&this.#b(p),m.attrs_diff?.stop?.new===!0&&this.#w(p),m.attrs_diff?.cancel?.new===!0&&this.#y(p),m.attrs_diff?.share?.new===!0&&this.#_(p)),m.node===h&&m.fired&&m.attrs_diff?.impact?.new===!0&&this.#E(h),m.node===h&&m.fired&&m.attrs_diff?.vibrate?.new===!0&&this.#x(h),m.node===n&&m.fired&&m.attrs_diff?.scan?.new===!0&&this.#I(n),m.node===r&&m.fired&&m.attrs_diff?.choose?.new===!0&&this.#T(r,"choose"),m.node===r&&m.fired&&m.attrs_diff?.capture?.new===!0&&this.#T(r,"capture"),m.node===i&&m.fired&&m.attrs_diff?.verify?.new===!0&&this.#C(i),m.node===a&&m.fired&&m.attrs_diff?.schedule?.new===!0&&this.#D(a),m.node===c&&m.fired&&m.attrs_diff?.register?.new===!0&&this.#O(c);for(let b of this.resolvers.values()){if(m.node!==b._node)continue;let{cacheTime:w}=m.node.attr;if(typeof w!="number"||!Number.isFinite(w)||w<0&&w!==-1)throw new TypeError("Device cacheTime must be -1 or a nonnegative number of seconds");if(b.cacheTime=w,b.name==="location"){if(typeof m.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.reconcile()}}}}})}attach(e,{dispose:t=null}={}){if(this.assertLive(),this.provider)throw new Error("A device provider is already attached");if(!Array.isArray(e.capabilities)||e.capabilities.some(r=>![...Vf,"camera","biometrics","notifications","push","shortcuts","barcode","network","lifecycle","haptics","audio","clipboard","links","orientation","gyroscope","accelerometer","database"].includes(r)))throw new TypeError("Unknown device provider capability");if(t!==null&&typeof t!="function")throw new TypeError("Device attachment dispose must be a function");this.releaseProvider=t,this.provider=e,this.installData(),this.reconcile(),this.#m("orientation",(r,n)=>e.startOrientationEvents(r,n),(r,n)=>{if(!["portrait","landscape"].includes(n?.type)||!["primary","secondary"].includes(n.direction)||!Number.isFinite(n.timestamp))throw new TypeError("Invalid screen orientation from device provider");let i=new x;for(let s of["type","direction","timestamp"])i.setItem(s,n[s]);r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("network",(r,n)=>e.startNetworkEvents(r,n),(r,n)=>{if(typeof n?.connected!="boolean"||!["none","unknown","wifi","cellular"].includes(n.type))throw new TypeError("Invalid network state from device provider");let i=new x;i.setItem("connected",n.connected),i.setItem("type",n.type),r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("lifecycle",(r,n)=>e.startLifecycleEvents(r,n),(r,n)=>{if(n?.kind==="state"&&typeof n.active=="boolean")r.staticValue.setItem("active",n.active);else if(n?.kind==="pause"||n?.kind==="resume")r.staticValue.setItem("event",n.kind),r.staticValue.setItem("sequence",r.staticValue.getItem("sequence")+1);else throw new TypeError("Invalid lifecycle event from device provider");r.setAttr({status:"success",error:null},!0,!0,!1)}),e.capabilities.includes("links")&&this.#R(this.gramlot.data.getNode("_gramlot.device.links")),e.capabilities.includes("shortcuts")&&this.#$(this.gramlot.data.getNode("_gramlot.device.shortcuts")),e.capabilities.includes("push")&&this.#A(this.gramlot.data.getNode("_gramlot.device.push")),e.capabilities.includes("notifications")&&this.#S(this.gramlot.data.getNode("_gramlot.device.notifications"))}assertLive(){if(this.disposed)throw new Error("DeviceHandler is disposed")}resolver(e){if(this.assertLive(),!this.resolvers.has(e))throw new TypeError(`Unknown device value: ${e}`);return this.resolvers.get(e)}invalidate(e){this.resolver(e).reset()}refresh(e){let t=this.resolver(e);if(t.request)return;let r={revision:t.revision,received:t.received};t.request=r,this.attributes(t,{status:"pending",error:null}),Promise.resolve().then(()=>{if(!(this.disposed||t.request!==r))return this.requireCapability(e),e==="appinfo"?this.provider.readAppInfo():this.provider.readLocation()}).then(n=>{this.disposed||t.request!==r||(this.accept(t,n),t.revision!==r.revision&&(t._lastUpdate=null))}).catch(n=>{!this.disposed&&t.request===r&&t.received===r.received&&this.failure(t,n)}).finally(()=>{t.request===r&&(t.request=null)})}#m(e,t,r){let n=this.gramlot.data.getNode(`_gramlot.device.${e}`);if(!this.provider.capabilities.includes(e)){n.setAttr(K({code:"UNAVAILABLE",message:`${e} is unavailable`}),!0,!0,!1);return}let i={controller:new AbortController};this.#s.set(e,i),n.setAttr({status:"pending",error:null},!0,!0,!1),i.start=Promise.resolve().then(()=>i.controller.signal.aborted?async()=>{}:t(s=>{if(!i.controller.signal.aborted)try{r(n,s)}catch(a){n.setAttr(K(a),!0,!0,!1)}},i.controller.signal)).then(s=>(i.controller.signal.aborted||n.setAttr({listening:!0},!0,!0,!1),s)),i.start.catch(s=>{let a=i.controller.signal.aborted;i.controller.abort(),a||n.setAttr({...K(s),listening:!1},!0,!0,!1)})}#g(e,t){let{node:r}=t;if(!r.attr.enabled){let i=t.stream;if(!i)return;t.stream=null,i.controller.abort(),t.cleanup=i.start.then(s=>s(),()=>{}).then(()=>{!this.disposed&&!t.stream&&r.setAttr({watching:!1,status:"idle",error:null},!0,!0,!1)}),t.cleanup.catch(s=>{this.disposed||r.setAttr(K(s),!0,!0,!1)});return}if(t.stream)return;let n={controller:new AbortController};t.stream=n,n.start=t.cleanup.then(()=>{if(n.controller.signal.aborted)return async()=>{};this.requireCapability(e);let i=s=>{if(!(this.disposed||n.controller.signal.aborted))try{if(s?.kind==="state"&&typeof s.watching=="boolean")r.setAttr({watching:s.watching,status:s.watching?"pending":"idle",error:null},!0,!0,!1);else if(s?.kind==="sample"){for(let l of["x","y","z","timestamp"])if(!Number.isFinite(s[l]))throw new TypeError(`Invalid ${e}.${l}`);if(!r.attr.watching||r.staticValue&&s.timestamp<r.staticValue.getItem("timestamp"))return;let a=new x;for(let l of["x","y","z","timestamp"])a.setItem(l,s[l]);r.setValue(a,!0,{status:"success",error:null},!0,!1)}else if(s?.kind==="error"&&s.error instanceof Error)r.setAttr({...K(s.error),watching:!1},!0,!0,!1);else throw new TypeError(`Invalid ${e} event`)}catch(a){r.setAttr(K(a),!0,!0,!1)}};return e==="gyroscope"?this.provider.startGyroscopeUpdates(i,n.controller.signal):this.provider.startAccelerometerUpdates(i,n.controller.signal)}),n.start.catch(i=>{!this.disposed&&!n.controller.signal.aborted&&r.setAttr({...K(i),watching:!1},!0,!0,!1)}),r.setAttr({status:"pending",error:null},!0,!0,!1)}#b(e){let t=this.#n;if(t){if(t.phase!=="complete")return;t.phase="replacing",e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),t.close=t.start.then(n=>n.dispose()).then(()=>{this.disposed||t.controller.signal.aborted||this.#n!==t||(this.#n=null,this.#b(e))}).catch(n=>{!this.disposed&&this.#n===t&&(t.phase="failed",e.setAttr(K(n),!0,!0,!1))});return}let r={controller:new AbortController,phase:"starting"};this.#n=r,e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.start=Promise.resolve().then(async()=>r.controller.signal.aborted?null:(this.requireCapability("audio"),this.provider.startAudioRecording(n=>{this.#n===r&&!r.controller.signal.aborted&&this.#y(e,n)},r.controller.signal))),r.start.then(n=>{!n||r.controller.signal.aborted||this.disposed||(r.phase="recording",e.setAttr({status:"recording",error:null,recording:!0},!0,!0,!1))}).catch(n=>{r.controller.signal.aborted||this.disposed||(this.#n===r&&(this.#n=null),e.setAttr({...K(n),recording:!1},!0,!0,!1))})}#w(e){let t=this.#n;!t||t.phase!=="recording"||(t.phase="stopping",e.setAttr({status:"pending",error:null},!0,!0,!1),t.stop=t.start.then(r=>r.stop()).then(r=>{if(t.controller.signal.aborted||this.disposed)return;if(typeof r?.url!="string"||!r.url||typeof r.mimeType!="string"||!r.mimeType.startsWith("audio/")||!Number.isFinite(r.duration)||r.duration<0)throw new TypeError("Invalid audio result from device provider");let n=new x;for(let i of["url","mimeType","duration"])n.setItem(i,r[i]);t.phase="complete",e.setValue(n,!0,{status:"success",error:null,recording:!1},!0,!1)}).catch(r=>{!t.controller.signal.aborted&&!this.disposed&&this.#y(e,r)}))}#_(e){let t=this.#n;if(t?.phase!=="sharing"){if(!t||t.phase!=="complete"){let r=K(new Error("Record and stop audio before sharing"));e.setAttr({shareStatus:r.status,shareError:r.error,shareActivity:null},!0,!0,!1);return}t.phase="sharing",e.setAttr({shareStatus:"pending",shareError:null,shareActivity:null},!0,!0,!1),t.share=t.start.then(r=>r.share(t.controller.signal)).then(r=>{if(!(t.controller.signal.aborted||this.disposed)){if(typeof r?.activity!="string")throw new TypeError("Invalid audio share result from device provider");e.setAttr({shareStatus:"success",shareError:null,shareActivity:r.activity},!0,!0,!1)}}).catch(r=>{if(t.controller.signal.aborted||this.disposed)return;let n=K(r);e.setAttr({shareStatus:n.status,shareError:n.error,shareActivity:null},!0,!0,!1)}).finally(()=>{this.#n===t&&!t.controller.signal.aborted&&(t.phase="complete")})}}#y(e,t={code:"CANCELLED",message:"Audio recording cancelled"}){let r=this.#n;!r||r.phase==="closing"||r.phase==="sharing"||(r.phase="closing",r.controller.abort(),e.setValue(null,!0,{status:"pending",error:null,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.close=r.start.then(n=>n===null?void 0:n.dispose(),n=>{if(n?.code!=="CANCELLED")throw n}).then(()=>{this.disposed||this.#n!==r||(this.#n=null,e.setAttr({...K(t),recording:!1},!0,!0,!1))}).catch(n=>{!this.disposed&&this.#n===r&&(r.phase="failed",e.setAttr(K(n),!0,!0,!1))}))}#v(e,t){if(this.#t)return;let r=new AbortController;this.#t=r;let n=e.attr.text;e.setValue(null,!0,{status:"pending",error:null,operation:t},!0,!1),Promise.resolve().then(async()=>{if(r.signal.aborted)return;this.requireCapability("clipboard");let i;if(t==="copy"){if(typeof n!="string")throw new TypeError("Clipboard text must be a string");await this.provider.copyText(n,r.signal),i={text:n}}else i=await this.provider.pasteText(r.signal);if(r.signal.aborted)return;if(typeof i?.text!="string")throw new TypeError("Invalid clipboard text from device provider");let s=new x;s.setItem("text",i.text),e.setValue(s,!0,{status:"success",error:null},!0,!1)}).catch(i=>{r.signal.aborted||e.setAttr(K(i),!0,!0,!1)}).finally(()=>{this.#t===r&&(this.#t=null)})}#x(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{duration:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!Number.isInteger(r)||r<1||r>5e3)throw new TypeError("Vibration duration must be an integer from 1 to 5000 milliseconds");if(await this.provider.vibrate(r,t.signal),t.signal.aborted)return;let n=new x;n.setItem("duration",r),n.setItem("acknowledged",!0),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(n=>{t.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#E(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{style:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!["light","medium","heavy"].includes(r))throw new TypeError("Invalid haptic style");if(await this.provider.impact(r,t.signal),t.signal.aborted)return;let n=new x;n.setItem("style",r),n.setItem("acknowledged",!0),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(n=>{t.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#I(e){if(this.#o)return;let t=new AbortController;this.#o=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("barcode"),this.provider.scanBarcode(t.signal)}).then(r=>{if(t.signal.aborted)return;if(typeof r?.text!="string"||!r.text||typeof r.format!="string"||!r.format)throw new TypeError("Invalid barcode result from device provider");let n=new x;n.setItem("text",r.text),n.setItem("format",r.format),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setAttr(K(r),!0,!0,!1)}).finally(()=>{this.#o===t&&(this.#o=null)})}#T(e,t){if(this.#r)return;let r=new AbortController;this.#r=r,e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(()=>{if(!r.signal.aborted)return this.requireCapability("camera"),t==="choose"?this.provider.choosePhoto(r.signal):this.provider.takePhoto(r.signal)}).then(n=>{if(r.signal.aborted)return;if(typeof n?.url!="string"||!n.url||typeof n.format!="string"||!n.format)throw new TypeError("Invalid camera photo from device provider");let i=new x;i.setItem("url",n.url),i.setItem("format",n.format),e.setValue(i,!0,{status:"success",error:null},!0,!1)}).catch(n=>{r.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#r===r&&(this.#r=null)})}#C(e){if(this.#l)return;let t=new AbortController;this.#l=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("biometrics"),this.provider.verifyBiometrics(t.signal)}).then(()=>{if(t.signal.aborted)return;let r=new x;r.setItem("verified",!0),e.setValue(r,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setValue(null,!0,K(r),!0,!1)}).finally(()=>{this.#l===t&&(this.#l=null)})}#S(e){if(this.#u)return this.#u.start;let t={controller:new AbortController};return this.#u=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startNotificationEvents(r=>{if(!t.controller.signal.aborted)try{if(!["received","action"].includes(r.kind)||!Number.isInteger(r.id)||typeof r.title!="string"||typeof r.body!="string"||r.kind==="action"&&typeof r.actionId!="string")throw new TypeError("Invalid notification event from device provider");let n=new x;for(let i of["id","title","body"])n.setItem(i,r[i]);r.kind==="action"&&n.setItem("actionId",r.actionId),e.staticValue.setItem(r.kind,n)}catch(n){e.setAttr({listenerError:K(n).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),this.#u===t&&(this.#u=null),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#D(e){if(this.#c)return;let t=new AbortController;this.#c=t;let r=e.staticValue.getItem("request"),n=r instanceof x?Object.fromEntries(["id","title","body","delay"].map(i=>[i,r.getItem(i)])):null;e.staticValue.setItem("scheduled",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{if(!t.signal.aborted){if(this.requireCapability("notifications"),!n||!Number.isInteger(n.id)||n.id<1||n.id>2147483647||typeof n.title!="string"||!n.title.trim()||typeof n.body!="string"||!n.body.trim()||typeof n.delay!="number"||!Number.isFinite(n.delay)||n.delay<=0)throw new TypeError("Notification requires a positive 32-bit id, title, body and positive delay in seconds");if(await this.#S(e),!t.signal.aborted)return this.provider.scheduleNotification(n,t.signal)}}).then(i=>{if(t.signal.aborted)return;if(i?.id!==n.id||typeof i.at!="number"||!Number.isFinite(i.at))throw new TypeError("Invalid notification scheduling acknowledgement");let s=new x;s.setItem("id",i.id),s.setItem("at",i.at),e.staticValue.setItem("scheduled",s),e.setAttr({status:"success",error:null},!0,!0,!1)}).catch(i=>{t.signal.aborted||e.setAttr(K(i),!0,!0,!1)}).finally(()=>{this.#c===t&&(this.#c=null)})}#k(){let e=this.#d;return this.#d=null,e&&clearTimeout(e.timer),e}#N(e,t){if(t.kind==="registration"){if(typeof t.token!="string"||!t.token)throw new TypeError("Invalid push registration token");this.#k();let r=new x;r.setItem("token",t.token),e.staticValue.setItem("registration",r),e.setAttr({status:"success",error:null},!0,!0,!1)}else if(t.kind==="registrationError")this.#k(),e.staticValue.setItem("registration",null),e.setAttr(K(t.error),!0,!0,!1);else{if(!["received","action"].includes(t.kind))throw new TypeError("Invalid push event kind");let r=["id","title","body","messageId","destination"];t.kind==="action"&&r.push("actionId");let n=new x;for(let i of r){if(typeof t[i]!="string")throw new TypeError(`Invalid push event ${i}`);n.setItem(i,t[i])}e.staticValue.setItem(t.kind,n)}}#A(e){if(this.#f)return this.#f.start;let t={controller:new AbortController};return this.#f=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startPushEvents(r=>{if(!t.controller.signal.aborted)try{this.#N(e,r)}catch(n){e.setAttr({listenerError:K(n).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),this.#f===t&&(this.#f=null),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#O(e){if(this.#d)return;let t={controller:new AbortController,timer:null};this.#d=t,t.timer=setTimeout(()=>{this.disposed||this.#d!==t||(this.#k(),t.controller.abort(),e.setAttr(K({code:"TIMEOUT",message:"Push registration has not returned a token"}),!0,!0,!1))},3e4),e.staticValue.setItem("registration",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{t.controller.signal.aborted||(this.requireCapability("push"),await this.#A(e),!(t.controller.signal.aborted||this.#d!==t)&&await this.provider.registerPush(t.controller.signal))}).catch(r=>{this.disposed||this.#d!==t||(this.#k(),t.controller.abort(),e.setAttr(K(r),!0,!0,!1))})}#$(e){let t={controller:new AbortController};this.#p=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startShortcutEvents((r,n=null)=>{if(!t.controller.signal.aborted)try{if(n)throw n;for(let s of["id","destination"])if(typeof r?.[s]!="string"||!r[s])throw new TypeError(`Invalid shortcut request ${s}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new x;i.setItem("id",r.id),i.setItem("destination",r.destination),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:K(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)})}#R(e){let t={controller:new AbortController};this.#h=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startLinkEvents((r,n=null)=>{if(!t.controller.signal.aborted)try{if(n)throw n;for(let s of["id","url"])if(typeof r?.[s]!="string"||!r[s])throw new TypeError(`Invalid link request ${s}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new x;i.setItem("id",r.id),i.setItem("url",r.url),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:K(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let n=t.controller.signal.aborted;t.controller.abort(),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)})}requireCapability(e){if(!this.provider||!this.provider.capabilities.includes(e))throw Object.assign(new Error(`${e} is unavailable in this environment`),{code:"UNAVAILABLE"})}attributes(e,t){let r=e.writing;e.writing=!0;try{e._node.setAttr(t,!0,!0,!1)}finally{e.writing=r}}accept(e,t){let r=e.name==="appinfo"?["id","name","version","build"]:["latitude","longitude","accuracy","timestamp"],n=e.name==="appinfo"?"string":"number";for(let l of r)if(typeof t[l]!==n||n==="number"&&!Number.isFinite(t[l]))throw new TypeError(`Invalid ${e.name}.${l} from device provider`);let i=e.cachedValue;if(e.name==="location"&&i&&t.timestamp<i.getItem("timestamp")){this.attributes(e,{status:"success",error:null});return}let s=new x;for(let l of r)s.setItem(l,t[l]);e._lastUpdate=Date.now(),e.failed=!1,e.received++;let a=e.writing;e.writing=!0;try{e._node.setValue(s,!0,{status:"success",error:null},!0,!1)}finally{e.writing=a}}failure(e,t){e.failed=!0,this.attributes(e,K(t))}reconcile(){let e=this.resolvers.get("location");if(e._node.attr.enabled){if(this.monitor)return;let t={stop:null,controller:new AbortController};this.monitor=t,t.start=Promise.resolve(this.cleanup).then(()=>this.disposed||this.monitor!==t?null:(this.requireCapability("location"),this.provider.startLocationUpdates((r,n)=>{if(!(this.disposed||this.monitor!==t))if(n)this.failure(e,n);else try{this.accept(e,r)}catch(i){this.failure(e,i)}},t.controller.signal))),t.start.then(r=>{r===null||this.disposed||this.monitor!==t||(t.stop=r,this.attributes(e,{watching:!0}))}).catch(r=>{!this.disposed&&this.monitor===t&&(this.attributes(e,{watching:!1}),this.failure(e,r))}),this.attributes(e,{status:"pending",error:null})}else if(this.monitor){let t=this.monitor;this.monitor=null,t.controller.abort(),this.retiring=t,this.cleanup=t.start.then(r=>r===null?void 0:r(),()=>{}).then(()=>{if(this.retiring===t&&(this.retiring=null),!this.disposed){let r={watching:!1};!this.monitor&&!e.request&&e._node.attr.status==="pending"&&Object.assign(r,{status:"cancelled",error:null}),this.attributes(e,r)}}),this.cleanup.catch(r=>{this.disposed||this.failure(e,r)})}}async openDatabase(e){if(this.assertLive(),!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(e)||typeof e!="string")throw new TypeError("Invalid database name");if(this.#e)throw new Error("This page already owns a database connection");let t=this.gramlot.data.getNode("_gramlot.device.database"),r=(i,s=null)=>{this.disposed||t.setAttr({status:i,error:s},!0,!0,!1)};if(!this.provider.capabilities.includes("database")){let i=Object.assign(new Error("Native database unavailable"),{code:"UNAVAILABLE"});throw r("unavailable",{code:i.code,message:i.message}),i}let n={controller:new AbortController,close:null,start:null};this.#e=n,r("pending"),n.start=this.provider.openDatabase(e,n.controller.signal);try{let i=await n.start,s=!1,a=null,l=()=>a||(s=!0,a=i.close().then(()=>{r("closed")},u=>{throw r("error",{code:"FAILED",message:u.message}),u}).finally(()=>{this.#e===n&&(this.#e=null)}),a);if(n.close=l,this.disposed||n.controller.signal.aborted)throw await l(),Object.assign(new Error("Page closed"),{code:"CANCELLED"});let c=async(u,d,f)=>{if(this.assertLive(),s)throw new Error("Database connection is closed");r("pending");try{let h=await i[u](d,f);return r("success"),h}catch(h){throw r("error",{code:"FAILED",message:h.message}),h}};return r("success"),{query:(u,d=[])=>c("query",u,d),execute:(u,d=[])=>c("execute",u,d),close:l}}catch(i){throw this.#e===n&&(this.#e=null),this.disposed||t.setAttr(K(i),!0,!0,!1),i}}dispose(){if(this.disposed)return;this.disposed=!0;let e=this.#e;e?.controller.abort(),e&&(this.cleanup=Promise.all([this.cleanup,e.start.then(()=>e.close?.(),()=>{})]).then(()=>{}));let t=[...this.#a.values()].map(u=>{let d=u.stream;return u.stream=null,d?.controller.abort(),d?d.start.then(f=>f(),()=>{}):u.cleanup});this.#t?.abort(),this.#t=null;let r=this.#n;this.#n=null,r?.controller.abort(),this.#i?.abort(),this.#i=null;let n=[...this.#s.values()];this.#s.clear();for(let u of n)u.controller.abort();let i=this.#h;this.#h=null,i?.controller.abort();let s=this.#p;this.#p=null,s?.controller.abort(),this.#k()?.controller.abort();let a=this.#f;this.#f=null,a?.controller.abort(),this.#o?.abort(),this.#o=null,this.#r?.abort(),this.#r=null,this.#l?.abort(),this.#l=null,this.#c?.abort(),this.#c=null;let l=this.#u;this.#u=null,l?.controller.abort(),this.gramlot.data.unsubscribe("gramlot.device",{any:!0});let c=this.monitor;if(this.monitor=null,c?.controller.abort(),c)this.cleanup=c.start.then(u=>u===null?void 0:u(),()=>{});else if(this.retiring?.stop){let u=this.retiring;this.cleanup=this.cleanup.catch(()=>u.stop())}l&&(this.cleanup=Promise.all([this.cleanup,l.start.then(u=>u(),()=>{})]).then(()=>{})),a&&(this.cleanup=Promise.all([this.cleanup,a.start.then(u=>u(),()=>{})]).then(()=>{})),i&&(this.cleanup=Promise.all([this.cleanup,i.start.then(u=>u(),()=>{})]).then(()=>{})),s&&(this.cleanup=Promise.all([this.cleanup,s.start.then(u=>u(),()=>{})]).then(()=>{})),this.cleanup=Promise.all([this.cleanup,...t,...n.map(u=>u.start.then(d=>d(),()=>{}))]).then(()=>{}),r&&(this.cleanup=Promise.all([this.cleanup,r.start.then(u=>u===null?void 0:u.dispose(),u=>{if(u?.code!=="CANCELLED")throw u})]).then(()=>{})),this.cleanup=this.cleanup.finally(()=>this.releaseProvider?.()),this.cleanup.catch(u=>{this.cleanupError=u});for(let u of this.resolvers.values())u.request=null}};var Gf=2e3;function Zb(o){if(!(o instanceof Date))return String(o??"");let e=o.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}var $o=class{constructor(e,t){this.gramlot=e,this.document=t}branch(e){let t=this.gramlot.data.getItem(e);if(!(t instanceof x))throw new Error(`gramlot.utl.inout: no data Bag at '${e}'`);return t}mailText(e){let t=[],r=(n,i)=>{for(let s of n.getNodes()){let a=i+s.label;s.value instanceof x?r(s.value,`${a}.`):t.push(`${a}: ${Zb(s.value)}`)}};return r(this.branch(e),""),t.join(`
231
231
  `)}mailtoUrl(e,t){let r=`mailto:${encodeURIComponent(t)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(e))}`;if(r.length>Gf)throw new Error(`gramlot.utl.inout.sendMail: the email of '${e}' is ${r.length} characters long, over the mailto: limit of ${Gf}; send it with sendHttp or save it as a file`);return r}sendMail(e,t){this.open(this.mailtoUrl(e,t))}async sendHttp(e,t){let r=JSON.stringify(this.branch(e).asDict(!1,!1,!0)),n=await this.document.defaultView.fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:r});if(!n.ok)throw new Error(`gramlot.utl.inout.sendHttp: ${t} answered ${n.status}`);return n}save(e,t){this.saveText(this.branch(e).toTytx(),t,"application/json")}restore(e){let t=this.document.createElement("input");return t.type="file",t.accept=".json,application/json",new Promise((r,n)=>{let i=()=>n(new this.document.defaultView.DOMException("File selection cancelled","AbortError"));t.addEventListener("cancel",i,{once:!0}),t.addEventListener("change",async()=>{if(t.removeEventListener("cancel",i),!t.files.length){i();return}try{let s=j(await t.files[0].text());if(!(s instanceof x))throw new TypeError("the file must contain a typed Bag");this.gramlot.data.setItem(e,s),r(s)}catch(s){n(new Error(`gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${s.message}`,{cause:s}))}},{once:!0}),t.click()})}download(e,t,r){if(!["json","xml"].includes(r))throw new Error(`gramlot.utl.inout.download: format '${r}' is not 'json' or 'xml'`);let n=this.branch(e);if(r==="json")this.saveText(n.toJson(!1),t,"application/json");else{let i=e.split(".").at(-1);this.saveText(`<?xml version='1.0' encoding='UTF-8'?>
232
- <${i}>${n.toXml()}</${i}>`,t,"application/xml")}}async copyText(e){if(typeof e!="string")throw new TypeError("gramlot.utl.inout.copyText: text must be a string");await this.document.defaultView.navigator.clipboard.writeText(e)}saveText(e,t,r){let n=this.document.defaultView,i=n.URL.createObjectURL(new n.Blob([e],{type:r}));this.open(i,t),n.setTimeout(()=>n.URL.revokeObjectURL(i),1e3)}open(e,t=null){let r=this.document.createElement("a");r.href=e,t!==null&&(r.download=t),r.click()}};var $o=class extends Ne{constructor(e,t){super(e),this.inout=new Oo(e,t)}};var Ro=class{#e;#t;constructor({pageId:e,uploadUrl:t=null,rpcUrl:r="/gramlot/rpc",closeUrl:n="/gramlot/close",rootId:i="gramlot-root",capabilities:s=[],element:a=null,document:l=a?.ownerDocument??globalThis.document,transport:c=null,collections:u=[],locale:d=null,timeZone:f=null,devices:h=[],serverAdapter:p=new Rt,nameSyntax:m=null,websocketUrl:b=null}={}){this.#t=[Vi,...u.filter(_=>_ instanceof Xt)],this.registerDocument(l),this.commands=new Dn,this.pageId=e,this.uploadUrl=t;let w=d==null||f==null?l.defaultView.Intl.DateTimeFormat().resolvedOptions():null;this.devices=Object.freeze([...h]),this.locale=d??w.locale,this.timeZone=f??w.timeZone,Object.defineProperty(this,"_subscriptions",{value:new ys(this)}),this.capabilities=Object.freeze([...s]),this.serverAdapter=p,this.src=new Co(this,{collections:u,destination:a??l.getElementById(i),subscriptions:this._subscriptions,nameSyntax:m===null?eo:mr.fromJSON(m)}),this.#e=Cn.install({document:l,root:this.src.renderer.destination}),this.data=this.src.builder.data,this.dvc=new No(this),this.dom=new Do(this),this.utl=new $o(this,l),this.state="ready",this.abort=new AbortController,Object.defineProperty(this,"_frames",{value:new Bi(this,l)}),b!==null&&(this._pageStore=new Pi(this,b,l)),this.rpc=new Qn(this,{rpcUrl:r,closeUrl:n,document:l,transport:c}),this._frames.connect(),this.rpc.transport&&(this.pagehide=_=>{_.persisted||this.dispose()},l.defaultView.addEventListener("pagehide",this.pagehide),this.window=l.defaultView)}publish(e,t={}){return this._subscriptions.publish(e,t)}registerDocument(e){for(let t of this.#t)t.register(e.defaultView)}getCollection(e){return this.#t.find(t=>t.name===e)}subscribe(e,t){return this._subscriptions.subscribe(e,t)}unsubscribe(e){this._subscriptions.unsubscribe(e)}format(e,t){return oo(e,t,{locale:this.locale,timeZone:this.timeZone})}start(){return this.state==="disposed"?Promise.reject(new Error("Gramlot is disposed")):this.rpc.transport?this.loading?this.loading:this.state==="started"?Promise.resolve(this):(this.state="loading",this.loading=this.loadMain().finally(()=>{this.loading=null}),this.loading):Promise.reject(new Error("This Gramlot instance has no server transport"))}async loadMain(){let e;try{e=await this.rpc.callEnvelope("source","main")}catch(t){throw this.state==="disposed"?new Error("Gramlot was disposed during main",{cause:t}):(this.state="failed",t)}if(this.state==="disposed")throw new Error("Gramlot was disposed during main");try{return this.src.mountMainSource(e.value,e.data)}catch(t){throw this.state!=="disposed"&&(this.state="failed"),t}}dispose(){if(this.state!=="disposed"){this.state="disposed",this.dvc.dispose(),this.#e.dispose(),this._subscriptions.dispose(),this.pagehide&&this.window.removeEventListener("pagehide",this.pagehide),this.abort.abort();try{try{this.src.binding.dispose()}finally{this.src.renderer.dispose()}}finally{if(this._pageStore?.close(),this._frames.dispose(),this.rpc.transport)try{this.rpc.transport.close(this.pageId)}finally{this.rpc.transport.dispose()}}}}};var ic=class{constructor({config:e,resources:t,document:r=globalThis.document}){this.config=e,this.resources=t,this.document=r,this.serverAdapter=new Rt}async run(){let{config:e,resources:t,document:r}=this,n=r.defaultView;t.serverAdapter!==void 0&&(this.serverAdapter=await this.loadServerAdapter(t.serverAdapter));let i=!1,s,a,l=[],c=new Promise(d=>{s=d}),u=d=>{if(!(d.persisted||i)){i=!0;try{this.closePage()}finally{s(null)}}};n.addEventListener("pagehide",u);try{let d=t.css.map(_=>new Promise((v,E)=>{let D=r.createElement("link");D.rel="stylesheet",D.href=_;let k=()=>{D.removeEventListener("load",C),D.removeEventListener("error",O)};l.push(k);let C=()=>{k(),v()},O=()=>{k(),E(new Error(`${_}: stylesheet load failed`))};D.addEventListener("load",C),D.addEventListener("error",O),r.head.append(D)})),f=t.js.map(async({url:_,group:v})=>{try{return{logicClass:(await import(new URL(_,r.baseURI).href)).Logic,group:v,resource:_}}catch(E){throw new Error(`${_}: import failed: ${E.message}`,{cause:E})}}),h=new Set,p=(t.collections??[]).map(async _=>{if(!_||typeof _!="object"||Object.keys(_).sort().join(",")!=="buildId,name,url"||typeof _.name!="string"||typeof _.url!="string"||typeof _.buildId!="string"||!/^sha256:[0-9a-f]{64}$/.test(_.buildId)||h.has(_.name))throw new TypeError("Invalid or duplicate collection bootstrap record");h.add(_.name);let{name:v,url:E,buildId:D}=_,k;try{k=await import(new URL(E,r.baseURI).href)}catch(C){throw new Error(`${v}: collection import failed: ${C.message}`,{cause:C})}if(k.default?.name!==v||k.buildId!==D)throw new Error(`${v}: collection identity mismatch; expected ${D}, received ${k.buildId}`);return k.default}),m=await Promise.race([Promise.all([Promise.all(d),Promise.all(f),Promise.all(p)]),c]);if(i)return null;let[,b,w]=m;bn.check(b);for(let _ of w)_.register(n);a=new Ro({...e,document:r,serverAdapter:this.serverAdapter,collections:[...e.collections??[],...w]}),n.removeEventListener("pagehide",u);for(let _ of w)_.registerCommands(a);for(let{logicClass:_,group:v,resource:E}of b)a.src.logicRegistry.register(_,{group:v,resource:E});return n.gramlot=a,await a.start(),a}catch(d){throw a?a.dispose():i||this.closePage(),d}finally{for(let d of l)d();n.removeEventListener("pagehide",u)}}async loadServerAdapter(e){let t;try{t=await import(new URL(e,this.document.baseURI).href)}catch(r){throw new Error(`${e}: server adapter import failed: ${r.message}`,{cause:r})}return new t.default}closePage(){let e=this.serverAdapter.createTransport({...this.config,document:this.document});try{e.close(this.config.pageId)}finally{e.dispose()}}};var xs=Symbol("gramlot.source"),ks=Symbol("gramlot.endpoint"),jo=Symbol("gramlot.upload"),Kb=new Map([[xs,"registerSource"],[ks,"registerEndpoint"],[jo,"registerUpload"]]);function sc(o,e,t,r){let n=Kb.get(t);if(e==="main")throw new TypeError(`${n} cannot declare main`);let i=Object.getOwnPropertyDescriptor(o.prototype,e)?.value;if(typeof i!="function")throw new TypeError(`${n} requires an own method of ${o.name}: ${String(e)}`);if(i[t])throw new TypeError(`${t===xs?"Source method":t===ks?"Endpoint":"Upload operation"} already registered: ${e}`);if([xs,ks,jo].some(s=>i[s])){let s=t!==jo&&!i[jo]?`${e} is declared both as Source method and endpoint`:`${e} has conflicting declarations`;throw new TypeError(s)}i[t]={auth:r}}var Es=class{static registerSource(e,{auth:t=null}={}){sc(this,e,xs,t)}static registerEndpoint(e,{auth:t=null}={}){sc(this,e,ks,t)}static registerUpload(e,{auth:t=null}={}){sc(this,e,jo,t)}},Po=class extends Es{static gramlots=[];static title="Gramlot";static devices=[];static locale=null;static timeZone=null;static installable=!1;static appIcon=null;manifest({baseUrl:e="./"}={}){let{title:t,appIcon:r}=this.constructor;if(typeof r!="string"||!r)throw new TypeError("An installable Page needs appIcon");return{id:e,name:t,short_name:t,start_url:e,scope:e,display:"standalone",icons:[{src:e+r.replace(/^\/+/,""),sizes:"512x512",type:"image/png"}]}}static css=[];static css_theme=null;static css_requires="";static js_requires="";static sourceBuilder=me;main(e){throw new Error("Page.main(root) must be implemented")}};var wn=class extends Po{static shellId="frame";static datapath=null;main(e){let t=e.div({id:this.constructor.shellId,datapath:this.constructor.datapath,class:"frame-page",height:"100vh",display:"flex",flex_direction:"column",min_height:0}),r=t.borderContainer({node_label:"frame",height:"100%",flex:"1",min_height:0});for(let n of["top","bottom","left","right","center"])if(this[n]!==void 0){let i=r.contentPane({region:n,node_label:n});this[n](i)}this.behavior(t)}center(e){}behavior(e){}};var Bo=class extends wn{static title="Application";static shellId="index";static datapath="index";static navigation=null;main(e){let{navigation:t,datapath:r}=this.constructor;if(!(t instanceof x))throw new TypeError("IndexPage.navigation must be a Bag");e.dataSetter({destination_path:`${r}.navigation`,value:t}),e.dataSetter({destination_path:`${r}.navigationSelection`,value:null}),e.dataSetter({destination_path:`${r}.active`,value:null}),e.dataSetter({destination_path:`${r}.opened`,value:new x}),super.main(e)}left(e){e.setAttr({width:"240px",splitter:!0,drawer:!0,drawer_label:"Navigation"}),e.tree({node_label:"tree",storepath:".navigation",labelAttribute:"title",hideValues:!0,selectedPath:"^.navigationSelection"})}center(e){e.tabContainer({node_label:"tabs",height:"100%",selectedPage:"^.active"})}behavior(e){e.dataController({func:"indexMount",_onStart:!0})}index_panel(e,{selection:t}){this.panel(e,t.getNode("#0"))}panel(e,t){e.iframe({src:t.attr.url,title:t.attr.title??t.label,width:"100%",height:"100%",border:0})}};Bo.registerSource("index_panel");function ac(o,e,t=()=>{},r=()=>{},{state:n=e.getRelativeData("."),createEntry:i=null,onLoad:s=()=>{}}={}){let a=n.getItem("navigation");if(!(a instanceof x))throw new TypeError("IndexPage navigation must be a Bag");let l=e.value.getNode("frame.center.tabs"),c=e.builder,u=new Map,d={entries:u,disposed:!1,selecting:!1,sequence:0,requested:null};Object.defineProperty(e,"indexContext",{value:d,configurable:!0});let f=n.getItem("opened");for(let k of f.getNodes()){let{url:C,path:O,title:L}=k.attr,z=l.value.getNode(k.label),V={url:C,path:O,title:L,pane:z,node:a.getNode(O),loading:!1};r(V),u.set(C,V),d.sequence++}let h=(k,C,O)=>{try{s(k.url,C,O)}catch(L){o.binding.reportError(L,"Page load callback failed")}},p=(k,C,O)=>{k.loading&&(k.loading=!1,h(k,C,O))},m=k=>{if(!d.disposed){d.selecting=!0;try{n.setItem("active",k.url),n.setItem("navigationSelection",k.path),t(u,k.url)}finally{d.selecting=!1}}};function b(k){w(k).catch(C=>{d.disposed||o.binding.reportError(C,"Page could not be opened")})}async function w(k){let C=a.getNode(k);if(!C)throw new Error(`Unknown index navigation path: ${k}`);let O=C.attr.url;if(O==null)return;if(typeof O!="string"||!O)throw new TypeError("IndexPage URL must be nonempty text");d.requested=O;let L=u.get(O);if(L){L.path=k,m(L);return}for(;l.value!==null&&l.value.getNode(`page${d.sequence}`);)d.sequence++;let z=Z(c.wrapSource(l).contentPane({node_label:`page${d.sequence++}`,title:C.attr.title??C.label,pageName:O,height:"100%",closable:!0})),V=n.getItem("active");L={url:O,path:k,node:C,pane:z,title:C.attr.title??C.label,loading:!0},u.set(O,L);try{if(h(L,"loading"),d.disposed||u.get(O)!==L||(m(L),d.disposed||u.get(O)!==L))return;if(i)await i(L);else{let le=new x;if(le.setItem(C.label,null,{...C.attr}),!await o.binding.gramlot.src.remoteSource(z,"index_panel",{selection:le}))throw new Error("Panel loading was cancelled")}if(d.disposed||u.get(O)!==L)return;f.setItem(z.label,null,{url:O,path:L.path,title:L.title}),r(L)}catch(le){if(d.disposed||u.get(O)!==L)return;try{if(o.binding.reportError(le,"Page could not be opened"),u.delete(O),f.getNode(z.label)&&f.popNode(z.label),z.parentBag&&z.parentBag.popNode(z.label),!d.disposed&&d.requested===O){let _e=u.get(V);if(d.requested=_e?.url??null,_e)m(_e);else{d.selecting=!0;try{n.setItem("active",null),n.setItem("navigationSelection",null),t(u,null)}finally{d.selecting=!1}}}}finally{p(L,"error",le)}return}d.disposed||u.get(O)!==L||(p(L,"ready"),!d.disposed&&u.get(O)===L&&d.requested===O&&m(L))}let _=`${e.getAttr("id")}-page-close`;e.value.subscribe(_,{any:k=>{if(k.evt!=="del")return;let C=[...u.values()].find(z=>z.pane===k.node);if(!C)return;let{url:O,pane:L}=C;if(!(d.disposed||o.disposed||u.get(O)!==C)){u.delete(O),f.getNode(L.label)&&f.popNode(L.label);try{if(n.getItem("active")===O){let z=[...u.values()].at(-1);if(d.requested=z?.url??null,z)m(z);else{d.selecting=!0;try{n.setItem("active",null),n.setItem("navigationSelection",null),t(u,null)}finally{d.selecting=!1}}}else t(u,n.getItem("active"))}finally{p(C,"cancelled")}}}});let v=`${e.getAttr("id")}-selection`;n.subscribe(v,{any:k=>{if(!(d.selecting||d.disposed)){if(k.node===n.getNode("navigationSelection")){let C=n.getItem("navigationSelection");C!==null&&b(C)}else if(k.node===n.getNode("active")){let C=u.get(n.getItem("active"));C&&(d.requested=C.url,m(C))}}}});let E=()=>{if(!d.disposed){d.disposed=!0,n.unsubscribe(v,{any:!0}),e.value.unsubscribe(_,{any:!0});for(let k of u.values())k.loading&&(k.pane.parentBag&&k.pane.parentBag.popNode(k.pane.label),p(k,"cancelled"));u.clear(),e.indexContext===d&&delete e.indexContext}};d.dispose=E,o.onDispose(e,E);let D=u.get(n.getItem("active"));return D?m(D):n.getItem("navigationSelection")!==null&&b(n.getItem("navigationSelection")),d}var Ts=class{indexMount(e){ac(this.page.src.renderer,e.parentNode)}};function Ss(o,{datapath:e,value:t,language:r="text",height:n="420px",...i}){if(!e)throw new TypeError("codeMirrorWithOptions requires datapath");let s=o.borderContainer({datapath:e,height:n,class:"gramlot-editor-options"}),a={language:r,indentUnit:4,fontSize:14,fontFamily:"monospace",lineNumbers:!0,lineWrapping:!0,folding:!0,bracketMatching:!0,autoCloseBrackets:!0,autoIndent:!0,autocompletion:!0,highlightActiveLine:!0,highlightSelectionMatches:!0};for(let[d,f]of Object.entries(a))s.dataSetter({destination_path:`.settings.${d}`,value:f});let l=s.contentPane({region:"right",width:"250px",drawer:"close",drawer_label:"Options",drawer_icon:"\u2699",drawer_minimize:!1,padding:"12px",overflow:"auto",class:"gramlot-editor-settings"});l.h3("Editor options"),l.filteringSelect({value:"^.settings.language",lbl:"Language",values:"text:Plain text,python:Python,javascript:JavaScript,typescript:TypeScript,json:JSON,html:HTML,css:CSS,xml:XML,markdown:Markdown,sql:SQL,typst:Typst"}),l.numberTextBox({value:"^.settings.indentUnit",lbl:"Indent spaces",min:1,max:16,dtype:"L",validate_notnull:!0}),l.numberTextBox({value:"^.settings.fontSize",lbl:"Font size",min:8,max:48,dtype:"L",validate_notnull:!0}),l.textbox({value:"^.settings.fontFamily",lbl:"Font family"});let c={lineNumbers:"Line numbers",lineWrapping:"Wrap lines",folding:"Code folding",bracketMatching:"Match brackets",autoCloseBrackets:"Close brackets and quotes",autoIndent:"Automatic indentation",autocompletion:"Local completion",highlightActiveLine:"Highlight current line",highlightSelectionMatches:"Highlight matching selections"};for(let[d,f]of Object.entries(c))l.checkbox({value:`^.settings.${d}`,label:f,display:"block",margin_top:"8px"});return s.contentPane({region:"center",min_height:0}).codeMirror({...i,value:t,height:"100%",...Object.fromEntries(Object.keys(a).map(d=>[d,`^.settings.${d}`]))}),s}var Mo=class o extends et{static internalParams=new Set([...et.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,root:t,path:r="",onError:n}){super({cacheTime:-1,onError:n}),this.gramlot=e,this.method="directory_tree",this.params={root:t,path:r},this.children=new Set}get closed(){return this.#e}startLoad(e){if(this.loading)return this.loading;let t=new AbortController;return this.#t=t,e({controller:t,method:this.method,params:this.params,ignored:!1})}async loadAsync({controller:e,method:t,params:r}){let{signal:n}=e,i,s=new Promise((a,l)=>{i=()=>l(n.reason),n.addEventListener("abort",i,{once:!0})});try{let a=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:n}),s]);if(n.aborted)throw n.reason;return a}finally{n.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof x))throw new TypeError("directory_tree must return a Bag");for(let t of this.children)t.abort();this.children.clear();for(let t of e.getNodes())if(t.attr.is_directory){let r=new o({gramlot:this.gramlot,root:this.params.root,path:t.attr.path,onError:this.onError});this.children.add(r),e.setResolver(t.label,r)}return e}abort(){this.#e=!0,this.#t?.abort();for(let e of this.children)e.abort();this.children.clear()}},Lo=class{constructor(e,t){this.gramlot=e,this.source=t,this.request=null,this.resolver=null,this.disposed=!1}get state(){return this.source.getRelativeData(".")}async open(e){this.request?.abort();let t=this.request=new AbortController;this.state.setItem("status","Opening directory\u2026");try{let r=await this.gramlot.rpc.call("data","workspace_open",{root:e},{signal:t.signal});if(this.disposed||t.signal.aborted)return null;let n=new Mo({gramlot:this.gramlot,root:r.root,onError:s=>this.state.setItem("status",s.message)}),i=n.prepareValue(r.entries);return this.resolver?.abort(),this.resolver=n,this.state.setItem("selectedPath",null),this.state.setItem("store",i),this.state.setItem("writable",r.writable),this.state.setItem("root",r.root),this.state.setItem("status",""),r.root}catch(r){return!this.disposed&&!t.signal.aborted&&this.state.setItem("status",r.message),null}finally{this.request===t&&(this.request=null)}}dispose(){this.disposed=!0,this.request?.abort(),this.resolver?.abort()}},Rr=class{fileSystemMount(e){let t=e.parentNode,r=new Lo(this.page,t);Object.defineProperty(t,"fileSystemController",{value:r,configurable:!0}),this.page.src.renderer.onDispose(t,()=>r.dispose())}fileSystemOpen(e,{root:t}){if(t)return e.parentNode.fileSystemController.open(t)}};function Hf(o,{datapath:e,...t}){let r=o.div({datapath:e,class:"gramlot-filesystem",...t});return r.dataSetter({destination_path:".store",value:new x}),r.dataSetter({destination_path:".root",value:null}),r.dataSetter({destination_path:".requestedRoot",value:null}),r.dataSetter({destination_path:".selectedPath",value:null}),r.dataSetter({destination_path:".status",value:""}),r.dataController({func:"fileSystemMount",_onBuilt:!0}),r.dataController({func:"fileSystemOpen",root:"^.requestedRoot"}),r.tree({storepath:".store",selectedPath:"^.selectedPath",labelAttribute:"caption",hideValues:!0,class:"gramlot-filesystem-tree"}),r.div("^.status",{role:"status",class:"gramlot-filesystem-status"}),r}var Jb=(o,e)=>"d_"+[...new TextEncoder().encode(JSON.stringify([o,e]))].map(t=>t.toString(16).padStart(2,"0")).join(""),As=class{constructor(e,t){this.gramlot=e,this.source=t,this.pending=new Map,this.disposed=!1}get state(){return this.source.getRelativeData(".")}get documents(){return this.state.getItem("documents")}async open(e,t){if(!/\.(?:py|js|mjs|ts|json|html|css|xml|md|markdown|sql|typ|txt|png|jpg|jpeg|webp)$/i.test(t))return null;let r=Jb(e,t),n=this.documents.getNodes().find(a=>!a.value.getItem("isNew")&&a.value.getItem("root")===e&&a.value.getItem("path")===t);if(n)return n.label;if(this.pending.has(r))return this.pending.get(r).promise;let i=new AbortController,s=this.gramlot.rpc.call("data","document_read",{root:e,path:t},{signal:i.signal}).then(a=>{if(this.disposed||i.signal.aborted)return null;let l=new x,c=a.language==="image"?a.content.toTytx():a.content;for(let[u,d]of Object.entries({...a,content:c,root:e,saved:c,busy:!1}))l.setItem(u,d);if(a.language==="image"){let u=a.content;l.setItem("annotations",u),u.subscribe("ide-annotations",{any:()=>l.setItem("content",u.toTytx())})}return this.documents.setItem(r,l),r}).finally(()=>this.pending.delete(r));return this.pending.set(r,{request:i,promise:s}),s}newDocument(e,t,r=""){let n=`new_${G()}`,i=new x;for(let[s,a]of Object.entries({language:e,root:r,path:`Untitled${t}`,content:"",saved:"",writable:!0,busy:!1,isNew:!0,createHidden:!0,saveRoot:r,savePath:`Untitled${t}`}))i.setItem(s,a);return this.documents.setItem(n,i),n}async create(e){let t=this.documents.getItem(e);if(!t||!t.getItem("isNew")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("saveRoot"),n=t.getItem("savePath");if(t.getItem("path").endsWith(".typ.py")!==n.endsWith(".typ.py"))throw new Error("The .typ.py extension is required for the Typst Python recipe document type.");let i=t.getItem("content"),s=new AbortController;t.setItem("busy",!0);let a=this.gramlot.rpc.call("data","document_create",{root:r,path:n,content:i},{signal:s.signal}).then(l=>this.disposed||s.signal.aborted?!1:(t.setItem("root",l.root),t.setItem("path",l.path),t.setItem("revision",l.revision),t.setItem("saved",i),t.setItem("isNew",!1),t.setItem("createHidden",!0),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:s,promise:a}),a}invalidateRecipe(e){let t=this.documents.getItem(e);t.getItem("path").endsWith(".typ.py")&&(t.getItem("rendering")&&this.pending.get(e)?.request.abort(),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generate preview to render the current Python recipe."))}async renderRecipe(e){let t=this.documents.getItem(e);if(!t||!t.getItem("path").endsWith(".typ.py")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),n=new AbortController;t.setItem("busy",!0),t.setItem("rendering",!0),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generating Typst on the server\u2026");let i=this.gramlot.rpc.call("data","document_render_typst",{content:r},{signal:n.signal}).then(s=>this.disposed||n.signal.aborted||t.getItem("content")!==r?!1:(t.setItem("typstSource",s.source),t.setItem("previewHidden",!1),t.setItem("renderStatus","Typst generated from the current recipe."),!0)).catch(s=>(!this.disposed&&!n.signal.aborted&&t.setItem("renderStatus",s.message),!1)).finally(()=>{this.pending.delete(e),this.disposed||(t.setItem("rendering",!1),t.setItem("busy",!1))});return this.pending.set(e,{request:n,promise:i}),i}dirty(e){let t=this.documents.getItem(e);return t&&t.getItem("content")!==t.getItem("saved")}async save(e){let t=this.documents.getItem(e);if(!t||t.getItem("isNew")||!this.dirty(e)||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),n=new AbortController;t.setItem("busy",!0);let i=t.getItem("language")==="image",s=i?t.getItem("annotationPath"):t.getItem("path"),a=i&&t.getItem("revision")===null,l=this.gramlot.rpc.call("data",a?"document_create":"document_save",{root:t.getItem("root"),path:s,content:i?x.fromTytx(r):r,...a?{}:{revision:t.getItem("revision")}},{signal:n.signal}).then(c=>this.disposed||n.signal.aborted?!1:(t.setItem("revision",c.revision),t.setItem("saved",r),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:n,promise:l}),l}revert(e){let t=this.documents.getItem(e);return!t||!this.dirty(e)||this.pending.has(e)?!1:(t.setItem("content",t.getItem("saved")),t.getItem("language")==="image"&&(t.getItem("annotations").replace(x.fromTytx(t.getItem("saved"))),t.setItem("content",t.getItem("saved"))),!0)}canClose(e,t=!1){return!this.pending.has(e)&&(t||!this.dirty(e))}close(e,t=!1){return this.canClose(e,t)?(this.documents.popNode(e),this.state.getItem("active")===e&&this.state.setItem("active",this.documents.getNodes()[0]?.label??null),!0):!1}dispose(){this.disposed=!0;for(let{request:e}of this.pending.values())e.abort()}},Is=class{constructor(e){this.storage=e,this.key="gramlot.ide.recentWorkspaces"}read(){let e=this.storage.getItem(this.key),t=e===null?[]:JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"||!r))throw new TypeError("Invalid recent workspace preference");return t.slice(0,6)}remember(e){let t=[e,...this.read().filter(r=>r!==e)].slice(0,6);return this.storage.setItem(this.key,JSON.stringify(t)),t}choices(e=this.read()){let t=new x;return e.forEach((r,n)=>t.setItem(`r${n}`,r,{caption:r})),t}};function Be(o){for(let e=o;e;e=e.parentNode){let t=e.ideContext;if(t)return t}throw new Error("IDE operation requires a node inside a mounted IDE")}var Cs=class{fileSystemMount(e){return Rr.prototype.fileSystemMount.call(this,e)}fileSystemOpen(e,t){return Rr.prototype.fileSystemOpen.call(this,e,t)}ideMount(e){let t=e.parentNode,r={scope:t,documents:new As(this.page,t),requested:0,editorPrefix:`ide_${G()}`,recent:new Is(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage)};Object.defineProperty(t,"ideContext",{value:r,configurable:!0});let{documents:n,recent:i}=r,s=t.getRelativeData("."),a=i.read();s.setItem("recent",i.choices(a)),s.setItem("workspace",a[0]??"");let l=s.getItem("browser");l.subscribe("ide-browser",{any:u=>{if(u.node===l.getNode("root")){let d=l.getItem("root");s.setItem("workspace",d),s.setItem("recent",i.choices(i.remember(d))),s.setItem("status",`Workspace: ${d}`)}else if(u.node===l.getNode("selectedPath")){let d=l.getItem("selectedPath"),f=d===null?null:l.getItem("store").getNode(d);f&&!f.attr.is_directory&&this.ideOpenDocument(t,l.getItem("root"),f.attr.path)}}});let c=n.documents;c.subscribe("ide-documents",{any:u=>{if(["content","saved","busy","writable","view","isNew","path","root"].includes(u.node.label))for(let d of t.value.getNode("frame.center.tabs").value?.getNodes()??[]){let f=d.getAttr("documentKey"),h=n.documents.getItem(f);h&&(u.node===h.getNode("content")&&n.invalidateRecipe(f),this.ideDocumentState(t,f),d.setAttr({title:`${n.dirty(f)?"\u25CF ":""}${h.getItem("path")}`}))}}}),this.page.src.renderer.onDispose(r.scope,()=>{l.unsubscribe("ide-browser",{any:!0}),c.unsubscribe("ide-documents",{any:!0}),n.dispose()})}ideOpenWorkspace(e){let r=Be(e).scope.getRelativeData("."),n=r.getItem("workspace");n&&n!==r.getItem("browser.root")&&r.setItem("browser.requestedRoot",n)}async ideUploadCompleted(e,{result:t}){let r=Be(e),n=r.scope.getRelativeData(".");if(n.getItem("browser.root")!==t.root)return;n.setItem("upload.open",!1);let i=r.scope.value.getNode("frame.left.browser").fileSystemController;if(i.request)return;await i.open(t.root)===t.root&&!r.documents.disposed&&n.getItem("browser.root")===t.root&&await this.ideOpenDocument(r.scope,t.root,t.path)}ideDocumentState(e,t){let r=Be(e),{documents:n}=r,i=n.documents.getItem(t),s=!n.dirty(t)&&!i.getItem("isNew")||i.getItem("busy");i.setItem("saveDisabled",!!(s||!i.getItem("writable"))),i.setItem("revertDisabled",!!(!n.dirty(t)||i.getItem("busy"))),i.setItem("displayPath",i.getItem("isNew")?i.getItem("path"):`${i.getItem("root")}/${i.getItem("path")}`),i.setItem("pdfFilename",i.getItem("path").split("/").at(-1).replace(/\.typ(?:\.py)?$/i,".pdf")),i.setItem("renderDisabled",!!(i.getItem("busy")||!i.getItem("writable"))),this.ideHistoryState(i)}async ideOpenDocument(e,t,r){let n=Be(e),{documents:i}=n,s=n.scope.getRelativeData("."),a=++n.requested;try{let l=await i.open(t,r);if(l===null||i.disposed)return;this.ideShowDocument(e,l),a===n.requested&&(s.setItem("active",l),s.setItem("status",`${r}${i.documents.getItem(l).getItem("writable")?"":" (draft only \u2014 Remote Edit is disabled)"}`))}catch(l){i.disposed||s.setItem("status",l.message)}}ideNew(e){let t=Be(e),{documents:r}=t,n=t.scope.getRelativeData("."),i=n.getItem("newType"),s=i==="typstRecipe"?"python":i,a={typstRecipe:".typ.py",typst:".typ",markdown:".md",html:".html",python:".py",javascript:".js",typescript:".ts",json:".json",css:".css",sql:".sql",xml:".xml",text:".txt"},l=r.newDocument(s,a[i],n.getItem("workspace"));r.documents.getItem(l).setItem("writable",n.getItem("browser.writable")===!0),++t.requested,this.ideShowDocument(e,l),n.setItem("active",l),n.setItem("status","New document. Choose directory and name when saving.")}ideShowDocument(e,t){let r=Be(e),{documents:n}=r,s=n.documents.getItem(t).getItem("path"),a=r.scope.value.getNode("frame.center.tabs");if(!a.value?.getNode(t)){let l=n.documents.getItem(t),c=s.endsWith(".typ.py");c&&n.invalidateRecipe(t),l.setItem("readonly",!1),this.ideDocumentState(e,t),l.setItem("view","code"),l.setItem("createHidden",!0),l.setItem("undoDisabled",!0),l.setItem("redoDisabled",!0);let u=Z(a.builder.wrapSource(a).contentPane({node_label:t,title:s,pageName:t,documentKey:t,closable:!0,onClose:"ideClose",height:"100%"})),d=u.builder.wrapSource(u).div({display:"flex",flex_direction:"column",height:"100%"}),f=d.div({datapath:`.documents.${t}`,display:"flex",align_items:"center",gap:"6px",padding:"4px 12px",height:"40px",flex_shrink:0,box_sizing:"border-box",class:"gramlot-ide-document-toolbar",role:"toolbar","aria-label":`Commands for ${s}`});for(let[m,b,w,_]of[["save","M5 3h12l4 4v14H3V3h2 M7 3v6h10V3 M7 21v-8h10v8","Save","ideSave"],["revert","M3 10a9 9 0 1 1 2 8 M3 4v6h6 M12 7v5l3 2","Revert to saved","ideRevert"],["undo","M9 5 3 11l6 6 M3 11h12a6 6 0 0 1 6 6v2","Undo","ideUndo"],["redo","m15 5 6 6-6 6 M21 11H9a6 6 0 0 0-6 6v2","Redo","ideRedo"]]){let v=f.button({title:w,"aria-label":w,disabled:`^.${m}Disabled`,class:`button--quiet gramlot-ide-${m}`});v.svg({viewBox:"0 0 24 24",width:18,height:18,fill:"none",stroke:"currentColor",stroke_width:1.7,stroke_linecap:"round",stroke_linejoin:"round","aria-hidden":"true"}).path({d:b}),v.dataController({func:_,documentKey:t})}c&&f.button("Generate preview",{disabled:"^.renderDisabled",class:"button--quiet"}).dataController({func:"ideRenderRecipe",documentKey:t}),f.div("^.displayPath",{class:"gramlot-ide-document-path",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap",min_width:0,flex:"1"});let h=d.div({datapath:`.documents.${t}`,hidden:"^.createHidden",padding:"8px 12px",display:"flex",gap:"8px",align_items:"end",flex_shrink:0});h.textbox({value:"^.saveRoot",lbl:"Directory",flex:"1",disabled:"^.busy"}),h.textbox({value:"^.savePath",lbl:"File name",flex:"1",disabled:"^.busy"}),h.button("Create file",{disabled:"^.busy"}).dataController({func:"ideCreate",documentKey:t}),h.button("Cancel",{disabled:"^.busy",class:"button--quiet"}).dataController({func:"ideCancelCreate",documentKey:t});let p=d.div({flex:"1",min_height:0});if(l.getItem("language")==="image")p.drawingPane({image:`^.documents.${t}.image`,annotations:`^.documents.${t}.annotations`,height:"100%"});else{let m=l.getItem("language")==="html",b=l.getItem("language")==="markdown",w=m||b,_=l.getItem("language")==="typst",v=w||_||c,E=v?p.tabContainer({height:"100%",selectedPage:`^.documents.${t}.view`}):null,D=v?E.contentPane({title:"Code",pageName:"code",height:"100%"}):p;if(Ss(D,{datapath:`.documents.${t}`,value:"^.content",language:l.getItem("language"),height:"100%",readonly:"^.readonly",nodeId:`${r.editorPrefix}_editor_${t}`,editorView:"code",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_editor_${t}_save`]:!0}),_&&E.contentPane({title:"Preview",pageName:"preview",height:"100%"}).typstPreview({value:`^.documents.${t}.content`,filename:`^.documents.${t}.pdfFilename`,height:"100%"}),c){let k=E.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});k.div(`^.documents.${t}.renderStatus`,{role:"status",padding:"8px 12px",white_space:"pre-wrap",overflow:"auto",max_height:"30%"}),k.typstPreview({value:`^.documents.${t}.typstSource`,filename:`^.documents.${t}.pdfFilename`,hidden:`^.documents.${t}.previewHidden`,flex:"1",min_height:0}),E.contentPane({title:"Generated Typst",pageName:"generated",height:"100%"}).codeMirror({value:`^.documents.${t}.typstSource`,language:"typst",readonly:!0,height:"100%"})}if(w){let k=E.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});b&&(l.setItem("allowHtml",!1),k.checkbox({value:`^.documents.${t}.allowHtml`,label:"Allow embedded HTML",class:"gramlot-ide-allow-html",padding:"8px 12px",flex_shrink:0})),k[m?"htmlPreview":"markdownPreview"]({value:`^.documents.${t}.content`,flex:"1",min_height:0,...b?{allowHtml:`^.documents.${t}.allowHtml`}:{}}),E.contentPane({title:"Rich text",pageName:"rich",height:"100%"})[m?"htmlEditor":"markdownEditor"]({datapath:`.documents.${t}`,value:"^.content",readonly:"^.readonly",height:"100%",nodeId:`${r.editorPrefix}_rich_editor_${t}`,editorView:"rich",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_rich_editor_${t}_save`]:!0})}}}}async ideRenderRecipe(e,{documentKey:t}){let r=Be(e),{documents:n}=r;n.documents.getItem(t).setItem("view","preview"),await n.renderRecipe(t)}ideCancelCreate(e,{documentKey:t}){let r=Be(e),{documents:n}=r;n.documents.getItem(t).setItem("createHidden",!0)}async ideCreate(e,{documentKey:t}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData(".");i.setItem("status","Creating file\u2026");try{let s=await n.create(t);if(!n.disposed&&s){i.setItem("status","File created.");let a=i.getItem("browser");a.getItem("root")&&await r.scope.value.getNode("frame.left.browser").fileSystemController.open(a.getItem("root"))}}catch(s){n.disposed||i.setItem("status",s.message)}}async ideSave(e,{documentKey:t=null}={}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData("."),s=t??i.getItem("active");if(!s||n.documents.getItem(s).getItem("saveDisabled"))return;let a=n.documents.getItem(s);if(a.getItem("isNew")){a.setItem("createHidden",!1);return}i.setItem("status","Saving\u2026");try{let l=await n.save(s);n.disposed||i.setItem("status",l?"Saved.":"Document is read only or a request is pending.")}catch(l){n.disposed||i.setItem("status",l.message)}}ideRevert(e,{documentKey:t}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData(".");n.revert(t)&&i.setItem("status","Restored the last saved version.")}ideHistoryChanged(e,{canUndo:t,canRedo:r}){let n=e.getRelativeData("."),i=e.getAttr("editorView");n.setItem(`${i}CanUndo`,t),n.setItem(`${i}CanRedo`,r),this.ideHistoryState(n)}ideHistoryState(e){let t=e.getItem("view");e.setItem("undoDisabled",!e.getItem(`${t}CanUndo`)),e.setItem("redoDisabled",!e.getItem(`${t}CanRedo`))}ideEditor(e,t){let r=Be(e),{documents:n}=r,i=n.documents.getItem(t).getItem("view")==="rich",s=this.page.src.binding.nodeIds.get(`${r.editorPrefix}_${i?"rich_":""}editor_${t}`);return this.page.src.renderer.records.get(s).element}ideUndo(e,{documentKey:t}){this.ideEditor(e,t).undo()}ideRedo(e,{documentKey:t}){this.ideEditor(e,t).redo()}ideClose(e){let t=Be(e),{documents:r}=t,n=t.scope.getRelativeData("."),i=e.getAttr("documentKey");return r.canClose(i)?!0:(n.setItem("status","Save or revert your changes before closing. Pending operations must finish first."),!1)}ideClosed(e,{pageName:t}){this.ideForgetDocument(e,t)}ideForgetDocument(e,t,r=!1){let n=Be(e),{documents:i}=n,s=n.scope.getRelativeData("."),a=i.documents.getItem(t),l=s.getItem("browser"),c=l.getItem("selectedPath"),u=c===null?null:l.getItem("store").getNode(c);a&&l.getItem("root")===a.getItem("root")&&u?.attr.path===a.getItem("path")&&l.setItem("selectedPath",null),i.close(t,r)}};var tr=class extends Y{constructor({readOnly:e=!1}={}){super({cacheTime:-1,readOnly:e}),this.store=null,this.path=null,this.pending=null}bind(e,t){if(this.store!==null)throw new Error("TreeStoreResolver is already bound");this.store=e,this.path=t}load(){if(this.store===null)throw new Error("TreeStoreResolver is not bound to a store");if(this.pending!==null)return this.pending;let e=this.node,t=this.path?this.store.pathFor(e):"",r=this.store.load(t,t?e.label:null,t?{...e.attr}:{});return this.pending=r,r.finally(()=>{this.pending===r&&(this.pending=null)}).catch(()=>{}),r}};Ni(tr,{module:"gramlot.tree_store",name:"TreeStoreResolver",encode:()=>({args:[],kwargs:{}}),decode:()=>new tr});var Fo=class{constructor({gramlot:e,method:t,params:r={}}){if(!e||typeof t!="string"||!t)throw new TypeError("TreeStore requires a page and method");for(let n of["path","label","attributes"])if(Object.hasOwn(r,n))throw new TypeError(`TreeStore params reserves ${n}`);this.gramlot=e,this.method=t,this.params={...r},this.controller=new AbortController,this.root=null}pathFor(e){let t=[];for(;e&&e.parentBag!==this.root;)t.unshift(e.label),e=e.parentNode;if(!e||this.root===null)throw new Error("TreeStore node is outside its root");return t.unshift(e.label),t.join(".")}async load(e="",t=null,r={}){if(this.controller.signal.aborted)throw this.controller.signal.reason;let n=await this.gramlot.rpc.call("data",this.method,{...this.params,path:e,label:t,attributes:r},{signal:this.controller.signal});if(this.controller.signal.aborted)throw this.controller.signal.reason;if(!(n instanceof x))throw new TypeError("TreeStore method must return a Bag");e||(this.root=n,n.setBackref());let i=(s,a)=>{for(let l of s.getNodes()){let c=a?`${a}.${l.label}`:l.label;l.resolver instanceof tr&&l.resolver.bind(this,c),l.staticValue instanceof x&&i(l.staticValue,c)}};return i(n,e),n}dispose(){this.controller.abort()}},Ds=class{treeFavoriteActionState(e,{item:t,state:r}){let n=t.resolver!==null||t.staticValue instanceof x;if(t.getAttr("favoriteEntry")===!0)return{hidden:!1,icon:"\u2715",title:"Remove favorite"};let i=!n&&r.getNodes().some(s=>s.getAttr("fieldpath")===t.getAttr("fieldpath"));return{hidden:n,icon:i?"\u2665":"\u2661",title:i?"Remove favorite":"Add favorite"}}treeFavoritesMount(e,{favoriteKey:t}){let n=this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.getItem(t);this.setTreeFavorites(e.getRelativeData("."),n===null?[]:j(n))}setTreeFavorites(e,t){if(!Array.isArray(t))throw new TypeError("Tree favorites must be an array");let r=new x;t.forEach((n,i)=>{if(!n||typeof n.fieldpath!="string"||typeof n.path!="string"||typeof n.caption!="string"||!n.attrs||typeof n.attrs!="object")throw new TypeError("Invalid tree favorite");let s={...n.attrs};for(let a of["caption","fullcaption"])typeof s[a]=="string"&&(s[a]=s[a].replace(/(^|\.)!!(?:\[[^\]]+\])?/g,"$1"));r.setItem(`favorite_${i}`,null,{...s,favoriteEntry:!0,originalPath:n.path})}),e.setItem("favorites",r)}treeFavoriteToggle(e,{item:t,path:r,favoriteKey:n}){if(t.resolver||t.staticValue instanceof x)return;let i=t.getAttr(),s=e.getRelativeData("."),a=s.getItem("favorites").getNodes().map(u=>{let{favoriteEntry:d,originalPath:f,...h}=u.getAttr();return{fieldpath:h.fieldpath,path:f,caption:h.caption,attrs:h}}),l=a.findIndex(u=>u.fieldpath===i.fieldpath);l===-1?a.push({fieldpath:i.fieldpath,path:r,caption:i.caption,attrs:{...i}}):a.splice(l,1),this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.setItem(n,R(a)),this.setTreeFavorites(s,a)}treeStoreMount(e,{storeMethod:t,storeParams:r}){let n=e.parentNode,i=e.getRelativeData("."),s=new Fo({gramlot:this.page,method:t,params:r});this.page.src.renderer.onDispose(n,()=>s.dispose());let a=new tr({readOnly:!0});return a.bind(s,""),i.setResolver("store",a),Promise.resolve(i.getItem("store")).then(l=>{s.controller.signal.aborted||i.setItem("store",l)})}treeInspect(e,{item:t,path:r}){let n=this.page.src.binding.bindingFor(e),i=!1,s=`tree_inspect_${G()}`,a=()=>{},l=()=>{i||(i=!0,a(),this.page.src.source.getNode(s)&&this.page.src.source.popNode(s))};a=n.track(l);try{let c=new me,u=c.root.html_dialog({nodeId:s,request:s,connect_oncancel:"treeInspectClose",connect_onclose:"treeInspectClose","aria-labelledby":`${s}_title`,style:"width:min(36rem,calc(100% - 48px));max-height:80vh;overflow:auto;"});u.h2("Attributes",{id:`${s}_title`}),u.p(`==${JSON.stringify(r)}`),u.html_button("Close",{type:"button",autofocus:!0,request:s,connect_onclick:"treeInspectClose"});let d=u.table();for(let[h,p]of Object.entries(t.getAttr())){let m=d.tr();m.th(`==${JSON.stringify(h)}`,{scope:"row"});let b=typeof p=="string"?p:p===void 0?"undefined":R(p);m.td(`==${JSON.stringify(b)}`)}this.page.src.source.setItem(s,this.page.src.prepareSource(c.source));let f=this.page.src.binding.nodeIds.get(s);Object.defineProperty(f,"treeInspectClose",{value:l,configurable:!0}),this.page.src.renderer.onDispose(f,()=>{l(),delete f.treeInspectClose}),this.page.dom.getDomNode(f).showModal()}catch(c){throw l(),c}}treeInspectClose(e,t){t.preventDefault();let r=this.page.src.binding.nodeIds.get(e.getAttr("request"));r&&r.treeInspectClose()}};var _n=class{constructor({maxBytes:e}){if(!Number.isSafeInteger(e)||e<0)throw new TypeError("maxBytes must be a nonnegative safe integer");this.maxBytes=e}write(e){throw new Error("UploadTarget.write must be implemented")}finish(){throw new Error("UploadTarget.finish must be implemented")}abort(){throw new Error("UploadTarget.abort must be implemented")}status(){throw new Error("UploadTarget.status must be implemented")}};var Qb=new Set(Object.entries(new Je().schema).filter(([,o])=>!o._meta?.data_element&&!o._meta?.subbuilder&&!o._meta?.container).map(([o])=>o));function yn(o){if(!(o==null||o==="html")){if(!Array.isArray(o)||o.some(e=>typeof e!="string"||!e||e.trim()!==e))throw new TypeError('catalogue must be "html" or a list of tag names');if(!o.includes("div"))throw new Error("catalogue must include div for pageRoot")}}function vn(o,e,t={}){return o==null?!0:Array.isArray(o)?o.includes(e):!t.gramlot_component&&!t.data_element&&!t.subbuilder&&!t.container&&Qb.has(t.render_tag??e)}function tt(o,e){if(o==null)return;let t=(r,n)=>{for(let i of r.getNodes()){let s=n?`${n}.${i.label}`:i.label;if(!vn(o,i.nodeTag,i.getAttr("_meta")??{}))throw new Error(`Tag ${i.nodeTag} is outside the editor catalogue at ${s}`);if(i.resolver)throw new Error(`Catalogue scope requires materialized Source at ${s}`);let a=i.getValue(!0);a instanceof N&&t(a,s)}};t(e,"")}var Ce={navigation:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%224%22%20width%3D%2218%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M9%204v16M5.5%208h1M5.5%2012h1%22%2F%3E%3C%2Fsvg%3E",catalogue:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%2214%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%223%22%20y%3D%2214%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M14%2017.5h7M17.5%2014v7%22%2F%3E%3C%2Fsvg%3E",properties:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M4%206h16M4%2012h16M4%2018h16%22%2F%3E%3Ccircle%20cx%3D%228%22%20cy%3D%226%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2216%22%20cy%3D%2212%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2210%22%20cy%3D%2218%22%20r%3D%222%22%2F%3E%3C%2Fsvg%3E",new:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M14%202H6a2%202%200%200%200-2%202v16a2%202%200%200%200%202%202h12a2%202%200%200%200%202-2V8Z%20M14%202v6h6%20M8%2015h8%20M12%2011v8%22%2F%3E%3C%2Fsvg%3E",download:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M12%203v12m-5-5%205%205%205-5%20M4%2016v4a1%201%200%200%200%201%201h14a1%201%200%200%200%201-1v-4%22%2F%3E%3C%2Fsvg%3E",copy:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2212%22%20height%3D%2213%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M16%208V5a2%202%200%200%200-2-2H5a2%202%200%200%200-2%202v9a2%202%200%200%200%202%202h3%22%2F%3E%3C%2Fsvg%3E"};Ce.open="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%207V5a2%202%200%200%201%202-2h5l2%202h7a2%202%200%200%201%202%202v2M3%209h18l-2%2011H4z%22%2F%3E%3C%2Fsvg%3E";Ce.cut="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Ccircle%20cx%3D%226%22%20cy%3D%226%22%20r%3D%223%22%2F%3E%3Ccircle%20cx%3D%226%22%20cy%3D%2218%22%20r%3D%223%22%2F%3E%3Cpath%20d%3D%22m8%208%2012%2012M8%2016%2020%204%22%2F%3E%3C%2Fsvg%3E";Ce.paste="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%225%22%20y%3D%225%22%20width%3D%2214%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Crect%20x%3D%229%22%20y%3D%222%22%20width%3D%226%22%20height%3D%225%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M9%2012h6m-6%204h6%22%2F%3E%3C%2Fsvg%3E";Ce.appearance="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%228%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%2F%3E%3Cpath%20d%3D%22M12%204a8%208%200%200%201%200%2016z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";var Ns=class{constructor(e,{datapath:t="__editor",dataRoot:r="",editorId:n="visual",uploadOperation:i="import_source",codeDocument:s=null,catalogue:a=null,fileCommands:l=!0,canvasCss:c=null,...u}={}){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(n))throw new Error("editorId must be a literal identifier");if(!r&&t!=="__editor"&&!t.startsWith("__editor."))throw new Error("Root Data editing requires an __editor datapath");if(yn(a),c!=null&&(!Array.isArray(c)||c.some(nr=>typeof nr!="string")))throw new TypeError("canvasCss must be a list of CSS texts");this.dataRoot=r;let d=this.pane=e.main({node_label:n,datapath:t,visualEditorId:n,...u,nodeId:`${n}Editor`,class:`visual-editor-shell ${u.class??""}`,overflow:"hidden",tabindex:0,connect_onkeydown:"clipboardShortcut"});d.dataSetter({destination_path:".catalogueScope",value:a}),d.dataSetter({destination_path:".canvasCss",value:c}),d.dataSetter({destination_path:".uploadQueue",value:new x}),d.dataController({func:"initializeEditor",dataRoot:this.dataRoot,_init:!0}),d.dataController({func:"showProperties",path:"^.selection",_init:!0}),d.dataController({func:"initializeCanvasSelection",_onBuilt:!0}),d.dataController({func:"initializeDocument",_onBuilt:!0}),d.dataController({func:"highlightSelection",path:"^.selection",_init:!0}),d.style("^.appearanceCss"),d.dataController({func:"initializeEditorAppearance",_onBuilt:!0}),d.dataController({func:"applyEditorAppearance",profile:"^.appearanceProfile",palette:"^.appearancePalette",mode:"^.appearanceMode"});let f=this.rail=d.menu({presentation:"bar",orientation:"vertical",aria_label:"Editor panels",class:"visual-editor-rail"});this.toolButton(f.menuline({group:!0}),"Source / Data","toggleNavigation",Ce.navigation),this.toolButton(f.menuline({group:!0}),"Catalogue","openCatalogue",Ce.catalogue),this.toolButton(f.menuline({group:!0}),"Properties","openProperties",Ce.properties),this.toolButton(f.menuline({group:!0}),"Clipboard","this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))",Ce.paste,{dropTarget:!0,dropTypes:"app/source",dropTags:`${n}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard"}),f.spacer({flex:1}),this.toolButton(f.menuline({group:!0}),"Appearance","this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))",Ce.appearance);let h=d.framePane({node_label:"layout",height:"100%",id:`${n}-editor-frame`,class:"visual-editor-layout"});h.top.setAttr({height:"30px"});let p=h.top.menu({presentation:"bar",aria_label:"Editor tools",class:"visual-editor-toolbar"});p.menuline({group:!0}).span("Source editor",{class:"visual-editor-brand"});let m=p.menuline({group:!0,gap:"4px",hidden:!l});for(let[nr,Zo,Ko]of[["New","newPage","new"],["Open","openUpload","open"],["Download","downloadPage","download"],["Copy Source","copySource","copy"]])this.toolButton(m,nr,Zo,Ce[Ko],{id:`${n}-${Ko}`});p.menuline({group:!0}).span({class:"visual-toolbar-divider",aria_hidden:"true"});let b=p.menuline({group:!0,gap:"2px"});this.toolButton(b,"Cut branch","cutBranch",Ce.cut,{title:"Cut branch (F8)"}),this.toolButton(b,"Copy branch","copyBranch",Ce.copy),this.toolButton(b,"Paste branch","pasteBranch",Ce.paste,{title:"Paste branch (F9)"}),p.spacer({flex:1}),p.menuline({group:!0,hidden:"^.modified:=!{}"}).span("Unsaved changes",{role:"status",class:"visual-editor-hint"}),p.menuline({group:!0}).span("^.fileStatus",{role:"status",class:"visual-editor-file-status"}),p.menuline({group:!0}).span("^.filename",{class:"visual-editor-filename"});let w=h.left;w.setAttr({width:"min(240px, 34vw)",splitter:!0,drawer:"^.navigationOpen",default_drawer:!0,drawer_label:"Source / Data",drawer_onclick:"this.SET('.navigationOpen', show ? true : 'close')",display:"flex",flex_direction:"column",min_height:0,class:"visual-editor-sidebar"});let _=w.borderContainer({height:"100%",flex:1,min_height:0}),v=_.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),E=v.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),D=E.contentPane({node_label:"source",region:"center",title:"Source",detachable:!0,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(D,"sourceSearch","Search Source"),D.tree({storepath:`*S.${Z(d).fullpath.split(".").slice(1).join(".")}.layout.center.design`,hideValues:!0,getLabel:"sourceLabel",searchText:"^.sourceSearch",selectedPath:"^.selection",draggable:!0,dragTags:`${n}Source`,effectAllowed:"all",onDrag:"prepareSource",dropTarget:!0,dropTypes:"app/widget,app/source,app/clipboard",dropTags:`widget,${n}Source,${n}Clipboard`,dropEffect:"^.sourceDropEffect",onDrop:"dropNode",id:`${n}-source-tree`,class:"visual-source-tree",flex:1,min_height:0});let k=E.contentPane({node_label:"clipboard",region:"bottom",height:"112px",splitter:!0,minSize:80,title:"Clipboard",detachable:!0,hidden:"^.clipboardVisible:=!{}",display:"flex",flex_direction:"column",min_height:0,overflow:"hidden",dropTarget:!0,dropTypes:"app/source",dropTags:`${n}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard",class:"visual-clipboard"});k.span("Drop a branch here \xB7 Option to copy",{class:"visual-editor-hint"}),k.tree({storepath:".clipboard",hideValues:!0,labelAttribute:"name",selectedPath:"^.clipboardSelection",draggable:!0,dragTags:`${n}Clipboard`,effectAllowed:"copy",onDrag:"prepareClipboard",id:`${n}-clipboard-tree`,class:"visual-clipboard-tree",flex:1,min_height:0}),k.p("^.error",{role:"alert",class:"visual-editor-hint"});let C=v.contentPane({node_label:"data",region:"bottom",title:"Data",detachable:!0,height:"108px",splitter:!0,minSize:80,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(C,"dataSearch","Search Data"),C.tree({storepath:this.dataRoot?`*D.${this.dataRoot}`:"*D",excludeRoot:this.dataRoot?null:"__editor",searchText:"^.dataSearch",id:`${n}-data-tree`,flex:1,min_height:0});let O=h.center;O.setAttr({overflow:"auto",class:"visual-editor-workspace"});let L=O.div({node_label:"design",class:"visual-editor-canvas"});L.div({node_label:"pageRoot",...this.dataRoot?{datapath:this.dataRoot}:{}});let z=d.floatingPane({title:"Widget catalogue",open:"^.catalogueOpen",default_open:!1,width:"280px",height:"400px",class:"visual-editor-popup",movable:!0,resizable:!0});this.search(z.frame.top,"catalogueSearch","Search widgets"),z.frame.center.tree({storepath:".catalogue",hideValues:!0,labelAttribute:"caption",searchText:"^.catalogueSearch",draggable:!0,dragTags:"widget",effectAllowed:"all",onDrag:"prepareWidget",id:`${n}-widget-tree`});let V=_.contentPane({region:"bottom",height:"^.propertiesHeight",default_height:"200px",minSize:140,splitter:!0,title:"^.propertiesTitle",detachable:!0,hidden:"^.propertiesOpen:=!{}",display:"flex",flex_direction:"column",overflow:"hidden",min_height:0});V.div({nodeId:`${n}EditorFields`,class:"visual-editor-fields",display:"flex",flex_direction:"column",flex:1,min_height:0}).span(""),V.p("^.propertyError",{role:"alert",class:"visual-editor-hint",margin:"3px"}),d.dialog({class:"visual-editor-popup",title:"Open Source",open:"^.uploadOpen",width:"480px",height:"300px",movable:!0,resizable:!0}).frame.center.uploader({operation:i,storepath:".uploadQueue",accept:".grmlt",multiple:!1,autoUpload:!0,onComplete:"sourceUploaded",id:`${n}-uploader`});let _e=d.dialog({class:"visual-editor-popup",title:"Save branch to clipboard",open:"^.clipboardOpen",width:"380px",height:"210px"});_e.frame.center.textbox({value:"^.clipboardDraft.name",lbl:"Name",margin:"12px"}),_e.frame.center.p("^.error",{role:"alert",margin:"12px"});let ht=_e.frame.bottom.menu({presentation:"bar",aria_label:"Clipboard commands",padding:"3px 6px"});ht.spacer({flex:1});let ne=ht.menuline({group:!0,gap:"8px"});ne.button("Cancel",{action:"this.SET('.clipboardOpen', false)"}),ne.button("Save branch",{action:"saveClipboard"});let X=d.dialog({class:"visual-editor-popup",title:"Required parameters",open:"^.insertionOpen",width:"400px",height:"280px",movable:!0,resizable:!0});X.frame.center.div({nodeId:`${n}InsertFields`,class:"visual-editor-fields",padding:"6px"}).span(""),X.frame.center.p("^.error",{role:"alert"});let pt=X.frame.bottom.menu({presentation:"bar",aria_label:"Insertion commands",padding:"3px 6px",border_top:"1px solid var(--gramlot-border)"});pt.spacer({flex:1});let Yo=pt.menuline({group:!0,gap:"8px"});Yo.button("Cancel",{action:"this.SET('.insertionOpen', false)"}),Yo.button("Insert",{action:"insertWidget"});let Dt=d.floatingPane({class:"visual-editor-popup",title:"Appearance",open:"^.appearanceOpen",default_open:!1,width:"280px",height:"260px",movable:!0,resizable:!0}).frame.center.formlet({columns:1,lbl_position:"TL",gap:"4px",padding:"6px"});Dt.filteringSelect({validate_notnull:!0,lbl:"Theme",value:"^.appearanceProfile",values:"base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela"}),Dt.filteringSelect({validate_notnull:!0,lbl:"Colors",value:"^.appearancePalette",values:"default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue"}),Dt.filteringSelect({validate_notnull:!0,lbl:"Mode",value:"^.appearanceMode",values:"light:Light,dark:Dark"}),d.p("^.error",{role:"alert",class:"visual-editor-error",hidden:"^.error:=!{}"}),this.frame=h,this.toolbar=p,this.design=L,s!==null&&this.codeDocument(s)}toolButton(e,t,r,n,i={}){let s=e.button({aria_label:t,title:t,action:r,class:"button--quiet visual-editor-tool",...i});return s.span({class:"visual-tool-icon",aria_hidden:"true",style:`mask-image:url("${n}")`}),s}codeDocument(e,t=this.frame){if(!["python","javascript"].includes(e.language))throw new TypeError("Expected a Python or JavaScript page document");let r=this.pane;r.setAttr({codeDocumentKey:e.key}),r.dataSetter({destination_path:".codeDocument",value:new x({...e,saved:e.content,busy:!1,status:""})});let n=`#${r.getAttr("visualEditorId")}Editor`;(t===this.frame?this.toolbar:t.top.menu({presentation:"bar",aria_label:"Code drawer"})).menuline({group:!0}).button("Code",{action:"openCode",class:"button--quiet"});let s=t.right;s.setAttr({class:"visual-editor-code",datapath:n,title:"Page code",detachable:!0,width:"60%",minSize:240,splitter:!0,drawer:"^.codeOpen",default_drawer:"close",drawer_label:"Code",drawer_minimize:!1,drawer_onclick:"this.SET('.codeOpen', show ? true : 'close')",min_height:0,overflow:"hidden"});let a=s.framePane({height:"100%",width:"100%",min_width:0,flex:1});a.top.setAttr({height:"26px"}),a.bottom.setAttr({height:"48px"}),a.center.setAttr({display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"}),a.top.div(e.path,{padding:"3px 6px",font_size:"12px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),a.center.codeMirror({value:"^.codeDocument.content",language:e.language,live:!0,readonly:"^.codeDocument.writable:=!{}",height:"100%",box_height:"100%",box_c_height:"100%",box_min_height:0,box_c_min_height:0,fontSize:13,flex:1,min_height:0}),a.bottom.div("^.codeDocument.status",{role:"status",font_size:"12px",padding:"4px 10px"});let l=a.bottom.menu({presentation:"bar",aria_label:"Page code commands",padding:"3px 6px"});l.spacer({flex:1});let c=l.menuline({group:!0,gap:"6px"});c.button("Close",{action:"this.SET('.codeOpen', 'close')"}),c.button("Preview saved",{action:"codePreview",disabled:"^.codeDocument.busy"}),c.button("Save",{action:"codeSave",disabled:"^.codeSaveDisabled"}),r.dataFormula({result_path:".codeSaveDisabled",formula:"!writable || busy || content === saved",writable:"^.codeDocument.writable",busy:"^.codeDocument.busy",content:"^.codeDocument.content",saved:"^.codeDocument.saved",_init:!0})}search(e,t,r){let i=e.menu({presentation:"bar",aria_label:r,class:"visual-search-toolbar"}).menuline({group:!0,flex:1,min_width:0}).div({class:"visual-search-field"});i.span({class:"visual-search-icon",aria_hidden:"true"}),i.input({type:"search",value:`^.${t}`,default:"",live:!0,placeholder:r,aria_label:r}),i.html_button({type:"button",class:"visual-search-clear",aria_label:`Clear ${r.toLowerCase()}`,hidden:`^.${t}:={} === ''`,connect_onclick:`this.SET('.${t}', '')`})}};var Os=class extends _n{constructor({catalogue:e=null}={}){super({maxBytes:5*1024*1024}),yn(e),this.catalogue=e,this.decoder=new TextDecoder("utf-8",{fatal:!0}),this.parts=[],this.outcome={state:"pending"}}write(e){this.parts.push(this.decoder.decode(e,{stream:!0}))}finish(){this.parts.push(this.decoder.decode());let e=this.parts.join("");this.parts=[];let t=j(e);if(!(t instanceof N)||t.length!==1||t.getNodes()[0].label!=="pageRoot")throw new TypeError("Expected one pageRoot Source");return tt(this.catalogue,t),this.outcome={state:"completed",result:e},this.outcome}abort(){return this.outcome.state!=="completed"&&(this.parts=[],this.outcome={state:"unsaved"}),this.outcome}status(){return this.outcome}};var _c={};ee(_c,{default:()=>mh});function ew(o,e){this.v=o,this.k=e}function Xf(o,e){(e==null||e>o.length)&&(e=o.length);for(var t=0,r=Array(e);t<e;t++)r[t]=o[t];return r}function tw(o){if(Array.isArray(o))return o}function rw(o,e){var t=o==null?null:typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(t!=null){var r,n,i,s,a=[],l=!0,c=!1;try{if(i=(t=t.call(o)).next,e===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(r=i.call(t)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(u){c=!0,n=u}finally{try{if(!l&&t.return!=null&&(s=t.return(),Object(s)!==s))return}finally{if(c)throw n}}return a}}function nw(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
233
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ow(o,e){return tw(o)||rw(o,e)||iw(o,e)||nw()}function iw(o,e){if(o){if(typeof o=="string")return Xf(o,e);var t={}.toString.call(o).slice(8,-1);return t==="Object"&&o.constructor&&(t=o.constructor.name),t==="Map"||t==="Set"?Array.from(o):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Xf(o,e):void 0}}function $s(o){var e,t;function r(i,s){try{var a=o[i](s),l=a.value,c=l instanceof ew;Promise.resolve(c?l.v:l).then(function(u){if(c){var d=i==="return"&&l.k?i:"next";if(!l.k||u.done)return r(d,u);u=o[d](u).value}n(!!a.done,u)},function(u){r("throw",u)})}catch(u){n(2,u)}}function n(i,s){i===2?e.reject(s):e.resolve({value:s,done:i}),(e=e.next)?r(e.key,e.arg):t=null}this._invoke=function(i,s){return new Promise(function(a,l){var c={key:i,arg:s,resolve:a,reject:l,next:null};t?t=t.next=c:(e=t=c,r(i,s))})},typeof o.return!="function"&&(this.return=void 0)}$s.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},$s.prototype.next=function(o){return this._invoke("next",o)},$s.prototype.throw=function(o){return this._invoke("throw",o)},$s.prototype.return=function(o){return this._invoke("return",o)};var ch=Object.entries,Yf=Object.setPrototypeOf,sw=Object.isFrozen,uh=Object.getPrototypeOf,dh=Object.getOwnPropertyDescriptor,we=Object.freeze,ke=Object.seal,xn=Object.create,fh=typeof Reflect<"u"&&Reflect,bc=fh.apply,wc=fh.construct;we||(we=function(e){return e});ke||(ke=function(e){return e});bc||(bc=function(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return e.apply(t,n)});wc||(wc=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return new e(...r)});var St=ae(Array.prototype.forEach);Array.prototype.indexOf;var aw=ae(Array.prototype.lastIndexOf),Zf=ae(Array.prototype.pop),zo=ae(Array.prototype.push),lw=ae(Array.prototype.slice),cw=ae(Array.prototype.splice),kn=Array.isArray,lc=hh(Set),cc=ae(Set.prototype.add),qo=ae(Set.prototype.has),jr=ae(String.prototype.toLowerCase),uc=ae(String.prototype.toString),Kf=ae(String.prototype.match),Uo=ae(String.prototype.replace),Jf=ae(String.prototype.indexOf),uw=ae(String.prototype.trim),dw=ae(Number.prototype.toString),fw=ae(Boolean.prototype.toString),Qf=typeof BigInt>"u"?null:ae(BigInt.prototype.toString),eh=typeof Symbol>"u"?null:ae(Symbol.prototype.toString),Me=ae(Object.prototype.hasOwnProperty),Vo=ae(Object.prototype.toString),xe=ae(RegExp.prototype.test),At=hh(TypeError);function ae(o){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return bc(o,e,r)}}function hh(o){return function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return wc(o,t)}}function J(o,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jr;if(Yf&&Yf(o,null),!kn(e))return o;let r=e.length;for(;r--;){let n=e[r];if(typeof n=="string"){let i=t(n);i!==n&&(sw(e)||(e[r]=i),n=i)}o[n]=!0}return o}function hw(o){for(let e=0;e<o.length;e++)Me(o,e)||(o[e]=null);return o}function ze(o){let e=xn(null);for(let r of ch(o)){var t=ow(r,2);let n=t[0],i=t[1];Me(o,n)&&(kn(i)?e[n]=hw(i):i&&typeof i=="object"&&i.constructor===Object?e[n]=ze(i):e[n]=i)}return e}function pw(o){switch(typeof o){case"string":return o;case"number":return dw(o);case"boolean":return fw(o);case"bigint":return Qf?Qf(o):"0";case"symbol":return eh?eh(o):"Symbol()";case"undefined":return Vo(o);case"function":case"object":{if(o===null)return Vo(o);let e=o,t=Ve(e,"toString");if(typeof t=="function"){let r=t(e);return typeof r=="string"?r:Vo(r)}return Vo(o)}default:return Vo(o)}}function Ve(o,e){for(;o!==null;){let r=dh(o,e);if(r){if(r.get)return ae(r.get);if(typeof r.value=="function")return ae(r.value)}o=uh(o)}function t(){return null}return t}function mw(o,e){for(;o!==null;){let t=dh(o,e);if(t)return t.get?ae(t.get):null;o=uh(o)}return null}function gw(o){try{return xe(o,""),!0}catch{return!1}}var th=we(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),dc=we(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),fc=we(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),bw=we(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),hc=we(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),ww=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),rh=we(["#text"]),nh=we(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),pc=we(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),oh=we(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Rs=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_w=ke(/{{[\w\W]*|^[\w\W]*}}/g),yw=ke(/<%[\w\W]*|^[\w\W]*%>/g),vw=ke(/\${[\w\W]*/g),xw=ke(/^data-[\-\w.\u00B7-\uFFFF]+$/),kw=ke(/^aria-[\-\w]+$/),ih=ke(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ew=ke(/^(?:\w+script|data):/i),Tw=ke(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Sw=ke(/^html$/i),Aw=ke(/^[a-z][.\w]*(-[.\w]+)+$/i),mc=ke(/<[/\w!]/g),sh=ke(/<[/\w]/g),Iw=ke(/<\/no(script|embed|frames)/i),ah=ke(/\/>/i),fe={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Cw=we(J({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),Dw=function(){return typeof window>"u"?null:window},Nw=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},lh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},rr=function(e,t,r,n){return Me(e,t)&&kn(e[t])?J(n.base?ze(n.base):{},e[t],n.transform):r},gc=function(e,t,r){let n=Me(e,t)?e[t]:void 0;return n&&typeof n=="object"?ze(n):r()};function ph(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Dw(),e=I=>ph(I);if(e.version="3.4.17",e.removed=[],!o||!o.document||o.document.nodeType!==fe.document||!o.Element)return e.isSupported=!1,e;let t=o.document,r=t,n=r.currentScript;o.DocumentFragment;let i=o.HTMLTemplateElement,s=o.Node,a=o.Element,l=o.NodeFilter;o.NamedNodeMap===void 0&&(o.NamedNodeMap||o.MozNamedAttrMap),o.HTMLFormElement;let c=o.DOMParser,u=o.trustedTypes,d=a.prototype,f=Ve(d,"cloneNode"),h=Ve(d,"remove"),p=Ve(d,"removeAttributeNode"),m=Ve(d,"nextSibling"),b=Ve(d,"childNodes"),w=Ve(d,"parentNode"),_=Ve(d,"shadowRoot"),v=Ve(d,"attributes"),E=s&&s.prototype?Ve(s.prototype,"nodeType"):null,D=s&&s.prototype?Ve(s.prototype,"nodeName"):null,k=s&&s.prototype?Ve(s.prototype,"ownerDocument"):null,C=function(g){return E?E(g):g.nodeType},O=function(g){return D?D(g):g.nodeName},L=mw(d,"namespaceURI"),z=function(g){return L?L(g):g.namespaceURI};if(typeof i=="function"){let I=t.createElement("template");I.content&&I.content.ownerDocument&&(t=I.content.ownerDocument)}let V,le="",_e,ht=!1,ne=0,X=function(){if(ne>0)throw At('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},pt=function(g){X(),ne++;try{return V.createHTML(g)}finally{ne--}},Yo=function(g){X(),ne++;try{return V.createScriptURL(g)}finally{ne--}},Jc=function(){return ht||(_e=Nw(u,n),ht=!0),_e},Dt=t,nr=Dt.implementation,Zo=Dt.createNodeIterator,Ko=Dt.createDocumentFragment,Sh=Dt.getElementsByTagName,Ah=r.importNode,oe=lh();e.isSupported=typeof ch=="function"&&typeof w=="function"&&nr&&nr.createHTMLDocument!==void 0;let Ih=_w,Ch=yw,Dh=vw,Nh=xw,Oh=kw,$h=Ew,Qc=Tw,Rh=Aw,eu=ih,ie=null,Xs=J({},[...th,...dc,...fc,...hc,...rh]),se=null,Ys=J({},[...nh,...pc,...oh,...Rs]),rt=Object.seal(xn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Tn=null,tu=null,Nt=Object.seal(xn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ru=!0,Zs=!0,nu=!1,Ks=!0,mt=!1,or=!0,ir=!1,Js=!1,Jo=null,Qo=null,Qs=!1,Pr=!1,ei=!1,ti=!1,ou=!0,iu=!1,su="user-content-",ea=!0,ta=!1,sr=null,Br={},ar=null,au=J({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),lu=null,cu=J({},["audio","video","img","source","image","track"]),uu=null,du=J({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ri="http://www.w3.org/1998/Math/MathML",ni="http://www.w3.org/2000/svg",nt="http://www.w3.org/1999/xhtml",Mr=nt,ra=!1,na=null,jh=J({},[ri,ni,nt],uc),fu=we(["mi","mo","mn","ms","mtext"]),oa=J({},fu),hu=we(["annotation-xml"]),ia=J({},hu),Ph=J({},["title","style","font","a","script"]),Sn=null,Bh=["application/xhtml+xml","text/html"],Mh="text/html",ue=null,Lr=null,Lh=t.createElement("form"),pu=function(g){return g instanceof RegExp||g instanceof Function},sa=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Lr&&Lr===g)return;(!g||typeof g!="object")&&(g={}),g=ze(g),Sn=Bh.indexOf(g.PARSER_MEDIA_TYPE)===-1?Mh:g.PARSER_MEDIA_TYPE,ue=Sn==="application/xhtml+xml"?uc:jr,ie=rr(g,"ALLOWED_TAGS",Xs,{transform:ue}),se=rr(g,"ALLOWED_ATTR",Ys,{transform:ue}),na=rr(g,"ALLOWED_NAMESPACES",jh,{transform:uc}),uu=rr(g,"ADD_URI_SAFE_ATTR",du,{transform:ue,base:du}),lu=rr(g,"ADD_DATA_URI_TAGS",cu,{transform:ue,base:cu}),ar=rr(g,"FORBID_CONTENTS",au,{transform:ue}),Tn=rr(g,"FORBID_TAGS",ze({}),{transform:ue}),tu=rr(g,"FORBID_ATTR",ze({}),{transform:ue}),Br=Me(g,"USE_PROFILES")?g.USE_PROFILES&&typeof g.USE_PROFILES=="object"?ze(g.USE_PROFILES):g.USE_PROFILES:!1,ru=g.ALLOW_ARIA_ATTR!==!1,Zs=g.ALLOW_DATA_ATTR!==!1,nu=g.ALLOW_UNKNOWN_PROTOCOLS||!1,Ks=g.ALLOW_SELF_CLOSE_IN_ATTR!==!1,mt=g.SAFE_FOR_TEMPLATES||!1,or=g.SAFE_FOR_XML!==!1,ir=g.WHOLE_DOCUMENT||!1,Pr=g.RETURN_DOM||!1,ei=g.RETURN_DOM_FRAGMENT||!1,ti=g.RETURN_TRUSTED_TYPE||!1,Qs=g.FORCE_BODY||!1,ou=g.SANITIZE_DOM!==!1,iu=g.SANITIZE_NAMED_PROPS||!1,ea=g.KEEP_CONTENT!==!1,ta=g.IN_PLACE||!1,eu=gw(g.ALLOWED_URI_REGEXP)?g.ALLOWED_URI_REGEXP:ih,Mr=typeof g.NAMESPACE=="string"?g.NAMESPACE:nt,oa=gc(g,"MATHML_TEXT_INTEGRATION_POINTS",()=>J({},fu)),ia=gc(g,"HTML_INTEGRATION_POINTS",()=>J({},hu));let y=gc(g,"CUSTOM_ELEMENT_HANDLING",()=>xn(null));if(rt=xn(null),Me(y,"tagNameCheck")&&pu(y.tagNameCheck)&&(rt.tagNameCheck=y.tagNameCheck),Me(y,"attributeNameCheck")&&pu(y.attributeNameCheck)&&(rt.attributeNameCheck=y.attributeNameCheck),Me(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(rt.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),ke(rt),mt&&(Zs=!1),ei&&(Pr=!0),Br&&(ie=J({},rh),se=xn(null),Br.html===!0&&(J(ie,th),J(se,nh)),Br.svg===!0&&(J(ie,dc),J(se,pc),J(se,Rs)),Br.svgFilters===!0&&(J(ie,fc),J(se,pc),J(se,Rs)),Br.mathMl===!0&&(J(ie,hc),J(se,oh),J(se,Rs))),Nt.tagCheck=null,Nt.attributeCheck=null,Me(g,"ADD_TAGS")&&(typeof g.ADD_TAGS=="function"?Nt.tagCheck=g.ADD_TAGS:kn(g.ADD_TAGS)&&(ie===Xs&&(ie=ze(ie)),J(ie,g.ADD_TAGS,ue))),Me(g,"ADD_ATTR")&&(typeof g.ADD_ATTR=="function"?Nt.attributeCheck=g.ADD_ATTR:kn(g.ADD_ATTR)&&(se===Ys&&(se=ze(se)),J(se,g.ADD_ATTR,ue))),Me(g,"ADD_FORBID_CONTENTS")&&kn(g.ADD_FORBID_CONTENTS)&&(ar===au&&(ar=ze(ar)),J(ar,g.ADD_FORBID_CONTENTS,ue)),ea&&(ie["#text"]=!0),ir&&J(ie,["html","head","body"]),ie.table&&(J(ie,["tbody"]),delete Tn.tbody),g.TRUSTED_TYPES_POLICY){if(typeof g.TRUSTED_TYPES_POLICY.createHTML!="function")throw At('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof g.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw At('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let T=V;V=g.TRUSTED_TYPES_POLICY;try{le=pt("")}catch(S){throw V=T,S}}else g.TRUSTED_TYPES_POLICY===null?(V=void 0,le=""):(V===void 0&&(V=Jc()),V&&typeof le=="string"&&(le=pt("")));we&&we(g),Lr=g},mu=J({},[...dc,...fc,...bw]),gu=J({},[...hc,...ww]),Fh=function(g,y,T){return y.namespaceURI===nt?g==="svg":y.namespaceURI===ri?g==="svg"&&(T==="annotation-xml"||oa[T]):!!mu[g]},zh=function(g,y,T){return y.namespaceURI===nt?g==="math":y.namespaceURI===ni?g==="math"&&ia[T]:!!gu[g]},qh=function(g,y,T){return y.namespaceURI===ni&&!ia[T]||y.namespaceURI===ri&&!oa[T]?!1:!gu[g]&&(Ph[g]||!mu[g])},Uh=function(g){let y=z(g),T=jr(O(g)),S=w(g),P,F;return S&&C(S)===fe.element?(P={namespaceURI:z(S)},F=jr(O(S))):(P={namespaceURI:Mr},F="template"),na[y]?y===ni?Fh(T,P,F):y===ri?zh(T,P,F):y===nt?qh(T,P,F):!!(Sn==="application/xhtml+xml"&&na[y]):!1},Ot=function(g){zo(e.removed,{element:g});try{w(g).removeChild(g)}catch{if(h(g),!w(g))throw At("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},bu=function(g,y,T){try{p(g,y)}catch{try{g.removeAttribute(T)}catch{}}},aa=function(g){ca(g);let y=b(g);y&&St(lw(y),S=>{try{h(S)}catch{}});let T=C(g)===fe.element?v(g):null;if(T)for(let S=T.length-1;S>=0;--S){let P=T[S],F=P&&P.name;typeof F=="string"&&bu(g,P,F)}},Fr=function(g,y,T){if(!T)try{T=y.getAttributeNode(g)}catch{T=null}zo(e.removed,{attribute:T||null,from:y});try{T?p(y,T):y.removeAttribute(g)}catch{try{y.removeAttribute(g)}catch{}}if(g==="is")if(Pr||ei)try{Ot(y)}catch{}else try{y.setAttribute(g,"")}catch{}},wu=function(g){let y=v(g);if(y)for(let T=y.length-1;T>=0;--T){let S=y[T],P=S&&S.name;typeof P!="string"||se[ue(P)]||bu(g,S,P)}},la=function(g,y){let T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,S=[g];for(;S.length>0;){let P=S.pop();if(y(P)===!1)continue;if(T&&C(P)===fe.element){let W=_(P);$t(W)&&S.push(W)}let F=b(P);if(F)for(let W=F.length-1;W>=0;--W)S.push(F[W])}},ca=function(g){la(g,y=>{C(y)===fe.element&&wu(y)})},ua=function(g){let y=[];return la(g,T=>{y.push(T)},!0),y},Vh=function(g,y){let T=lc();St(ua(g),S=>{C(S)===fe.element&&cc(T,S)}),St(y,S=>{C(S)===fe.element&&!qo(T,S)&&wu(S)})},_u=function(g,y){let T=!1;return St(e.removed,S=>{S.element&&(T=T||S.element===g,ca(S.element))}),Vh(g,y),T},Wh=8,Gh=function(g,y){let T=sr,S=null,P=()=>(S||(S=lc(),St(y,F=>{cc(S,F)})),S);for(let F=0;;F++){let W=ua(g),he=[g],ot=!1;if(St(W,De=>{C(De)===fe.documentFragment?zo(he,De):!ot&&!qo(T,De)&&(ot=qo(P(),De))}),!ot)return;if(F>=Wh)throw At("the tree kept changing during in-place sanitization; refusing to return it");St(he,(De,$e)=>{Hh(De,$e>0,g,P())})}},Hh=function(g,y,T,S){let P=da(g),F;for(;F=P.nextNode();)!qo(S,F)||qo(sr,F)||(y&&We(oe.uponSanitizeShadowNode,F,null),ha(F,T),pa(F,T),$t(F.content)&&In(F.content))},Xh=function(g){sr&&cc(sr,g)},yu=function(g,y){return or?g==="patchsrc"?!0:g==="for"&&y!=="label"&&y!=="output":!1},Yh=function(g){or&&la(g,y=>{let T=C(y);if(T===fe.processingInstruction||T===fe.comment&&xe(sh,y.data)){try{h(y)}catch{}return!1}if(T===fe.element){let S=y,P=ue(O(y));try{S.hasAttribute&&S.hasAttribute("patchsrc")&&S.removeAttribute("patchsrc"),S.hasAttribute&&S.hasAttribute("for")&&yu("for",P)&&S.removeAttribute("for")}catch{}}return!0})},vu=function(g){let y=null,T=null;if(Qs)g="<remove></remove>"+g;else{let F=Kf(g,/^[\r\n\t ]+/);T=F&&F[0]}Sn==="application/xhtml+xml"&&Mr===nt&&(g='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+g+"</body></html>");let S=V?pt(g):g;if(Mr===nt)try{y=new c().parseFromString(S,Sn)}catch{}if(!y||!y.documentElement){y=nr.createDocument(Mr,"template",null);try{y.documentElement.innerHTML=ra?le:S}catch{}}let P=y.body||y.documentElement;return g&&T&&P.insertBefore(t.createTextNode(T),P.childNodes[0]||null),Mr===nt?Sh.call(y,ir?"html":"body")[0]:ir?y.documentElement:P},da=function(g){let y=k?k(g):g.ownerDocument;return Zo.call(y||g,g,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},oi=function(g){return g=Uo(g,Ih," "),g=Uo(g,Ch," "),g=Uo(g,Dh," "),g},fa=function(g){var y;xu(g);let T=(y=g.querySelectorAll)===null||y===void 0?void 0:y.call(g,"template");T&&St(T,S=>{$t(S.content)&&fa(S.content)})},xu=function(g){g.normalize();let y=k?k(g):g.ownerDocument,T=Zo.call(y||g,g,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),S=T.nextNode();for(;S;)S.data=oi(S.data),S=T.nextNode()},ii=function(g){let y=D?D(g):null;return typeof y!="string"||ue(y)!=="form"?!1:typeof g.nodeName!="string"||typeof g.textContent!="string"||typeof g.removeChild!="function"||g.attributes!==v(g)||typeof g.removeAttribute!="function"||typeof g.removeAttributeNode!="function"||typeof g.getAttributeNode!="function"||typeof g.setAttribute!="function"||typeof g.namespaceURI!="string"||typeof g.insertBefore!="function"||typeof g.hasChildNodes!="function"||g.nodeType!==E(g)||g.childNodes!==b(g)},$t=function(g){if(!E||typeof g!="object"||g===null)return!1;try{return E(g)===fe.documentFragment}catch{return!1}},An=function(g){if(!E||typeof g!="object"||g===null)return!1;try{return typeof E(g)=="number"}catch{return!1}};function We(I,g,y){I.length!==0&&St(I,T=>{T.call(e,g,y,Lr)})}let Zh=function(g,y){return!!(or&&g.hasChildNodes()&&!An(g.firstElementChild)&&xe(mc,g.textContent)&&xe(mc,g.innerHTML)||or&&Cw[y]&&C(g)===fe.element&&z(g)===nt&&(An(g.firstElementChild)||typeof g.textContent=="string"&&xe(mc,g.textContent))||g.nodeType===fe.processingInstruction||or&&g.nodeType===fe.comment&&xe(sh,g.data))},si=function(g,y){if(g instanceof RegExp)return xe(g,y);if(g instanceof Function){for(var T=arguments.length,S=new Array(T>2?T-2:0),P=2;P<T;P++)S[P-2]=arguments[P];return!!g(y,...S)}return!1},Kh=function(g,y,T){if(!Tn[y]&&Tu(y)&&si(rt.tagNameCheck,y))return!1;if(ea&&!ar[y]&&!ar[jr(y)]){let S=w(g),P=b(g);if(P&&S){let F=P.length;for(let W=F-1;W>=0;--W){let he=g===T?f(P[W],!0):P[W];S.insertBefore(he,m(g))}}}return Ot(g),!0},ku=function(g,y,T,S){return g.length===0?y:y===T||y===S?ze(y):y},zr=function(g,y){return g===y||w(g)!==null?!1:(ta&&ca(g),!0)},ha=function(g,y){if(Xh(g),We(oe.beforeSanitizeElements,g,null),zr(g,y))return!0;if(ii(g))return Ot(g),!0;let T=ue(O(g));if(ie=ku(oe.uponSanitizeElement,ie,Xs,Jo),We(oe.uponSanitizeElement,g,{tagName:T,allowedTags:ie}),zr(g,y))return!0;if(Zh(g,T))return Ot(g),!0;if(Tn[T]||!(Nt.tagCheck instanceof Function&&Nt.tagCheck(T))&&!ie[T]){let S=Kh(g,T,y);return S===!1&&(We(oe.afterSanitizeElements,g,null),zr(g,y))?!0:S}if(C(g)===fe.element&&!Uh(g)||(T==="noscript"||T==="noembed"||T==="noframes")&&xe(Iw,g.innerHTML))return Ot(g),!0;if(mt&&g.nodeType===fe.text){let S=oi(g.textContent);g.textContent!==S&&(zo(e.removed,{element:g.cloneNode()}),g.textContent=S)}return We(oe.afterSanitizeElements,g,null),zr(g,y)},Eu=function(g,y,T){if(tu[y]||yu(y,g)||ou&&(y==="id"||y==="name")&&(T in t||T in Lh))return!1;let S=se[y]||Nt.attributeCheck instanceof Function&&Nt.attributeCheck(y,g);return Zs&&xe(Nh,y)||ru&&xe(Oh,y)?!0:S?uu[y]||xe(eu,Uo(T,Qc,""))||(y==="src"||y==="xlink:href"||y==="href")&&g!=="script"&&Jf(T,"data:")===0&&lu[g]||nu&&!xe($h,Uo(T,Qc,""))?!0:!T:Tu(g)&&si(rt.tagNameCheck,g)&&si(rt.attributeNameCheck,y,g)||y==="is"&&rt.allowCustomizedBuiltInElements&&si(rt.tagNameCheck,T)},Jh=J({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Tu=function(g){return!Jh[jr(g)]&&xe(Rh,g)},Qh=function(g,y,T,S){if(V&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!T)switch(u.getAttributeType(g,y)){case"TrustedHTML":return pt(S);case"TrustedScriptURL":return Yo(S)}return S},ep=function(g,y,T,S){try{return T?g.setAttributeNS(T,y,S):g.setAttribute(y,S),ii(g)?(Ot(g),!1):!0}catch{return Fr(y,g),!1}},Su=function(g,y){return or&&xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,y)?!0:jr(g)==="attributename"&&Kf(y,"href")!==null},pa=function(g,y){if(We(oe.beforeSanitizeAttributes,g,null),zr(g,y))return;let T=g.attributes;if(!T||ii(g))return;se=ku(oe.uponSanitizeAttribute,se,Ys,Qo);let S={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0},P=T.length,F=ue(g.nodeName);for(;P--;){let W=T[P],he=W.name,ot=W.namespaceURI,De=W.value,$e=ue(he),qr=De,Re=he==="value"?qr:uw(qr),Au=!1;if(S.attrName=$e,S.attrValue=Re,S.keepAttr=!0,S.forceKeepAttr=void 0,We(oe.uponSanitizeAttribute,g,S),Re=S.attrValue,iu&&($e==="id"||$e==="name")&&Jf(Re,su)!==0&&(Fr(he,g,W),Re=su+Re,Au=!0),Su(he,Re)){Fr(he,g,W);continue}if(!S.forceKeepAttr){if(!S.keepAttr){Fr(he,g,W);continue}if(!Ks&&xe(ah,Re)){Fr(he,g,W);continue}if(mt&&(Re=oi(Re)),!Eu(F,$e,Re)){Fr(he,g,W);continue}Re=Qh(F,$e,ot,Re),Re!==qr&&ep(g,he,ot,Re)&&Au&&Zf(e.removed)}}We(oe.afterSanitizeAttributes,g,null),zr(g,y)},In=function(g){let y=null,T=da(g);for(We(oe.beforeSanitizeShadowDOM,g,null);y=T.nextNode();)if(We(oe.uponSanitizeShadowNode,y,null),ha(y,g),pa(y,g),$t(y.content)&&In(y.content),C(y)===fe.element){let S=_(y);$t(S)&&(ma(S),In(S))}mt&&xu(g),We(oe.afterSanitizeShadowDOM,g,null)},ma=function(g){let y=[{node:g,shadow:null}];for(;y.length>0;){let T=y.pop();if(T.shadow){In(T.shadow);continue}let S=T.node,P=C(S)===fe.element,F=b(S);if(F)for(let W=F.length-1;W>=0;--W)y.push({node:F[W],shadow:null});if(P){let W=D?D(S):null;if(typeof W=="string"&&ue(W)==="template"){let he=S.content;$t(he)&&y.push({node:he,shadow:null})}}if(P){let W=_(S);$t(W)&&y.push({node:null,shadow:W},{node:W,shadow:null})}}};return e.sanitize=function(I){let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,T=null,S=null,P=null;if(ra=!I,ra&&(I="<!-->"),typeof I!="string"&&!An(I)&&(I=pw(I),typeof I!="string"))throw At("dirty is not a string, aborting");if(!e.isSupported)return I;Js?(ie=Jo,se=Qo):sa(g),(oe.uponSanitizeElement.length>0||oe.uponSanitizeAttribute.length>0)&&(ie=ze(ie)),oe.uponSanitizeAttribute.length>0&&(se=ze(se)),e.removed=[];let F=ta&&typeof I!="string"&&An(I),W=[],he=sr;if(F){Yh(I);let $e=O(I);if(typeof $e=="string"){let qr=ue($e);if(!ie[qr]||Tn[qr])throw aa(I),At("root node is forbidden and cannot be sanitized in-place")}if(ii(I))throw aa(I),At("root node is clobbered and cannot be sanitized in-place");W=ua(I),sr=lc()}else if(An(I))y=vu("<!---->"),T=y.ownerDocument.importNode(I,!0),T.nodeType===fe.element&&T.nodeName==="BODY"||T.nodeName==="HTML"?y=T:y.appendChild(T),ma(y);else{if(!Pr&&!mt&&!ir&&I.indexOf("<")===-1)return V&&ti?pt(I):I;if(y=vu(I),!y)return Pr?null:ti?le:""}y&&Qs&&Ot(y.firstChild);let ot=F?I:y;try{F&&ma(I);let $e=da(ot);for(;S=$e.nextNode();)ha(S,ot),pa(S,ot),$t(S.content)&&In(S.content);F&&Gh(I,W)}catch($e){throw F&&(aa(I),_u(I,W)),$e}finally{sr=he}if(F){if(_u(I,W))throw At("a node selected for removal could not be safely returned; refusing to sanitize in place");return mt&&fa(I),I}if(Pr){if(mt&&fa(y),ei)for(P=Ko.call(y.ownerDocument);y.firstChild;)P.appendChild(y.firstChild);else P=y;return(se.shadowroot||se.shadowrootmode)&&(P=Ah.call(r,P,!0)),P}let De=ir?y.outerHTML:y.innerHTML;return ir&&ie["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&xe(Sw,y.ownerDocument.doctype.name)&&(De="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
234
- `+De),mt&&(De=oi(De)),V&&ti?pt(De):De},e.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};sa(I),Js=!0,Jo=ie,Qo=se},e.clearConfig=function(){Lr=null,Js=!1,Jo=null,Qo=null,V=_e,le=""},e.isValidAttribute=function(I,g,y){Lr||sa({});let T=ue(I),S=ue(g);return typeof y=="string"&&(Su(g,y)||!Ks&&xe(ah,y))?!1:Eu(T,S,y)},e.addHook=function(I,g){typeof g=="function"&&Me(oe,I)&&zo(oe[I],g)},e.removeHook=function(I,g){if(Me(oe,I)){if(g!==void 0){let y=aw(oe[I],g);return y===-1?void 0:cw(oe[I],y,1)[0]}return Zf(oe[I])}},e.removeHooks=function(I){Me(oe,I)&&(oe[I]=[])},e.removeAllHooks=function(){oe=lh()},e}var mh=ph();function Ow(){return import("@gramlot/gramlot/markdown")}var yc=class o extends et{static internalParams=new Set([...et.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,method:t,directory:r,onError:n}){super({cacheTime:-1,onError:n}),this.gramlot=e,this.method=t,this.params={directory:r},this.children=new Set}get closed(){return this.#e}startLoad(e){if(this.loading)return this.loading;let t=new AbortController;return this.#t=t,e({controller:t,method:this.method,params:this.params,ignored:!1})}async loadAsync({controller:e,method:t,params:r}){let{signal:n}=e,i,s=new Promise((a,l)=>{i=()=>l(n.reason),n.addEventListener("abort",i,{once:!0})});try{let a=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:n}),s]);if(n.aborted)throw n.reason;return a}finally{n.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof x))throw new TypeError("Directory navigation must return a Bag");for(let t of this.children)t.abort();this.children.clear();for(let t of e.getNodes())if(t.attr.directory!==void 0){let r=new o({gramlot:this.gramlot,method:this.method,directory:t.attr.directory,onError:this.onError});this.children.add(r),e.setResolver(t.label,r)}return e}abort(){this.#e=!0,this.#t?.abort();for(let e of this.children)e.abort();this.children.clear()}};var vc={};ee(vc,{Labelbox:()=>js});function js(o){return class extends o{setLabelbox(e){let{box:t,labelBox:r,fieldLabel:n}=e;Object.assign(this,{box:t,labelBox:r,fieldLabel:n}),n.addEventListener("click",()=>{this.control.focus(),this.control.localName==="input"&&["checkbox","radio"].includes(this.control.type)&&this.control.click()})}projectAttributes(e,t){let r=super.projectAttributes(e,t),{lbl:n,lbl_value:i,lbl_values:s}=this.parameters,a=s==null?n??"":to(gr(s),i,n);return a?this.control.setAttribute("aria-label",a):this.control.removeAttribute("aria-label"),r}}}js.labelbox=!0;js.parameters={lbl:{dtype:"T",qualification:"intl_str",nullable:!0,binding:"read"},lbl_value:{dtype:"T",nullable:!0,binding:"twoWay"},lbl_values:{dtype:"T",nullable:!0,binding:"read"},lbl_position:{dtype:"T",default:"TL",binding:"read",enum:Li}};var Ic={};ee(Ic,{FieldState:()=>Ac});var Sc={};ee(Sc,{validateInput:()=>Ms,validationParameters:()=>Tc});var Ec=["select","notnull","empty","case","len","min","max","email","regex","call","remote"],$w=["nodup","exist","gridnodup"],Ps=o=>o==null||o==="",xc=(o,e)=>o instanceof Promise?o.then(e):e(o);function Ms(o,e,t={}){let r={value:o,modified:!1,error:null,warnings:[],issues:[],datachanges:[]},n=Object.fromEntries(Object.entries(e).map(([c,u])=>[c.slice(9),u])),i=c=>Object.hasOwn(e,`validate_${c}`)&&e[`validate_${c}`]!=null;for(let c of $w)if(i(c))throw new Error(`validate_${c} requires the DB/grid integration.`);let s=(c,u,d=!1)=>t.invoke(c,e[c],{...n,value:u,result:r,validations:n,userChange:!0,signal:t.signal},d),a=(c,u)=>{if(u==null||u===!0)return;if(typeof u!="boolean"&&typeof u!="string"&&(typeof u!="object"||Array.isArray(u)))throw new TypeError("A validator returns true, false, null, an error code, or a result object/Bag.");let d=`validate_${c}`,f=u instanceof x?Object.fromEntries(u.getNodes().map(w=>[w.label,w.value])):typeof u=="object"?u:{errorcode:u===!1?"error":u};if(Object.hasOwn(f,"value")&&(r.modified||=!Object.is(r.value,f.value),r.value=f.value),f.data!=null&&(t.checkDataPatch(f.data),r.datachanges.push(f.data)),!f.errorcode)return;let h=e[`${d}_iswarning`]??f.iswarning??!!(e[`${d}_warning`]&&!e[`${d}_error`]),p=e[`${d}_${f.errorcode}`]||e[`${d}_${h?"warning":"error"}`]||f.message||e[`${d}_${h?"error":"warning"}`]||String(f.errorcode),m=zt(p,w=>w?{...n,...f,value:r.value}[w]:r.value);if(m==null)throw new Error("A validation message references a missing value.");let b={rule:c,code:f.errorcode,severity:h?"warning":"error",message:m};r.issues.push(b),h?r.warnings.push(m):(r.error=m,r.required=!!f.required)},l=c=>{if(t.signal?.aborted)throw t.signal.reason;if(r.error||c===Ec.length)return r;let u=Ec[c],d=`validate_${u}`,f=e[d];if(!i(u)||f===!1&&u!=="empty")return l(c+1);let h=m=>{if(!m)return l(c+1);let b;return u==="remote"&&r.value==null?l(c+1):(u==="call"?b=s(d,r.value):u==="remote"?b=t.remote(f,{...Rw(e),value:r.value},t.signal):b=jw(u,f,r.value,t),xc(b,w=>{if(t.signal?.aborted)throw t.signal.reason;let _=()=>(a(u,w),l(c+1));return u==="remote"&&e.validate__onResult?xc(t.invoke("validate__onResult",e.validate__onResult,{result:w,value:r.value,validations:n,signal:t.signal}),_):_()}))},p=e[`${d}_if`];return xc(p==null?!0:typeof p=="boolean"?p:s(`${d}_if`,r.value,!0),h)};return l(0)}function Rw(o){let e=new Set(["if","error","warning","iswarning"]);return Object.fromEntries(Object.entries(o).filter(([t])=>t.startsWith("validate_remote_")&&!e.has(t.slice(16))).map(([t,r])=>[t.slice(16),r]))}function Wo(o,e,t={}){return{errorcode:o,message:e,...t}}function jw(o,e,t,r){if(o==="select")return r.selection(t,r.signal);if(o==="notnull")return Ps(t)&&e?Wo("notnull","A value is required.",{required:!0}):null;if(o==="empty")return Ps(t)?{value:e}:null;if(o==="len"){if(typeof e!="string"||!/^(?:\d+|\d+:\d*|:\d+)$/.test(e))throw new Error("Invalid validate_len: use a length or min:max.");let[n,i]=e.split(":"),s=Number(n||0),a=i===void 0?s:i===""?1/0:Number(i);if(s>a)throw new Error("Invalid validate_len: minimum exceeds maximum.");if(Ps(t))return;if(typeof t!="string")throw new TypeError("validate_len requires a text value.");return t.length<s||t.length>a?Wo(s===a?"wrong length":t.length<s?"too short":"too long",s===a?`Enter exactly ${s} characters.`:a===1/0?`Enter at least ${s} characters.`:s===0?`Enter no more than ${a} characters.`:`Enter between ${s} and ${a} characters.`):void 0}if(!Ps(t)){if(o==="case"){if(typeof t!="string")throw new TypeError("validate_case requires a text value.");switch(e){case"upper":case"u":return{value:t.toUpperCase()};case"lower":case"l":return{value:t.toLowerCase()};case"title":case"t":return{value:t.replace(/\p{L}[\p{L}\p{M}]*/gu,n=>n[0].toUpperCase()+n.slice(1).toLowerCase())};case"capitalize":case"c":return{value:t[0].toUpperCase()+t.slice(1).toLowerCase()};default:throw new Error("Invalid validate_case: use upper, lower, title or capitalize.")}}if(o==="min"||o==="max"){let n;if(r.isDecimal?.(t))n=t.comparedTo(e);else if(t instanceof Date&&e instanceof Date)n=t.getTime()-e.getTime();else if(typeof t=="number"&&Number.isFinite(t)&&typeof e=="number"&&Number.isFinite(e))n=t-e;else throw new TypeError(`validate_${o} requires matching numeric or date/time values.`);return(o==="min"?n<0:n>0)?Wo(o,`Value must be ${o==="min"?"at least":"at most"} ${e}.`):void 0}if(o==="email"){if(typeof t!="string")throw new TypeError("validate_email requires a text value.");return/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(t)?null:Wo("email","Check email format.",{iswarning:!0})}if(o==="regex"){if(typeof t!="string"||typeof e!="string")throw new TypeError("validate_regex requires text.");let n=e.trim(),i=n.startsWith("!");return new RegExp(i?n.slice(1):n,"u").test(t)!==i?null:Wo("regex","The value does not match the required pattern.")}}}var Go={dtype:"T",nullable:!0,binding:"read"},Bs={dtype:"B",nullable:!0,binding:"read"},kc={dtype:["T","L","N","R","B","D","H","DH","DHZ"],nullable:!0,binding:"read"},Tc={validate_select:Bs,validate_notnull:{...Bs,default:!1},validate_empty:kc,validate_case:{...Go,enum:["upper","lower","title","capitalize","u","l","t","c"]},validate_len:Go,validate_min:kc,validate_max:kc,validate_email:Bs,validate_regex:Go,validate_call:{dtype:"T",nullable:!0},validate_remote:Go,validate_onAccept:{dtype:"T",nullable:!0},validate_onReject:{dtype:"T",nullable:!0},validate__onResult:{dtype:"T",nullable:!0},validate_timeout:{dtype:"L",nullable:!0,binding:"read"},...Object.fromEntries(Ec.flatMap(o=>[[`validate_${o}_if`,{dtype:["T","B"],nullable:!0}],[`validate_${o}_iswarning`,Bs],...["error","warning"].map(e=>[`validate_${o}_${e}`,{...Go,qualification:"intl_str"}])]))};var Pw=1800,gh=200;function Ac(o){return class extends o{get supportsFormValidation(){return!0}static validationParameters(e){let t={...Fi(this.gramlotComponent,e),...e};return this.constrained&&t.validate_select==null&&(t.validate_select=!0),t}static get validationExecutor(){return Ms}get validationExecutor(){return this.constructor.validationExecutor}connectedCallback(){super.connectedCallback(),this.pageContext?.form&&this.pageContext.formValidate()}#e=!1;#t;#r;#n;#o=new kr;#i;#s={};validationResult=null;constructor(){super(),this.message=this.ownerDocument.createElement("small"),this.message.id="field-message",this.message.hidden=!0,this.message.setAttribute("aria-live","polite"),this.message.setAttribute("popover","manual"),this.message.setAttribute("role","tooltip");let e=this.ownerDocument.createElement("style");e.textContent=`#control[aria-invalid="true"]{background:var(--gramlot-error-background,#fff1f0)}
232
+ <${i}>${n.toXml()}</${i}>`,t,"application/xml")}}async copyText(e){if(typeof e!="string")throw new TypeError("gramlot.utl.inout.copyText: text must be a string");await this.document.defaultView.navigator.clipboard.writeText(e)}saveText(e,t,r){let n=this.document.defaultView,i=n.URL.createObjectURL(new n.Blob([e],{type:r}));this.open(i,t),n.setTimeout(()=>n.URL.revokeObjectURL(i),1e3)}open(e,t=null){let r=this.document.createElement("a");r.href=e,t!==null&&(r.download=t),r.click()}};var Ro=class extends Ne{constructor(e,t){super(e),this.inout=new $o(e,t)}};var jo=class{#e;#t;constructor({pageId:e,uploadUrl:t=null,rpcUrl:r="/gramlot/rpc",closeUrl:n="/gramlot/close",rootId:i="gramlot-root",capabilities:s=[],element:a=null,document:l=a?.ownerDocument??globalThis.document,transport:c=null,collections:u=[],locale:d=null,timeZone:f=null,devices:h=[],serverAdapter:p=new Rt,nameSyntax:m=null,websocketUrl:b=null}={}){this.#t=[Wi,...u.filter(_=>_ instanceof Xt)],this.registerDocument(l),this.commands=new Nn,this.pageId=e,this.uploadUrl=t;let w=d==null||f==null?l.defaultView.Intl.DateTimeFormat().resolvedOptions():null;this.devices=Object.freeze([...h]),this.locale=d??w.locale,this.timeZone=f??w.timeZone,Object.defineProperty(this,"_subscriptions",{value:new vs(this)}),this.capabilities=Object.freeze([...s]),this.serverAdapter=p,this.src=new Do(this,{collections:u,destination:a??l.getElementById(i),subscriptions:this._subscriptions,nameSyntax:m===null?to:mr.fromJSON(m)}),this.#e=Dn.install({document:l,root:this.src.renderer.destination}),this.data=this.src.builder.data,this.dvc=new Oo(this),this.dom=new No(this),this.utl=new Ro(this,l),this.state="ready",this.abort=new AbortController,Object.defineProperty(this,"_frames",{value:new Mi(this,l)}),b!==null&&(this._pageStore=new Bi(this,b,l)),this.rpc=new eo(this,{rpcUrl:r,closeUrl:n,document:l,transport:c}),this._frames.connect(),this.rpc.transport&&(this.pagehide=_=>{_.persisted||this.dispose()},l.defaultView.addEventListener("pagehide",this.pagehide),this.window=l.defaultView)}publish(e,t={}){return this._subscriptions.publish(e,t)}registerDocument(e){for(let t of this.#t)t.register(e.defaultView)}getCollection(e){return this.#t.find(t=>t.name===e)}subscribe(e,t){return this._subscriptions.subscribe(e,t)}unsubscribe(e){this._subscriptions.unsubscribe(e)}format(e,t){return io(e,t,{locale:this.locale,timeZone:this.timeZone})}start(){return this.state==="disposed"?Promise.reject(new Error("Gramlot is disposed")):this.rpc.transport?this.loading?this.loading:this.state==="started"?Promise.resolve(this):(this.state="loading",this.loading=this.loadMain().finally(()=>{this.loading=null}),this.loading):Promise.reject(new Error("This Gramlot instance has no server transport"))}async loadMain(){let e;try{e=await this.rpc.callEnvelope("source","main")}catch(t){throw this.state==="disposed"?new Error("Gramlot was disposed during main",{cause:t}):(this.state="failed",t)}if(this.state==="disposed")throw new Error("Gramlot was disposed during main");try{return this.src.mountMainSource(e.value,e.data)}catch(t){throw this.state!=="disposed"&&(this.state="failed"),t}}dispose(){if(this.state!=="disposed"){this.state="disposed",this.dvc.dispose(),this.#e.dispose(),this._subscriptions.dispose(),this.pagehide&&this.window.removeEventListener("pagehide",this.pagehide),this.abort.abort();try{try{this.src.binding.dispose()}finally{this.src.renderer.dispose()}}finally{if(this._pageStore?.close(),this._frames.dispose(),this.rpc.transport)try{this.rpc.transport.close(this.pageId)}finally{this.rpc.transport.dispose()}}}}};var sc=class{constructor({config:e,resources:t,document:r=globalThis.document}){this.config=e,this.resources=t,this.document=r,this.serverAdapter=new Rt}async run(){let{config:e,resources:t,document:r}=this,n=r.defaultView;t.serverAdapter!==void 0&&(this.serverAdapter=await this.loadServerAdapter(t.serverAdapter));let i=!1,s,a,l=[],c=new Promise(d=>{s=d}),u=d=>{if(!(d.persisted||i)){i=!0;try{this.closePage()}finally{s(null)}}};n.addEventListener("pagehide",u);try{let d=t.css.map(_=>new Promise((v,E)=>{let D=r.createElement("link");D.rel="stylesheet",D.href=_;let k=()=>{D.removeEventListener("load",C),D.removeEventListener("error",O)};l.push(k);let C=()=>{k(),v()},O=()=>{k(),E(new Error(`${_}: stylesheet load failed`))};D.addEventListener("load",C),D.addEventListener("error",O),r.head.append(D)})),f=t.js.map(async({url:_,group:v})=>{try{return{logicClass:(await import(new URL(_,r.baseURI).href)).Logic,group:v,resource:_}}catch(E){throw new Error(`${_}: import failed: ${E.message}`,{cause:E})}}),h=new Set,p=(t.collections??[]).map(async _=>{if(!_||typeof _!="object"||Object.keys(_).sort().join(",")!=="buildId,name,url"||typeof _.name!="string"||typeof _.url!="string"||typeof _.buildId!="string"||!/^sha256:[0-9a-f]{64}$/.test(_.buildId)||h.has(_.name))throw new TypeError("Invalid or duplicate collection bootstrap record");h.add(_.name);let{name:v,url:E,buildId:D}=_,k;try{k=await import(new URL(E,r.baseURI).href)}catch(C){throw new Error(`${v}: collection import failed: ${C.message}`,{cause:C})}if(k.default?.name!==v||k.buildId!==D)throw new Error(`${v}: collection identity mismatch; expected ${D}, received ${k.buildId}`);return k.default}),m=await Promise.race([Promise.all([Promise.all(d),Promise.all(f),Promise.all(p)]),c]);if(i)return null;let[,b,w]=m;bn.check(b);for(let _ of w)_.register(n);a=new jo({...e,document:r,serverAdapter:this.serverAdapter,collections:[...e.collections??[],...w]}),n.removeEventListener("pagehide",u);for(let _ of w)_.registerCommands(a);for(let{logicClass:_,group:v,resource:E}of b)a.src.logicRegistry.register(_,{group:v,resource:E});return n.gramlot=a,await a.start(),a}catch(d){throw a?a.dispose():i||this.closePage(),d}finally{for(let d of l)d();n.removeEventListener("pagehide",u)}}async loadServerAdapter(e){let t;try{t=await import(new URL(e,this.document.baseURI).href)}catch(r){throw new Error(`${e}: server adapter import failed: ${r.message}`,{cause:r})}return new t.default}closePage(){let e=this.serverAdapter.createTransport({...this.config,document:this.document});try{e.close(this.config.pageId)}finally{e.dispose()}}};var ks=Symbol("gramlot.source"),Es=Symbol("gramlot.endpoint"),Po=Symbol("gramlot.upload"),Kb=new Map([[ks,"registerSource"],[Es,"registerEndpoint"],[Po,"registerUpload"]]);function ac(o,e,t,r){let n=Kb.get(t);if(e==="main")throw new TypeError(`${n} cannot declare main`);let i=Object.getOwnPropertyDescriptor(o.prototype,e)?.value;if(typeof i!="function")throw new TypeError(`${n} requires an own method of ${o.name}: ${String(e)}`);if(i[t])throw new TypeError(`${t===ks?"Source method":t===Es?"Endpoint":"Upload operation"} already registered: ${e}`);if([ks,Es,Po].some(s=>i[s])){let s=t!==Po&&!i[Po]?`${e} is declared both as Source method and endpoint`:`${e} has conflicting declarations`;throw new TypeError(s)}i[t]={auth:r}}var Ts=class{static registerSource(e,{auth:t=null}={}){ac(this,e,ks,t)}static registerEndpoint(e,{auth:t=null}={}){ac(this,e,Es,t)}static registerUpload(e,{auth:t=null}={}){ac(this,e,Po,t)}},Bo=class extends Ts{static gramlots=[];static title="Gramlot";static devices=[];static locale=null;static timeZone=null;static installable=!1;static appIcon=null;manifest({baseUrl:e="./"}={}){let{title:t,appIcon:r}=this.constructor;if(typeof r!="string"||!r)throw new TypeError("An installable Page needs appIcon");return{id:e,name:t,short_name:t,start_url:e,scope:e,display:"standalone",icons:[{src:e+r.replace(/^\/+/,""),sizes:"512x512",type:"image/png"}]}}static css=[];static css_theme=null;static css_requires="";static js_requires="";static sourceBuilder=me;main(e){throw new Error("Page.main(root) must be implemented")}};var wn=class extends Bo{static shellId="frame";static datapath=null;main(e){let t=e.div({id:this.constructor.shellId,datapath:this.constructor.datapath,class:"frame-page",height:"100vh",display:"flex",flex_direction:"column",min_height:0}),r=t.borderContainer({node_label:"frame",height:"100%",flex:"1",min_height:0});for(let n of["top","bottom","left","right","center"])if(this[n]!==void 0){let i=r.contentPane({region:n,node_label:n});this[n](i)}this.behavior(t)}center(e){}behavior(e){}};var Mo=class extends wn{static title="Application";static shellId="index";static datapath="index";static navigation=null;main(e){let{navigation:t,datapath:r}=this.constructor;if(!(t instanceof x))throw new TypeError("IndexPage.navigation must be a Bag");e.dataSetter({destination_path:`${r}.navigation`,value:t}),e.dataSetter({destination_path:`${r}.navigationSelection`,value:null}),e.dataSetter({destination_path:`${r}.active`,value:null}),e.dataSetter({destination_path:`${r}.opened`,value:new x}),super.main(e)}left(e){e.setAttr({width:"240px",splitter:!0,drawer:!0,drawer_label:"Navigation"}),e.tree({node_label:"tree",storepath:".navigation",labelAttribute:"title",hideValues:!0,selectedPath:"^.navigationSelection"})}center(e){e.tabContainer({node_label:"tabs",height:"100%",selectedPage:"^.active"})}behavior(e){e.dataController({func:"indexMount",_onStart:!0})}index_panel(e,{selection:t}){this.panel(e,t.getNode("#0"))}panel(e,t){e.iframe({src:t.attr.url,title:t.attr.title??t.label,width:"100%",height:"100%",border:0})}};Mo.registerSource("index_panel");function lc(o,e,t=()=>{},r=()=>{},{state:n=e.getRelativeData("."),createEntry:i=null,onLoad:s=()=>{}}={}){let a=n.getItem("navigation");if(!(a instanceof x))throw new TypeError("IndexPage navigation must be a Bag");let l=e.value.getNode("frame.center.tabs"),c=e.builder,u=new Map,d={entries:u,disposed:!1,selecting:!1,sequence:0,requested:null};Object.defineProperty(e,"indexContext",{value:d,configurable:!0});let f=n.getItem("opened");for(let k of f.getNodes()){let{url:C,path:O,title:L}=k.attr,z=l.value.getNode(k.label),V={url:C,path:O,title:L,pane:z,node:a.getNode(O),loading:!1};r(V),u.set(C,V),d.sequence++}let h=(k,C,O)=>{try{s(k.url,C,O)}catch(L){o.binding.reportError(L,"Page load callback failed")}},p=(k,C,O)=>{k.loading&&(k.loading=!1,h(k,C,O))},m=k=>{if(!d.disposed){d.selecting=!0;try{n.setItem("active",k.url),n.setItem("navigationSelection",k.path),t(u,k.url)}finally{d.selecting=!1}}};function b(k){w(k).catch(C=>{d.disposed||o.binding.reportError(C,"Page could not be opened")})}async function w(k){let C=a.getNode(k);if(!C)throw new Error(`Unknown index navigation path: ${k}`);let O=C.attr.url;if(O==null)return;if(typeof O!="string"||!O)throw new TypeError("IndexPage URL must be nonempty text");d.requested=O;let L=u.get(O);if(L){L.path=k,m(L);return}for(;l.value!==null&&l.value.getNode(`page${d.sequence}`);)d.sequence++;let z=Z(c.wrapSource(l).contentPane({node_label:`page${d.sequence++}`,title:C.attr.title??C.label,pageName:O,height:"100%",closable:!0})),V=n.getItem("active");L={url:O,path:k,node:C,pane:z,title:C.attr.title??C.label,loading:!0},u.set(O,L);try{if(h(L,"loading"),d.disposed||u.get(O)!==L||(m(L),d.disposed||u.get(O)!==L))return;if(i)await i(L);else{let le=new x;if(le.setItem(C.label,null,{...C.attr}),!await o.binding.gramlot.src.remoteSource(z,"index_panel",{selection:le}))throw new Error("Panel loading was cancelled")}if(d.disposed||u.get(O)!==L)return;f.setItem(z.label,null,{url:O,path:L.path,title:L.title}),r(L)}catch(le){if(d.disposed||u.get(O)!==L)return;try{if(o.binding.reportError(le,"Page could not be opened"),u.delete(O),f.getNode(z.label)&&f.popNode(z.label),z.parentBag&&z.parentBag.popNode(z.label),!d.disposed&&d.requested===O){let _e=u.get(V);if(d.requested=_e?.url??null,_e)m(_e);else{d.selecting=!0;try{n.setItem("active",null),n.setItem("navigationSelection",null),t(u,null)}finally{d.selecting=!1}}}}finally{p(L,"error",le)}return}d.disposed||u.get(O)!==L||(p(L,"ready"),!d.disposed&&u.get(O)===L&&d.requested===O&&m(L))}let _=`${e.getAttr("id")}-page-close`;e.value.subscribe(_,{any:k=>{if(k.evt!=="del")return;let C=[...u.values()].find(z=>z.pane===k.node);if(!C)return;let{url:O,pane:L}=C;if(!(d.disposed||o.disposed||u.get(O)!==C)){u.delete(O),f.getNode(L.label)&&f.popNode(L.label);try{if(n.getItem("active")===O){let z=[...u.values()].at(-1);if(d.requested=z?.url??null,z)m(z);else{d.selecting=!0;try{n.setItem("active",null),n.setItem("navigationSelection",null),t(u,null)}finally{d.selecting=!1}}}else t(u,n.getItem("active"))}finally{p(C,"cancelled")}}}});let v=`${e.getAttr("id")}-selection`;n.subscribe(v,{any:k=>{if(!(d.selecting||d.disposed)){if(k.node===n.getNode("navigationSelection")){let C=n.getItem("navigationSelection");C!==null&&b(C)}else if(k.node===n.getNode("active")){let C=u.get(n.getItem("active"));C&&(d.requested=C.url,m(C))}}}});let E=()=>{if(!d.disposed){d.disposed=!0,n.unsubscribe(v,{any:!0}),e.value.unsubscribe(_,{any:!0});for(let k of u.values())k.loading&&(k.pane.parentBag&&k.pane.parentBag.popNode(k.pane.label),p(k,"cancelled"));u.clear(),e.indexContext===d&&delete e.indexContext}};d.dispose=E,o.onDispose(e,E);let D=u.get(n.getItem("active"));return D?m(D):n.getItem("navigationSelection")!==null&&b(n.getItem("navigationSelection")),d}var Ss=class{indexMount(e){lc(this.page.src.renderer,e.parentNode)}};function As(o,{datapath:e,value:t,language:r="text",height:n="420px",...i}){if(!e)throw new TypeError("codeMirrorWithOptions requires datapath");let s=o.borderContainer({datapath:e,height:n,class:"gramlot-editor-options"}),a={language:r,indentUnit:4,fontSize:14,fontFamily:"monospace",lineNumbers:!0,lineWrapping:!0,folding:!0,bracketMatching:!0,autoCloseBrackets:!0,autoIndent:!0,autocompletion:!0,highlightActiveLine:!0,highlightSelectionMatches:!0};for(let[d,f]of Object.entries(a))s.dataSetter({destination_path:`.settings.${d}`,value:f});let l=s.contentPane({region:"right",width:"250px",drawer:"close",drawer_label:"Options",drawer_icon:"\u2699",drawer_minimize:!1,padding:"12px",overflow:"auto",class:"gramlot-editor-settings"});l.h3("Editor options"),l.filteringSelect({value:"^.settings.language",lbl:"Language",values:"text:Plain text,python:Python,javascript:JavaScript,typescript:TypeScript,json:JSON,html:HTML,css:CSS,xml:XML,markdown:Markdown,sql:SQL,typst:Typst"}),l.numberTextBox({value:"^.settings.indentUnit",lbl:"Indent spaces",min:1,max:16,dtype:"L",validate_notnull:!0}),l.numberTextBox({value:"^.settings.fontSize",lbl:"Font size",min:8,max:48,dtype:"L",validate_notnull:!0}),l.textbox({value:"^.settings.fontFamily",lbl:"Font family"});let c={lineNumbers:"Line numbers",lineWrapping:"Wrap lines",folding:"Code folding",bracketMatching:"Match brackets",autoCloseBrackets:"Close brackets and quotes",autoIndent:"Automatic indentation",autocompletion:"Local completion",highlightActiveLine:"Highlight current line",highlightSelectionMatches:"Highlight matching selections"};for(let[d,f]of Object.entries(c))l.checkbox({value:`^.settings.${d}`,label:f,display:"block",margin_top:"8px"});return s.contentPane({region:"center",min_height:0}).codeMirror({...i,value:t,height:"100%",...Object.fromEntries(Object.keys(a).map(d=>[d,`^.settings.${d}`]))}),s}var Lo=class o extends et{static internalParams=new Set([...et.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,root:t,path:r="",onError:n}){super({cacheTime:-1,onError:n}),this.gramlot=e,this.method="directory_tree",this.params={root:t,path:r},this.children=new Set}get closed(){return this.#e}startLoad(e){if(this.loading)return this.loading;let t=new AbortController;return this.#t=t,e({controller:t,method:this.method,params:this.params,ignored:!1})}async loadAsync({controller:e,method:t,params:r}){let{signal:n}=e,i,s=new Promise((a,l)=>{i=()=>l(n.reason),n.addEventListener("abort",i,{once:!0})});try{let a=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:n}),s]);if(n.aborted)throw n.reason;return a}finally{n.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof x))throw new TypeError("directory_tree must return a Bag");for(let t of this.children)t.abort();this.children.clear();for(let t of e.getNodes())if(t.attr.is_directory){let r=new o({gramlot:this.gramlot,root:this.params.root,path:t.attr.path,onError:this.onError});this.children.add(r),e.setResolver(t.label,r)}return e}abort(){this.#e=!0,this.#t?.abort();for(let e of this.children)e.abort();this.children.clear()}},Fo=class{constructor(e,t){this.gramlot=e,this.source=t,this.request=null,this.resolver=null,this.disposed=!1}get state(){return this.source.getRelativeData(".")}async open(e){this.request?.abort();let t=this.request=new AbortController;this.state.setItem("status","Opening directory\u2026");try{let r=await this.gramlot.rpc.call("data","workspace_open",{root:e},{signal:t.signal});if(this.disposed||t.signal.aborted)return null;let n=new Lo({gramlot:this.gramlot,root:r.root,onError:s=>this.state.setItem("status",s.message)}),i=n.prepareValue(r.entries);return this.resolver?.abort(),this.resolver=n,this.state.setItem("selectedPath",null),this.state.setItem("store",i),this.state.setItem("writable",r.writable),this.state.setItem("root",r.root),this.state.setItem("status",""),r.root}catch(r){return!this.disposed&&!t.signal.aborted&&this.state.setItem("status",r.message),null}finally{this.request===t&&(this.request=null)}}dispose(){this.disposed=!0,this.request?.abort(),this.resolver?.abort()}},Rr=class{fileSystemMount(e){let t=e.parentNode,r=new Fo(this.page,t);Object.defineProperty(t,"fileSystemController",{value:r,configurable:!0}),this.page.src.renderer.onDispose(t,()=>r.dispose())}fileSystemOpen(e,{root:t}){if(t)return e.parentNode.fileSystemController.open(t)}};function Hf(o,{datapath:e,...t}){let r=o.div({datapath:e,class:"gramlot-filesystem",...t});return r.dataSetter({destination_path:".store",value:new x}),r.dataSetter({destination_path:".root",value:null}),r.dataSetter({destination_path:".requestedRoot",value:null}),r.dataSetter({destination_path:".selectedPath",value:null}),r.dataSetter({destination_path:".status",value:""}),r.dataController({func:"fileSystemMount",_onBuilt:!0}),r.dataController({func:"fileSystemOpen",root:"^.requestedRoot"}),r.tree({storepath:".store",selectedPath:"^.selectedPath",labelAttribute:"caption",hideValues:!0,class:"gramlot-filesystem-tree"}),r.div("^.status",{role:"status",class:"gramlot-filesystem-status"}),r}var Jb=(o,e)=>"d_"+[...new TextEncoder().encode(JSON.stringify([o,e]))].map(t=>t.toString(16).padStart(2,"0")).join(""),Is=class{constructor(e,t){this.gramlot=e,this.source=t,this.pending=new Map,this.disposed=!1}get state(){return this.source.getRelativeData(".")}get documents(){return this.state.getItem("documents")}async open(e,t){if(!/\.(?:py|js|mjs|ts|json|html|css|xml|md|markdown|sql|typ|txt|png|jpg|jpeg|webp)$/i.test(t))return null;let r=Jb(e,t),n=this.documents.getNodes().find(a=>!a.value.getItem("isNew")&&a.value.getItem("root")===e&&a.value.getItem("path")===t);if(n)return n.label;if(this.pending.has(r))return this.pending.get(r).promise;let i=new AbortController,s=this.gramlot.rpc.call("data","document_read",{root:e,path:t},{signal:i.signal}).then(a=>{if(this.disposed||i.signal.aborted)return null;let l=new x,c=a.language==="image"?a.content.toTytx():a.content;for(let[u,d]of Object.entries({...a,content:c,root:e,saved:c,busy:!1}))l.setItem(u,d);if(a.language==="image"){let u=a.content;l.setItem("annotations",u),u.subscribe("ide-annotations",{any:()=>l.setItem("content",u.toTytx())})}return this.documents.setItem(r,l),r}).finally(()=>this.pending.delete(r));return this.pending.set(r,{request:i,promise:s}),s}newDocument(e,t,r=""){let n=`new_${G()}`,i=new x;for(let[s,a]of Object.entries({language:e,root:r,path:`Untitled${t}`,content:"",saved:"",writable:!0,busy:!1,isNew:!0,createHidden:!0,saveRoot:r,savePath:`Untitled${t}`}))i.setItem(s,a);return this.documents.setItem(n,i),n}async create(e){let t=this.documents.getItem(e);if(!t||!t.getItem("isNew")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("saveRoot"),n=t.getItem("savePath");if(t.getItem("path").endsWith(".typ.py")!==n.endsWith(".typ.py"))throw new Error("The .typ.py extension is required for the Typst Python recipe document type.");let i=t.getItem("content"),s=new AbortController;t.setItem("busy",!0);let a=this.gramlot.rpc.call("data","document_create",{root:r,path:n,content:i},{signal:s.signal}).then(l=>this.disposed||s.signal.aborted?!1:(t.setItem("root",l.root),t.setItem("path",l.path),t.setItem("revision",l.revision),t.setItem("saved",i),t.setItem("isNew",!1),t.setItem("createHidden",!0),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:s,promise:a}),a}invalidateRecipe(e){let t=this.documents.getItem(e);t.getItem("path").endsWith(".typ.py")&&(t.getItem("rendering")&&this.pending.get(e)?.request.abort(),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generate preview to render the current Python recipe."))}async renderRecipe(e){let t=this.documents.getItem(e);if(!t||!t.getItem("path").endsWith(".typ.py")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),n=new AbortController;t.setItem("busy",!0),t.setItem("rendering",!0),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generating Typst on the server\u2026");let i=this.gramlot.rpc.call("data","document_render_typst",{content:r},{signal:n.signal}).then(s=>this.disposed||n.signal.aborted||t.getItem("content")!==r?!1:(t.setItem("typstSource",s.source),t.setItem("previewHidden",!1),t.setItem("renderStatus","Typst generated from the current recipe."),!0)).catch(s=>(!this.disposed&&!n.signal.aborted&&t.setItem("renderStatus",s.message),!1)).finally(()=>{this.pending.delete(e),this.disposed||(t.setItem("rendering",!1),t.setItem("busy",!1))});return this.pending.set(e,{request:n,promise:i}),i}dirty(e){let t=this.documents.getItem(e);return t&&t.getItem("content")!==t.getItem("saved")}async save(e){let t=this.documents.getItem(e);if(!t||t.getItem("isNew")||!this.dirty(e)||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),n=new AbortController;t.setItem("busy",!0);let i=t.getItem("language")==="image",s=i?t.getItem("annotationPath"):t.getItem("path"),a=i&&t.getItem("revision")===null,l=this.gramlot.rpc.call("data",a?"document_create":"document_save",{root:t.getItem("root"),path:s,content:i?x.fromTytx(r):r,...a?{}:{revision:t.getItem("revision")}},{signal:n.signal}).then(c=>this.disposed||n.signal.aborted?!1:(t.setItem("revision",c.revision),t.setItem("saved",r),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:n,promise:l}),l}revert(e){let t=this.documents.getItem(e);return!t||!this.dirty(e)||this.pending.has(e)?!1:(t.setItem("content",t.getItem("saved")),t.getItem("language")==="image"&&(t.getItem("annotations").replace(x.fromTytx(t.getItem("saved"))),t.setItem("content",t.getItem("saved"))),!0)}canClose(e,t=!1){return!this.pending.has(e)&&(t||!this.dirty(e))}close(e,t=!1){return this.canClose(e,t)?(this.documents.popNode(e),this.state.getItem("active")===e&&this.state.setItem("active",this.documents.getNodes()[0]?.label??null),!0):!1}dispose(){this.disposed=!0;for(let{request:e}of this.pending.values())e.abort()}},Cs=class{constructor(e){this.storage=e,this.key="gramlot.ide.recentWorkspaces"}read(){let e=this.storage.getItem(this.key),t=e===null?[]:JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"||!r))throw new TypeError("Invalid recent workspace preference");return t.slice(0,6)}remember(e){let t=[e,...this.read().filter(r=>r!==e)].slice(0,6);return this.storage.setItem(this.key,JSON.stringify(t)),t}choices(e=this.read()){let t=new x;return e.forEach((r,n)=>t.setItem(`r${n}`,r,{caption:r})),t}};function Be(o){for(let e=o;e;e=e.parentNode){let t=e.ideContext;if(t)return t}throw new Error("IDE operation requires a node inside a mounted IDE")}var Ds=class{fileSystemMount(e){return Rr.prototype.fileSystemMount.call(this,e)}fileSystemOpen(e,t){return Rr.prototype.fileSystemOpen.call(this,e,t)}ideMount(e){let t=e.parentNode,r={scope:t,documents:new Is(this.page,t),requested:0,editorPrefix:`ide_${G()}`,recent:new Cs(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage)};Object.defineProperty(t,"ideContext",{value:r,configurable:!0});let{documents:n,recent:i}=r,s=t.getRelativeData("."),a=i.read();s.setItem("recent",i.choices(a)),s.setItem("workspace",a[0]??"");let l=s.getItem("browser");l.subscribe("ide-browser",{any:u=>{if(u.node===l.getNode("root")){let d=l.getItem("root");s.setItem("workspace",d),s.setItem("recent",i.choices(i.remember(d))),s.setItem("status",`Workspace: ${d}`)}else if(u.node===l.getNode("selectedPath")){let d=l.getItem("selectedPath"),f=d===null?null:l.getItem("store").getNode(d);f&&!f.attr.is_directory&&this.ideOpenDocument(t,l.getItem("root"),f.attr.path)}}});let c=n.documents;c.subscribe("ide-documents",{any:u=>{if(["content","saved","busy","writable","view","isNew","path","root"].includes(u.node.label))for(let d of t.value.getNode("frame.center.tabs").value?.getNodes()??[]){let f=d.getAttr("documentKey"),h=n.documents.getItem(f);h&&(u.node===h.getNode("content")&&n.invalidateRecipe(f),this.ideDocumentState(t,f),d.setAttr({title:`${n.dirty(f)?"\u25CF ":""}${h.getItem("path")}`}))}}}),this.page.src.renderer.onDispose(r.scope,()=>{l.unsubscribe("ide-browser",{any:!0}),c.unsubscribe("ide-documents",{any:!0}),n.dispose()})}ideOpenWorkspace(e){let r=Be(e).scope.getRelativeData("."),n=r.getItem("workspace");n&&n!==r.getItem("browser.root")&&r.setItem("browser.requestedRoot",n)}async ideUploadCompleted(e,{result:t}){let r=Be(e),n=r.scope.getRelativeData(".");if(n.getItem("browser.root")!==t.root)return;n.setItem("upload.open",!1);let i=r.scope.value.getNode("frame.left.browser").fileSystemController;if(i.request)return;await i.open(t.root)===t.root&&!r.documents.disposed&&n.getItem("browser.root")===t.root&&await this.ideOpenDocument(r.scope,t.root,t.path)}ideDocumentState(e,t){let r=Be(e),{documents:n}=r,i=n.documents.getItem(t),s=!n.dirty(t)&&!i.getItem("isNew")||i.getItem("busy");i.setItem("saveDisabled",!!(s||!i.getItem("writable"))),i.setItem("revertDisabled",!!(!n.dirty(t)||i.getItem("busy"))),i.setItem("displayPath",i.getItem("isNew")?i.getItem("path"):`${i.getItem("root")}/${i.getItem("path")}`),i.setItem("pdfFilename",i.getItem("path").split("/").at(-1).replace(/\.typ(?:\.py)?$/i,".pdf")),i.setItem("renderDisabled",!!(i.getItem("busy")||!i.getItem("writable"))),this.ideHistoryState(i)}async ideOpenDocument(e,t,r){let n=Be(e),{documents:i}=n,s=n.scope.getRelativeData("."),a=++n.requested;try{let l=await i.open(t,r);if(l===null||i.disposed)return;this.ideShowDocument(e,l),a===n.requested&&(s.setItem("active",l),s.setItem("status",`${r}${i.documents.getItem(l).getItem("writable")?"":" (draft only \u2014 Remote Edit is disabled)"}`))}catch(l){i.disposed||s.setItem("status",l.message)}}ideNew(e){let t=Be(e),{documents:r}=t,n=t.scope.getRelativeData("."),i=n.getItem("newType"),s=i==="typstRecipe"?"python":i,a={typstRecipe:".typ.py",typst:".typ",markdown:".md",html:".html",python:".py",javascript:".js",typescript:".ts",json:".json",css:".css",sql:".sql",xml:".xml",text:".txt"},l=r.newDocument(s,a[i],n.getItem("workspace"));r.documents.getItem(l).setItem("writable",n.getItem("browser.writable")===!0),++t.requested,this.ideShowDocument(e,l),n.setItem("active",l),n.setItem("status","New document. Choose directory and name when saving.")}ideShowDocument(e,t){let r=Be(e),{documents:n}=r,s=n.documents.getItem(t).getItem("path"),a=r.scope.value.getNode("frame.center.tabs");if(!a.value?.getNode(t)){let l=n.documents.getItem(t),c=s.endsWith(".typ.py");c&&n.invalidateRecipe(t),l.setItem("readonly",!1),this.ideDocumentState(e,t),l.setItem("view","code"),l.setItem("createHidden",!0),l.setItem("undoDisabled",!0),l.setItem("redoDisabled",!0);let u=Z(a.builder.wrapSource(a).contentPane({node_label:t,title:s,pageName:t,documentKey:t,closable:!0,onClose:"ideClose",height:"100%"})),d=u.builder.wrapSource(u).div({display:"flex",flex_direction:"column",height:"100%"}),f=d.div({datapath:`.documents.${t}`,display:"flex",align_items:"center",gap:"6px",padding:"4px 12px",height:"40px",flex_shrink:0,box_sizing:"border-box",class:"gramlot-ide-document-toolbar",role:"toolbar","aria-label":`Commands for ${s}`});for(let[m,b,w,_]of[["save","M5 3h12l4 4v14H3V3h2 M7 3v6h10V3 M7 21v-8h10v8","Save","ideSave"],["revert","M3 10a9 9 0 1 1 2 8 M3 4v6h6 M12 7v5l3 2","Revert to saved","ideRevert"],["undo","M9 5 3 11l6 6 M3 11h12a6 6 0 0 1 6 6v2","Undo","ideUndo"],["redo","m15 5 6 6-6 6 M21 11H9a6 6 0 0 0-6 6v2","Redo","ideRedo"]]){let v=f.button({title:w,"aria-label":w,disabled:`^.${m}Disabled`,class:`button--quiet gramlot-ide-${m}`});v.svg({viewBox:"0 0 24 24",width:18,height:18,fill:"none",stroke:"currentColor",stroke_width:1.7,stroke_linecap:"round",stroke_linejoin:"round","aria-hidden":"true"}).path({d:b}),v.dataController({func:_,documentKey:t})}c&&f.button("Generate preview",{disabled:"^.renderDisabled",class:"button--quiet"}).dataController({func:"ideRenderRecipe",documentKey:t}),f.div("^.displayPath",{class:"gramlot-ide-document-path",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap",min_width:0,flex:"1"});let h=d.div({datapath:`.documents.${t}`,hidden:"^.createHidden",padding:"8px 12px",display:"flex",gap:"8px",align_items:"end",flex_shrink:0});h.textbox({value:"^.saveRoot",lbl:"Directory",flex:"1",disabled:"^.busy"}),h.textbox({value:"^.savePath",lbl:"File name",flex:"1",disabled:"^.busy"}),h.button("Create file",{disabled:"^.busy"}).dataController({func:"ideCreate",documentKey:t}),h.button("Cancel",{disabled:"^.busy",class:"button--quiet"}).dataController({func:"ideCancelCreate",documentKey:t});let p=d.div({flex:"1",min_height:0});if(l.getItem("language")==="image")p.drawingPane({image:`^.documents.${t}.image`,annotations:`^.documents.${t}.annotations`,height:"100%"});else{let m=l.getItem("language")==="html",b=l.getItem("language")==="markdown",w=m||b,_=l.getItem("language")==="typst",v=w||_||c,E=v?p.tabContainer({height:"100%",selectedPage:`^.documents.${t}.view`}):null,D=v?E.contentPane({title:"Code",pageName:"code",height:"100%"}):p;if(As(D,{datapath:`.documents.${t}`,value:"^.content",language:l.getItem("language"),height:"100%",readonly:"^.readonly",nodeId:`${r.editorPrefix}_editor_${t}`,editorView:"code",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_editor_${t}_save`]:!0}),_&&E.contentPane({title:"Preview",pageName:"preview",height:"100%"}).typstPreview({value:`^.documents.${t}.content`,filename:`^.documents.${t}.pdfFilename`,height:"100%"}),c){let k=E.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});k.div(`^.documents.${t}.renderStatus`,{role:"status",padding:"8px 12px",white_space:"pre-wrap",overflow:"auto",max_height:"30%"}),k.typstPreview({value:`^.documents.${t}.typstSource`,filename:`^.documents.${t}.pdfFilename`,hidden:`^.documents.${t}.previewHidden`,flex:"1",min_height:0}),E.contentPane({title:"Generated Typst",pageName:"generated",height:"100%"}).codeMirror({value:`^.documents.${t}.typstSource`,language:"typst",readonly:!0,height:"100%"})}if(w){let k=E.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});b&&(l.setItem("allowHtml",!1),k.checkbox({value:`^.documents.${t}.allowHtml`,label:"Allow embedded HTML",class:"gramlot-ide-allow-html",padding:"8px 12px",flex_shrink:0})),k[m?"htmlPreview":"markdownPreview"]({value:`^.documents.${t}.content`,flex:"1",min_height:0,...b?{allowHtml:`^.documents.${t}.allowHtml`}:{}}),E.contentPane({title:"Rich text",pageName:"rich",height:"100%"})[m?"htmlEditor":"markdownEditor"]({datapath:`.documents.${t}`,value:"^.content",readonly:"^.readonly",height:"100%",nodeId:`${r.editorPrefix}_rich_editor_${t}`,editorView:"rich",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_rich_editor_${t}_save`]:!0})}}}}async ideRenderRecipe(e,{documentKey:t}){let r=Be(e),{documents:n}=r;n.documents.getItem(t).setItem("view","preview"),await n.renderRecipe(t)}ideCancelCreate(e,{documentKey:t}){let r=Be(e),{documents:n}=r;n.documents.getItem(t).setItem("createHidden",!0)}async ideCreate(e,{documentKey:t}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData(".");i.setItem("status","Creating file\u2026");try{let s=await n.create(t);if(!n.disposed&&s){i.setItem("status","File created.");let a=i.getItem("browser");a.getItem("root")&&await r.scope.value.getNode("frame.left.browser").fileSystemController.open(a.getItem("root"))}}catch(s){n.disposed||i.setItem("status",s.message)}}async ideSave(e,{documentKey:t=null}={}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData("."),s=t??i.getItem("active");if(!s||n.documents.getItem(s).getItem("saveDisabled"))return;let a=n.documents.getItem(s);if(a.getItem("isNew")){a.setItem("createHidden",!1);return}i.setItem("status","Saving\u2026");try{let l=await n.save(s);n.disposed||i.setItem("status",l?"Saved.":"Document is read only or a request is pending.")}catch(l){n.disposed||i.setItem("status",l.message)}}ideRevert(e,{documentKey:t}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData(".");n.revert(t)&&i.setItem("status","Restored the last saved version.")}ideHistoryChanged(e,{canUndo:t,canRedo:r}){let n=e.getRelativeData("."),i=e.getAttr("editorView");n.setItem(`${i}CanUndo`,t),n.setItem(`${i}CanRedo`,r),this.ideHistoryState(n)}ideHistoryState(e){let t=e.getItem("view");e.setItem("undoDisabled",!e.getItem(`${t}CanUndo`)),e.setItem("redoDisabled",!e.getItem(`${t}CanRedo`))}ideEditor(e,t){let r=Be(e),{documents:n}=r,i=n.documents.getItem(t).getItem("view")==="rich",s=this.page.src.binding.nodeIds.get(`${r.editorPrefix}_${i?"rich_":""}editor_${t}`);return this.page.src.renderer.records.get(s).element}ideUndo(e,{documentKey:t}){this.ideEditor(e,t).undo()}ideRedo(e,{documentKey:t}){this.ideEditor(e,t).redo()}ideClose(e){let t=Be(e),{documents:r}=t,n=t.scope.getRelativeData("."),i=e.getAttr("documentKey");return r.canClose(i)?!0:(n.setItem("status","Save or revert your changes before closing. Pending operations must finish first."),!1)}ideClosed(e,{pageName:t}){this.ideForgetDocument(e,t)}ideForgetDocument(e,t,r=!1){let n=Be(e),{documents:i}=n,s=n.scope.getRelativeData("."),a=i.documents.getItem(t),l=s.getItem("browser"),c=l.getItem("selectedPath"),u=c===null?null:l.getItem("store").getNode(c);a&&l.getItem("root")===a.getItem("root")&&u?.attr.path===a.getItem("path")&&l.setItem("selectedPath",null),i.close(t,r)}};var tr=class extends Y{constructor({readOnly:e=!1}={}){super({cacheTime:-1,readOnly:e}),this.store=null,this.path=null,this.pending=null}bind(e,t){if(this.store!==null)throw new Error("TreeStoreResolver is already bound");this.store=e,this.path=t}load(){if(this.store===null)throw new Error("TreeStoreResolver is not bound to a store");if(this.pending!==null)return this.pending;let e=this.node,t=this.path?this.store.pathFor(e):"",r=this.store.load(t,t?e.label:null,t?{...e.attr}:{});return this.pending=r,r.finally(()=>{this.pending===r&&(this.pending=null)}).catch(()=>{}),r}};Oi(tr,{module:"gramlot.tree_store",name:"TreeStoreResolver",encode:()=>({args:[],kwargs:{}}),decode:()=>new tr});var zo=class{constructor({gramlot:e,method:t,params:r={}}){if(!e||typeof t!="string"||!t)throw new TypeError("TreeStore requires a page and method");for(let n of["path","label","attributes"])if(Object.hasOwn(r,n))throw new TypeError(`TreeStore params reserves ${n}`);this.gramlot=e,this.method=t,this.params={...r},this.controller=new AbortController,this.root=null}pathFor(e){let t=[];for(;e&&e.parentBag!==this.root;)t.unshift(e.label),e=e.parentNode;if(!e||this.root===null)throw new Error("TreeStore node is outside its root");return t.unshift(e.label),t.join(".")}async load(e="",t=null,r={}){if(this.controller.signal.aborted)throw this.controller.signal.reason;let n=await this.gramlot.rpc.call("data",this.method,{...this.params,path:e,label:t,attributes:r},{signal:this.controller.signal});if(this.controller.signal.aborted)throw this.controller.signal.reason;if(!(n instanceof x))throw new TypeError("TreeStore method must return a Bag");e||(this.root=n,n.setBackref());let i=(s,a)=>{for(let l of s.getNodes()){let c=a?`${a}.${l.label}`:l.label;l.resolver instanceof tr&&l.resolver.bind(this,c),l.staticValue instanceof x&&i(l.staticValue,c)}};return i(n,e),n}dispose(){this.controller.abort()}},Ns=class{treeFavoriteActionState(e,{item:t,state:r}){let n=t.resolver!==null||t.staticValue instanceof x;if(t.getAttr("favoriteEntry")===!0)return{hidden:!1,icon:"\u2715",title:"Remove favorite"};let i=!n&&r.getNodes().some(s=>s.getAttr("fieldpath")===t.getAttr("fieldpath"));return{hidden:n,icon:i?"\u2665":"\u2661",title:i?"Remove favorite":"Add favorite"}}treeFavoritesMount(e,{favoriteKey:t}){let n=this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.getItem(t);this.setTreeFavorites(e.getRelativeData("."),n===null?[]:j(n))}setTreeFavorites(e,t){if(!Array.isArray(t))throw new TypeError("Tree favorites must be an array");let r=new x;t.forEach((n,i)=>{if(!n||typeof n.fieldpath!="string"||typeof n.path!="string"||typeof n.caption!="string"||!n.attrs||typeof n.attrs!="object")throw new TypeError("Invalid tree favorite");let s={...n.attrs};for(let a of["caption","fullcaption"])typeof s[a]=="string"&&(s[a]=s[a].replace(/(^|\.)!!(?:\[[^\]]+\])?/g,"$1"));r.setItem(`favorite_${i}`,null,{...s,favoriteEntry:!0,originalPath:n.path})}),e.setItem("favorites",r)}treeFavoriteToggle(e,{item:t,path:r,favoriteKey:n}){if(t.resolver||t.staticValue instanceof x)return;let i=t.getAttr(),s=e.getRelativeData("."),a=s.getItem("favorites").getNodes().map(u=>{let{favoriteEntry:d,originalPath:f,...h}=u.getAttr();return{fieldpath:h.fieldpath,path:f,caption:h.caption,attrs:h}}),l=a.findIndex(u=>u.fieldpath===i.fieldpath);l===-1?a.push({fieldpath:i.fieldpath,path:r,caption:i.caption,attrs:{...i}}):a.splice(l,1),this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.setItem(n,R(a)),this.setTreeFavorites(s,a)}treeStoreMount(e,{storeMethod:t,storeParams:r}){let n=e.parentNode,i=e.getRelativeData("."),s=new zo({gramlot:this.page,method:t,params:r});this.page.src.renderer.onDispose(n,()=>s.dispose());let a=new tr({readOnly:!0});return a.bind(s,""),i.setResolver("store",a),Promise.resolve(i.getItem("store")).then(l=>{s.controller.signal.aborted||i.setItem("store",l)})}treeInspect(e,{item:t,path:r}){let n=this.page.src.binding.bindingFor(e),i=!1,s=`tree_inspect_${G()}`,a=()=>{},l=()=>{i||(i=!0,a(),this.page.src.source.getNode(s)&&this.page.src.source.popNode(s))};a=n.track(l);try{let c=new me,u=c.root.html_dialog({nodeId:s,request:s,connect_oncancel:"treeInspectClose",connect_onclose:"treeInspectClose","aria-labelledby":`${s}_title`,style:"width:min(36rem,calc(100% - 48px));max-height:80vh;overflow:auto;"});u.h2("Attributes",{id:`${s}_title`}),u.p(`==${JSON.stringify(r)}`),u.html_button("Close",{type:"button",autofocus:!0,request:s,connect_onclick:"treeInspectClose"});let d=u.table();for(let[h,p]of Object.entries(t.getAttr())){let m=d.tr();m.th(`==${JSON.stringify(h)}`,{scope:"row"});let b=typeof p=="string"?p:p===void 0?"undefined":R(p);m.td(`==${JSON.stringify(b)}`)}this.page.src.source.setItem(s,this.page.src.prepareSource(c.source));let f=this.page.src.binding.nodeIds.get(s);Object.defineProperty(f,"treeInspectClose",{value:l,configurable:!0}),this.page.src.renderer.onDispose(f,()=>{l(),delete f.treeInspectClose}),this.page.dom.getDomNode(f).showModal()}catch(c){throw l(),c}}treeInspectClose(e,t){t.preventDefault();let r=this.page.src.binding.nodeIds.get(e.getAttr("request"));r&&r.treeInspectClose()}};var _n=class{constructor({maxBytes:e}){if(!Number.isSafeInteger(e)||e<0)throw new TypeError("maxBytes must be a nonnegative safe integer");this.maxBytes=e}write(e){throw new Error("UploadTarget.write must be implemented")}finish(){throw new Error("UploadTarget.finish must be implemented")}abort(){throw new Error("UploadTarget.abort must be implemented")}status(){throw new Error("UploadTarget.status must be implemented")}};var Qb=new Set(Object.entries(new Je().schema).filter(([,o])=>!o._meta?.data_element&&!o._meta?.subbuilder&&!o._meta?.container).map(([o])=>o));function yn(o){if(!(o==null||o==="html")){if(!Array.isArray(o)||o.some(e=>typeof e!="string"||!e||e.trim()!==e))throw new TypeError('catalogue must be "html" or a list of tag names');if(!o.includes("div"))throw new Error("catalogue must include div for pageRoot")}}function vn(o,e,t={}){return o==null?!0:Array.isArray(o)?o.includes(e):!t.gramlot_component&&!t.data_element&&!t.subbuilder&&!t.container&&Qb.has(t.render_tag??e)}function tt(o,e){if(o==null)return;let t=(r,n)=>{for(let i of r.getNodes()){let s=n?`${n}.${i.label}`:i.label;if(!vn(o,i.nodeTag,i.getAttr("_meta")??{}))throw new Error(`Tag ${i.nodeTag} is outside the editor catalogue at ${s}`);if(i.resolver)throw new Error(`Catalogue scope requires materialized Source at ${s}`);let a=i.getValue(!0);a instanceof N&&t(a,s)}};t(e,"")}var Ce={navigation:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%224%22%20width%3D%2218%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M9%204v16M5.5%208h1M5.5%2012h1%22%2F%3E%3C%2Fsvg%3E",catalogue:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%2214%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%223%22%20y%3D%2214%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M14%2017.5h7M17.5%2014v7%22%2F%3E%3C%2Fsvg%3E",properties:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M4%206h16M4%2012h16M4%2018h16%22%2F%3E%3Ccircle%20cx%3D%228%22%20cy%3D%226%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2216%22%20cy%3D%2212%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2210%22%20cy%3D%2218%22%20r%3D%222%22%2F%3E%3C%2Fsvg%3E",new:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M14%202H6a2%202%200%200%200-2%202v16a2%202%200%200%200%202%202h12a2%202%200%200%200%202-2V8Z%20M14%202v6h6%20M8%2015h8%20M12%2011v8%22%2F%3E%3C%2Fsvg%3E",download:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M12%203v12m-5-5%205%205%205-5%20M4%2016v4a1%201%200%200%200%201%201h14a1%201%200%200%200%201-1v-4%22%2F%3E%3C%2Fsvg%3E",copy:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2212%22%20height%3D%2213%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M16%208V5a2%202%200%200%200-2-2H5a2%202%200%200%200-2%202v9a2%202%200%200%200%202%202h3%22%2F%3E%3C%2Fsvg%3E"};Ce.open="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%207V5a2%202%200%200%201%202-2h5l2%202h7a2%202%200%200%201%202%202v2M3%209h18l-2%2011H4z%22%2F%3E%3C%2Fsvg%3E";Ce.cut="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Ccircle%20cx%3D%226%22%20cy%3D%226%22%20r%3D%223%22%2F%3E%3Ccircle%20cx%3D%226%22%20cy%3D%2218%22%20r%3D%223%22%2F%3E%3Cpath%20d%3D%22m8%208%2012%2012M8%2016%2020%204%22%2F%3E%3C%2Fsvg%3E";Ce.paste="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%225%22%20y%3D%225%22%20width%3D%2214%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Crect%20x%3D%229%22%20y%3D%222%22%20width%3D%226%22%20height%3D%225%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M9%2012h6m-6%204h6%22%2F%3E%3C%2Fsvg%3E";Ce.appearance="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%228%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%2F%3E%3Cpath%20d%3D%22M12%204a8%208%200%200%201%200%2016z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";var Os=class{constructor(e,{datapath:t="__editor",dataRoot:r="",editorId:n="visual",uploadOperation:i="import_source",codeDocument:s=null,catalogue:a=null,fileCommands:l=!0,canvasCss:c=null,...u}={}){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(n))throw new Error("editorId must be a literal identifier");if(!r&&t!=="__editor"&&!t.startsWith("__editor."))throw new Error("Root Data editing requires an __editor datapath");if(yn(a),c!=null&&(!Array.isArray(c)||c.some(nr=>typeof nr!="string")))throw new TypeError("canvasCss must be a list of CSS texts");this.dataRoot=r;let d=this.pane=e.main({node_label:n,datapath:t,visualEditorId:n,...u,nodeId:`${n}Editor`,class:`visual-editor-shell ${u.class??""}`,overflow:"hidden",tabindex:0,connect_onkeydown:"clipboardShortcut"});d.dataSetter({destination_path:".catalogueScope",value:a}),d.dataSetter({destination_path:".canvasCss",value:c}),d.dataSetter({destination_path:".uploadQueue",value:new x}),d.dataController({func:"initializeEditor",dataRoot:this.dataRoot,_init:!0}),d.dataController({func:"showProperties",path:"^.selection",_init:!0}),d.dataController({func:"initializeCanvasSelection",_onBuilt:!0}),d.dataController({func:"initializeDocument",_onBuilt:!0}),d.dataController({func:"highlightSelection",path:"^.selection",_init:!0}),d.style("^.appearanceCss"),d.dataController({func:"initializeEditorAppearance",_onBuilt:!0}),d.dataController({func:"applyEditorAppearance",profile:"^.appearanceProfile",palette:"^.appearancePalette",mode:"^.appearanceMode"});let f=this.rail=d.menu({presentation:"bar",orientation:"vertical",aria_label:"Editor panels",class:"visual-editor-rail"});this.toolButton(f.menuline({group:!0}),"Source / Data","toggleNavigation",Ce.navigation),this.toolButton(f.menuline({group:!0}),"Catalogue","openCatalogue",Ce.catalogue),this.toolButton(f.menuline({group:!0}),"Properties","openProperties",Ce.properties),this.toolButton(f.menuline({group:!0}),"Clipboard","this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))",Ce.paste,{dropTarget:!0,dropTypes:"app/source",dropTags:`${n}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard"}),f.spacer({flex:1}),this.toolButton(f.menuline({group:!0}),"Appearance","this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))",Ce.appearance);let h=d.framePane({node_label:"layout",height:"100%",id:`${n}-editor-frame`,class:"visual-editor-layout"});h.top.setAttr({height:"30px"});let p=h.top.menu({presentation:"bar",aria_label:"Editor tools",class:"visual-editor-toolbar"});p.menuline({group:!0}).span("Source editor",{class:"visual-editor-brand"});let m=p.menuline({group:!0,gap:"4px",hidden:!l});for(let[nr,Ko,Jo]of[["New","newPage","new"],["Open","openUpload","open"],["Download","downloadPage","download"],["Copy Source","copySource","copy"]])this.toolButton(m,nr,Ko,Ce[Jo],{id:`${n}-${Jo}`});p.menuline({group:!0}).span({class:"visual-toolbar-divider",aria_hidden:"true"});let b=p.menuline({group:!0,gap:"2px"});this.toolButton(b,"Cut branch","cutBranch",Ce.cut,{title:"Cut branch (F8)"}),this.toolButton(b,"Copy branch","copyBranch",Ce.copy),this.toolButton(b,"Paste branch","pasteBranch",Ce.paste,{title:"Paste branch (F9)"}),p.spacer({flex:1}),p.menuline({group:!0,hidden:"^.modified:=!{}"}).span("Unsaved changes",{role:"status",class:"visual-editor-hint"}),p.menuline({group:!0}).span("^.fileStatus",{role:"status",class:"visual-editor-file-status"}),p.menuline({group:!0}).span("^.filename",{class:"visual-editor-filename"});let w=h.left;w.setAttr({width:"min(240px, 34vw)",splitter:!0,drawer:"^.navigationOpen",default_drawer:!0,drawer_label:"Source / Data",drawer_onclick:"this.SET('.navigationOpen', show ? true : 'close')",display:"flex",flex_direction:"column",min_height:0,class:"visual-editor-sidebar"});let _=w.borderContainer({height:"100%",flex:1,min_height:0}),v=_.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),E=v.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),D=E.contentPane({node_label:"source",region:"center",title:"Source",detachable:!0,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(D,"sourceSearch","Search Source"),D.tree({storepath:`*S.${Z(d).fullpath.split(".").slice(1).join(".")}.layout.center.design`,hideValues:!0,getLabel:"sourceLabel",searchText:"^.sourceSearch",selectedPath:"^.selection",draggable:!0,dragTags:`${n}Source`,effectAllowed:"all",onDrag:"prepareSource",dropTarget:!0,dropTypes:"app/widget,app/source,app/clipboard",dropTags:`widget,${n}Source,${n}Clipboard`,dropEffect:"^.sourceDropEffect",onDrop:"dropNode",id:`${n}-source-tree`,class:"visual-source-tree",flex:1,min_height:0});let k=E.contentPane({node_label:"clipboard",region:"bottom",height:"112px",splitter:!0,minSize:80,title:"Clipboard",detachable:!0,hidden:"^.clipboardVisible:=!{}",display:"flex",flex_direction:"column",min_height:0,overflow:"hidden",dropTarget:!0,dropTypes:"app/source",dropTags:`${n}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard",class:"visual-clipboard"});k.span("Drop a branch here \xB7 Option to copy",{class:"visual-editor-hint"}),k.tree({storepath:".clipboard",hideValues:!0,labelAttribute:"name",selectedPath:"^.clipboardSelection",draggable:!0,dragTags:`${n}Clipboard`,effectAllowed:"copy",onDrag:"prepareClipboard",id:`${n}-clipboard-tree`,class:"visual-clipboard-tree",flex:1,min_height:0}),k.p("^.error",{role:"alert",class:"visual-editor-hint"});let C=v.contentPane({node_label:"data",region:"bottom",title:"Data",detachable:!0,height:"108px",splitter:!0,minSize:80,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(C,"dataSearch","Search Data"),C.tree({storepath:this.dataRoot?`*D.${this.dataRoot}`:"*D",excludeRoot:this.dataRoot?null:"__editor",searchText:"^.dataSearch",id:`${n}-data-tree`,flex:1,min_height:0});let O=h.center;O.setAttr({overflow:"auto",class:"visual-editor-workspace"});let L=O.div({node_label:"design",class:"visual-editor-canvas"});L.div({node_label:"pageRoot",...this.dataRoot?{datapath:this.dataRoot}:{}});let z=d.floatingPane({title:"Widget catalogue",open:"^.catalogueOpen",default_open:!1,width:"280px",height:"400px",class:"visual-editor-popup",movable:!0,resizable:!0});this.search(z.frame.top,"catalogueSearch","Search widgets"),z.frame.center.tree({storepath:".catalogue",hideValues:!0,labelAttribute:"caption",searchText:"^.catalogueSearch",draggable:!0,dragTags:"widget",effectAllowed:"all",onDrag:"prepareWidget",id:`${n}-widget-tree`});let V=_.contentPane({region:"bottom",height:"^.propertiesHeight",default_height:"200px",minSize:140,splitter:!0,title:"^.propertiesTitle",detachable:!0,hidden:"^.propertiesOpen:=!{}",display:"flex",flex_direction:"column",overflow:"hidden",min_height:0});V.div({nodeId:`${n}EditorFields`,class:"visual-editor-fields",display:"flex",flex_direction:"column",flex:1,min_height:0}).span(""),V.p("^.propertyError",{role:"alert",class:"visual-editor-hint",margin:"3px"}),d.dialog({class:"visual-editor-popup",title:"Open Source",open:"^.uploadOpen",width:"480px",height:"300px",movable:!0,resizable:!0}).frame.center.uploader({operation:i,storepath:".uploadQueue",accept:".grmlt",multiple:!1,autoUpload:!0,onComplete:"sourceUploaded",id:`${n}-uploader`});let _e=d.dialog({class:"visual-editor-popup",title:"Save branch to clipboard",open:"^.clipboardOpen",width:"380px",height:"210px"});_e.frame.center.textbox({value:"^.clipboardDraft.name",lbl:"Name",margin:"12px"}),_e.frame.center.p("^.error",{role:"alert",margin:"12px"});let ht=_e.frame.bottom.menu({presentation:"bar",aria_label:"Clipboard commands",padding:"3px 6px"});ht.spacer({flex:1});let ne=ht.menuline({group:!0,gap:"8px"});ne.button("Cancel",{action:"this.SET('.clipboardOpen', false)"}),ne.button("Save branch",{action:"saveClipboard"});let X=d.dialog({class:"visual-editor-popup",title:"Required parameters",open:"^.insertionOpen",width:"400px",height:"280px",movable:!0,resizable:!0});X.frame.center.div({nodeId:`${n}InsertFields`,class:"visual-editor-fields",padding:"6px"}).span(""),X.frame.center.p("^.error",{role:"alert"});let pt=X.frame.bottom.menu({presentation:"bar",aria_label:"Insertion commands",padding:"3px 6px",border_top:"1px solid var(--gramlot-border)"});pt.spacer({flex:1});let Zo=pt.menuline({group:!0,gap:"8px"});Zo.button("Cancel",{action:"this.SET('.insertionOpen', false)"}),Zo.button("Insert",{action:"insertWidget"});let Dt=d.floatingPane({class:"visual-editor-popup",title:"Appearance",open:"^.appearanceOpen",default_open:!1,width:"280px",height:"260px",movable:!0,resizable:!0}).frame.center.formlet({columns:1,lbl_position:"TL",gap:"4px",padding:"6px"});Dt.filteringSelect({validate_notnull:!0,lbl:"Theme",value:"^.appearanceProfile",values:"base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela"}),Dt.filteringSelect({validate_notnull:!0,lbl:"Colors",value:"^.appearancePalette",values:"default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue"}),Dt.filteringSelect({validate_notnull:!0,lbl:"Mode",value:"^.appearanceMode",values:"light:Light,dark:Dark"}),d.p("^.error",{role:"alert",class:"visual-editor-error",hidden:"^.error:=!{}"}),this.frame=h,this.toolbar=p,this.design=L,s!==null&&this.codeDocument(s)}toolButton(e,t,r,n,i={}){let s=e.button({aria_label:t,title:t,action:r,class:"button--quiet visual-editor-tool",...i});return s.span({class:"visual-tool-icon",aria_hidden:"true",style:`mask-image:url("${n}")`}),s}codeDocument(e,t=this.frame){if(!["python","javascript"].includes(e.language))throw new TypeError("Expected a Python or JavaScript page document");let r=this.pane;r.setAttr({codeDocumentKey:e.key}),r.dataSetter({destination_path:".codeDocument",value:new x({...e,saved:e.content,busy:!1,status:""})});let n=`#${r.getAttr("visualEditorId")}Editor`;(t===this.frame?this.toolbar:t.top.menu({presentation:"bar",aria_label:"Code drawer"})).menuline({group:!0}).button("Code",{action:"openCode",class:"button--quiet"});let s=t.right;s.setAttr({class:"visual-editor-code",datapath:n,title:"Page code",detachable:!0,width:"60%",minSize:240,splitter:!0,drawer:"^.codeOpen",default_drawer:"close",drawer_label:"Code",drawer_minimize:!1,drawer_onclick:"this.SET('.codeOpen', show ? true : 'close')",min_height:0,overflow:"hidden"});let a=s.framePane({height:"100%",width:"100%",min_width:0,flex:1});a.top.setAttr({height:"26px"}),a.bottom.setAttr({height:"48px"}),a.center.setAttr({display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"}),a.top.div(e.path,{padding:"3px 6px",font_size:"12px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),a.center.codeMirror({value:"^.codeDocument.content",language:e.language,live:!0,readonly:"^.codeDocument.writable:=!{}",height:"100%",box_height:"100%",box_c_height:"100%",box_min_height:0,box_c_min_height:0,fontSize:13,flex:1,min_height:0}),a.bottom.div("^.codeDocument.status",{role:"status",font_size:"12px",padding:"4px 10px"});let l=a.bottom.menu({presentation:"bar",aria_label:"Page code commands",padding:"3px 6px"});l.spacer({flex:1});let c=l.menuline({group:!0,gap:"6px"});c.button("Close",{action:"this.SET('.codeOpen', 'close')"}),c.button("Preview saved",{action:"codePreview",disabled:"^.codeDocument.busy"}),c.button("Save",{action:"codeSave",disabled:"^.codeSaveDisabled"}),r.dataFormula({result_path:".codeSaveDisabled",formula:"!writable || busy || content === saved",writable:"^.codeDocument.writable",busy:"^.codeDocument.busy",content:"^.codeDocument.content",saved:"^.codeDocument.saved",_init:!0})}search(e,t,r){let i=e.menu({presentation:"bar",aria_label:r,class:"visual-search-toolbar"}).menuline({group:!0,flex:1,min_width:0}).div({class:"visual-search-field"});i.span({class:"visual-search-icon",aria_hidden:"true"}),i.input({type:"search",value:`^.${t}`,default:"",live:!0,placeholder:r,aria_label:r}),i.html_button({type:"button",class:"visual-search-clear",aria_label:`Clear ${r.toLowerCase()}`,hidden:`^.${t}:={} === ''`,connect_onclick:`this.SET('.${t}', '')`})}};var $s=class extends _n{constructor({catalogue:e=null}={}){super({maxBytes:5*1024*1024}),yn(e),this.catalogue=e,this.decoder=new TextDecoder("utf-8",{fatal:!0}),this.parts=[],this.outcome={state:"pending"}}write(e){this.parts.push(this.decoder.decode(e,{stream:!0}))}finish(){this.parts.push(this.decoder.decode());let e=this.parts.join("");this.parts=[];let t=j(e);if(!(t instanceof N)||t.length!==1||t.getNodes()[0].label!=="pageRoot")throw new TypeError("Expected one pageRoot Source");return tt(this.catalogue,t),this.outcome={state:"completed",result:e},this.outcome}abort(){return this.outcome.state!=="completed"&&(this.parts=[],this.outcome={state:"unsaved"}),this.outcome}status(){return this.outcome}};var yc={};ee(yc,{default:()=>mh});function ew(o,e){this.v=o,this.k=e}function Xf(o,e){(e==null||e>o.length)&&(e=o.length);for(var t=0,r=Array(e);t<e;t++)r[t]=o[t];return r}function tw(o){if(Array.isArray(o))return o}function rw(o,e){var t=o==null?null:typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(t!=null){var r,n,i,s,a=[],l=!0,c=!1;try{if(i=(t=t.call(o)).next,e===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(r=i.call(t)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(u){c=!0,n=u}finally{try{if(!l&&t.return!=null&&(s=t.return(),Object(s)!==s))return}finally{if(c)throw n}}return a}}function nw(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
233
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ow(o,e){return tw(o)||rw(o,e)||iw(o,e)||nw()}function iw(o,e){if(o){if(typeof o=="string")return Xf(o,e);var t={}.toString.call(o).slice(8,-1);return t==="Object"&&o.constructor&&(t=o.constructor.name),t==="Map"||t==="Set"?Array.from(o):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Xf(o,e):void 0}}function Rs(o){var e,t;function r(i,s){try{var a=o[i](s),l=a.value,c=l instanceof ew;Promise.resolve(c?l.v:l).then(function(u){if(c){var d=i==="return"&&l.k?i:"next";if(!l.k||u.done)return r(d,u);u=o[d](u).value}n(!!a.done,u)},function(u){r("throw",u)})}catch(u){n(2,u)}}function n(i,s){i===2?e.reject(s):e.resolve({value:s,done:i}),(e=e.next)?r(e.key,e.arg):t=null}this._invoke=function(i,s){return new Promise(function(a,l){var c={key:i,arg:s,resolve:a,reject:l,next:null};t?t=t.next=c:(e=t=c,r(i,s))})},typeof o.return!="function"&&(this.return=void 0)}Rs.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Rs.prototype.next=function(o){return this._invoke("next",o)},Rs.prototype.throw=function(o){return this._invoke("throw",o)},Rs.prototype.return=function(o){return this._invoke("return",o)};var ch=Object.entries,Yf=Object.setPrototypeOf,sw=Object.isFrozen,uh=Object.getPrototypeOf,dh=Object.getOwnPropertyDescriptor,we=Object.freeze,ke=Object.seal,xn=Object.create,fh=typeof Reflect<"u"&&Reflect,wc=fh.apply,_c=fh.construct;we||(we=function(e){return e});ke||(ke=function(e){return e});wc||(wc=function(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return e.apply(t,n)});_c||(_c=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return new e(...r)});var St=ae(Array.prototype.forEach);Array.prototype.indexOf;var aw=ae(Array.prototype.lastIndexOf),Zf=ae(Array.prototype.pop),Uo=ae(Array.prototype.push),lw=ae(Array.prototype.slice),cw=ae(Array.prototype.splice),kn=Array.isArray,cc=hh(Set),uc=ae(Set.prototype.add),qo=ae(Set.prototype.has),jr=ae(String.prototype.toLowerCase),dc=ae(String.prototype.toString),Kf=ae(String.prototype.match),Vo=ae(String.prototype.replace),Jf=ae(String.prototype.indexOf),uw=ae(String.prototype.trim),dw=ae(Number.prototype.toString),fw=ae(Boolean.prototype.toString),Qf=typeof BigInt>"u"?null:ae(BigInt.prototype.toString),eh=typeof Symbol>"u"?null:ae(Symbol.prototype.toString),Me=ae(Object.prototype.hasOwnProperty),Wo=ae(Object.prototype.toString),xe=ae(RegExp.prototype.test),At=hh(TypeError);function ae(o){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return wc(o,e,r)}}function hh(o){return function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return _c(o,t)}}function J(o,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jr;if(Yf&&Yf(o,null),!kn(e))return o;let r=e.length;for(;r--;){let n=e[r];if(typeof n=="string"){let i=t(n);i!==n&&(sw(e)||(e[r]=i),n=i)}o[n]=!0}return o}function hw(o){for(let e=0;e<o.length;e++)Me(o,e)||(o[e]=null);return o}function ze(o){let e=xn(null);for(let r of ch(o)){var t=ow(r,2);let n=t[0],i=t[1];Me(o,n)&&(kn(i)?e[n]=hw(i):i&&typeof i=="object"&&i.constructor===Object?e[n]=ze(i):e[n]=i)}return e}function pw(o){switch(typeof o){case"string":return o;case"number":return dw(o);case"boolean":return fw(o);case"bigint":return Qf?Qf(o):"0";case"symbol":return eh?eh(o):"Symbol()";case"undefined":return Wo(o);case"function":case"object":{if(o===null)return Wo(o);let e=o,t=Ve(e,"toString");if(typeof t=="function"){let r=t(e);return typeof r=="string"?r:Wo(r)}return Wo(o)}default:return Wo(o)}}function Ve(o,e){for(;o!==null;){let r=dh(o,e);if(r){if(r.get)return ae(r.get);if(typeof r.value=="function")return ae(r.value)}o=uh(o)}function t(){return null}return t}function mw(o,e){for(;o!==null;){let t=dh(o,e);if(t)return t.get?ae(t.get):null;o=uh(o)}return null}function gw(o){try{return xe(o,""),!0}catch{return!1}}var th=we(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),fc=we(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),hc=we(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),bw=we(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),pc=we(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),ww=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),rh=we(["#text"]),nh=we(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),mc=we(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),oh=we(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),js=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_w=ke(/{{[\w\W]*|^[\w\W]*}}/g),yw=ke(/<%[\w\W]*|^[\w\W]*%>/g),vw=ke(/\${[\w\W]*/g),xw=ke(/^data-[\-\w.\u00B7-\uFFFF]+$/),kw=ke(/^aria-[\-\w]+$/),ih=ke(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ew=ke(/^(?:\w+script|data):/i),Tw=ke(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Sw=ke(/^html$/i),Aw=ke(/^[a-z][.\w]*(-[.\w]+)+$/i),gc=ke(/<[/\w!]/g),sh=ke(/<[/\w]/g),Iw=ke(/<\/no(script|embed|frames)/i),ah=ke(/\/>/i),fe={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Cw=we(J({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),Dw=function(){return typeof window>"u"?null:window},Nw=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},lh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},rr=function(e,t,r,n){return Me(e,t)&&kn(e[t])?J(n.base?ze(n.base):{},e[t],n.transform):r},bc=function(e,t,r){let n=Me(e,t)?e[t]:void 0;return n&&typeof n=="object"?ze(n):r()};function ph(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Dw(),e=I=>ph(I);if(e.version="3.4.17",e.removed=[],!o||!o.document||o.document.nodeType!==fe.document||!o.Element)return e.isSupported=!1,e;let t=o.document,r=t,n=r.currentScript;o.DocumentFragment;let i=o.HTMLTemplateElement,s=o.Node,a=o.Element,l=o.NodeFilter;o.NamedNodeMap===void 0&&(o.NamedNodeMap||o.MozNamedAttrMap),o.HTMLFormElement;let c=o.DOMParser,u=o.trustedTypes,d=a.prototype,f=Ve(d,"cloneNode"),h=Ve(d,"remove"),p=Ve(d,"removeAttributeNode"),m=Ve(d,"nextSibling"),b=Ve(d,"childNodes"),w=Ve(d,"parentNode"),_=Ve(d,"shadowRoot"),v=Ve(d,"attributes"),E=s&&s.prototype?Ve(s.prototype,"nodeType"):null,D=s&&s.prototype?Ve(s.prototype,"nodeName"):null,k=s&&s.prototype?Ve(s.prototype,"ownerDocument"):null,C=function(g){return E?E(g):g.nodeType},O=function(g){return D?D(g):g.nodeName},L=mw(d,"namespaceURI"),z=function(g){return L?L(g):g.namespaceURI};if(typeof i=="function"){let I=t.createElement("template");I.content&&I.content.ownerDocument&&(t=I.content.ownerDocument)}let V,le="",_e,ht=!1,ne=0,X=function(){if(ne>0)throw At('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},pt=function(g){X(),ne++;try{return V.createHTML(g)}finally{ne--}},Zo=function(g){X(),ne++;try{return V.createScriptURL(g)}finally{ne--}},Jc=function(){return ht||(_e=Nw(u,n),ht=!0),_e},Dt=t,nr=Dt.implementation,Ko=Dt.createNodeIterator,Jo=Dt.createDocumentFragment,Sh=Dt.getElementsByTagName,Ah=r.importNode,oe=lh();e.isSupported=typeof ch=="function"&&typeof w=="function"&&nr&&nr.createHTMLDocument!==void 0;let Ih=_w,Ch=yw,Dh=vw,Nh=xw,Oh=kw,$h=Ew,Qc=Tw,Rh=Aw,eu=ih,ie=null,Ys=J({},[...th,...fc,...hc,...pc,...rh]),se=null,Zs=J({},[...nh,...mc,...oh,...js]),rt=Object.seal(xn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Sn=null,tu=null,Nt=Object.seal(xn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ru=!0,Ks=!0,nu=!1,Js=!0,mt=!1,or=!0,ir=!1,Qs=!1,Qo=null,ei=null,ea=!1,Pr=!1,ti=!1,ri=!1,ou=!0,iu=!1,su="user-content-",ta=!0,ra=!1,sr=null,Br={},ar=null,au=J({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),lu=null,cu=J({},["audio","video","img","source","image","track"]),uu=null,du=J({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ni="http://www.w3.org/1998/Math/MathML",oi="http://www.w3.org/2000/svg",nt="http://www.w3.org/1999/xhtml",Mr=nt,na=!1,oa=null,jh=J({},[ni,oi,nt],dc),fu=we(["mi","mo","mn","ms","mtext"]),ia=J({},fu),hu=we(["annotation-xml"]),sa=J({},hu),Ph=J({},["title","style","font","a","script"]),An=null,Bh=["application/xhtml+xml","text/html"],Mh="text/html",ue=null,Lr=null,Lh=t.createElement("form"),pu=function(g){return g instanceof RegExp||g instanceof Function},aa=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Lr&&Lr===g)return;(!g||typeof g!="object")&&(g={}),g=ze(g),An=Bh.indexOf(g.PARSER_MEDIA_TYPE)===-1?Mh:g.PARSER_MEDIA_TYPE,ue=An==="application/xhtml+xml"?dc:jr,ie=rr(g,"ALLOWED_TAGS",Ys,{transform:ue}),se=rr(g,"ALLOWED_ATTR",Zs,{transform:ue}),oa=rr(g,"ALLOWED_NAMESPACES",jh,{transform:dc}),uu=rr(g,"ADD_URI_SAFE_ATTR",du,{transform:ue,base:du}),lu=rr(g,"ADD_DATA_URI_TAGS",cu,{transform:ue,base:cu}),ar=rr(g,"FORBID_CONTENTS",au,{transform:ue}),Sn=rr(g,"FORBID_TAGS",ze({}),{transform:ue}),tu=rr(g,"FORBID_ATTR",ze({}),{transform:ue}),Br=Me(g,"USE_PROFILES")?g.USE_PROFILES&&typeof g.USE_PROFILES=="object"?ze(g.USE_PROFILES):g.USE_PROFILES:!1,ru=g.ALLOW_ARIA_ATTR!==!1,Ks=g.ALLOW_DATA_ATTR!==!1,nu=g.ALLOW_UNKNOWN_PROTOCOLS||!1,Js=g.ALLOW_SELF_CLOSE_IN_ATTR!==!1,mt=g.SAFE_FOR_TEMPLATES||!1,or=g.SAFE_FOR_XML!==!1,ir=g.WHOLE_DOCUMENT||!1,Pr=g.RETURN_DOM||!1,ti=g.RETURN_DOM_FRAGMENT||!1,ri=g.RETURN_TRUSTED_TYPE||!1,ea=g.FORCE_BODY||!1,ou=g.SANITIZE_DOM!==!1,iu=g.SANITIZE_NAMED_PROPS||!1,ta=g.KEEP_CONTENT!==!1,ra=g.IN_PLACE||!1,eu=gw(g.ALLOWED_URI_REGEXP)?g.ALLOWED_URI_REGEXP:ih,Mr=typeof g.NAMESPACE=="string"?g.NAMESPACE:nt,ia=bc(g,"MATHML_TEXT_INTEGRATION_POINTS",()=>J({},fu)),sa=bc(g,"HTML_INTEGRATION_POINTS",()=>J({},hu));let y=bc(g,"CUSTOM_ELEMENT_HANDLING",()=>xn(null));if(rt=xn(null),Me(y,"tagNameCheck")&&pu(y.tagNameCheck)&&(rt.tagNameCheck=y.tagNameCheck),Me(y,"attributeNameCheck")&&pu(y.attributeNameCheck)&&(rt.attributeNameCheck=y.attributeNameCheck),Me(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(rt.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),ke(rt),mt&&(Ks=!1),ti&&(Pr=!0),Br&&(ie=J({},rh),se=xn(null),Br.html===!0&&(J(ie,th),J(se,nh)),Br.svg===!0&&(J(ie,fc),J(se,mc),J(se,js)),Br.svgFilters===!0&&(J(ie,hc),J(se,mc),J(se,js)),Br.mathMl===!0&&(J(ie,pc),J(se,oh),J(se,js))),Nt.tagCheck=null,Nt.attributeCheck=null,Me(g,"ADD_TAGS")&&(typeof g.ADD_TAGS=="function"?Nt.tagCheck=g.ADD_TAGS:kn(g.ADD_TAGS)&&(ie===Ys&&(ie=ze(ie)),J(ie,g.ADD_TAGS,ue))),Me(g,"ADD_ATTR")&&(typeof g.ADD_ATTR=="function"?Nt.attributeCheck=g.ADD_ATTR:kn(g.ADD_ATTR)&&(se===Zs&&(se=ze(se)),J(se,g.ADD_ATTR,ue))),Me(g,"ADD_FORBID_CONTENTS")&&kn(g.ADD_FORBID_CONTENTS)&&(ar===au&&(ar=ze(ar)),J(ar,g.ADD_FORBID_CONTENTS,ue)),ta&&(ie["#text"]=!0),ir&&J(ie,["html","head","body"]),ie.table&&(J(ie,["tbody"]),delete Sn.tbody),g.TRUSTED_TYPES_POLICY){if(typeof g.TRUSTED_TYPES_POLICY.createHTML!="function")throw At('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof g.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw At('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let T=V;V=g.TRUSTED_TYPES_POLICY;try{le=pt("")}catch(S){throw V=T,S}}else g.TRUSTED_TYPES_POLICY===null?(V=void 0,le=""):(V===void 0&&(V=Jc()),V&&typeof le=="string"&&(le=pt("")));we&&we(g),Lr=g},mu=J({},[...fc,...hc,...bw]),gu=J({},[...pc,...ww]),Fh=function(g,y,T){return y.namespaceURI===nt?g==="svg":y.namespaceURI===ni?g==="svg"&&(T==="annotation-xml"||ia[T]):!!mu[g]},zh=function(g,y,T){return y.namespaceURI===nt?g==="math":y.namespaceURI===oi?g==="math"&&sa[T]:!!gu[g]},Uh=function(g,y,T){return y.namespaceURI===oi&&!sa[T]||y.namespaceURI===ni&&!ia[T]?!1:!gu[g]&&(Ph[g]||!mu[g])},qh=function(g){let y=z(g),T=jr(O(g)),S=w(g),P,F;return S&&C(S)===fe.element?(P={namespaceURI:z(S)},F=jr(O(S))):(P={namespaceURI:Mr},F="template"),oa[y]?y===oi?Fh(T,P,F):y===ni?zh(T,P,F):y===nt?Uh(T,P,F):!!(An==="application/xhtml+xml"&&oa[y]):!1},Ot=function(g){Uo(e.removed,{element:g});try{w(g).removeChild(g)}catch{if(h(g),!w(g))throw At("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},bu=function(g,y,T){try{p(g,y)}catch{try{g.removeAttribute(T)}catch{}}},la=function(g){ua(g);let y=b(g);y&&St(lw(y),S=>{try{h(S)}catch{}});let T=C(g)===fe.element?v(g):null;if(T)for(let S=T.length-1;S>=0;--S){let P=T[S],F=P&&P.name;typeof F=="string"&&bu(g,P,F)}},Fr=function(g,y,T){if(!T)try{T=y.getAttributeNode(g)}catch{T=null}Uo(e.removed,{attribute:T||null,from:y});try{T?p(y,T):y.removeAttribute(g)}catch{try{y.removeAttribute(g)}catch{}}if(g==="is")if(Pr||ti)try{Ot(y)}catch{}else try{y.setAttribute(g,"")}catch{}},wu=function(g){let y=v(g);if(y)for(let T=y.length-1;T>=0;--T){let S=y[T],P=S&&S.name;typeof P!="string"||se[ue(P)]||bu(g,S,P)}},ca=function(g,y){let T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,S=[g];for(;S.length>0;){let P=S.pop();if(y(P)===!1)continue;if(T&&C(P)===fe.element){let W=_(P);$t(W)&&S.push(W)}let F=b(P);if(F)for(let W=F.length-1;W>=0;--W)S.push(F[W])}},ua=function(g){ca(g,y=>{C(y)===fe.element&&wu(y)})},da=function(g){let y=[];return ca(g,T=>{y.push(T)},!0),y},Vh=function(g,y){let T=cc();St(da(g),S=>{C(S)===fe.element&&uc(T,S)}),St(y,S=>{C(S)===fe.element&&!qo(T,S)&&wu(S)})},_u=function(g,y){let T=!1;return St(e.removed,S=>{S.element&&(T=T||S.element===g,ua(S.element))}),Vh(g,y),T},Wh=8,Gh=function(g,y){let T=sr,S=null,P=()=>(S||(S=cc(),St(y,F=>{uc(S,F)})),S);for(let F=0;;F++){let W=da(g),he=[g],ot=!1;if(St(W,De=>{C(De)===fe.documentFragment?Uo(he,De):!ot&&!qo(T,De)&&(ot=qo(P(),De))}),!ot)return;if(F>=Wh)throw At("the tree kept changing during in-place sanitization; refusing to return it");St(he,(De,$e)=>{Hh(De,$e>0,g,P())})}},Hh=function(g,y,T,S){let P=fa(g),F;for(;F=P.nextNode();)!qo(S,F)||qo(sr,F)||(y&&We(oe.uponSanitizeShadowNode,F,null),pa(F,T),ma(F,T),$t(F.content)&&Cn(F.content))},Xh=function(g){sr&&uc(sr,g)},yu=function(g,y){return or?g==="patchsrc"?!0:g==="for"&&y!=="label"&&y!=="output":!1},Yh=function(g){or&&ca(g,y=>{let T=C(y);if(T===fe.processingInstruction||T===fe.comment&&xe(sh,y.data)){try{h(y)}catch{}return!1}if(T===fe.element){let S=y,P=ue(O(y));try{S.hasAttribute&&S.hasAttribute("patchsrc")&&S.removeAttribute("patchsrc"),S.hasAttribute&&S.hasAttribute("for")&&yu("for",P)&&S.removeAttribute("for")}catch{}}return!0})},vu=function(g){let y=null,T=null;if(ea)g="<remove></remove>"+g;else{let F=Kf(g,/^[\r\n\t ]+/);T=F&&F[0]}An==="application/xhtml+xml"&&Mr===nt&&(g='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+g+"</body></html>");let S=V?pt(g):g;if(Mr===nt)try{y=new c().parseFromString(S,An)}catch{}if(!y||!y.documentElement){y=nr.createDocument(Mr,"template",null);try{y.documentElement.innerHTML=na?le:S}catch{}}let P=y.body||y.documentElement;return g&&T&&P.insertBefore(t.createTextNode(T),P.childNodes[0]||null),Mr===nt?Sh.call(y,ir?"html":"body")[0]:ir?y.documentElement:P},fa=function(g){let y=k?k(g):g.ownerDocument;return Ko.call(y||g,g,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ii=function(g){return g=Vo(g,Ih," "),g=Vo(g,Ch," "),g=Vo(g,Dh," "),g},ha=function(g){var y;xu(g);let T=(y=g.querySelectorAll)===null||y===void 0?void 0:y.call(g,"template");T&&St(T,S=>{$t(S.content)&&ha(S.content)})},xu=function(g){g.normalize();let y=k?k(g):g.ownerDocument,T=Ko.call(y||g,g,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),S=T.nextNode();for(;S;)S.data=ii(S.data),S=T.nextNode()},si=function(g){let y=D?D(g):null;return typeof y!="string"||ue(y)!=="form"?!1:typeof g.nodeName!="string"||typeof g.textContent!="string"||typeof g.removeChild!="function"||g.attributes!==v(g)||typeof g.removeAttribute!="function"||typeof g.removeAttributeNode!="function"||typeof g.getAttributeNode!="function"||typeof g.setAttribute!="function"||typeof g.namespaceURI!="string"||typeof g.insertBefore!="function"||typeof g.hasChildNodes!="function"||g.nodeType!==E(g)||g.childNodes!==b(g)},$t=function(g){if(!E||typeof g!="object"||g===null)return!1;try{return E(g)===fe.documentFragment}catch{return!1}},In=function(g){if(!E||typeof g!="object"||g===null)return!1;try{return typeof E(g)=="number"}catch{return!1}};function We(I,g,y){I.length!==0&&St(I,T=>{T.call(e,g,y,Lr)})}let Zh=function(g,y){return!!(or&&g.hasChildNodes()&&!In(g.firstElementChild)&&xe(gc,g.textContent)&&xe(gc,g.innerHTML)||or&&Cw[y]&&C(g)===fe.element&&z(g)===nt&&(In(g.firstElementChild)||typeof g.textContent=="string"&&xe(gc,g.textContent))||g.nodeType===fe.processingInstruction||or&&g.nodeType===fe.comment&&xe(sh,g.data))},ai=function(g,y){if(g instanceof RegExp)return xe(g,y);if(g instanceof Function){for(var T=arguments.length,S=new Array(T>2?T-2:0),P=2;P<T;P++)S[P-2]=arguments[P];return!!g(y,...S)}return!1},Kh=function(g,y,T){if(!Sn[y]&&Tu(y)&&ai(rt.tagNameCheck,y))return!1;if(ta&&!ar[y]&&!ar[jr(y)]){let S=w(g),P=b(g);if(P&&S){let F=P.length;for(let W=F-1;W>=0;--W){let he=g===T?f(P[W],!0):P[W];S.insertBefore(he,m(g))}}}return Ot(g),!0},ku=function(g,y,T,S){return g.length===0?y:y===T||y===S?ze(y):y},zr=function(g,y){return g===y||w(g)!==null?!1:(ra&&ua(g),!0)},pa=function(g,y){if(Xh(g),We(oe.beforeSanitizeElements,g,null),zr(g,y))return!0;if(si(g))return Ot(g),!0;let T=ue(O(g));if(ie=ku(oe.uponSanitizeElement,ie,Ys,Qo),We(oe.uponSanitizeElement,g,{tagName:T,allowedTags:ie}),zr(g,y))return!0;if(Zh(g,T))return Ot(g),!0;if(Sn[T]||!(Nt.tagCheck instanceof Function&&Nt.tagCheck(T))&&!ie[T]){let S=Kh(g,T,y);return S===!1&&(We(oe.afterSanitizeElements,g,null),zr(g,y))?!0:S}if(C(g)===fe.element&&!qh(g)||(T==="noscript"||T==="noembed"||T==="noframes")&&xe(Iw,g.innerHTML))return Ot(g),!0;if(mt&&g.nodeType===fe.text){let S=ii(g.textContent);g.textContent!==S&&(Uo(e.removed,{element:g.cloneNode()}),g.textContent=S)}return We(oe.afterSanitizeElements,g,null),zr(g,y)},Eu=function(g,y,T){if(tu[y]||yu(y,g)||ou&&(y==="id"||y==="name")&&(T in t||T in Lh))return!1;let S=se[y]||Nt.attributeCheck instanceof Function&&Nt.attributeCheck(y,g);return Ks&&xe(Nh,y)||ru&&xe(Oh,y)?!0:S?uu[y]||xe(eu,Vo(T,Qc,""))||(y==="src"||y==="xlink:href"||y==="href")&&g!=="script"&&Jf(T,"data:")===0&&lu[g]||nu&&!xe($h,Vo(T,Qc,""))?!0:!T:Tu(g)&&ai(rt.tagNameCheck,g)&&ai(rt.attributeNameCheck,y,g)||y==="is"&&rt.allowCustomizedBuiltInElements&&ai(rt.tagNameCheck,T)},Jh=J({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Tu=function(g){return!Jh[jr(g)]&&xe(Rh,g)},Qh=function(g,y,T,S){if(V&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!T)switch(u.getAttributeType(g,y)){case"TrustedHTML":return pt(S);case"TrustedScriptURL":return Zo(S)}return S},ep=function(g,y,T,S){try{return T?g.setAttributeNS(T,y,S):g.setAttribute(y,S),si(g)?(Ot(g),!1):!0}catch{return Fr(y,g),!1}},Su=function(g,y){return or&&xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,y)?!0:jr(g)==="attributename"&&Kf(y,"href")!==null},ma=function(g,y){if(We(oe.beforeSanitizeAttributes,g,null),zr(g,y))return;let T=g.attributes;if(!T||si(g))return;se=ku(oe.uponSanitizeAttribute,se,Zs,ei);let S={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0},P=T.length,F=ue(g.nodeName);for(;P--;){let W=T[P],he=W.name,ot=W.namespaceURI,De=W.value,$e=ue(he),Ur=De,Re=he==="value"?Ur:uw(Ur),Au=!1;if(S.attrName=$e,S.attrValue=Re,S.keepAttr=!0,S.forceKeepAttr=void 0,We(oe.uponSanitizeAttribute,g,S),Re=S.attrValue,iu&&($e==="id"||$e==="name")&&Jf(Re,su)!==0&&(Fr(he,g,W),Re=su+Re,Au=!0),Su(he,Re)){Fr(he,g,W);continue}if(!S.forceKeepAttr){if(!S.keepAttr){Fr(he,g,W);continue}if(!Js&&xe(ah,Re)){Fr(he,g,W);continue}if(mt&&(Re=ii(Re)),!Eu(F,$e,Re)){Fr(he,g,W);continue}Re=Qh(F,$e,ot,Re),Re!==Ur&&ep(g,he,ot,Re)&&Au&&Zf(e.removed)}}We(oe.afterSanitizeAttributes,g,null),zr(g,y)},Cn=function(g){let y=null,T=fa(g);for(We(oe.beforeSanitizeShadowDOM,g,null);y=T.nextNode();)if(We(oe.uponSanitizeShadowNode,y,null),pa(y,g),ma(y,g),$t(y.content)&&Cn(y.content),C(y)===fe.element){let S=_(y);$t(S)&&(ga(S),Cn(S))}mt&&xu(g),We(oe.afterSanitizeShadowDOM,g,null)},ga=function(g){let y=[{node:g,shadow:null}];for(;y.length>0;){let T=y.pop();if(T.shadow){Cn(T.shadow);continue}let S=T.node,P=C(S)===fe.element,F=b(S);if(F)for(let W=F.length-1;W>=0;--W)y.push({node:F[W],shadow:null});if(P){let W=D?D(S):null;if(typeof W=="string"&&ue(W)==="template"){let he=S.content;$t(he)&&y.push({node:he,shadow:null})}}if(P){let W=_(S);$t(W)&&y.push({node:null,shadow:W},{node:W,shadow:null})}}};return e.sanitize=function(I){let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,T=null,S=null,P=null;if(na=!I,na&&(I="<!-->"),typeof I!="string"&&!In(I)&&(I=pw(I),typeof I!="string"))throw At("dirty is not a string, aborting");if(!e.isSupported)return I;Qs?(ie=Qo,se=ei):aa(g),(oe.uponSanitizeElement.length>0||oe.uponSanitizeAttribute.length>0)&&(ie=ze(ie)),oe.uponSanitizeAttribute.length>0&&(se=ze(se)),e.removed=[];let F=ra&&typeof I!="string"&&In(I),W=[],he=sr;if(F){Yh(I);let $e=O(I);if(typeof $e=="string"){let Ur=ue($e);if(!ie[Ur]||Sn[Ur])throw la(I),At("root node is forbidden and cannot be sanitized in-place")}if(si(I))throw la(I),At("root node is clobbered and cannot be sanitized in-place");W=da(I),sr=cc()}else if(In(I))y=vu("<!---->"),T=y.ownerDocument.importNode(I,!0),T.nodeType===fe.element&&T.nodeName==="BODY"||T.nodeName==="HTML"?y=T:y.appendChild(T),ga(y);else{if(!Pr&&!mt&&!ir&&I.indexOf("<")===-1)return V&&ri?pt(I):I;if(y=vu(I),!y)return Pr?null:ri?le:""}y&&ea&&Ot(y.firstChild);let ot=F?I:y;try{F&&ga(I);let $e=fa(ot);for(;S=$e.nextNode();)pa(S,ot),ma(S,ot),$t(S.content)&&Cn(S.content);F&&Gh(I,W)}catch($e){throw F&&(la(I),_u(I,W)),$e}finally{sr=he}if(F){if(_u(I,W))throw At("a node selected for removal could not be safely returned; refusing to sanitize in place");return mt&&ha(I),I}if(Pr){if(mt&&ha(y),ti)for(P=Jo.call(y.ownerDocument);y.firstChild;)P.appendChild(y.firstChild);else P=y;return(se.shadowroot||se.shadowrootmode)&&(P=Ah.call(r,P,!0)),P}let De=ir?y.outerHTML:y.innerHTML;return ir&&ie["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&xe(Sw,y.ownerDocument.doctype.name)&&(De="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
234
+ `+De),mt&&(De=ii(De)),V&&ri?pt(De):De},e.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};aa(I),Qs=!0,Qo=ie,ei=se},e.clearConfig=function(){Lr=null,Qs=!1,Qo=null,ei=null,V=_e,le=""},e.isValidAttribute=function(I,g,y){Lr||aa({});let T=ue(I),S=ue(g);return typeof y=="string"&&(Su(g,y)||!Js&&xe(ah,y))?!1:Eu(T,S,y)},e.addHook=function(I,g){typeof g=="function"&&Me(oe,I)&&Uo(oe[I],g)},e.removeHook=function(I,g){if(Me(oe,I)){if(g!==void 0){let y=aw(oe[I],g);return y===-1?void 0:cw(oe[I],y,1)[0]}return Zf(oe[I])}},e.removeHooks=function(I){Me(oe,I)&&(oe[I]=[])},e.removeAllHooks=function(){oe=lh()},e}var mh=ph();function Ow(){return import("@gramlot/gramlot/markdown")}var vc=class o extends et{static internalParams=new Set([...et.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,method:t,directory:r,onError:n}){super({cacheTime:-1,onError:n}),this.gramlot=e,this.method=t,this.params={directory:r},this.children=new Set}get closed(){return this.#e}startLoad(e){if(this.loading)return this.loading;let t=new AbortController;return this.#t=t,e({controller:t,method:this.method,params:this.params,ignored:!1})}async loadAsync({controller:e,method:t,params:r}){let{signal:n}=e,i,s=new Promise((a,l)=>{i=()=>l(n.reason),n.addEventListener("abort",i,{once:!0})});try{let a=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:n}),s]);if(n.aborted)throw n.reason;return a}finally{n.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof x))throw new TypeError("Directory navigation must return a Bag");for(let t of this.children)t.abort();this.children.clear();for(let t of e.getNodes())if(t.attr.directory!==void 0){let r=new o({gramlot:this.gramlot,method:this.method,directory:t.attr.directory,onError:this.onError});this.children.add(r),e.setResolver(t.label,r)}return e}abort(){this.#e=!0,this.#t?.abort();for(let e of this.children)e.abort();this.children.clear()}};var xc={};ee(xc,{Labelbox:()=>Ps});function Ps(o){return class extends o{setLabelbox(e){let{box:t,labelBox:r,fieldLabel:n}=e;Object.assign(this,{box:t,labelBox:r,fieldLabel:n}),n.addEventListener("click",()=>{this.control.focus(),this.control.localName==="input"&&["checkbox","radio"].includes(this.control.type)&&this.control.click()})}projectAttributes(e,t){let r=super.projectAttributes(e,t),{lbl:n,lbl_value:i,lbl_values:s}=this.parameters,a=s==null?n??"":ro(gr(s),i,n);return a?this.control.setAttribute("aria-label",a):this.control.removeAttribute("aria-label"),r}}}Ps.labelbox=!0;Ps.parameters={lbl:{dtype:"T",qualification:"intl_str",nullable:!0,binding:"read"},lbl_value:{dtype:"T",nullable:!0,binding:"twoWay"},lbl_values:{dtype:"T",nullable:!0,binding:"read"},lbl_position:{dtype:"T",default:"TL",binding:"read",enum:Fi}};var Cc={};ee(Cc,{FieldState:()=>Ic});var Ac={};ee(Ac,{validateInput:()=>Ls,validationParameters:()=>Sc});var Tc=["select","notnull","empty","case","len","min","max","email","regex","call","remote"],$w=["nodup","exist","gridnodup"],Bs=o=>o==null||o==="",kc=(o,e)=>o instanceof Promise?o.then(e):e(o);function Ls(o,e,t={}){let r={value:o,modified:!1,error:null,warnings:[],issues:[],datachanges:[]},n=Object.fromEntries(Object.entries(e).map(([c,u])=>[c.slice(9),u])),i=c=>Object.hasOwn(e,`validate_${c}`)&&e[`validate_${c}`]!=null;for(let c of $w)if(i(c))throw new Error(`validate_${c} requires the DB/grid integration.`);let s=(c,u,d=!1)=>t.invoke(c,e[c],{...n,value:u,result:r,validations:n,userChange:!0,signal:t.signal},d),a=(c,u)=>{if(u==null||u===!0)return;if(typeof u!="boolean"&&typeof u!="string"&&(typeof u!="object"||Array.isArray(u)))throw new TypeError("A validator returns true, false, null, an error code, or a result object/Bag.");let d=`validate_${c}`,f=u instanceof x?Object.fromEntries(u.getNodes().map(w=>[w.label,w.value])):typeof u=="object"?u:{errorcode:u===!1?"error":u};if(Object.hasOwn(f,"value")&&(r.modified||=!Object.is(r.value,f.value),r.value=f.value),f.data!=null&&(t.checkDataPatch(f.data),r.datachanges.push(f.data)),!f.errorcode)return;let h=e[`${d}_iswarning`]??f.iswarning??!!(e[`${d}_warning`]&&!e[`${d}_error`]),p=e[`${d}_${f.errorcode}`]||e[`${d}_${h?"warning":"error"}`]||f.message||e[`${d}_${h?"error":"warning"}`]||String(f.errorcode),m=zt(p,w=>w?{...n,...f,value:r.value}[w]:r.value);if(m==null)throw new Error("A validation message references a missing value.");let b={rule:c,code:f.errorcode,severity:h?"warning":"error",message:m};r.issues.push(b),h?r.warnings.push(m):(r.error=m,r.required=!!f.required)},l=c=>{if(t.signal?.aborted)throw t.signal.reason;if(r.error||c===Tc.length)return r;let u=Tc[c],d=`validate_${u}`,f=e[d];if(!i(u)||f===!1&&u!=="empty")return l(c+1);let h=m=>{if(!m)return l(c+1);let b;return u==="remote"&&r.value==null?l(c+1):(u==="call"?b=s(d,r.value):u==="remote"?b=t.remote(f,{...Rw(e),value:r.value},t.signal):b=jw(u,f,r.value,t),kc(b,w=>{if(t.signal?.aborted)throw t.signal.reason;let _=()=>(a(u,w),l(c+1));return u==="remote"&&e.validate__onResult?kc(t.invoke("validate__onResult",e.validate__onResult,{result:w,value:r.value,validations:n,signal:t.signal}),_):_()}))},p=e[`${d}_if`];return kc(p==null?!0:typeof p=="boolean"?p:s(`${d}_if`,r.value,!0),h)};return l(0)}function Rw(o){let e=new Set(["if","error","warning","iswarning"]);return Object.fromEntries(Object.entries(o).filter(([t])=>t.startsWith("validate_remote_")&&!e.has(t.slice(16))).map(([t,r])=>[t.slice(16),r]))}function Go(o,e,t={}){return{errorcode:o,message:e,...t}}function jw(o,e,t,r){if(o==="select")return r.selection(t,r.signal);if(o==="notnull")return Bs(t)&&e?Go("notnull","A value is required.",{required:!0}):null;if(o==="empty")return Bs(t)?{value:e}:null;if(o==="len"){if(typeof e!="string"||!/^(?:\d+|\d+:\d*|:\d+)$/.test(e))throw new Error("Invalid validate_len: use a length or min:max.");let[n,i]=e.split(":"),s=Number(n||0),a=i===void 0?s:i===""?1/0:Number(i);if(s>a)throw new Error("Invalid validate_len: minimum exceeds maximum.");if(Bs(t))return;if(typeof t!="string")throw new TypeError("validate_len requires a text value.");return t.length<s||t.length>a?Go(s===a?"wrong length":t.length<s?"too short":"too long",s===a?`Enter exactly ${s} characters.`:a===1/0?`Enter at least ${s} characters.`:s===0?`Enter no more than ${a} characters.`:`Enter between ${s} and ${a} characters.`):void 0}if(!Bs(t)){if(o==="case"){if(typeof t!="string")throw new TypeError("validate_case requires a text value.");switch(e){case"upper":case"u":return{value:t.toUpperCase()};case"lower":case"l":return{value:t.toLowerCase()};case"title":case"t":return{value:t.replace(/\p{L}[\p{L}\p{M}]*/gu,n=>n[0].toUpperCase()+n.slice(1).toLowerCase())};case"capitalize":case"c":return{value:t[0].toUpperCase()+t.slice(1).toLowerCase()};default:throw new Error("Invalid validate_case: use upper, lower, title or capitalize.")}}if(o==="min"||o==="max"){let n;if(r.isDecimal?.(t))n=t.comparedTo(e);else if(t instanceof Date&&e instanceof Date)n=t.getTime()-e.getTime();else if(typeof t=="number"&&Number.isFinite(t)&&typeof e=="number"&&Number.isFinite(e))n=t-e;else throw new TypeError(`validate_${o} requires matching numeric or date/time values.`);return(o==="min"?n<0:n>0)?Go(o,`Value must be ${o==="min"?"at least":"at most"} ${e}.`):void 0}if(o==="email"){if(typeof t!="string")throw new TypeError("validate_email requires a text value.");return/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(t)?null:Go("email","Check email format.",{iswarning:!0})}if(o==="regex"){if(typeof t!="string"||typeof e!="string")throw new TypeError("validate_regex requires text.");let n=e.trim(),i=n.startsWith("!");return new RegExp(i?n.slice(1):n,"u").test(t)!==i?null:Go("regex","The value does not match the required pattern.")}}}var Ho={dtype:"T",nullable:!0,binding:"read"},Ms={dtype:"B",nullable:!0,binding:"read"},Ec={dtype:["T","L","N","R","B","D","H","DH","DHZ"],nullable:!0,binding:"read"},Sc={validate_select:Ms,validate_notnull:{...Ms,default:!1},validate_empty:Ec,validate_case:{...Ho,enum:["upper","lower","title","capitalize","u","l","t","c"]},validate_len:Ho,validate_min:Ec,validate_max:Ec,validate_email:Ms,validate_regex:Ho,validate_call:{dtype:"T",nullable:!0},validate_remote:Ho,validate_onAccept:{dtype:"T",nullable:!0},validate_onReject:{dtype:"T",nullable:!0},validate__onResult:{dtype:"T",nullable:!0},validate_timeout:{dtype:"L",nullable:!0,binding:"read"},...Object.fromEntries(Tc.flatMap(o=>[[`validate_${o}_if`,{dtype:["T","B"],nullable:!0}],[`validate_${o}_iswarning`,Ms],...["error","warning"].map(e=>[`validate_${o}_${e}`,{...Ho,qualification:"intl_str"}])]))};var Pw=1800,gh=200;function Ic(o){return class extends o{get supportsFormValidation(){return!0}static validationParameters(e){let t={...zi(this.gramlotComponent,e),...e};return this.constrained&&t.validate_select==null&&(t.validate_select=!0),t}static get validationExecutor(){return Ls}get validationExecutor(){return this.constructor.validationExecutor}connectedCallback(){super.connectedCallback(),this.pageContext?.form&&this.pageContext.formValidate()}#e=!1;#t;#r;#n;#o=new kr;#i;#s={};validationResult=null;constructor(){super(),this.message=this.ownerDocument.createElement("small"),this.message.id="field-message",this.message.hidden=!0,this.message.setAttribute("aria-live","polite"),this.message.setAttribute("popover","manual"),this.message.setAttribute("role","tooltip");let e=this.ownerDocument.createElement("style");e.textContent=`#control[aria-invalid="true"]{background:var(--gramlot-error-background,#fff1f0)}
235
235
  input#control[aria-invalid="true"],textarea#control[aria-invalid="true"]{color:var(--gramlot-error,#8c1d18)}
236
236
  #field-message{position:fixed;inset:auto;margin:0;padding:.4em .65em;border:1px solid var(--gramlot-error,#b3261e);border-radius:var(--gramlot-radius-sm,4px);
237
237
  color:var(--gramlot-error,#8c1d18);background:var(--gramlot-error-background,#fff1f0);font:inherit;font-size:.85em;box-shadow:var(--gramlot-shadow,0 2px 8px #0003);
@@ -239,10 +239,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
239
239
  #field-message[data-severity="warning"]{color:var(--gramlot-warning,#805600);border-color:var(--gramlot-warning,#805600);background:var(--gramlot-warning-background,#fff8df)}
240
240
  #field-message[data-fading]{opacity:0}
241
241
  @media(prefers-reduced-motion:reduce){#field-message{transition:none}}`,this.shadowRoot.append(e),this.control.setAttribute("aria-describedby",this.message.id),this.controlBox.append(this.message),this.control.addEventListener("input",()=>this.cancelValidation()),this.control.addEventListener("compositionstart",()=>this.cancelValidation()),this.control.addEventListener("focusin",()=>this.#l()),this.control.addEventListener("mouseenter",()=>this.#l()),this.control.addEventListener("keydown",t=>{t.key==="Escape"&&(this.cancelValidation(),this.#a())})}#a(){this.ownerDocument.defaultView.clearTimeout(this.#r),this.#n?.abort(),this.#n=null,this.message.hidden||this.message.hidePopover(),this.message.hidden=!0,this.message.removeAttribute("data-fading")}#l(){if(!this.message.textContent||!this.isConnected)return;this.#a();let e=this.ownerDocument.defaultView;this.message.hidden=!1,this.message.showPopover(),wr(this.message,this.control),this.#r=e.setTimeout(()=>{this.message.hidden||(this.message.setAttribute("data-fading",""),this.#r=e.setTimeout(()=>this.#a(),gh))},Pw),this.#n=new e.AbortController;let t={capture:!0,signal:this.#n.signal};e.addEventListener("scroll",()=>this.#a(),t),e.addEventListener("resize",()=>this.#a(),t)}releaseControl(){this.#o.cancel(),this.#a(),super.releaseControl()}disconnectedCallback(){this.releaseControl()}setFieldState({invalid:e=!1,pending:t=!1}={}){this.control.setAttribute("aria-invalid",String(e)),this.control.setAttribute("aria-busy",String(t))}error(e){this.#e=!1,["input","textarea"].includes(this.control.localName)&&this.control.setCustomValidity(e),this.control.setAttribute("aria-invalid",String(!!e)),this.message.textContent=e,e?this.#l():this.#a()}restoreFormValue(e){this.error(""),this.#e=!1,super.restoreFormValue(e)}cancelValidation(){this.pageContext?.form&&this.pageContext.formCancelValidation(),this.#o.cancel(),this.#i=null,this.control.setAttribute("aria-busy","false")}presentValidation(e){this.validationResult=e,this.control.setAttribute("aria-busy","false"),this.error(e.error||""),this.message.dataset.severity=e.error?"error":"warning",this.#e=!!e.error,!e.error&&e.warnings.length&&(this.message.textContent=e.warnings.join(`
242
- `),this.#l())}validateCandidate(e,t){if(this.pageContext.form){let r=this.validationSelection();return t(e),this.pageContext.formValidateCandidate(e,r)}return this.cancelValidation(),this.#i=this.pageContext.validationCurrent(),this.#o.start(e,this.#s,{...this.pageContext,selection:r=>this.validateSelection(r)},Ms,r=>{if(this.#i=null,r.ok)try{t(r.value)}catch(n){r.ok=!1,r.result.error=n.message}this.presentValidation(r.result),r.ok||this.finishValidation(r)},()=>this.control.setAttribute("aria-busy","true"))}finishValidation(e){e.result&&this.pageContext.finishValidation(e)}shouldProjectControlValue(e){!this.pageContext?.form&&this.#i&&!this.#i()&&this.cancelValidation();let t=this.sameControlValue(e,this.#t);return t&&this.#e?!1:(!t&&!this.pageContext?.form&&this.cancelValidation(),this.#t=e,!t&&this.#e&&this.error(""),!0)}projectAttributes(e,t){let r=super.projectAttributes(e,t),n=Object.fromEntries(Object.entries(e).filter(([l])=>l.startsWith("validate_"))),i=new Set([...Object.keys(n),...Object.keys(this.#s)]);!this.pageContext?.form&&([...i].some(l=>!Object.is(n[l],this.#s[l]))||e.disabled||e.readonly)&&this.cancelValidation();let s=[...i].some(l=>!Object.is(n[l],this.#s[l]));this.#s=n,s&&this.pageContext?.form&&this.pageContext.formValidate();for(let l of Object.keys(n))delete r[l];let a=!!this.parameters.validate_notnull;return this.control.setAttribute("aria-required",String(a)),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.required=a),r}}}Ac.parameters=Tc;var En=new TextEncoder,bh=o=>`export {default} from "./collection.js";
242
+ `),this.#l())}validateCandidate(e,t){if(this.pageContext.form){let r=this.validationSelection();return t(e),this.pageContext.formValidateCandidate(e,r)}return this.cancelValidation(),this.#i=this.pageContext.validationCurrent(),this.#o.start(e,this.#s,{...this.pageContext,selection:r=>this.validateSelection(r)},Ls,r=>{if(this.#i=null,r.ok)try{t(r.value)}catch(n){r.ok=!1,r.result.error=n.message}this.presentValidation(r.result),r.ok||this.finishValidation(r)},()=>this.control.setAttribute("aria-busy","true"))}finishValidation(e){e.result&&this.pageContext.finishValidation(e)}shouldProjectControlValue(e){!this.pageContext?.form&&this.#i&&!this.#i()&&this.cancelValidation();let t=this.sameControlValue(e,this.#t);return t&&this.#e?!1:(!t&&!this.pageContext?.form&&this.cancelValidation(),this.#t=e,!t&&this.#e&&this.error(""),!0)}projectAttributes(e,t){let r=super.projectAttributes(e,t),n=Object.fromEntries(Object.entries(e).filter(([l])=>l.startsWith("validate_"))),i=new Set([...Object.keys(n),...Object.keys(this.#s)]);!this.pageContext?.form&&([...i].some(l=>!Object.is(n[l],this.#s[l]))||e.disabled||e.readonly)&&this.cancelValidation();let s=[...i].some(l=>!Object.is(n[l],this.#s[l]));this.#s=n,s&&this.pageContext?.form&&this.pageContext.formValidate();for(let l of Object.keys(n))delete r[l];let a=!!this.parameters.validate_notnull;return this.control.setAttribute("aria-required",String(a)),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.required=a),r}}}Ic.parameters=Sc;var En=new TextEncoder,bh=o=>`export {default} from "./collection.js";
243
243
  export * from "./collection.js";
244
244
  export const buildId = "${o}";
245
- `,Cc=o=>typeof o=="string"&&o.length>0&&!/[\\\x00-\x1f:?#%]/.test(o)&&!o.split("/").some(e=>!e||e==="."||e==="..");function wh(o,e){if(!o||typeof o.name!="string"||!o.name||!["grammar","commands","module"].every(t=>Cc(o[t]))||!Array.isArray(o.css)||!o.css.every(Cc)||!Array.isArray(o.dependencies)||!o.dependencies.every(t=>typeof t=="string"&&t.length>0)||!Array.isArray(o.files)||!o.files.every(Cc)||new Set(o.files).size!==o.files.length||!(e instanceof Map)||e.size!==o.files.length||o.files.some(t=>!(e.get(t)instanceof Uint8Array))||[o.grammar,o.commands,o.module,...o.css].some(t=>!e.has(t)))throw new TypeError("Invalid collection artifact metadata or file inventory")}async function _h(o,e){wh(o,e);let t=[En.encode("gramlot-build-v1\0")],r=(l,c)=>{let u=typeof c=="string"?En.encode(c):c;t.push(En.encode(`${l}\0${u.length}\0`),u)};for(let l of["name","grammar","commands","module"])r(l,o[l]);for(let l of o.css)r("css",l);for(let l of o.dependencies)r("dependency",l);let n=(l,c)=>{let u=En.encode(l),d=En.encode(c);for(let f=0;f<Math.min(u.length,d.length);f++)if(u[f]!==d[f])return u[f]-d[f];return u.length-d.length};for(let l of[...o.files].sort(n))r("path",l),r("content",l===o.module?bh("__GRAMLOT_BUILD_ID__"):e.get(l));let i=new Uint8Array(t.reduce((l,c)=>l+c.length,0)),s=0;for(let l of t)i.set(l,s),s+=l.length;let a=await crypto.subtle.digest("SHA-256",i);return"sha256:"+[...new Uint8Array(a)].map(l=>l.toString(16).padStart(2,"0")).join("")}async function Bw(o,e){if(wh(o,e),typeof o.buildId!="string"||!/^sha256:[a-f0-9]{64}$/.test(o.buildId))throw new TypeError("Invalid collection buildId");let t=En.encode(bh(o.buildId)),r=e.get(o.module);if(r.length!==t.length||r.some((n,i)=>n!==t[i]))throw new Error("Invalid collection wrapper");if(await _h(o,e)!==o.buildId)throw new Error(`Collection fingerprint mismatch: ${o.name}`)}var Nc={};ee(Nc,{captureVideoFrame:()=>Dc});function Dc(o,e){if(!e.videoWidth||!e.videoHeight)throw new Error("Video image is not ready");let t=o.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;let r=t.getContext("2d");if(!r)throw new Error("Video image is unavailable");return r.drawImage(e,0,0),t}function It(o,e,t){return Object.assign(new Error(e,t?{cause:t}:void 0),{code:o})}function Ls(o){return o.name==="NotAllowedError"||o.name==="SecurityError"?It("PERMISSION_DENIED","Camera permission was denied",o):o.name==="NotFoundError"||o.name==="OverconstrainedError"?It("UNAVAILABLE","Camera is unavailable",o):It("FAILED",o.message||"Camera failed",o)}var Fs=()=>It("CANCELLED","Photo capture cancelled"),Oc=class{constructor({document:e}){if(!e?.defaultView)throw new TypeError("BrowserCameraProvider requires a document");this.document=e,this.capabilities=Object.freeze(e.defaultView.navigator.mediaDevices?.getUserMedia?["camera"]:[])}takePhoto(e){if(e.aborted)return Promise.reject(Fs());if(!this.capabilities.includes("camera"))return Promise.reject(It("UNAVAILABLE","Camera is unavailable"));let t=this.document,r=t.defaultView;return new Promise((n,i)=>{let s=!1,a=null,l=new r.AbortController,c={signal:l.signal},u=t.createElement("dialog");u.className="gramlot-camera-dialog",u.setAttribute("aria-label","Take photo");let d=t.createElement("style");d.textContent=`
245
+ `,Dc=o=>typeof o=="string"&&o.length>0&&!/[\\\x00-\x1f:?#%]/.test(o)&&!o.split("/").some(e=>!e||e==="."||e==="..");function wh(o,e){if(!o||typeof o.name!="string"||!o.name||!["grammar","commands","module"].every(t=>Dc(o[t]))||!Array.isArray(o.css)||!o.css.every(Dc)||!Array.isArray(o.dependencies)||!o.dependencies.every(t=>typeof t=="string"&&t.length>0)||!Array.isArray(o.files)||!o.files.every(Dc)||new Set(o.files).size!==o.files.length||!(e instanceof Map)||e.size!==o.files.length||o.files.some(t=>!(e.get(t)instanceof Uint8Array))||[o.grammar,o.commands,o.module,...o.css].some(t=>!e.has(t)))throw new TypeError("Invalid collection artifact metadata or file inventory")}async function _h(o,e){wh(o,e);let t=[En.encode("gramlot-build-v1\0")],r=(l,c)=>{let u=typeof c=="string"?En.encode(c):c;t.push(En.encode(`${l}\0${u.length}\0`),u)};for(let l of["name","grammar","commands","module"])r(l,o[l]);for(let l of o.css)r("css",l);for(let l of o.dependencies)r("dependency",l);let n=(l,c)=>{let u=En.encode(l),d=En.encode(c);for(let f=0;f<Math.min(u.length,d.length);f++)if(u[f]!==d[f])return u[f]-d[f];return u.length-d.length};for(let l of[...o.files].sort(n))r("path",l),r("content",l===o.module?bh("__GRAMLOT_BUILD_ID__"):e.get(l));let i=new Uint8Array(t.reduce((l,c)=>l+c.length,0)),s=0;for(let l of t)i.set(l,s),s+=l.length;let a=await crypto.subtle.digest("SHA-256",i);return"sha256:"+[...new Uint8Array(a)].map(l=>l.toString(16).padStart(2,"0")).join("")}async function Bw(o,e){if(wh(o,e),typeof o.buildId!="string"||!/^sha256:[a-f0-9]{64}$/.test(o.buildId))throw new TypeError("Invalid collection buildId");let t=En.encode(bh(o.buildId)),r=e.get(o.module);if(r.length!==t.length||r.some((n,i)=>n!==t[i]))throw new Error("Invalid collection wrapper");if(await _h(o,e)!==o.buildId)throw new Error(`Collection fingerprint mismatch: ${o.name}`)}var Oc={};ee(Oc,{captureVideoFrame:()=>Nc});function Nc(o,e){if(!e.videoWidth||!e.videoHeight)throw new Error("Video image is not ready");let t=o.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;let r=t.getContext("2d");if(!r)throw new Error("Video image is unavailable");return r.drawImage(e,0,0),t}function It(o,e,t){return Object.assign(new Error(e,t?{cause:t}:void 0),{code:o})}function Fs(o){return o.name==="NotAllowedError"||o.name==="SecurityError"?It("PERMISSION_DENIED","Camera permission was denied",o):o.name==="NotFoundError"||o.name==="OverconstrainedError"?It("UNAVAILABLE","Camera is unavailable",o):It("FAILED",o.message||"Camera failed",o)}var zs=()=>It("CANCELLED","Photo capture cancelled"),$c=class{constructor({document:e}){if(!e?.defaultView)throw new TypeError("BrowserCameraProvider requires a document");this.document=e,this.capabilities=Object.freeze(e.defaultView.navigator.mediaDevices?.getUserMedia?["camera"]:[])}takePhoto(e){if(e.aborted)return Promise.reject(zs());if(!this.capabilities.includes("camera"))return Promise.reject(It("UNAVAILABLE","Camera is unavailable"));let t=this.document,r=t.defaultView;return new Promise((n,i)=>{let s=!1,a=null,l=new r.AbortController,c={signal:l.signal},u=t.createElement("dialog");u.className="gramlot-camera-dialog",u.setAttribute("aria-label","Take photo");let d=t.createElement("style");d.textContent=`
246
246
  .gramlot-camera-dialog{max-width:calc(100vw - 2rem);max-height:calc(100vh - 2rem);border:1px solid var(--gramlot-border,#d5dde6);
247
247
  border-radius:14px;padding:20px;color:var(--gramlot-ink,#202a35);background:var(--gramlot-surface,#fff);
248
248
  box-shadow:0 24px 64px #14243a42;font:14px/1.4 system-ui,sans-serif}
@@ -252,8 +252,8 @@ export const buildId = "${o}";
252
252
  .gramlot-camera-dialog .actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}
253
253
  .gramlot-camera-dialog button{font:inherit;cursor:pointer;padding:.4em .8em;border:1px solid var(--gramlot-border-control,#aab4c0);border-radius:6px;background:var(--gramlot-button-background,#fff);color:var(--gramlot-button-color,#202a35)}
254
254
  .gramlot-camera-dialog button.primary{background:var(--gramlot-action,#3766b5);color:#fff}.gramlot-camera-dialog button:disabled{opacity:.55}
255
- `;let f=t.createElement("h2");f.textContent="Take photo";let h=t.createElement("video");h.muted=!0,h.autoplay=!0,h.playsInline=!0;let p=t.createElement("p");p.setAttribute("role","status"),p.textContent="Waiting for camera\u2026";let m=t.createElement("div");m.className="actions";let b=t.createElement("button");b.type="button",b.textContent="Cancel";let w=t.createElement("button");w.type="button",w.textContent="Capture",w.className="primary",w.disabled=!0,m.append(b,w),u.append(d,f,h,p,m);let _=k=>{for(let C of k.getTracks())C.stop()},v=(k,C)=>{s||(s=!0,l.abort(),e.removeEventListener("abort",E),a&&(_(a),a=null),h.srcObject=null,u.open&&u.close(),u.remove(),k?i(k):n(C))},E=()=>v(Fs());e.addEventListener("abort",E,{once:!0}),b.addEventListener("click",E,c),u.addEventListener("cancel",k=>{k.preventDefault(),E()},c),u.addEventListener("close",()=>{s||E()},c);let D=()=>{!s&&h.videoWidth>0&&h.videoHeight>0&&(w.disabled=!1,p.textContent="")};h.addEventListener("loadedmetadata",D,c),w.addEventListener("click",()=>{try{let C=Dc(t,h).toDataURL("image/jpeg",.9);if(!C.startsWith("data:image/jpeg;"))throw new Error("Camera image encoding failed");v(null,{url:C,format:"jpeg"})}catch(k){v(Ls(k))}},c),t.body.append(u);try{u.showModal()}catch(k){v(Ls(k));return}if(e.aborted){E();return}Promise.resolve().then(()=>s?null:r.navigator.mediaDevices.getUserMedia({video:!0,audio:!1})).then(async k=>{if(k){if(s){_(k);return}a=k,h.srcObject=a;for(let C of a.getTracks())C.addEventListener("ended",()=>v(It("UNAVAILABLE","Camera stopped")),c);try{await h.play(),D()}catch(C){v(Ls(C))}}},k=>v(Ls(k)))})}choosePhoto(e){if(e.aborted)return Promise.reject(Fs());let t=this.document,r=t.defaultView;return new Promise((n,i)=>{let s=!1,a=null,l=new r.AbortController,c={signal:l.signal},u=t.createElement("input");u.type="file",u.accept="image/png,image/jpeg,image/webp",u.hidden=!0;let d=(h,p)=>{s||(s=!0,l.abort(),e.removeEventListener("abort",f),a&&a.readyState===1&&a.abort(),u.remove(),h?i(h):n(p))},f=()=>d(Fs());if(e.addEventListener("abort",f,{once:!0}),u.addEventListener("cancel",f,c),u.addEventListener("change",()=>{let h=u.files[0];if(!h||!["image/png","image/jpeg","image/webp"].includes(h.type)){d(It("FAILED","Select a PNG, JPEG or WebP image"));return}a=new r.FileReader,a.onload=()=>d(null,{url:a.result,format:h.type.slice(6)}),a.onerror=()=>d(It("FAILED","Photo could not be read",a.error)),a.readAsDataURL(h)},c),t.body.append(u),e.aborted){f();return}try{u.click()}catch(h){d(It("FAILED","Photo selection failed",h))}})}};var $c=new WeakMap,Mw=/^m_[a-f0-9]+$/;function jc(o,e,{messages:t}){if(!(t instanceof x)||t instanceof N)throw new TypeError("Chat messages require a Data Bag");let r=e.parentNode,n=o.dom.getDomNode(r);if(!n)return;let i=$c.get(r);i||(i={rows:new Map,active:!0},$c.set(r,i),o.src.renderer.onDispose(r,()=>{i.active=!1;for(let u of i.rows.keys())r.getRelativeData(".messageData").popNode(u);i.rows.clear(),$c.delete(r)}));let s=t.getNodes();for(let u of s)if(!Mw.test(u.label)||!["user","assistant"].includes(u.attr.role)||typeof u.attr.author!="string"||!(typeof u.staticValue=="string"||u.staticValue instanceof de))throw new TypeError("Chat messages require a stable label, role, author and string or Gramlot Source");let a=n.scrollHeight-n.clientHeight-n.scrollTop<48,l=[];for(let u of s){let d=i.rows.get(u.label);if(d&&d.value===u.staticValue&&d.role===u.attr.role&&d.author===u.attr.author)continue;let f=new me,h=f.root.article({node_label:u.label,datapath:r.absDatapath(".messageData."+u.label),"data-role":u.attr.role,"aria-label":u.attr.author}),p=Z(h.div());typeof u.staticValue=="string"?f.wrapSource(p).div("=="+JSON.stringify(u.staticValue),{white_space:"pre-wrap"}):p.setValue(o.src.prepareSource(u.staticValue.toTytx()));let m=o.src.prepareSource(f.source);o.src.renderer.validateCandidate(m),l.push({message:u,old:d,child:m.getNode(u.label)})}let c=new Set(s.map(u=>u.label));for(let[u]of i.rows)c.has(u)||(r.value.popNode(u),r.getRelativeData(".messageData").popNode(u),i.rows.delete(u));for(let{message:u,old:d,child:f}of l)d&&r.value.popNode(u.label),d||r.setRelativeData(".messageData."+u.label,new x),o.src.builder.setChild(r.value,f.nodeTag,f.value,{...f.attr,node_label:u.label}),i.rows.set(u.label,{value:u.staticValue,role:u.attr.role,author:u.attr.author});a&&queueMicrotask(()=>{i.active&&(n.scrollTop=n.scrollHeight)})}function vh(o,e,t=null){if(o.getRelativeData(".pending")||o.getRelativeData(".picking")||!o.getRelativeData(".conversation.ready"))return;let r=G();o.SET(".requestId",r),o.SET(".pending",!0),o.SET(".error",""),o.SET(".conversation.request",new x({id:r,action:e,text:t,attachments:j(R(o.getRelativeData(".attachments")))}))}function Pc(o,e){let t=e.getRelativeData(".draft");typeof t!="string"||!t.trim()&&!e.getRelativeData(".attachments").length||vh(e,"send",t)}function Bc(o,e){vh(e,"reset")}function Mc(o,e,{response:t}){if(t!==null){if(!(t instanceof x))throw new TypeError("Chat response requires a Data Bag");t.getItem("id")===e.getRelativeData(".requestId")&&(t.getItem("accepted")&&t.getItem("submitted")===e.getRelativeData(".draft")&&e.SET(".draft",""),t.getItem("accepted")&&t.getItem("submitted")!==null&&e.SET(".attachments",new x),e.SET(".pending",!1),e.SET(".error",t.getItem("error")))}}var Rc=new WeakMap;function Lc(o,e){let t=e.parentNode,r=Rc.get(t);if(!r){let n=o.dom.getDomNode(t);if(!n)return;let i=n.closest("[data-chat-composer]"),s=n.querySelector("textarea"),a=i.querySelector("[data-chat-top]"),l=i.querySelector("[data-chat-toolbar]"),c=n.ownerDocument.defaultView,u=0,d=!0,f=()=>{if(u=0,!d)return;s.style.height="0px";let m=c.getComputedStyle(s),b=parseFloat(m.borderTopWidth)+parseFloat(m.borderBottomWidth),w=Math.max(44,Math.min(180,s.scrollHeight+b));s.style.height=w+"px",s.style.overflowY=s.scrollHeight+b>w?"auto":"hidden";let _=Math.ceil(n.getBoundingClientRect().height+a.getBoundingClientRect().height+l.getBoundingClientRect().height+2);e.getRelativeData(".composerHeight")!==_&&e.SET(".composerHeight",_)},h=()=>{d&&!u&&(u=c.requestAnimationFrame(f))},p=new c.ResizeObserver(h);for(let m of[n,a,l])p.observe(m);o.src.renderer.onDispose(t,()=>{d=!1,p.disconnect(),u&&c.cancelAnimationFrame(u),Rc.delete(t)}),r={schedule:h},Rc.set(t,r)}r.schedule()}var Lw=["txt","md","csv","json","py","js","ts","jsx","tsx","html","css","sql","yaml","yml","xml","sh","toml","log"],yh={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",pdf:"application/pdf",...Object.fromEntries(Lw.map(o=>[o,"text/plain"]))};function Fw(o,e){return new Promise((t,r)=>{let n=new e.FileReader;n.onload=()=>t(n.result.slice(n.result.indexOf(",")+1)),n.onerror=()=>r(new Error("Could not read the selected file.")),n.readAsDataURL(o)})}async function Fc(o,e){if(e.getRelativeData(".pending")||e.getRelativeData(".picking"))return;let t=o.dom.getDomNode(e.parentNode).ownerDocument,r=t.createElement("input");r.type="file",r.multiple=!0,r.accept=Object.keys(yh).map(a=>"."+a).join(","),r.style.display="none",t.body.append(r);let n=!0,i,s=o.src.renderer.onDispose(e.parentNode,()=>{n=!1,r.remove(),i([])});e.SET(".picking",!0),e.SET(".error","");try{let a=await new Promise(u=>{i=u,r.addEventListener("cancel",()=>u([]),{once:!0}),r.addEventListener("change",()=>u([...r.files]),{once:!0}),r.click()});if(!n||!a.length)return;let l=j(R(e.getRelativeData(".attachments")));if(l.length+a.length>5)throw new Error("Choose at most 5 files.");let c=l.getNodes().reduce((u,d)=>u+d.staticValue.getItem("size"),0);for(let u of a){let d=yh[u.name.split(".").pop().toLowerCase()];if(!d)throw new Error("Supported files: PNG, JPEG, WebP, PDF and UTF-8 text/code.");let f=d==="text/plain"?1024*1024:2*1024*1024;if(c+=u.size,!u.size||u.size>f||c>4*1024*1024)throw new Error("Limits: 2 MiB per file, 1 MiB for text, 4 MiB total.");let h=await Fw(u,t.defaultView);if(d==="text/plain"){let p=Uint8Array.from(atob(h),m=>m.charCodeAt(0));if(new TextDecoder("utf-8",{fatal:!0}).decode(p),p.includes(0))throw new Error("The selected file is not UTF-8 text.")}l.setItem("a_"+G(),new x({name:u.name,mediaType:d,size:u.size,data:h}))}n&&e.SET(".attachments",l)}catch(a){n&&e.SET(".error",a.message)}finally{s(),r.remove(),n&&e.SET(".picking",!1)}}function zc(o,e){e.getRelativeData(".pending")||e.getRelativeData(".attachments").popNode(e.getAttr("attachment_id"))}function qc(o,e,{attachments:t}){let r=e.parentNode;for(let s of[...r.value.getNodes()])s.label.startsWith("a_")&&r.value.popNode(s.label);let n=new me;for(let s of t.getNodes()){let a=s.staticValue,l=n.root.div({node_label:s.label,display:"flex",align_items:"center",gap:"6px",padding:"4px 8px",border:"1px solid var(--gramlot-border-control,#aaa)",border_radius:"10px",flex_shrink:0});a.getItem("mediaType").startsWith("image/")&&l.img({src:"data:"+a.getItem("mediaType")+";base64,"+a.getItem("data"),alt:"Attachment preview",width:"36px",height:"36px",object_fit:"cover",border_radius:"6px"}),l.span("=="+JSON.stringify(a.getItem("name")),{font_size:"12px",max_width:"180px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),l.button({icon:"\xD7","aria-label":"Remove "+a.getItem("name"),disabled:"^.pending",class:"button--quiet"}).dataController({func:"chatRemoveAttachment",attachment_id:s.label})}let i=o.src.prepareSource(n.source);o.src.renderer.validateCandidate(i);for(let s of i.getNodes())o.src.builder.setChild(r.value,s.nodeTag,s.value,{...s.attr,node_label:s.label})}var zs=class{constructor({app:e,editor:t,design:r}){this.renderer=e.src.renderer,this.design=r;let n=this.renderer.records.get(r).presentation;this.frame=n.ownerDocument.createElement("iframe"),this.frame.title="Page canvas",this.frame.className="visual-editor-canvas-frame",this.frame.style.cssText="display:block;width:100%;height:100%;min-height:240px;border:0;background:white",n.before(this.frame);let i=this.frame.contentDocument;e.registerDocument(i);let s=i.createElement("style");s.textContent="html,body{margin:0;min-height:100%;} .visual-editor-canvas{min-height:100vh;}",this.styles=i.createElement("style");let a=i.createElement("style");a.textContent=".gramlot-source-selected{outline:2px solid #8ab4f8!important;outline-offset:-2px!important;}",i.head.append(s,this.styles,a),this.body=i.body,this.renderer.mountDestination(r,this.body),this.release=this.renderer.onDispose(t,()=>this.dispose())}setCss(e){this.styles.textContent=e.join(`
256
- `)}dispose(){this.release?.(),this.release=null,this.frame.remove()}};var xh=["string","number","integer","boolean","date","time","datetime","null"];function Uc(o){if(o===null)return"null";if(["string","boolean"].includes(typeof o))return typeof o;if(typeof o=="number"&&Number.isFinite(o))return Number.isSafeInteger(o)?"integer":"number";if(o instanceof Date&&Number.isFinite(o.getTime())){let e=o.toISOString();return e.slice(0,10)==="1970-01-01"?"time":e.endsWith("T00:00:00.000Z")?"date":"datetime"}return null}function qs(o,e){if(e==="null")return"";if(o instanceof Date){let t=o.toISOString();return e==="date"?t.slice(0,10):e==="time"?t.slice(11,23):t}return String(o)}function Vc(o,e){if(o==="string")return e;if(o==="null")return null;if(o==="boolean"&&["true","false"].includes(e))return e==="true";if((o==="number"||o==="integer")&&/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e.trim())){let t=Number(e);if(Number.isFinite(t)&&(o!=="integer"||Number.isSafeInteger(t)))return t}if(["date","time","datetime"].includes(o)&&(o==="date"?/^\d{4}-\d{2}-\d{2}$/:o==="time"?/^\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?Z$/).test(e)){let r=o==="date"?`${e}T00:00:00Z`:o==="time"?`1970-01-01T${e}Z`:e,n=new Date(r);if(Number.isFinite(n.getTime())){let i=n.toISOString(),s=r.replace(/Z$/,"").split(/[T:.]/),a=i.replace(/Z$/,"").split(/[T:.]/);if(s.every((l,c)=>c===4?Number(l.padEnd(3,"0"))===Number(a[c]):l===a[c]))return n}}throw new Error(`Invalid ${o} value: ${e||"(empty)"}`)}var Ho=class{#e;#t;#r;#n;#o;#i=null;#s=null;#a=null;#l=!1;constructor({renderer:e,root:t,onSelect:r,canvas:n=e.records.get(t.parentNode)?.presentation}){if(!t?.parentNode||typeof r!="function")throw new TypeError("SourcePicker requires a mounted Source root and onSelect");if(!n||n.nodeType!==1)throw new TypeError("SourcePicker requires a mounted preview");this.#e=e,this.#t=t,this.#r=n,this.#n=r,n.addEventListener("pointerdown",this,!0),n.addEventListener("click",this,!0),this.#o=new n.ownerDocument.defaultView.MutationObserver(()=>this.#c()),this.#o.observe(n,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["class"]}),this.#a=e.onDispose(t.parentNode,()=>this.dispose())}handleEvent(e){if(this.#l)return;let t=this.#t.fullpath+".",r=e.composedPath().map(i=>this.#e.elements.get(i)).find(i=>i?.node.fullpath.startsWith(t));if(!r)return;e.composedPath().some(i=>i.nodeType===1&&(i.matches("input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]), textarea, select, label")||i.isContentEditable))||(e.preventDefault(),e.stopImmediatePropagation()),this.#n(r.node)}select(e){if(!this.#l){if(e===null)this.#i=null;else{let t=this.#t.fullpath+".";if(!e.fullpath.startsWith(t))throw new TypeError("Selected node must be inside the preview Source root");this.#i=e.fullpath.slice(t.length)}this.#c()}}#c(){if(this.#l)return;let e=this.#i?this.#t.staticValue.getNode(this.#i):null,t=e?this.#e.records.get(e)?.presentation:null,r=t?.nodeType===1?t:null;this.#s!==r&&(this.#s?.classList.remove("gramlot-source-selected"),this.#s=r),r&&!r.classList.contains("gramlot-source-selected")&&r.classList.add("gramlot-source-selected")}dispose(){this.#l||(this.#l=!0,this.#o.disconnect(),this.#r.removeEventListener("pointerdown",this,!0),this.#r.removeEventListener("click",this,!0),this.#s?.classList.remove("gramlot-source-selected"),this.#a?.(),this.#a=null,this.#s=null)}};var Wc={base:"",compact:`/* gramlot-compact: professional density profile; load after Base. */
255
+ `;let f=t.createElement("h2");f.textContent="Take photo";let h=t.createElement("video");h.muted=!0,h.autoplay=!0,h.playsInline=!0;let p=t.createElement("p");p.setAttribute("role","status"),p.textContent="Waiting for camera\u2026";let m=t.createElement("div");m.className="actions";let b=t.createElement("button");b.type="button",b.textContent="Cancel";let w=t.createElement("button");w.type="button",w.textContent="Capture",w.className="primary",w.disabled=!0,m.append(b,w),u.append(d,f,h,p,m);let _=k=>{for(let C of k.getTracks())C.stop()},v=(k,C)=>{s||(s=!0,l.abort(),e.removeEventListener("abort",E),a&&(_(a),a=null),h.srcObject=null,u.open&&u.close(),u.remove(),k?i(k):n(C))},E=()=>v(zs());e.addEventListener("abort",E,{once:!0}),b.addEventListener("click",E,c),u.addEventListener("cancel",k=>{k.preventDefault(),E()},c),u.addEventListener("close",()=>{s||E()},c);let D=()=>{!s&&h.videoWidth>0&&h.videoHeight>0&&(w.disabled=!1,p.textContent="")};h.addEventListener("loadedmetadata",D,c),w.addEventListener("click",()=>{try{let C=Nc(t,h).toDataURL("image/jpeg",.9);if(!C.startsWith("data:image/jpeg;"))throw new Error("Camera image encoding failed");v(null,{url:C,format:"jpeg"})}catch(k){v(Fs(k))}},c),t.body.append(u);try{u.showModal()}catch(k){v(Fs(k));return}if(e.aborted){E();return}Promise.resolve().then(()=>s?null:r.navigator.mediaDevices.getUserMedia({video:!0,audio:!1})).then(async k=>{if(k){if(s){_(k);return}a=k,h.srcObject=a;for(let C of a.getTracks())C.addEventListener("ended",()=>v(It("UNAVAILABLE","Camera stopped")),c);try{await h.play(),D()}catch(C){v(Fs(C))}}},k=>v(Fs(k)))})}choosePhoto(e){if(e.aborted)return Promise.reject(zs());let t=this.document,r=t.defaultView;return new Promise((n,i)=>{let s=!1,a=null,l=new r.AbortController,c={signal:l.signal},u=t.createElement("input");u.type="file",u.accept="image/png,image/jpeg,image/webp",u.hidden=!0;let d=(h,p)=>{s||(s=!0,l.abort(),e.removeEventListener("abort",f),a&&a.readyState===1&&a.abort(),u.remove(),h?i(h):n(p))},f=()=>d(zs());if(e.addEventListener("abort",f,{once:!0}),u.addEventListener("cancel",f,c),u.addEventListener("change",()=>{let h=u.files[0];if(!h||!["image/png","image/jpeg","image/webp"].includes(h.type)){d(It("FAILED","Select a PNG, JPEG or WebP image"));return}a=new r.FileReader,a.onload=()=>d(null,{url:a.result,format:h.type.slice(6)}),a.onerror=()=>d(It("FAILED","Photo could not be read",a.error)),a.readAsDataURL(h)},c),t.body.append(u),e.aborted){f();return}try{u.click()}catch(h){d(It("FAILED","Photo selection failed",h))}})}};var Rc=new WeakMap,Mw=/^m_[a-f0-9]+$/;function Pc(o,e,{messages:t}){if(!(t instanceof x)||t instanceof N)throw new TypeError("Chat messages require a Data Bag");let r=e.parentNode,n=o.dom.getDomNode(r);if(!n)return;let i=Rc.get(r);i||(i={rows:new Map,active:!0},Rc.set(r,i),o.src.renderer.onDispose(r,()=>{i.active=!1;for(let u of i.rows.keys())r.getRelativeData(".messageData").popNode(u);i.rows.clear(),Rc.delete(r)}));let s=t.getNodes();for(let u of s)if(!Mw.test(u.label)||!["user","assistant"].includes(u.attr.role)||typeof u.attr.author!="string"||!(typeof u.staticValue=="string"||u.staticValue instanceof de))throw new TypeError("Chat messages require a stable label, role, author and string or Gramlot Source");let a=n.scrollHeight-n.clientHeight-n.scrollTop<48,l=[];for(let u of s){let d=i.rows.get(u.label);if(d&&d.value===u.staticValue&&d.role===u.attr.role&&d.author===u.attr.author)continue;let f=new me,h=f.root.article({node_label:u.label,datapath:r.absDatapath(".messageData."+u.label),"data-role":u.attr.role,"aria-label":u.attr.author}),p=Z(h.div());typeof u.staticValue=="string"?f.wrapSource(p).div("=="+JSON.stringify(u.staticValue),{white_space:"pre-wrap"}):p.setValue(o.src.prepareSource(u.staticValue.toTytx()));let m=o.src.prepareSource(f.source);o.src.renderer.validateCandidate(m),l.push({message:u,old:d,child:m.getNode(u.label)})}let c=new Set(s.map(u=>u.label));for(let[u]of i.rows)c.has(u)||(r.value.popNode(u),r.getRelativeData(".messageData").popNode(u),i.rows.delete(u));for(let{message:u,old:d,child:f}of l)d&&r.value.popNode(u.label),d||r.setRelativeData(".messageData."+u.label,new x),o.src.builder.setChild(r.value,f.nodeTag,f.value,{...f.attr,node_label:u.label}),i.rows.set(u.label,{value:u.staticValue,role:u.attr.role,author:u.attr.author});a&&queueMicrotask(()=>{i.active&&(n.scrollTop=n.scrollHeight)})}function vh(o,e,t=null){if(o.getRelativeData(".pending")||o.getRelativeData(".picking")||!o.getRelativeData(".conversation.ready"))return;let r=G();o.SET(".requestId",r),o.SET(".pending",!0),o.SET(".error",""),o.SET(".conversation.request",new x({id:r,action:e,text:t,attachments:j(R(o.getRelativeData(".attachments")))}))}function Bc(o,e){let t=e.getRelativeData(".draft");typeof t!="string"||!t.trim()&&!e.getRelativeData(".attachments").length||vh(e,"send",t)}function Mc(o,e){vh(e,"reset")}function Lc(o,e,{response:t}){if(t!==null){if(!(t instanceof x))throw new TypeError("Chat response requires a Data Bag");t.getItem("id")===e.getRelativeData(".requestId")&&(t.getItem("accepted")&&t.getItem("submitted")===e.getRelativeData(".draft")&&e.SET(".draft",""),t.getItem("accepted")&&t.getItem("submitted")!==null&&e.SET(".attachments",new x),e.SET(".pending",!1),e.SET(".error",t.getItem("error")))}}var jc=new WeakMap;function Fc(o,e){let t=e.parentNode,r=jc.get(t);if(!r){let n=o.dom.getDomNode(t);if(!n)return;let i=n.closest("[data-chat-composer]"),s=n.querySelector("textarea"),a=i.querySelector("[data-chat-top]"),l=i.querySelector("[data-chat-toolbar]"),c=n.ownerDocument.defaultView,u=0,d=!0,f=()=>{if(u=0,!d)return;s.style.height="0px";let m=c.getComputedStyle(s),b=parseFloat(m.borderTopWidth)+parseFloat(m.borderBottomWidth),w=Math.max(44,Math.min(180,s.scrollHeight+b));s.style.height=w+"px",s.style.overflowY=s.scrollHeight+b>w?"auto":"hidden";let _=Math.ceil(n.getBoundingClientRect().height+a.getBoundingClientRect().height+l.getBoundingClientRect().height+2);e.getRelativeData(".composerHeight")!==_&&e.SET(".composerHeight",_)},h=()=>{d&&!u&&(u=c.requestAnimationFrame(f))},p=new c.ResizeObserver(h);for(let m of[n,a,l])p.observe(m);o.src.renderer.onDispose(t,()=>{d=!1,p.disconnect(),u&&c.cancelAnimationFrame(u),jc.delete(t)}),r={schedule:h},jc.set(t,r)}r.schedule()}var Lw=["txt","md","csv","json","py","js","ts","jsx","tsx","html","css","sql","yaml","yml","xml","sh","toml","log"],yh={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",pdf:"application/pdf",...Object.fromEntries(Lw.map(o=>[o,"text/plain"]))};function Fw(o,e){return new Promise((t,r)=>{let n=new e.FileReader;n.onload=()=>t(n.result.slice(n.result.indexOf(",")+1)),n.onerror=()=>r(new Error("Could not read the selected file.")),n.readAsDataURL(o)})}async function zc(o,e){if(e.getRelativeData(".pending")||e.getRelativeData(".picking"))return;let t=o.dom.getDomNode(e.parentNode).ownerDocument,r=t.createElement("input");r.type="file",r.multiple=!0,r.accept=Object.keys(yh).map(a=>"."+a).join(","),r.style.display="none",t.body.append(r);let n=!0,i,s=o.src.renderer.onDispose(e.parentNode,()=>{n=!1,r.remove(),i([])});e.SET(".picking",!0),e.SET(".error","");try{let a=await new Promise(u=>{i=u,r.addEventListener("cancel",()=>u([]),{once:!0}),r.addEventListener("change",()=>u([...r.files]),{once:!0}),r.click()});if(!n||!a.length)return;let l=j(R(e.getRelativeData(".attachments")));if(l.length+a.length>5)throw new Error("Choose at most 5 files.");let c=l.getNodes().reduce((u,d)=>u+d.staticValue.getItem("size"),0);for(let u of a){let d=yh[u.name.split(".").pop().toLowerCase()];if(!d)throw new Error("Supported files: PNG, JPEG, WebP, PDF and UTF-8 text/code.");let f=d==="text/plain"?1024*1024:2*1024*1024;if(c+=u.size,!u.size||u.size>f||c>4*1024*1024)throw new Error("Limits: 2 MiB per file, 1 MiB for text, 4 MiB total.");let h=await Fw(u,t.defaultView);if(d==="text/plain"){let p=Uint8Array.from(atob(h),m=>m.charCodeAt(0));if(new TextDecoder("utf-8",{fatal:!0}).decode(p),p.includes(0))throw new Error("The selected file is not UTF-8 text.")}l.setItem("a_"+G(),new x({name:u.name,mediaType:d,size:u.size,data:h}))}n&&e.SET(".attachments",l)}catch(a){n&&e.SET(".error",a.message)}finally{s(),r.remove(),n&&e.SET(".picking",!1)}}function Uc(o,e){e.getRelativeData(".pending")||e.getRelativeData(".attachments").popNode(e.getAttr("attachment_id"))}function qc(o,e,{attachments:t}){let r=e.parentNode;for(let s of[...r.value.getNodes()])s.label.startsWith("a_")&&r.value.popNode(s.label);let n=new me;for(let s of t.getNodes()){let a=s.staticValue,l=n.root.div({node_label:s.label,display:"flex",align_items:"center",gap:"6px",padding:"4px 8px",border:"1px solid var(--gramlot-border-control,#aaa)",border_radius:"10px",flex_shrink:0});a.getItem("mediaType").startsWith("image/")&&l.img({src:"data:"+a.getItem("mediaType")+";base64,"+a.getItem("data"),alt:"Attachment preview",width:"36px",height:"36px",object_fit:"cover",border_radius:"6px"}),l.span("=="+JSON.stringify(a.getItem("name")),{font_size:"12px",max_width:"180px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),l.button({icon:"\xD7","aria-label":"Remove "+a.getItem("name"),disabled:"^.pending",class:"button--quiet"}).dataController({func:"chatRemoveAttachment",attachment_id:s.label})}let i=o.src.prepareSource(n.source);o.src.renderer.validateCandidate(i);for(let s of i.getNodes())o.src.builder.setChild(r.value,s.nodeTag,s.value,{...s.attr,node_label:s.label})}var Us=class{constructor({app:e,editor:t,design:r}){this.renderer=e.src.renderer,this.design=r;let n=this.renderer.records.get(r).presentation;this.frame=n.ownerDocument.createElement("iframe"),this.frame.title="Page canvas",this.frame.className="visual-editor-canvas-frame",this.frame.style.cssText="display:block;width:100%;height:100%;min-height:240px;border:0;background:white",n.before(this.frame);let i=this.frame.contentDocument;e.registerDocument(i);let s=i.createElement("style");s.textContent="html,body{margin:0;min-height:100%;} .visual-editor-canvas{min-height:100vh;}",this.styles=i.createElement("style");let a=i.createElement("style");a.textContent=".gramlot-source-selected{outline:2px solid #8ab4f8!important;outline-offset:-2px!important;}",i.head.append(s,this.styles,a),this.body=i.body,this.renderer.mountDestination(r,this.body),this.release=this.renderer.onDispose(t,()=>this.dispose())}setCss(e){this.styles.textContent=e.join(`
256
+ `)}dispose(){this.release?.(),this.release=null,this.frame.remove()}};var xh=["string","number","integer","boolean","date","time","datetime","null"];function Vc(o){if(o===null)return"null";if(["string","boolean"].includes(typeof o))return typeof o;if(typeof o=="number"&&Number.isFinite(o))return Number.isSafeInteger(o)?"integer":"number";if(o instanceof Date&&Number.isFinite(o.getTime())){let e=o.toISOString();return e.slice(0,10)==="1970-01-01"?"time":e.endsWith("T00:00:00.000Z")?"date":"datetime"}return null}function qs(o,e){if(e==="null")return"";if(o instanceof Date){let t=o.toISOString();return e==="date"?t.slice(0,10):e==="time"?t.slice(11,23):t}return String(o)}function Wc(o,e){if(o==="string")return e;if(o==="null")return null;if(o==="boolean"&&["true","false"].includes(e))return e==="true";if((o==="number"||o==="integer")&&/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e.trim())){let t=Number(e);if(Number.isFinite(t)&&(o!=="integer"||Number.isSafeInteger(t)))return t}if(["date","time","datetime"].includes(o)&&(o==="date"?/^\d{4}-\d{2}-\d{2}$/:o==="time"?/^\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?Z$/).test(e)){let r=o==="date"?`${e}T00:00:00Z`:o==="time"?`1970-01-01T${e}Z`:e,n=new Date(r);if(Number.isFinite(n.getTime())){let i=n.toISOString(),s=r.replace(/Z$/,"").split(/[T:.]/),a=i.replace(/Z$/,"").split(/[T:.]/);if(s.every((l,c)=>c===4?Number(l.padEnd(3,"0"))===Number(a[c]):l===a[c]))return n}}throw new Error(`Invalid ${o} value: ${e||"(empty)"}`)}var Xo=class{#e;#t;#r;#n;#o;#i=null;#s=null;#a=null;#l=!1;constructor({renderer:e,root:t,onSelect:r,canvas:n=e.records.get(t.parentNode)?.presentation}){if(!t?.parentNode||typeof r!="function")throw new TypeError("SourcePicker requires a mounted Source root and onSelect");if(!n||n.nodeType!==1)throw new TypeError("SourcePicker requires a mounted preview");this.#e=e,this.#t=t,this.#r=n,this.#n=r,n.addEventListener("pointerdown",this,!0),n.addEventListener("click",this,!0),this.#o=new n.ownerDocument.defaultView.MutationObserver(()=>this.#c()),this.#o.observe(n,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["class"]}),this.#a=e.onDispose(t.parentNode,()=>this.dispose())}handleEvent(e){if(this.#l)return;let t=this.#t.fullpath+".",r=e.composedPath().map(i=>this.#e.elements.get(i)).find(i=>i?.node.fullpath.startsWith(t));if(!r)return;e.composedPath().some(i=>i.nodeType===1&&(i.matches("input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]), textarea, select, label")||i.isContentEditable))||(e.preventDefault(),e.stopImmediatePropagation()),this.#n(r.node)}select(e){if(!this.#l){if(e===null)this.#i=null;else{let t=this.#t.fullpath+".";if(!e.fullpath.startsWith(t))throw new TypeError("Selected node must be inside the preview Source root");this.#i=e.fullpath.slice(t.length)}this.#c()}}#c(){if(this.#l)return;let e=this.#i?this.#t.staticValue.getNode(this.#i):null,t=e?this.#e.records.get(e)?.presentation:null,r=t?.nodeType===1?t:null;this.#s!==r&&(this.#s?.classList.remove("gramlot-source-selected"),this.#s=r),r&&!r.classList.contains("gramlot-source-selected")&&r.classList.add("gramlot-source-selected")}dispose(){this.#l||(this.#l=!0,this.#o.disconnect(),this.#r.removeEventListener("pointerdown",this,!0),this.#r.removeEventListener("click",this,!0),this.#s?.classList.remove("gramlot-source-selected"),this.#a?.(),this.#a=null,this.#s=null)}};var Gc={base:"",compact:`/* gramlot-compact: professional density profile; load after Base. */
257
257
  @layer gramlot.tokens {
258
258
  :root {
259
259
  color-scheme: light;
@@ -1501,7 +1501,7 @@ export const buildId = "${o}";
1501
1501
  :where([role="toolbar"]) { background:Canvas; color:CanvasText; backdrop-filter:none; }
1502
1502
  }
1503
1503
  }
1504
- `},Gc={default:"",compact:`/* Color-only override: load after the chosen appearance profile. */
1504
+ `},Hc={default:"",compact:`/* Color-only override: load after the chosen appearance profile. */
1505
1505
  @layer gramlot.tokens {
1506
1506
  :root {
1507
1507
  color-scheme: light;
@@ -1777,8 +1777,8 @@ export const buildId = "${o}";
1777
1777
  --gramlot-warning-background: #413820;
1778
1778
  }
1779
1779
  }
1780
- `};function Q(o){for(let e=o;e;e=e.parentNode)if(e.getAttr("visualEditorId"))return e;throw new Error("Operation requires a VisualEditor Source ancestor")}function te(o){return Q(o).fullpath.split(".").slice(1).join(".")+".layout.center.design"}function Oe(o){return Q(o).absDatapath(".")}function Us(o,e){return o.rootBuilder.binding.nodeIds.get(Q(o).getAttr("visualEditorId")+e)}var kh=[["html.structure","Structure","main header footer nav section article aside div address search"],["html.text","Text and headings","h1 h2 h3 h4 h5 h6 hgroup p span a b strong i em small s u mark abbr cite code pre blockquote q br wbr hr time data dfn kbd samp var bdi bdo ruby rt rp sub sup ins del_"],["html.lists","Lists","ul ol li dl dt dd"],["html.forms","Forms","form input textarea select selectedcontent option optgroup datalist label fieldset legend output progress meter html_button"],["html.tables","Tables","table caption colgroup col thead tbody tfoot tr th td"],["html.media","Media and embedded content","img picture source audio video track canvas iframe embed object param map area"],["html.interaction","Disclosure and menus","details summary html_dialog html_menu"],["html.document","Document and metadata","html head body title base meta link style script noscript template slot"],["components.layout.containers","Containers","borderContainer contentPane framePane stackContainer tabContainer"],["components.layout.windows","Windows","dialog floatingPane"],["components.layout.composition","Composition","formlet groupBox trayPane transformPane"],["components.inputs.text","Text","textbox textBoxArea passwordbox"],["components.inputs.choices","Choices","checkbox radioButton radioButtonText checkBoxText filteringSelect comboBox callbackSelect dbSelect dbComboBox"],["components.inputs.numbers","Numbers and colors","numberTextBox horizontalSlider verticalSlider colorpicker"],["components.inputs.dates","Dates and times","dateTextBox timeTextBox dateCalendar"],["components.commands","Buttons and menus","button toggleButton dropDownButton menu menuline spacer"],["components.data","Trees and grids","tree grid searchBox"],["components.editors","Editors and previews","codeMirror htmlEditor htmlPreview markdownEditor markdownPreview typstPreview"]],zw={html:"HTML",components:"Gramlot","components.layout":"Layout","components.inputs":"Inputs"},Gs=Object.fromEntries(["class","style","width","height","padding","margin","color","background"].map(o=>[o,{dtype:"T",nullable:!0}])),Eh=Object.fromEntries(["lbl_","box_"].flatMap(o=>Object.entries(Gs).map(([e,t])=>[o+e,t]))),Hc=[["general","General"],["behaviour","Behaviour"],["validation","Validation"],["styles","Styles"],["container","Container"]],Vs=["T","B","L","R","N","D","H"];function Xc(o,e){return/^(lbl|box)(_|$)/.test(o)?"general":e.has(o)?"container":o.startsWith("validate_")?"validation":Object.hasOwn(Gs,o)||/^(icon|tab)/.test(o)||["design","labelPosition","switch_color","orientation"].includes(o)?"styles":/^(on[A-Z]|get[A-Z]|drag|drop)/.test(o)||["action","command","disabled","readonly","live","beforeClose","open","collapsed","closable","movable","resizable","collapsible","maximizable","maximized","persist","autoCollapse","openOnClick"].includes(o)?"behaviour":"general"}var Ct=(o,e,t=null)=>{let r=o.builder.schema[e];if(!r)throw new Error(`Unknown widget: ${e}`);let n=r._meta?.gramlot_component;return{...(!t||!(t.getValue(!0)instanceof t.builder.source.constructor))&&(!n||n.command&&!Object.hasOwn(n.parameters,"caption"))?{_text:{dtype:"T",nullable:!0}}:{},...Gs,...n?.labelbox?Eh:{},...n?.parameters??{},...o._getMeta("gramlot_component")?.childParameters??{}}},Ws=new WeakMap,Xo=new WeakMap,Yc=class{chatRender(e,t){return jc(this.page,e,t)}chatCompleted(e,t){Mc(this.page,e,t),e.GET(`${Oe(e)}.assistant.active`)&&e.SET(".pending",!0)}chatReset(e){return Bc(this.page,e)}chatResize(e){return Lc(this.page,e)}chatPickAttachments(e){return Fc(this.page,e)}chatRenderAttachments(e,t){return qc(this.page,e,t)}chatRemoveAttachment(e){return zc(this.page,e)}chatSend(e){if(e.GET(".pending")||!e.GET(".conversation.ready")||!e.GET(".draft")?.trim())return;let t=Q(e),r=t.GET(".editingMode"),n=e.builder.source.getNode(te(e)).value.toTytx(),i=r==="code"?t.GET(".codeDocument.content"):n;if(r==="code"&&!t.GET(".codeDocument.writable")){e.SET(".error","Page code editing is disabled by the host");return}let s=(t.GET(".assistantRun.run")??0)+1,a=t.GET(".catalogueScope"),l={commonParameters:Gs,labelboxParameters:Eh,widgets:{}};for(let[c,u]of Object.entries(e.builder.schema)){if(!vn(a,c,u._meta??{})||u._meta?.data_element||u._meta?.subbuilder||u._meta?.container)continue;let d=u._meta?.gramlot_component;l.widgets[c]={parameters:d?.parameters??{},labelbox:!!d?.labelbox,childParameters:d?.childParameters??{}}}return t.SET(".assistantRun",new x({run:s,mode:r,next:0,expected:i,blocked:!1})),t.SET(".assistantStatus","Waiting for editing instructions\u2026"),t.SET(".assistant.context",new x({run:s,mode:r,language:t.GET(".codeDocument.language")??null,codeWritable:t.GET(".codeDocument.writable")===!0,code:r==="code"?i:null,source:n,selected:t.GET(".selection"),schema:JSON.stringify(l)})),Pc(this.page,e)}assistantState(e,{active:t}){if(t===!1){e.SET(`${Oe(e)}.chat.pending`,!1);let r=Q(e);r.GET(".assistantRun.next")===0&&r.SET(".assistantStatus","")}}assistantApply(e,{operations:t}){if(!(t instanceof x))return;let r=Q(e);for(let n of t.getNodes()){if(n.attr.run!==r.GET(".assistantRun.run")||n.attr.index<r.GET(".assistantRun.next"))continue;let i=e.builder.source.getNode(te(e)).value,s=r.GET(".assistantRun.mode"),a=s==="code"?r.GET(".codeDocument.content"):i.toTytx(),l=!1,c=!1,u="";try{if(r.GET(".assistantRun.blocked"))throw c=!0,new Error("The document was replaced during editing");if(n.attr.index!==r.GET(".assistantRun.next"))throw c=!0,new Error("Editing sequence is incomplete");if(a!==r.GET(".assistantRun.expected"))throw c=!0,new Error("Source changed during the request. Remaining edits stopped; send a new instruction.");let d=JSON.parse(n.value);if(s==="code"){if(d.operation!=="replace_code"||typeof d.content!="string")throw new Error("Expected a Page code draft operation");if(!r.GET(".codeDocument.writable")||r.GET(".codeDocument.busy"))throw new Error("Page code draft is not editable now");r.SET(".codeDocument.content",d.content),r.SET(".codeDocument.status","AI draft \xB7 Save to apply"),r.SET(".codeOpen",!0)}else this.applySourceEdit(r,d);l=!0,r.SET(".assistantRun.expected",s==="code"?r.GET(".codeDocument.content"):i.toTytx()),r.SET(".assistantStatus",`Applied ${n.attr.index+1}: ${s==="code"?"Page code draft":d.operation+" "+d.path}`)}catch(d){u=d.message,(s==="code"?r.GET(".codeDocument.content"):i.toTytx())!==a&&(c=!0),r.SET(".assistantRun.blocked",c),r.SET(".assistantStatus",`${c?"Editing stopped":"Rejected"}: ${u}`)}r.SET(".assistantRun.next",n.attr.index+1),r.SET(".assistant.ack",new x({run:n.attr.run,index:n.attr.index,applied:l,stop:c,error:u,mode:s,code:s==="code"?r.GET(".codeDocument.content"):null,source:i.toTytx(),selected:r.GET(".selection")}))}}applySourceEdit(e,t){let{operation:r,path:n,parent:i,tag:s,label:a,attributes:l={},text:c}=t,u=v=>typeof v=="string"&&/^pageRoot(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(v);if(!u(n)||r==="move"&&!u(i))throw new Error(`Use dot-separated paths inside pageRoot: ${JSON.stringify(n)}`);if(!["insert","update","remove","move"].includes(r))throw new Error("Unknown Source editing operation");if(["remove","move"].includes(r)&&n==="pageRoot")throw new Error("The page root is protected");if(r==="insert"&&(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a)))throw new Error("Choose an explicit node label");if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Expected scalar attributes");for(let[v,E]of Object.entries(l))if(v.startsWith("_")||/^(connect_|on[A-Z]|script$|formula$|action$|func$|remote_)/.test(v)||["constructor","prototype"].includes(v)||E!==null&&typeof E=="object"||typeof E=="string"&&(E.startsWith("==")||E.includes(":=")))throw new Error(`Unsupported generated attribute: ${v}`);if(c!==void 0&&typeof c!="string")throw new Error("Text must be literal text");let d=e.builder.source.getNode(te(e)),f=e.rootBuilder.binding.gramlot,h=f.src.prepareSource(d.value.toTytx(),d.builder),p=h.getNode(n);if(!p)throw new Error("The Source target no longer exists");let m=p;if(r==="insert"){if(!e.builder.schema[s]||["script","style","iframe","object","embed"].includes(s)||e.builder.schema[s]._meta?.data_element)throw new Error("Choose a visual widget from the catalogue");if(p.value instanceof h.constructor&&p.value.getNode(a))throw new Error("This node label is already in use");m=p.builder.commandOnNode(p,s,c??null,{...l,node_label:a})}else if(r==="update"){if(c!==void 0&&p.value instanceof h.constructor)throw new Error("Text cannot replace a populated container");let v={...p.getAttr()};for(let[E,D]of Object.entries(l))D===null?delete v[E]:v[E]=D;p.setAttr(v,!0,!1,!1),c!==void 0&&p.setValue(c)}else if(r==="remove")p.parentBag.popNode(p.label);else{if(Object.keys(l).length||c!==void 0)throw new Error("Move and property edits must be separate operations");if(i===n||i.startsWith(n+"."))throw new Error("Cannot move a node into itself");let v=h.getNode(i);if(!v)throw new Error("The destination no longer exists");if(v.value instanceof h.constructor&&v.value.getNode(p.label))throw new Error("The destination already contains this label");m=this.appendBranch(v,p,p.label)}let b=v=>{if(v.value instanceof h.constructor){v.builder.validateChildren(v.nodeTag,v.value.getNodes().map(E=>E.nodeTag));for(let E of v.value.getNodes()){for(let[D,k]of Object.entries(Ct(v,E.nodeTag,E)))this.validateParameter(v,E,D,k,E.getAttr(D));b(E)}}};h.getNodes().forEach(b),tt(Q(e).GET(".catalogueScope"),h),f.src.renderer.validateCandidate(h,{replacingNode:d});let w=e.builder.source.getNode(`${te(e)}.${n}`),_=n;r==="insert"?(this.appendBranch(w,m,a),_=`${n}.${a}`):r==="update"?(w.setAttr({...m.getAttr()},!0,!1,!1),c!==void 0&&w.setValue(c)):r==="remove"?(_=n.slice(0,n.lastIndexOf(".")),w.parentBag.popNode(w.label)):(this.applyDrop(e,{item:e.builder.source.getNode(`${te(e)}.${i}`),path:i,dropValues:{"app/source":{path:n}}}),_=`${i}.${w.label}`),e.SET(".sourceSearch",""),e.SET(".selection",_)}initializeCanvasSelection(e){let t=e.rootBuilder.binding.renderer,r=e.builder.source.getNode(te(e)),n=Q(e),i=n.GET(".canvasCss");i!=null&&this.applyCanvasCss(n,i);let s=Ws.get(r);s?.dispose();let a=new Ho({renderer:t,root:r,...Xo.has(r)?{canvas:Xo.get(r).body}:{},onSelect:l=>{e.SET(".sourceSearch",""),e.SET(".selection",l.fullpath.slice(r.fullpath.length+1))}});Ws.set(r,a),s||t.onDispose(r.parentNode,()=>{Ws.delete(r),Xo.delete(r)}),this.highlightSelection(e)}applyCanvasCss(e,t){if(!Array.isArray(t)||t.some(s=>typeof s!="string"))throw new TypeError("canvas CSS must be a list of CSS texts");let r=Q(e),n=r.builder.source.getNode(te(r)),i=Xo.get(n);i||(i=new zs({app:r.rootBuilder.binding.gramlot,editor:r,design:n}),Xo.set(n,i)),i.setCss(t)}setCanvasCss(e,t){let r=Q(e);this.applyCanvasCss(r,t),r.SET(".canvasCss",t),this.initializeCanvasSelection(r)}highlightSelection(e){let t=e.builder.source.getNode(te(e)),r=e.GET(".selection");Ws.get(t)?.select(r?t.staticValue.getNode(r):null)}clipboardShortcut(e,t){if(t.defaultPrevented||t.repeat||e.GET(".clipboardOpen")||e.GET(".insertionOpen")||e.GET(".uploadOpen")||t.composedPath().some(i=>i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)))return;let r=t.key.toLowerCase(),n=r==="f8"?"cutBranch":r==="f9"?"pasteBranch":null;!n||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),this[n](e))}clipboardModifiers(e,t){e.SET(".clipboardDropEffect",t.altKey?"copy":"move")}cutBranch(e){this.beginClipboard(e,e.GET(".selection"),!1)}copyBranch(e){this.beginClipboard(e,e.GET(".selection"),!0)}dropClipboard(e,{dropValues:t,dropEffect:r}){this.beginClipboard(e,t["app/source"].path,r==="copy")}prepareClipboard(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","copy"),r["app/clipboard"]={path:t}}branchSnapshot(e,t){let r=e.builder.source.getNode(te(e)),i=e.rootBuilder.binding.gramlot.src.prepareSource(r.getValue(!0).toTytx(),r.builder).getNode(t);if(!i)throw new Error("The Source branch no longer exists");let s=l=>{if(l.resolver)throw new Error("Resolver-backed branches cannot be stored in this trial");l.value instanceof e.builder.source.constructor&&l.value.getNodes().forEach(s)};s(i);let a=new e.builder.source.constructor(null,i.builder);return i.parentBag.popNode(i.label),a.setItem(i.label,i.getValue(!0),{...i.getAttr()},">",!1,!1,"editor",!1,!0,null,i.nodeTag),a.toTytx()}beginClipboard(e,t,r){e.SET(".error","");try{if(!t||t==="pageRoot")throw new Error("Choose a branch below the page root");let n=e.builder.source.getNode(`${te(e)}.${t}`);if(!n)throw new Error("The Source branch no longer exists");let i=this.branchSnapshot(e,t);e.SET(".clipboardDraft",new x({path:t,copy:r,name:n.label,wire:i,parentTag:n.parentNode.nodeTag})),e.SET(".clipboardOpen",!0)}catch(n){e.SET(".error",n.message)}}saveClipboard(e){e.SET(".error","");try{let t=e.GET(".clipboardDraft.name")?.trim();if(!t)throw new Error("Choose a name for the branch");let r=e.GET(".clipboardDraft.path"),n=e.GET(".clipboardDraft.wire"),i=e.GET(".clipboardDraft.copy"),s=e.builder.source.getNode(`${te(e)}.${r}`);if(!i&&(!s||this.branchSnapshot(e,r)!==n))throw new Error("The branch changed; select it again before cutting");let a=e.GET(".clipboard"),l=1;for(;a.getNode(`branch_${l}`);)l++;let c=`branch_${l}`;a.setItem(c,n,{name:t,parentTag:e.GET(".clipboardDraft.parentTag")}),e.SET(".clipboardSelection",c),e.SET(".clipboardVisible",!0),i||(e.SET(".selection",r.slice(0,r.lastIndexOf("."))),s.parentBag.popNode(s.label)),e.SET(".clipboardOpen",!1),e.SET(".fileStatus",`${i?"Copied":"Cut"}: ${t}`)}catch(t){e.SET(".error",t.message)}}pasteBranch(e){e.SET(".error","");try{this.beginPaste(e,e.GET(".clipboardSelection"),e.GET(".selection"))}catch(t){e.SET(".error",t.message)}}beginPaste(e,t,r){let n=t?e.GET(".clipboard").getNode(t):null;if(!n)throw new Error("Choose a saved branch in the clipboard");let i=r?e.builder.source.getNode(`${te(e)}.${r}`):null;if(!i)throw new Error("Choose a destination in the Source tree");let s=e.rootBuilder.binding.gramlot.src.prepareSource(n.getValue(!0),i.builder);tt(Q(e).GET(".catalogueScope"),s);let a=s.getNodes()[0];i.builder.validateParent(a.nodeTag,i.nodeTag);let l=i.getValue(!0);i.builder.validateChildren(i.nodeTag,[...l instanceof e.builder.source.constructor?l.getNodes().map(w=>w.nodeTag):[],a.nodeTag]);let c={...a.getAttr()},u=i.builder.schema[a.nodeTag]._meta?.gramlot_component?.parameters??{},d=i.builder.schema[n.getAttr("parentTag")]?._meta?.gramlot_component?.childParameters??{};for(let w of Object.keys(d))w in u||delete c[w];a.setAttr(c,!0,!1,!1),e.SET(".insertion",new x({parentPath:r,tag:a.nodeTag,clipboard:s.toTytx()}));let f=Ct(i,a.nodeTag),h=Object.entries(f).filter(([w,_])=>_.required&&(c[w]==null||c[w]===""||_.unique));if(!h.length){this.finishPaste(e);return}let p=Us(e,"InsertFields");p.getValue(!0).clear();let m=e.builder.wrapSource(p);m.p(`Paste ${n.getAttr("name")} into ${i.label} [${i.nodeTag}]`,{class:"visual-editor-hint"});let b=m.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[w,_]of h)this.parameterField(e,b,a.nodeTag,w,_,"insertion",_.default);e.SET(".insertionOpen",!0)}appendBranch(e,t,r){let n=e.builder.source.constructor,i=e.getValue(!0);if(!(i instanceof n)){let s=i;i=new n(null,e.builder),e.builder.promoteNodeValue(e,s,i)}return t.parentBag.popNode(t.label),i.setItem(r,t.getValue(!0),{...t.getAttr()},">",!1,!1,"editor",!1,!0,null,t.nodeTag),i.getNode(r)}finishPaste(e){let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${te(e)}.${t}`);if(!r)throw new Error("The destination no longer exists");let n=e.rootBuilder.binding.gramlot,i=n.src.prepareSource(e.GET(".insertion.clipboard"),r.builder);tt(Q(e).GET(".catalogueScope"),i);let s=i.getNodes()[0],a={...s.getAttr()};for(let[b,w]of Object.entries(Ct(r,s.nodeTag))){if(!w.required)continue;let _=e.GET(`.insertion.types.${b}`),v=e.GET(`.insertion.parameters.${b}${w.enum?"":_?"."+_:""}`);v!=null&&(a[b]=v),this.validateParameter(r,null,b,w,a[b])}s.setAttr(a,!0,!1,!1);let l=r.getValue(!0),c=s.label,u=1;for(;l instanceof e.builder.source.constructor&&l.getNode(c);)c=`${s.label}_${u++}`;let d=e.builder.source.getNode(te(e)),f=n.src.prepareSource(d.getValue(!0).toTytx(),d.builder),h=f.getNode(t);h.builder.validateParent(s.nodeTag,h.nodeTag);let p=h.getValue(!0);h.builder.validateChildren(h.nodeTag,[...p instanceof e.builder.source.constructor?p.getNodes().map(b=>b.nodeTag):[],s.nodeTag]);let m=this.appendBranch(h,s,c);tt(Q(e).GET(".catalogueScope"),f),n.src.renderer.validateCandidate(f,{replacingNode:d}),this.appendBranch(r,m,c),e.SET(".insertionOpen",!1),e.SET(".sourceSearch",""),e.SET(".selection",`${t}.${c}`),e.SET(".fileStatus","Branch pasted")}openCode(e){let t=Q(e);t.SET(".codeOpen",!0),t.SET(".editingMode","code")}async codeSave(e){let t=Q(e),r=t.GET(".codeDocument");if(r.getItem("busy")||!r.getItem("writable"))return;let n=r.getItem("content"),i=r.getItem("revision"),s=!1;if(n===r.getItem("saved"))return;let a=new AbortController,l=this.page.src.renderer.onDispose(t,()=>a.abort());r.setItem("busy",!0),r.setItem("status","Saving Page code\u2026");let c=t.value.getNode("layout.center.design"),u=c.value.toTytx();try{let d=await this.page.rpc.call("data","editor_document_save",{key:t.getAttr("codeDocumentKey"),content:n,revision:i},{signal:a.signal});if(a.signal.aborted)return;r.setItem("revision",d.revision),r.setItem("saved",n),s=!0,r.setItem("status","Page code saved"),u!==c.value.toTytx()?r.setItem("status","Page code saved; Source changed meanwhile. Use Preview saved to replace it."):await this.codeLoadPreview(t,a)}catch(d){a.signal.aborted||r.setItem("status",`${s?"Page code saved; preview failed":"Save failed"}: ${d.message}`)}finally{l(),a.signal.aborted||r.setItem("busy",!1)}}async codePreview(e){let t=Q(e),r=t.GET(".codeDocument");if(r.getItem("busy"))return;let n=new AbortController,i=this.page.src.renderer.onDispose(t,()=>n.abort());r.setItem("busy",!0);try{await this.codeLoadPreview(t,n)}catch(s){n.signal.aborted||r.setItem("status",`Preview failed: ${s.message}`)}finally{i(),n.signal.aborted||r.setItem("busy",!1)}}async codeLoadPreview(e,t){let r=e.GET(".codeDocument"),n=e.value.getNode("layout.center.design"),i=n.value.toTytx(),s=await this.page.rpc.call("source","editor_document_preview",{key:e.getAttr("codeDocumentKey"),revision:r.getItem("revision"),data_root:e.GET(".dataRoot")},{signal:t.signal});if(t.signal.aborted)return;if(n.value.toTytx()!==i)throw new Error("Source changed while preparing preview; it was retained");let a=this.page.src.prepareSource(s,n.builder);tt(e.GET(".catalogueScope"),a),this.page.src.renderer.validateCandidate(a,{replacingNode:n}),e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),n.setValue(a,!0,{_text:null},!0),e.SET(".selection","pageRoot"),r.setItem("status",r.getItem("content")===r.getItem("saved")?"Saved Page code \xB7 preview updated":"Preview updated from saved page code; newer draft retained")}newPage(e){e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),e.SET(".insertionOpen",!1),e.SET(".error","");let t=e.builder.source.getNode(te(e));t.getValue(!0).clear();let r=e.GET(".dataRoot");if(r)e.SET(r,new x);else for(let n of e.rootBuilder.data.getNodes())n.label!=="__editor"&&e.rootBuilder.data.popNode(n.label);e.builder.wrapSource(t).div({node_label:"pageRoot",...r?{datapath:r}:{}}),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".sourceSearch",""),e.SET(".dataSearch",""),e.SET(".selection","pageRoot")}async copySource(e){e.SET(".fileStatus","");try{await e.rootBuilder.binding.gramlot.utl.inout.copyText(this.currentSource(e)),e.SET(".fileStatus","Source copied")}catch(t){e.SET(".fileStatus",`Copy failed: ${t.message}`)}}downloadPage(e){e.rootBuilder.binding.gramlot.utl.inout.saveText(this.currentSource(e),e.GET(".filename"),"application/json")}openUpload(e){e.SET(".uploadOpen",!0)}sourceUploaded(e,{item:t,result:r}){try{this.loadSource(e,{source:r,filename:t.value.getItem("name")}),e.SET(".fileStatus","Source opened"),e.SET(".uploadOpen",!1)}catch(n){throw e.SET(".fileStatus",`Open failed: ${n.message}`),n}}initializeDocument(e){let t=Q(e),r=t.builder.source,n=te(t).split("."),i=`${t.getAttr("visualEditorId")}-document`;t.SET(".modified",!1),r.subscribe(i,{any:s=>{n.every((a,l)=>s.pathlist[l]===a)&&t.SET(".modified",!0)}}),t.rootBuilder.binding.renderer.onDispose(t,()=>r.unsubscribe(i,{any:!0}))}currentSource(e){let t=Q(e);return t.builder.source.getNode(te(t)).getValue(!0).toTytx()}markSaved(e){Q(e).SET(".modified",!1)}loadSource(e,{source:t,filename:r}){let n=Q(e);if(typeof t!="string")throw new TypeError("source must be Source TYTX");if(typeof r!="string"||!r.trim())throw new TypeError("filename must be a non-empty string");let i=n.rootBuilder.binding.gramlot,s=n.builder.source.getNode(te(n)),a=i.src.prepareSource(t,s.builder),l=a.getNodes();if(l.length!==1||l[0].label!=="pageRoot")throw new Error("Expected one pageRoot Source");tt(n.GET(".catalogueScope"),a),i.src.renderer.validateCandidate(a,{replacingNode:s}),n.GET(".assistantRun")&&n.SET(".assistantRun.blocked",!0),n.SET(".selection",null),s.setValue(a,!0,{_text:null},!0),n.SET(".filename",r),n.SET(".insertionOpen",!1),n.SET(".sourceSearch",""),n.SET(".selection","pageRoot"),this.markSaved(n)}toggleNavigation(e){e.SET(".navigationOpen",e.GET(".navigationOpen")==="close"?!0:"close")}openCatalogue(e){e.SET(`${Oe(e)}.catalogueOpen`,!0)}openProperties(e){this.showProperties(e,{path:e.GET(".selection")})}sourceLabel(e,{item:t}){return{text:`${t.label} [${t.nodeTag}]`}}dropNode(e,t){e.SET(".error","");try{this.applyDrop(e,t)}catch(r){e.SET(".error",r.message)}}insertWidget(e){e.SET(".error","");try{this.applyInsert(e)}catch(t){e.SET(".error",t.message)}}initializeEditorAppearance(e){let t=Q(e),r=e.rootBuilder.binding.renderer.destination.ownerDocument;t.SET(".appearanceProfile","compact"),t.SET(".appearancePalette","joanna"),t.SET(".appearanceMode",r.documentElement.getAttribute("data-theme")||"dark")}applyEditorAppearance(e,{profile:t,palette:r,mode:n}){if(!t||!r||!n)return;if(!Object.hasOwn(Wc,t)||!Object.hasOwn(Gc,r)||!["light","dark"].includes(n))throw new Error("Choose a declared theme, palette and color mode");Q(e).SET(".appearanceCss",Wc[t]+`
1781
- `+Gc[r]),e.rootBuilder.binding.renderer.destination.ownerDocument.documentElement.setAttribute("data-theme",n)}initializeEditor(e,{dataRoot:t}){let r=e.GET(".catalogueScope");if(yn(r),Array.isArray(r)){for(let a of r)if(!e.builder.schema[a])throw new Error(`Unknown catalogue tag: ${a}`)}if(e.SET(".editingMode","source"),e.SET(".clipboard",new x),e.SET(".clipboardVisible",!1),e.SET(".clipboardDropEffect","move"),e.SET(".sourceDropEffect","move"),e.SET(".dataRoot",t),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".selection","pageRoot"),t)e.GET(t)==null&&e.SET(t,new x);else{let a=Oe(e),l=a.split(".").map(()=>"#parent").join(".");e.builder.source.getNode(te(e)).setAttr({datapath:`${a}.${l}`})}let n=new x,i=new Map([["",n]]),s=(a,l)=>{if(i.has(a))return i.get(a);let c=a.split("."),u=c.pop(),d=c.join("."),f=s(d,zw[d]),h=new x;return f.setItem(u,h,{caption:l}),i.set(a,h),h};for(let[a,l,c]of kh)c.split(" ").some(u=>e.builder.schema[u]&&vn(r,u,e.builder.schema[u]._meta??{}))&&s(a,l);for(let[a,l]of Object.entries(e.builder.schema).sort(([c],[u])=>c.localeCompare(u))){if(!vn(r,a,l._meta??{})||l._meta?.data_element||l._meta?.subbuilder||l._meta?.container)continue;let c=l._meta?.gramlot_component?"components":"html",u=kh.find(([f,,h])=>f.startsWith(c+".")&&h.split(" ").includes(a)),d=u?u[0]:`${c}.other`;s(d,u?u[1]:"Other elements").setItem(a,null,{caption:a,tag:a})}e.SET(".catalogue",n)}prepareWidget(e,{item:t,dragValues:r}){if(e.SET(".sourceDropEffect","copy"),!t.attr.tag)return!1;r["app/widget"]={tag:t.attr.tag}}prepareSource(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","move"),r["app/source"]={path:t}}applyDrop(e,{item:t,path:r,dropValues:n}){if(n["app/clipboard"]){this.beginPaste(e,n["app/clipboard"].path,r);return}if(n["app/source"]){let f=`${te(e)}.${n["app/source"].path}`,h=`${te(e)}.${r}`,p=e.builder.source.getNode(f);if(!p||f===`${te(e)}.pageRoot`)throw new Error("The page root cannot be moved");if(tt(Q(e).GET(".catalogueScope"),p.parentBag),p.resolver)throw new Error("Resolver-backed Source nodes cannot be moved in this trial");if(f===h||h.startsWith(f+"."))throw new Error("A node cannot be moved into itself");let m=t,b=p.parentBag,w=e.builder.source.constructor;if(p.builder!==m.builder)throw new Error("Nodes cannot cross builder dialects");let _=m.getValue(!0),v=_ instanceof w?_.getNodes().filter(D=>D!==p):[];if(_ instanceof w&&_!==b&&_.getNode(p.label))throw new Error("The target already contains this label");let E=m._getMeta("gramlot_component")?.childParameters??{};for(let[D,k]of Object.entries(E)){let C=p.getAttr(D);if(k.required&&C==null)throw new Error(`The moved node requires ${D}`);if(k.enum&&C!=null&&!k.enum.includes(C))throw new Error(`Invalid ${D}`);if(k.unique&&C!=null&&v.some(O=>O.getAttr(D)===C))throw new Error(`${D} is already in use`)}if(m.builder.validateParent(p.nodeTag,m.nodeTag),m.builder.validateChildren(m.nodeTag,[...v.map(D=>D.nodeTag),p.nodeTag]),_===b)b.move(b.getNodes().indexOf(p),v.length);else{let D=_ instanceof w?_:new w(null,m.builder);_ instanceof w||m.builder.promoteNodeValue(m,_,D);let k={label:p.label,tag:p.nodeTag,value:p.getValue(!0),attrs:{...p.getAttr()}};b.popNode(k.label),D.setItem(k.label,k.value,k.attrs,D.getNodes().length,!1,!1,"editor",!1,!0,null,k.tag)}e.SET(".selection",`${r}.${p.label}`);return}let i=n["app/widget"].tag;this.validateCatalogueTag(e,i),t.builder.validateParent(i,t.nodeTag);let s=t.getValue(!0);t.builder.validateChildren(t.nodeTag,[...s instanceof e.builder.source.constructor?s.getNodes().map(f=>f.nodeTag):[],i]);let a=Ct(t,i),l=Object.entries(a).filter(([,f])=>f.required);if(e.SET(".insertion",new x),e.SET(".insertion.parentPath",r),e.SET(".insertion.tag",i),!l.length){this.applyInsert(e);return}let c=Us(e,"InsertFields");c.getValue(!0).clear();let u=e.builder.wrapSource(c);u.p(`Insert ${i} into ${t.label} [${t.nodeTag}]`,{class:"visual-editor-hint"});let d=u.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[f,h]of l)this.parameterField(e,d,i,f,h,"insertion",h.default);e.SET(".insertionOpen",!0)}showProperties(e,{path:t}){let r=Us(e,"EditorFields");if(r.getValue(!0).clear(),e.SET(".propertyError",""),e.SET(".properties",new x),!t){e.SET(".propertiesOpen",!1);return}let n=e.builder.source.getNode(`${te(e)}.${t}`);if(!n){e.SET(".propertiesOpen",!1);return}let i=n.parentNode,s=Ct(i,n.nodeTag,n);e.SET(".properties.path",t),this.attributeRows(e,n),e.SET(".propertiesTitle",`${n.label} [${n.nodeTag}]`),e.SET(".propertiesHeight",`${Math.min(300,Math.max(180,80+Math.ceil(Object.keys(s).filter(f=>Xc(f,new Set)==="general").length/2)*38))}px`);let a=e.builder.wrapSource(r);t!=="pageRoot"&&a.p(t,{class:"visual-editor-destination"});let l=new Set(Object.keys(i._getMeta("gramlot_component")?.childParameters??{})),c=new Map(Hc.map(([f])=>[f,[]]));for(let f of Object.entries(s))c.get(Xc(f[0],l)).push(f);e.SET(".parameterTab",Hc.find(([f])=>c.get(f).length)[0]);let u=a.tabContainer({selectedPage:`^${Oe(e)}.parameterTab`,class:"visual-parameter-tabs",tabMode:"underline",height:"100%",min_height:0,flex:1});for(let[f,h]of Hc){if(!c.get(f).length)continue;let p=u.contentPane({pageName:f,title:h,overflow:"auto",padding:"4px",min_height:0,...f==="styles"?{nodeId:Q(e).getAttr("visualEditorId")+"StyleAttributes"}:{}});if(f==="styles"){this.attributeFields(e,p,n,"styles");continue}f==="container"&&p.p(`Child parameters of ${i.nodeTag}`,{class:"visual-editor-hint"}),f==="behaviour"&&Object.hasOwn(s,"action")&&p.p("action: use a named Logic method, for example openCatalogue.",{class:"visual-editor-hint"}),f==="behaviour"&&n.nodeTag==="borderContainer"&&p.p("persist remembers splitter sizes and requires a stable container id.",{class:"visual-editor-hint"});let m=p.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});f==="general"&&n._getMeta("gramlot_component")?.labelbox&&this.labelboxFields(e,m,n,s);let b,w=([,_])=>{let v=Array.isArray(_.dtype)?_.dtype:[_.dtype];return!_.enum&&!v.some(E=>Vs.includes(E))?2:_.dtype==="B"?1:0};for(let[_,v]of[...c.get(f)].sort((E,D)=>w(E)-w(D))){if(n._getMeta("gramlot_component")?.labelbox&&/^(lbl|box)(_|$)/.test(_))continue;let E=m;if(f==="validation"&&/(_if|_error|_warning|_iswarning)$/.test(_)){if(!b){let k=p.details({class:"visual-validation-advanced"});k.summary("Conditions and messages"),b=k.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"})}E=b}let D=_==="_text"?n.getValue(!0):n.getAttr(_);this.parameterField(e,E,n.nodeTag,_,v,"properties",D??v.default)}}let d=u.contentPane({nodeId:Q(e).getAttr("visualEditorId")+"MoreAttributes",pageName:"attributes",title:"More attributes",overflow:"auto",padding:"4px",min_height:0});this.attributeFields(e,d,n),e.SET(".propertiesOpen",!0)}attributeRows(e,t){let r=new x;for(let[n,i]of Object.entries(t.getAttr())){if(n==="_meta")continue;let s=Uc(i),a=s?qs(i,s):"[non-scalar value]";r.setItem(`r${r.length}`,new x({name:n,type:s??"readonly",text:a,original:a}))}e.SET(".properties.attributeRows",r),e.SET(".properties.attributeDraft",new x({name:"",type:"string",text:""})),e.SET(".properties.attributeDraftHidden",!0)}attributeFields(e,t,r,n="attributes"){let i=e.GET(".properties.path"),s=`${Oe(e)}.properties`,a=e.rootBuilder.binding.gramlot.src.renderer,l=new Set(Object.keys(r.parentNode._getMeta("gramlot_component")?.childParameters??{})),c=t.div({class:"visual-editor-attribute-list","aria-label":n==="styles"?"Style attributes":"Node attributes"}),u=c.div({class:"visual-editor-attribute-row visual-editor-attribute-heading"});u.span("Attribute",{class:"visual-editor-attribute-name"});let d=u.div({class:"visual-editor-attribute-value"});d.span("Value"),d.button("+",{action:"beginAttribute",editingPath:i,"aria-label":n==="styles"?"Add style attribute":"Add attribute",title:"Add attribute",class:"visual-editor-attribute-command"});for(let b of e.GET(".properties.attributeRows").getNodes()){let w=b.value.getItem("name"),_=b.value.getItem("type"),v=b.label;if(n==="styles"&&Xc(w,l)!=="styles"&&!a._isStyleContribution(w))continue;let E=_!=="readonly",D=c.div({class:"visual-editor-attribute-row"});D.span(w,{class:"visual-editor-attribute-name",title:w});let k=D.div({class:"visual-editor-attribute-value"});k.input({value:`^${s}.attributeRows.${v}.text`,disabled:!E,"aria-label":`${w} attribute value`,title:E?_:"Non-scalar values are read-only"}),k.button("\xD7",{action:"removeAttribute",attributeRow:v,editingPath:i,disabled:!E,"aria-label":`Remove ${w} attribute`,title:`Remove ${w}`,class:"visual-editor-attribute-command"}),E&&n==="attributes"&&D.dataController({func:"changeAttribute",value:`^${s}.attributeRows.${v}.text`,attributeRow:v,editingPath:i,_userChanges:!0})}let f=c.div({class:"visual-editor-attribute-row",hidden:`^${s}.attributeDraftHidden`,connect_onkeydown:"attributeDraftKey"});f.div({class:"visual-editor-attribute-name"}).input({value:`^${s}.attributeDraft.name`,live:!0,"aria-label":"New attribute name",placeholder:"Attribute name"});let p=f.div({class:"visual-editor-attribute-value"});p.input({value:`^${s}.attributeDraft.text`,live:!0,"aria-label":"New attribute value",placeholder:"Value"});let m=p.select({value:`^${s}.attributeDraft.type`,"aria-label":"New attribute type"});for(let b of xh)m.option(b,{value:b});p.button("\u2713",{action:"addAttribute",editingPath:i,"aria-label":"Apply new attribute",title:"Apply (Enter)",class:"visual-editor-attribute-command"}),p.button("\xD7",{action:"cancelAttribute","aria-label":"Cancel new attribute",title:"Cancel (Escape)",class:"visual-editor-attribute-command"})}beginAttribute(e,{editingPath:t}){let r=Q(e);t===r.GET(".selection")&&(r.SET(".properties.attributeDraft",new x({name:"",type:"string",text:""})),r.SET(".properties.attributeDraftHidden",!1),r.SET(".propertyError",""))}cancelAttribute(e){Q(e).SET(".properties.attributeDraftHidden",!0)}attributeDraftKey(e,t){if(t.isComposing||!["Enter","Escape"].includes(t.key))return;t.preventDefault(),t.stopPropagation();let r=Q(e);t.key==="Escape"?this.cancelAttribute(r):this.addAttribute(r,{editingPath:r.GET(".properties.path")})}addAttribute(e,{editingPath:t}){let r=Q(e);if(t===r.GET(".selection")){r.SET(".propertyError","");try{let n=r.GET(".properties.attributeDraft"),i=n.getItem("name");if(!i||!/^[^\s"'<>/=]+$/.test(i))throw new Error("Enter a valid attribute name.");if(["_meta","__proto__","constructor","prototype"].includes(i))throw new Error("Unsupported attribute name.");let s=r.builder.source.getNode(`${te(r)}.${t}`);if(!s)throw new Error("The selected Source node no longer exists");if(Object.hasOwn(s.getAttr(),i))throw new Error(`Duplicate attribute: ${i}`);let a=Vc(n.getItem("type"),String(n.getItem("text")??""));this.writeAttribute(r,s,t,i,a,!1)}catch(n){r.SET(".propertyError",n.message)}}}changeAttribute(e,{attributeRow:t,editingPath:r,value:n}){this.editAttribute(e,{attributeRow:t,editingPath:r,value:n,remove:!1})}removeAttribute(e,{attributeRow:t,editingPath:r}){this.editAttribute(e,{attributeRow:t,editingPath:r,remove:!0})}editAttribute(e,{attributeRow:t,editingPath:r,value:n,remove:i}){let s=Q(e);if(r===s.GET(".selection")){s.SET(".propertyError","");try{let a=s.GET(".properties.attributeRows").getItem(t);if(!a||a.getItem("type")==="readonly")throw new Error("This attribute is not editable");let l=a.getItem("name");if(["_meta","__proto__","constructor","prototype"].includes(l))throw new Error("Unsupported attribute name.");let c=s.builder.source.getNode(`${te(s)}.${r}`);if(!c)throw new Error("The selected Source node no longer exists");let u=c.getAttr(),d=Uc(u[l]);if(!Object.hasOwn(u,l)||d!==a.getItem("type")||qs(u[l],d)!==a.getItem("original"))throw new Error("Attribute changed; select the node again before editing.");let f=i?null:Vc(d,String(n??""));this.writeAttribute(s,c,r,l,f,i,a)}catch(a){s.SET(".propertyError",a.message)}}}writeAttribute(e,t,r,n,i,s,a=null){let l={...t.getAttr()};s?delete l[n]:l[n]=i;let c=Ct(t.parentNode,t.nodeTag,t);c[n]&&this.validateParameter(t.parentNode,t,n,c[n],s?null:i);let u=e.builder.source.getNode(te(e)),d=e.rootBuilder.binding.gramlot,f=d.src.prepareSource(u.getValue(!0).toTytx(),u.builder);if(f.getNode(r).setAttr(l,!0,!1,!1),tt(e.GET(".catalogueScope"),f),d.src.renderer.validateCandidate(f,{replacingNode:u}),t.setAttr(l,!0,!1,!1),a&&!s){let h=qs(i,a.getItem("type"));a.setItem("original",h),a.setItem("text",h);let p=e.GET(`.properties.types.${n}`);c[n]?.enum?e.SET(`.properties.parameters.${n}`,i):p&&e.SET(`.properties.parameters.${n}.${p}`,i)}else{let h=e.GET(".parameterTab")==="styles"?"styles":"attributes";this.showProperties(e,{path:r}),e.SET(".parameterTab",h)}}toggleLabelboxAttributes(e,{prefix:t}){e.SET(`.properties.${t}Hidden`,!e.GET(`.properties.${t}Hidden`))}labelboxFields(e,t,r,n){for(let i of["lbl","box"]){let s=i==="lbl"?"Label":"Box",a=t.div({class:"visual-labelbox-section",grid_column:"1 / -1"}),l=a.div({class:"visual-labelbox-heading"});i==="lbl"?this.parameterField(e,l,r.nodeTag,"lbl",n.lbl,"properties",r.getAttr("lbl")):l.span(s,{class:"visual-labelbox-title"}),l.button({iconSrc:Ce.properties,title:`Edit ${s.toLowerCase()} attributes`,"aria-label":`Edit ${s.toLowerCase()} attributes`,class:"button--quiet",action:"toggleLabelboxAttributes",prefix:i});let c=Object.entries(n).filter(([f])=>f.startsWith(i+"_"));e.SET(`.properties.${i}Hidden`,!0),e.SET(`.properties.${i}Attribute`,"");let u=a.div({class:"visual-labelbox-attribute",hidden:`^${Oe(e)}.properties.${i}Hidden`}),d=u.select({"aria-label":`${s} attribute`,value:`^${Oe(e)}.properties.${i}Attribute`});d.option("Which attribute?",{value:""});for(let[f]of c)d.option(f.slice(i.length+1),{value:f});u.div({node_label:"attributeValue"}).span(""),u.dataController({func:"renderLabelboxAttribute",_init:!0,parameterName:`^${Oe(e)}.properties.${i}Attribute`,editingPath:e.GET(".properties.path")})}}renderLabelboxAttribute(e,{parameterName:t,editingPath:r}){let n=e.parentBag.getNode("attributeValue");if(n.getValue(!0).clear(),!t||r!==e.GET(".selection"))return;let i=e.builder.source.getNode(`${te(e)}.${r}`),s=Ct(i.parentNode,i.nodeTag,i)[t];this.parameterField(e,e.builder.wrapSource(n),i.nodeTag,t,s,"properties",i.getAttr(t)??s.default,!0)}parameterField(e,t,r,n,i,s,a,l=!1){let c=n==="lbl"?"Label":n==="_text"&&e.builder.schema[r]._meta?.gramlot_component?.command?"caption":n==="_text"?"Text":n,u=`${Oe(e)}.${s}.parameters.${n}`;if(i.enum){e.SET(u,a??"");let b=t.select({lbl:l?null:c,lbl_position:"TL",value:`^${u}`,"aria-label":n});b.option("",{value:""});for(let w of i.enum)b.option(String(w),{value:w});s==="properties"&&t.dataController({func:"changeProperty",value:`^${u}`,_userChanges:!0,parameterName:n,editingPath:e.GET(".properties.path")});return}let d=Array.isArray(i.dtype)?i.dtype:i.dtype?[i.dtype]:[],f=d.filter(b=>Vs.includes(b));if(!f.length){t.p(`${c}: no editor is available for this declared type`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}let h="";if(a==null?h=f.length===1?f[0]:"":typeof a=="boolean"&&f.includes("B")?h="B":typeof a=="string"&&f.includes("T")?h="T":typeof a=="number"?h=f.find(b=>["L","R","N"].includes(b))??"":a instanceof Date?h=f.find(b=>["D","H"].includes(b))??"":f.length===1&&f[0]==="N"&&(h="N"),a!=null&&!h){t.p(`${c}: the current value is not editable with these scalar types`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}e.SET(`${Oe(e)}.${s}.types.${n}`,h);for(let b of f)e.SET(`${u}.${b}`,b===h?a??null:null);let p=!l&&(d.length>1||/^(tooltip|_text|action|placeholder|value)$|(_error|_warning|_if)$/.test(n)),m=t.div({class:"visual-parameter-field",grid_column:p?"1 / -1":"auto",grid_template_columns:d.length>1?"minmax(100px, 1fr) minmax(0, 2fr)":"minmax(0, 1fr)",align_items:"start"});if(d.length>1){let b=m.select({lbl:`${c} type`,lbl_position:"TL",value:`^${Oe(e)}.${s}.types.${n}`,"aria-label":`${n} type`});b.option("Not set",{value:""});for(let w of d)b.option(Vs.includes(w)?w:`${w} (unavailable)`,{value:w,disabled:!Vs.includes(w)});s==="properties"&&m.dataController({func:"changePropertyType",type:`^${Oe(e)}.${s}.types.${n}`,_userChanges:!0,parameterName:n,editingPath:e.GET(".properties.path")})}m.div({node_label:"input"}).span(""),m.dataController({func:"renderParameterInput",_init:!0,type:`^${Oe(e)}.${s}.types.${n}`,parameterName:n,parameterLabel:c,scope:s,compact:l,multiple:d.length>1})}renderParameterInput(e,{type:t,parameterName:r,parameterLabel:n,scope:i,multiple:s,compact:a}){let l=e.parentBag.getNode("input");if(l.getValue(!0).clear(),!t)return;let c=e.builder.wrapSource(l),u=s?`${n} (${t})`:n,d=`^${Oe(e)}.${i}.parameters.${r}.${t}`,f={lbl:a?null:u,lbl_position:"TL",value:d,"aria-label":u};if(t==="B")c.checkbox(f);else if(["L","R","N"].includes(t))c.numberTextBox({...f,dtype:t});else if(t==="D")c.dateTextBox(f);else if(t==="H")c.timeTextBox(f);else if(t==="T"&&/^(lbl|box)_color$/.test(r))c.colorpicker(f);else if(t==="T")c.textbox(f);else throw new Error(`No parameter editor for ${t}`);i==="properties"&&c.dataController({func:"changeProperty",value:d,_userChanges:!0,parameterName:r,editingPath:e.GET(".properties.path")})}changePropertyType(e,{type:t,parameterName:r,editingPath:n}){this.changeProperty(e,{parameterName:r,editingPath:n,value:t?e.GET(`.properties.parameters.${r}.${t}`):null})}changeProperty(e,{value:t,parameterName:r,editingPath:n}){if(n===e.GET(".selection")){e.SET(".propertyError","");try{let i=e.builder.source.getNode(`${te(e)}.${n}`);if(!i)throw new Error("The selected Source node no longer exists");if(r!=="_text"&&Object.is(i.getAttr(r),t))return;let a=Ct(i.parentNode,i.nodeTag,i)[r];if(!a)throw new Error(`Unknown parameter: ${r}`);if(this.validateParameter(i.parentNode,i,r,a,t),r==="_text")i.setValue(t??"");else{let l={...i.getAttr()};t==null||t===""?delete l[r]:l[r]=t,i.setAttr(l,!0,!1,!1)}this.attributeRows(e,i);for(let[l,c]of[["MoreAttributes","attributes"],["StyleAttributes","styles"]]){let u=Us(e,l);u.getValue(!0).clear(),this.attributeFields(e,e.builder.wrapSource(u),i,c)}}catch(i){e.SET(".propertyError",i.message)}}}validateParameter(e,t,r,n,i){let s=i==null||i==="";if(n.required&&s)throw new Error(`Choose ${r}`);if(!s&&n.enum&&!n.enum.includes(i))throw new Error(`Invalid ${r}`);let a=e.getValue(!0);if(!s&&n.unique&&a instanceof e.builder.source.constructor&&a.getNodes().some(l=>l!==t&&l.getAttr(r)===i))throw new Error(`${r} is already in use`)}validateCatalogueTag(e,t){let r=Q(e).GET(".catalogueScope");if(!vn(r,t,e.builder.schema[t]?._meta??{}))throw new Error(`Tag ${t} is outside the editor catalogue`)}applyInsert(e){if(e.GET(".insertion.clipboard")){this.finishPaste(e);return}let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${te(e)}.${t}`);if(!r)throw new Error("The target Source node is no longer available");let n=e.GET(".insertion.tag");this.validateCatalogueTag(e,n);let i={};for(let[a,l]of Object.entries(Ct(r,n)).filter(([,c])=>c.required)){let c=e.GET(`.insertion.types.${a}`),u=e.GET(`.insertion.parameters.${a}${l.enum?"":c?"."+c:""}`);this.validateParameter(r,null,a,l,u),i[a]=u}let s=r.builder.commandOnNode(r,n,null,i);e.SET(".insertionOpen",!1),e.SET(".selection",`${t}.${s.label}`)}};var Kc={};ee(Kc,{libraries:()=>Hs,loadLibrary:()=>Th});var Zc=(o,e,t)=>`https://cdn.jsdelivr.net/npm/${o}@${e}/${t}`,Hs=Object.freeze({echarts:Object.freeze({packages:{echarts:"6.1.0"},local:"echarts/dist/echarts.esm.min.mjs",url:Zc("echarts","6.1.0","dist/echarts.esm.min.mjs"),integrity:"sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt",format:"module"}),echartsGl:Object.freeze({packages:{"echarts-gl":"2.1.0"},local:"echarts-gl/dist/echarts-gl.min.js",url:null,integrity:null,format:"script",global:"echarts-gl"}),uplot:Object.freeze({packages:{uplot:"1.6.32"},local:"uplot/dist/uPlot.esm.js",url:Zc("uplot","1.6.32","dist/uPlot.esm.js"),integrity:"sha384-iUdBlEO5qc07+gOz+3rq/Besyud+KVIxM+xJEuUBObxLG3C/Dlkz8OYuPUcPrCGP",format:"module"}),uplotStyle:Object.freeze({packages:{uplot:"1.6.32"},local:"uplot/dist/uPlot.min.css",url:Zc("uplot","1.6.32","dist/uPlot.min.css"),integrity:"sha384-IfV0B7MIOYuO95kO9G5ySKPz/85zqFNOAs8iy4tkK5zd9izhJAB8b7lHrwYqqmYE",format:"style"}),plotly:Object.freeze({packages:{"plotly.js-dist-min":"4.2.0"},local:"plotly.js-dist-min",url:null,integrity:null,format:"module"}),vega:Object.freeze({packages:{vega:"6.4.0"},local:"vega",url:null,integrity:null,format:"module"}),writeExcelFile:Object.freeze({packages:{"write-excel-file":"4.1.1"},local:"write-excel-file/browser",url:null,integrity:null,format:"module"}),jodit:Object.freeze({packages:{jodit:"4.18.10"},local:"./components/jodit-engine.js",url:null,integrity:null,format:"module"}),codemirror:Object.freeze({packages:{"@codemirror/autocomplete":"6.20.4","@codemirror/commands":"6.11.1","@codemirror/lang-css":"6.3.1","@codemirror/lang-html":"6.4.12","@codemirror/lang-javascript":"6.2.5","@codemirror/lang-json":"6.0.2","@codemirror/lang-markdown":"6.5.2","@codemirror/lang-python":"6.2.1","@codemirror/lang-sql":"6.10.0","@codemirror/lang-xml":"6.1.0","@codemirror/language":"6.13.1","@codemirror/lint":"6.9.7","@codemirror/search":"6.7.2","@codemirror/state":"6.7.6","@codemirror/view":"6.43.15","@lezer/highlight":"1.2.5","codemirror-lang-typst":"0.6.0"},local:"./components/code-mirror-engine.js",url:null,integrity:null,format:"module"}),prosemirror:Object.freeze({packages:{"prosemirror-commands":"1.6.2","prosemirror-history":"1.4.1","prosemirror-keymap":"1.2.2","prosemirror-markdown":"1.13.1","prosemirror-model":"1.25.12","prosemirror-state":"1.4.3","prosemirror-view":"1.42.6"},local:"./components/prose-mirror-engine.js",url:null,integrity:null,format:"module"}),typst:Object.freeze({packages:{"@myriaddreamin/typst.ts":"0.7.0","@myriaddreamin/typst-ts-web-compiler":"0.7.0","@myriaddreamin/typst-ts-renderer":"0.7.0"},local:"./components/typst-client.js",url:null,integrity:null,format:"module"})});async function Th(o,e,t){if(!Object.hasOwn(Hs,o))throw new Error(`Unknown third-party library: ${o}`);let r=Hs[o],n=r.url!==null&&e.documentElement.getAttribute("data-gramlot-library-source")==="cdn";if(r.format==="style"){if(!n)return(await t()).default;let s=await e.defaultView.fetch(r.url,{integrity:r.integrity});if(!s.ok)throw new Error(`${o}: ${r.url} answered ${s.status}`);return s.text()}let i=n?await import(r.url):await t();return r.format==="script"?e.defaultView[r.global]:i}var qw=Object.freeze({"@genrojs/bag":Za,"@genrojs/builders":rl,"@genrojs/toolbox":Ll,"@genrojs/tytx":Ua,"decimal.js":xa,"@msgpack/msgpack":Mn,dompurify:_c,"./random-id.js":nl,"./format.js":_l,"./libraries.js":Kc,"./media-frame.js":Nc,"./validation-run.js":kl,"./renderer/attributes.js":xl,"./view/labelbox.js":ll,"./stores/column-filter.js":Bl,"./stores/collection-filter.js":zl,"./stores/id-set.js":Wl,"./stores/bag-collection-store.js":Gl,"./stores/bag-collection-view.js":Xl,"./components/bases.js":gl,"./components/choices.js":ol,"./components/choice-field-styles.js":ul,"./components/field-state.js":Ic,"./components/grid-formulas.js":Ql,"./components/grid-structure.js":tc,"./components/labelbox.js":vc,"./components/parameters.js":hl,"./components/popup.js":bl,"./components/validation.js":Sc});export{x as Bag,qe as BagNode,Oc as BrowserCameraProvider,ml as ChoiceGroup,Dn as CommandRegistry,Xt as ComponentCollection,No as DeviceHandler,Mo as DirectoryResolver,Do as DomHandler,Es as Exposed,Ac as FieldState,Lo as FileSystemController,Rr as FileSystemLogic,wn as FramePage,Ro as Gramlot,me as GramlotBuilder,Sr as GramlotHtmlRenderer,Io as GramlotRenderer,uo as GramlotSvgRenderer,Ne as Handler,Nn as HttpTransport,Cs as IdeLogic,Oo as InOut,Ts as IndexLogic,Bo as IndexPage,js as Labelbox,Cn as MobileEnvironment,pl as NativeControl,yc as NavigationResolver,Po as Page,ic as PageBootstrap,Jn as References,pr as RpcError,Qn as RpcHandler,Rt as ServerAdapter,Co as SourceHandler,Os as SourceImport,Ho as SourcePicker,Fo as TreeStore,Ds as TreeStoreLogic,tr as TreeStoreResolver,_n as UploadTarget,$o as UtilitiesHandler,Ns as VisualEditor,Yc as VisualEditorLogic,Mc as chatCompleted,Fc as chatPickAttachments,zc as chatRemoveAttachment,jc as chatRender,qc as chatRenderAttachments,Bc as chatReset,Lc as chatResize,Pc as chatSend,Ss as codeMirrorWithOptions,_h as collectionBuildId,mh as createDOMPurify,Ye as createDecimal,fl as defineCollection,Yt as defineComponent,Hf as fileSystemTree,j as fromTytx,La as fromTytxIter,Hs as libraries,Th as loadLibrary,Ow as loadMarkdown,ac as mountIndexPage,wo as parseDateExpression,qw as sharedModules,Z as sourceTarget,R as toTytx,Bw as verifyCollectionArtifact,Q as visualEditorScope};
1780
+ `};function Q(o){for(let e=o;e;e=e.parentNode)if(e.getAttr("visualEditorId"))return e;throw new Error("Operation requires a VisualEditor Source ancestor")}function te(o){return Q(o).fullpath.split(".").slice(1).join(".")+".layout.center.design"}function Oe(o){return Q(o).absDatapath(".")}function Vs(o,e){return o.rootBuilder.binding.nodeIds.get(Q(o).getAttr("visualEditorId")+e)}var kh=[["html.structure","Structure","main header footer nav section article aside div address search"],["html.text","Text and headings","h1 h2 h3 h4 h5 h6 hgroup p span a b strong i em small s u mark abbr cite code pre blockquote q br wbr hr time data dfn kbd samp var bdi bdo ruby rt rp sub sup ins del_"],["html.lists","Lists","ul ol li dl dt dd"],["html.forms","Forms","form input textarea select selectedcontent option optgroup datalist label fieldset legend output progress meter html_button"],["html.tables","Tables","table caption colgroup col thead tbody tfoot tr th td"],["html.media","Media and embedded content","img picture source audio video track canvas iframe embed object param map area"],["html.interaction","Disclosure and menus","details summary html_dialog html_menu"],["html.document","Document and metadata","html head body title base meta link style script noscript template slot"],["components.layout.containers","Containers","borderContainer contentPane framePane stackContainer tabContainer"],["components.layout.windows","Windows","dialog floatingPane"],["components.layout.composition","Composition","formlet groupBox trayPane transformPane"],["components.inputs.text","Text","textbox textBoxArea passwordbox"],["components.inputs.choices","Choices","checkbox radioButton radioButtonText checkBoxText filteringSelect comboBox callbackSelect dbSelect dbComboBox"],["components.inputs.numbers","Numbers and colors","numberTextBox horizontalSlider verticalSlider colorpicker"],["components.inputs.dates","Dates and times","dateTextBox timeTextBox dateCalendar"],["components.commands","Buttons and menus","button toggleButton dropDownButton menu menuline spacer"],["components.data","Trees and grids","tree grid searchBox"],["components.editors","Editors and previews","codeMirror htmlEditor htmlPreview markdownEditor markdownPreview typstPreview"]],zw={html:"HTML",components:"Gramlot","components.layout":"Layout","components.inputs":"Inputs"},Hs=Object.fromEntries(["class","style","width","height","padding","margin","color","background"].map(o=>[o,{dtype:"T",nullable:!0}])),Eh=Object.fromEntries(["lbl_","box_"].flatMap(o=>Object.entries(Hs).map(([e,t])=>[o+e,t]))),Xc=[["general","General"],["behaviour","Behaviour"],["validation","Validation"],["styles","Styles"],["container","Container"]],Ws=["T","B","L","R","N","D","H"];function Yc(o,e){return/^(lbl|box)(_|$)/.test(o)?"general":e.has(o)?"container":o.startsWith("validate_")?"validation":Object.hasOwn(Hs,o)||/^(icon|tab)/.test(o)||["design","labelPosition","switch_color","orientation"].includes(o)?"styles":/^(on[A-Z]|get[A-Z]|drag|drop)/.test(o)||["action","command","disabled","readonly","live","beforeClose","open","collapsed","closable","movable","resizable","collapsible","maximizable","maximized","persist","autoCollapse","openOnClick"].includes(o)?"behaviour":"general"}var Ct=(o,e,t=null)=>{let r=o.builder.schema[e];if(!r)throw new Error(`Unknown widget: ${e}`);let n=r._meta?.gramlot_component;return{...(!t||!(t.getValue(!0)instanceof t.builder.source.constructor))&&(!n||n.command&&!Object.hasOwn(n.parameters,"caption"))?{_text:{dtype:"T",nullable:!0}}:{},...Hs,...n?.labelbox?Eh:{},...n?.parameters??{},...o._getMeta("gramlot_component")?.childParameters??{}}},Gs=new WeakMap,Yo=new WeakMap,Zc=class{chatRender(e,t){return Pc(this.page,e,t)}chatCompleted(e,t){Lc(this.page,e,t),e.GET(`${Oe(e)}.assistant.active`)&&e.SET(".pending",!0)}chatReset(e){return Mc(this.page,e)}chatResize(e){return Fc(this.page,e)}chatPickAttachments(e){return zc(this.page,e)}chatRenderAttachments(e,t){return qc(this.page,e,t)}chatRemoveAttachment(e){return Uc(this.page,e)}chatSend(e){if(e.GET(".pending")||!e.GET(".conversation.ready")||!e.GET(".draft")?.trim())return;let t=Q(e),r=t.GET(".editingMode"),n=e.builder.source.getNode(te(e)).value.toTytx(),i=r==="code"?t.GET(".codeDocument.content"):n;if(r==="code"&&!t.GET(".codeDocument.writable")){e.SET(".error","Page code editing is disabled by the host");return}let s=(t.GET(".assistantRun.run")??0)+1,a=t.GET(".catalogueScope"),l={commonParameters:Hs,labelboxParameters:Eh,widgets:{}};for(let[c,u]of Object.entries(e.builder.schema)){if(!vn(a,c,u._meta??{})||u._meta?.data_element||u._meta?.subbuilder||u._meta?.container)continue;let d=u._meta?.gramlot_component;l.widgets[c]={parameters:d?.parameters??{},labelbox:!!d?.labelbox,childParameters:d?.childParameters??{}}}return t.SET(".assistantRun",new x({run:s,mode:r,next:0,expected:i,blocked:!1})),t.SET(".assistantStatus","Waiting for editing instructions\u2026"),t.SET(".assistant.context",new x({run:s,mode:r,language:t.GET(".codeDocument.language")??null,codeWritable:t.GET(".codeDocument.writable")===!0,code:r==="code"?i:null,source:n,selected:t.GET(".selection"),schema:JSON.stringify(l)})),Bc(this.page,e)}assistantState(e,{active:t}){if(t===!1){e.SET(`${Oe(e)}.chat.pending`,!1);let r=Q(e);r.GET(".assistantRun.next")===0&&r.SET(".assistantStatus","")}}assistantApply(e,{operations:t}){if(!(t instanceof x))return;let r=Q(e);for(let n of t.getNodes()){if(n.attr.run!==r.GET(".assistantRun.run")||n.attr.index<r.GET(".assistantRun.next"))continue;let i=e.builder.source.getNode(te(e)).value,s=r.GET(".assistantRun.mode"),a=s==="code"?r.GET(".codeDocument.content"):i.toTytx(),l=!1,c=!1,u="";try{if(r.GET(".assistantRun.blocked"))throw c=!0,new Error("The document was replaced during editing");if(n.attr.index!==r.GET(".assistantRun.next"))throw c=!0,new Error("Editing sequence is incomplete");if(a!==r.GET(".assistantRun.expected"))throw c=!0,new Error("Source changed during the request. Remaining edits stopped; send a new instruction.");let d=JSON.parse(n.value);if(s==="code"){if(d.operation!=="replace_code"||typeof d.content!="string")throw new Error("Expected a Page code draft operation");if(!r.GET(".codeDocument.writable")||r.GET(".codeDocument.busy"))throw new Error("Page code draft is not editable now");r.SET(".codeDocument.content",d.content),r.SET(".codeDocument.status","AI draft \xB7 Save to apply"),r.SET(".codeOpen",!0)}else this.applySourceEdit(r,d);l=!0,r.SET(".assistantRun.expected",s==="code"?r.GET(".codeDocument.content"):i.toTytx()),r.SET(".assistantStatus",`Applied ${n.attr.index+1}: ${s==="code"?"Page code draft":d.operation+" "+d.path}`)}catch(d){u=d.message,(s==="code"?r.GET(".codeDocument.content"):i.toTytx())!==a&&(c=!0),r.SET(".assistantRun.blocked",c),r.SET(".assistantStatus",`${c?"Editing stopped":"Rejected"}: ${u}`)}r.SET(".assistantRun.next",n.attr.index+1),r.SET(".assistant.ack",new x({run:n.attr.run,index:n.attr.index,applied:l,stop:c,error:u,mode:s,code:s==="code"?r.GET(".codeDocument.content"):null,source:i.toTytx(),selected:r.GET(".selection")}))}}applySourceEdit(e,t){let{operation:r,path:n,parent:i,tag:s,label:a,attributes:l={},text:c}=t,u=v=>typeof v=="string"&&/^pageRoot(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(v);if(!u(n)||r==="move"&&!u(i))throw new Error(`Use dot-separated paths inside pageRoot: ${JSON.stringify(n)}`);if(!["insert","update","remove","move"].includes(r))throw new Error("Unknown Source editing operation");if(["remove","move"].includes(r)&&n==="pageRoot")throw new Error("The page root is protected");if(r==="insert"&&(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a)))throw new Error("Choose an explicit node label");if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Expected scalar attributes");for(let[v,E]of Object.entries(l))if(v.startsWith("_")||/^(connect_|on[A-Z]|script$|formula$|action$|func$|remote_)/.test(v)||["constructor","prototype"].includes(v)||E!==null&&typeof E=="object"||typeof E=="string"&&(E.startsWith("==")||E.includes(":=")))throw new Error(`Unsupported generated attribute: ${v}`);if(c!==void 0&&typeof c!="string")throw new Error("Text must be literal text");let d=e.builder.source.getNode(te(e)),f=e.rootBuilder.binding.gramlot,h=f.src.prepareSource(d.value.toTytx(),d.builder),p=h.getNode(n);if(!p)throw new Error("The Source target no longer exists");let m=p;if(r==="insert"){if(!e.builder.schema[s]||["script","style","iframe","object","embed"].includes(s)||e.builder.schema[s]._meta?.data_element)throw new Error("Choose a visual widget from the catalogue");if(p.value instanceof h.constructor&&p.value.getNode(a))throw new Error("This node label is already in use");m=p.builder.commandOnNode(p,s,c??null,{...l,node_label:a})}else if(r==="update"){if(c!==void 0&&p.value instanceof h.constructor)throw new Error("Text cannot replace a populated container");let v={...p.getAttr()};for(let[E,D]of Object.entries(l))D===null?delete v[E]:v[E]=D;p.setAttr(v,!0,!1,!1),c!==void 0&&p.setValue(c)}else if(r==="remove")p.parentBag.popNode(p.label);else{if(Object.keys(l).length||c!==void 0)throw new Error("Move and property edits must be separate operations");if(i===n||i.startsWith(n+"."))throw new Error("Cannot move a node into itself");let v=h.getNode(i);if(!v)throw new Error("The destination no longer exists");if(v.value instanceof h.constructor&&v.value.getNode(p.label))throw new Error("The destination already contains this label");m=this.appendBranch(v,p,p.label)}let b=v=>{if(v.value instanceof h.constructor){v.builder.validateChildren(v.nodeTag,v.value.getNodes().map(E=>E.nodeTag));for(let E of v.value.getNodes()){for(let[D,k]of Object.entries(Ct(v,E.nodeTag,E)))this.validateParameter(v,E,D,k,E.getAttr(D));b(E)}}};h.getNodes().forEach(b),tt(Q(e).GET(".catalogueScope"),h),f.src.renderer.validateCandidate(h,{replacingNode:d});let w=e.builder.source.getNode(`${te(e)}.${n}`),_=n;r==="insert"?(this.appendBranch(w,m,a),_=`${n}.${a}`):r==="update"?(w.setAttr({...m.getAttr()},!0,!1,!1),c!==void 0&&w.setValue(c)):r==="remove"?(_=n.slice(0,n.lastIndexOf(".")),w.parentBag.popNode(w.label)):(this.applyDrop(e,{item:e.builder.source.getNode(`${te(e)}.${i}`),path:i,dropValues:{"app/source":{path:n}}}),_=`${i}.${w.label}`),e.SET(".sourceSearch",""),e.SET(".selection",_)}initializeCanvasSelection(e){let t=e.rootBuilder.binding.renderer,r=e.builder.source.getNode(te(e)),n=Q(e),i=n.GET(".canvasCss");i!=null&&this.applyCanvasCss(n,i);let s=Gs.get(r);s?.dispose();let a=new Xo({renderer:t,root:r,...Yo.has(r)?{canvas:Yo.get(r).body}:{},onSelect:l=>{e.SET(".sourceSearch",""),e.SET(".selection",l.fullpath.slice(r.fullpath.length+1))}});Gs.set(r,a),s||t.onDispose(r.parentNode,()=>{Gs.delete(r),Yo.delete(r)}),this.highlightSelection(e)}applyCanvasCss(e,t){if(!Array.isArray(t)||t.some(s=>typeof s!="string"))throw new TypeError("canvas CSS must be a list of CSS texts");let r=Q(e),n=r.builder.source.getNode(te(r)),i=Yo.get(n);i||(i=new Us({app:r.rootBuilder.binding.gramlot,editor:r,design:n}),Yo.set(n,i)),i.setCss(t)}setCanvasCss(e,t){let r=Q(e);this.applyCanvasCss(r,t),r.SET(".canvasCss",t),this.initializeCanvasSelection(r)}highlightSelection(e){let t=e.builder.source.getNode(te(e)),r=e.GET(".selection");Gs.get(t)?.select(r?t.staticValue.getNode(r):null)}clipboardShortcut(e,t){if(t.defaultPrevented||t.repeat||e.GET(".clipboardOpen")||e.GET(".insertionOpen")||e.GET(".uploadOpen")||t.composedPath().some(i=>i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)))return;let r=t.key.toLowerCase(),n=r==="f8"?"cutBranch":r==="f9"?"pasteBranch":null;!n||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),this[n](e))}clipboardModifiers(e,t){e.SET(".clipboardDropEffect",t.altKey?"copy":"move")}cutBranch(e){this.beginClipboard(e,e.GET(".selection"),!1)}copyBranch(e){this.beginClipboard(e,e.GET(".selection"),!0)}dropClipboard(e,{dropValues:t,dropEffect:r}){this.beginClipboard(e,t["app/source"].path,r==="copy")}prepareClipboard(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","copy"),r["app/clipboard"]={path:t}}branchSnapshot(e,t){let r=e.builder.source.getNode(te(e)),i=e.rootBuilder.binding.gramlot.src.prepareSource(r.getValue(!0).toTytx(),r.builder).getNode(t);if(!i)throw new Error("The Source branch no longer exists");let s=l=>{if(l.resolver)throw new Error("Resolver-backed branches cannot be stored in this trial");l.value instanceof e.builder.source.constructor&&l.value.getNodes().forEach(s)};s(i);let a=new e.builder.source.constructor(null,i.builder);return i.parentBag.popNode(i.label),a.setItem(i.label,i.getValue(!0),{...i.getAttr()},">",!1,!1,"editor",!1,!0,null,i.nodeTag),a.toTytx()}beginClipboard(e,t,r){e.SET(".error","");try{if(!t||t==="pageRoot")throw new Error("Choose a branch below the page root");let n=e.builder.source.getNode(`${te(e)}.${t}`);if(!n)throw new Error("The Source branch no longer exists");let i=this.branchSnapshot(e,t);e.SET(".clipboardDraft",new x({path:t,copy:r,name:n.label,wire:i,parentTag:n.parentNode.nodeTag})),e.SET(".clipboardOpen",!0)}catch(n){e.SET(".error",n.message)}}saveClipboard(e){e.SET(".error","");try{let t=e.GET(".clipboardDraft.name")?.trim();if(!t)throw new Error("Choose a name for the branch");let r=e.GET(".clipboardDraft.path"),n=e.GET(".clipboardDraft.wire"),i=e.GET(".clipboardDraft.copy"),s=e.builder.source.getNode(`${te(e)}.${r}`);if(!i&&(!s||this.branchSnapshot(e,r)!==n))throw new Error("The branch changed; select it again before cutting");let a=e.GET(".clipboard"),l=1;for(;a.getNode(`branch_${l}`);)l++;let c=`branch_${l}`;a.setItem(c,n,{name:t,parentTag:e.GET(".clipboardDraft.parentTag")}),e.SET(".clipboardSelection",c),e.SET(".clipboardVisible",!0),i||(e.SET(".selection",r.slice(0,r.lastIndexOf("."))),s.parentBag.popNode(s.label)),e.SET(".clipboardOpen",!1),e.SET(".fileStatus",`${i?"Copied":"Cut"}: ${t}`)}catch(t){e.SET(".error",t.message)}}pasteBranch(e){e.SET(".error","");try{this.beginPaste(e,e.GET(".clipboardSelection"),e.GET(".selection"))}catch(t){e.SET(".error",t.message)}}beginPaste(e,t,r){let n=t?e.GET(".clipboard").getNode(t):null;if(!n)throw new Error("Choose a saved branch in the clipboard");let i=r?e.builder.source.getNode(`${te(e)}.${r}`):null;if(!i)throw new Error("Choose a destination in the Source tree");let s=e.rootBuilder.binding.gramlot.src.prepareSource(n.getValue(!0),i.builder);tt(Q(e).GET(".catalogueScope"),s);let a=s.getNodes()[0];i.builder.validateParent(a.nodeTag,i.nodeTag);let l=i.getValue(!0);i.builder.validateChildren(i.nodeTag,[...l instanceof e.builder.source.constructor?l.getNodes().map(w=>w.nodeTag):[],a.nodeTag]);let c={...a.getAttr()},u=i.builder.schema[a.nodeTag]._meta?.gramlot_component?.parameters??{},d=i.builder.schema[n.getAttr("parentTag")]?._meta?.gramlot_component?.childParameters??{};for(let w of Object.keys(d))w in u||delete c[w];a.setAttr(c,!0,!1,!1),e.SET(".insertion",new x({parentPath:r,tag:a.nodeTag,clipboard:s.toTytx()}));let f=Ct(i,a.nodeTag),h=Object.entries(f).filter(([w,_])=>_.required&&(c[w]==null||c[w]===""||_.unique));if(!h.length){this.finishPaste(e);return}let p=Vs(e,"InsertFields");p.getValue(!0).clear();let m=e.builder.wrapSource(p);m.p(`Paste ${n.getAttr("name")} into ${i.label} [${i.nodeTag}]`,{class:"visual-editor-hint"});let b=m.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[w,_]of h)this.parameterField(e,b,a.nodeTag,w,_,"insertion",_.default);e.SET(".insertionOpen",!0)}appendBranch(e,t,r){let n=e.builder.source.constructor,i=e.getValue(!0);if(!(i instanceof n)){let s=i;i=new n(null,e.builder),e.builder.promoteNodeValue(e,s,i)}return t.parentBag.popNode(t.label),i.setItem(r,t.getValue(!0),{...t.getAttr()},">",!1,!1,"editor",!1,!0,null,t.nodeTag),i.getNode(r)}finishPaste(e){let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${te(e)}.${t}`);if(!r)throw new Error("The destination no longer exists");let n=e.rootBuilder.binding.gramlot,i=n.src.prepareSource(e.GET(".insertion.clipboard"),r.builder);tt(Q(e).GET(".catalogueScope"),i);let s=i.getNodes()[0],a={...s.getAttr()};for(let[b,w]of Object.entries(Ct(r,s.nodeTag))){if(!w.required)continue;let _=e.GET(`.insertion.types.${b}`),v=e.GET(`.insertion.parameters.${b}${w.enum?"":_?"."+_:""}`);v!=null&&(a[b]=v),this.validateParameter(r,null,b,w,a[b])}s.setAttr(a,!0,!1,!1);let l=r.getValue(!0),c=s.label,u=1;for(;l instanceof e.builder.source.constructor&&l.getNode(c);)c=`${s.label}_${u++}`;let d=e.builder.source.getNode(te(e)),f=n.src.prepareSource(d.getValue(!0).toTytx(),d.builder),h=f.getNode(t);h.builder.validateParent(s.nodeTag,h.nodeTag);let p=h.getValue(!0);h.builder.validateChildren(h.nodeTag,[...p instanceof e.builder.source.constructor?p.getNodes().map(b=>b.nodeTag):[],s.nodeTag]);let m=this.appendBranch(h,s,c);tt(Q(e).GET(".catalogueScope"),f),n.src.renderer.validateCandidate(f,{replacingNode:d}),this.appendBranch(r,m,c),e.SET(".insertionOpen",!1),e.SET(".sourceSearch",""),e.SET(".selection",`${t}.${c}`),e.SET(".fileStatus","Branch pasted")}openCode(e){let t=Q(e);t.SET(".codeOpen",!0),t.SET(".editingMode","code")}async codeSave(e){let t=Q(e),r=t.GET(".codeDocument");if(r.getItem("busy")||!r.getItem("writable"))return;let n=r.getItem("content"),i=r.getItem("revision"),s=!1;if(n===r.getItem("saved"))return;let a=new AbortController,l=this.page.src.renderer.onDispose(t,()=>a.abort());r.setItem("busy",!0),r.setItem("status","Saving Page code\u2026");let c=t.value.getNode("layout.center.design"),u=c.value.toTytx();try{let d=await this.page.rpc.call("data","editor_document_save",{key:t.getAttr("codeDocumentKey"),content:n,revision:i},{signal:a.signal});if(a.signal.aborted)return;r.setItem("revision",d.revision),r.setItem("saved",n),s=!0,r.setItem("status","Page code saved"),u!==c.value.toTytx()?r.setItem("status","Page code saved; Source changed meanwhile. Use Preview saved to replace it."):await this.codeLoadPreview(t,a)}catch(d){a.signal.aborted||r.setItem("status",`${s?"Page code saved; preview failed":"Save failed"}: ${d.message}`)}finally{l(),a.signal.aborted||r.setItem("busy",!1)}}async codePreview(e){let t=Q(e),r=t.GET(".codeDocument");if(r.getItem("busy"))return;let n=new AbortController,i=this.page.src.renderer.onDispose(t,()=>n.abort());r.setItem("busy",!0);try{await this.codeLoadPreview(t,n)}catch(s){n.signal.aborted||r.setItem("status",`Preview failed: ${s.message}`)}finally{i(),n.signal.aborted||r.setItem("busy",!1)}}async codeLoadPreview(e,t){let r=e.GET(".codeDocument"),n=e.value.getNode("layout.center.design"),i=n.value.toTytx(),s=await this.page.rpc.call("source","editor_document_preview",{key:e.getAttr("codeDocumentKey"),revision:r.getItem("revision"),data_root:e.GET(".dataRoot")},{signal:t.signal});if(t.signal.aborted)return;if(n.value.toTytx()!==i)throw new Error("Source changed while preparing preview; it was retained");let a=this.page.src.prepareSource(s,n.builder);tt(e.GET(".catalogueScope"),a),this.page.src.renderer.validateCandidate(a,{replacingNode:n}),e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),n.setValue(a,!0,{_text:null},!0),e.SET(".selection","pageRoot"),r.setItem("status",r.getItem("content")===r.getItem("saved")?"Saved Page code \xB7 preview updated":"Preview updated from saved page code; newer draft retained")}newPage(e){e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),e.SET(".insertionOpen",!1),e.SET(".error","");let t=e.builder.source.getNode(te(e));t.getValue(!0).clear();let r=e.GET(".dataRoot");if(r)e.SET(r,new x);else for(let n of e.rootBuilder.data.getNodes())n.label!=="__editor"&&e.rootBuilder.data.popNode(n.label);e.builder.wrapSource(t).div({node_label:"pageRoot",...r?{datapath:r}:{}}),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".sourceSearch",""),e.SET(".dataSearch",""),e.SET(".selection","pageRoot")}async copySource(e){e.SET(".fileStatus","");try{await e.rootBuilder.binding.gramlot.utl.inout.copyText(this.currentSource(e)),e.SET(".fileStatus","Source copied")}catch(t){e.SET(".fileStatus",`Copy failed: ${t.message}`)}}downloadPage(e){e.rootBuilder.binding.gramlot.utl.inout.saveText(this.currentSource(e),e.GET(".filename"),"application/json")}openUpload(e){e.SET(".uploadOpen",!0)}sourceUploaded(e,{item:t,result:r}){try{this.loadSource(e,{source:r,filename:t.value.getItem("name")}),e.SET(".fileStatus","Source opened"),e.SET(".uploadOpen",!1)}catch(n){throw e.SET(".fileStatus",`Open failed: ${n.message}`),n}}initializeDocument(e){let t=Q(e),r=t.builder.source,n=te(t).split("."),i=`${t.getAttr("visualEditorId")}-document`;t.SET(".modified",!1),r.subscribe(i,{any:s=>{n.every((a,l)=>s.pathlist[l]===a)&&t.SET(".modified",!0)}}),t.rootBuilder.binding.renderer.onDispose(t,()=>r.unsubscribe(i,{any:!0}))}currentSource(e){let t=Q(e);return t.builder.source.getNode(te(t)).getValue(!0).toTytx()}markSaved(e){Q(e).SET(".modified",!1)}loadSource(e,{source:t,filename:r}){let n=Q(e);if(typeof t!="string")throw new TypeError("source must be Source TYTX");if(typeof r!="string"||!r.trim())throw new TypeError("filename must be a non-empty string");let i=n.rootBuilder.binding.gramlot,s=n.builder.source.getNode(te(n)),a=i.src.prepareSource(t,s.builder),l=a.getNodes();if(l.length!==1||l[0].label!=="pageRoot")throw new Error("Expected one pageRoot Source");tt(n.GET(".catalogueScope"),a),i.src.renderer.validateCandidate(a,{replacingNode:s}),n.GET(".assistantRun")&&n.SET(".assistantRun.blocked",!0),n.SET(".selection",null),s.setValue(a,!0,{_text:null},!0),n.SET(".filename",r),n.SET(".insertionOpen",!1),n.SET(".sourceSearch",""),n.SET(".selection","pageRoot"),this.markSaved(n)}toggleNavigation(e){e.SET(".navigationOpen",e.GET(".navigationOpen")==="close"?!0:"close")}openCatalogue(e){e.SET(`${Oe(e)}.catalogueOpen`,!0)}openProperties(e){this.showProperties(e,{path:e.GET(".selection")})}sourceLabel(e,{item:t}){return{text:`${t.label} [${t.nodeTag}]`}}dropNode(e,t){e.SET(".error","");try{this.applyDrop(e,t)}catch(r){e.SET(".error",r.message)}}insertWidget(e){e.SET(".error","");try{this.applyInsert(e)}catch(t){e.SET(".error",t.message)}}initializeEditorAppearance(e){let t=Q(e),r=e.rootBuilder.binding.renderer.destination.ownerDocument;t.SET(".appearanceProfile","compact"),t.SET(".appearancePalette","joanna"),t.SET(".appearanceMode",r.documentElement.getAttribute("data-theme")||"dark")}applyEditorAppearance(e,{profile:t,palette:r,mode:n}){if(!t||!r||!n)return;if(!Object.hasOwn(Gc,t)||!Object.hasOwn(Hc,r)||!["light","dark"].includes(n))throw new Error("Choose a declared theme, palette and color mode");Q(e).SET(".appearanceCss",Gc[t]+`
1781
+ `+Hc[r]),e.rootBuilder.binding.renderer.destination.ownerDocument.documentElement.setAttribute("data-theme",n)}initializeEditor(e,{dataRoot:t}){let r=e.GET(".catalogueScope");if(yn(r),Array.isArray(r)){for(let a of r)if(!e.builder.schema[a])throw new Error(`Unknown catalogue tag: ${a}`)}if(e.SET(".editingMode","source"),e.SET(".clipboard",new x),e.SET(".clipboardVisible",!1),e.SET(".clipboardDropEffect","move"),e.SET(".sourceDropEffect","move"),e.SET(".dataRoot",t),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".selection","pageRoot"),t)e.GET(t)==null&&e.SET(t,new x);else{let a=Oe(e),l=a.split(".").map(()=>"#parent").join(".");e.builder.source.getNode(te(e)).setAttr({datapath:`${a}.${l}`})}let n=new x,i=new Map([["",n]]),s=(a,l)=>{if(i.has(a))return i.get(a);let c=a.split("."),u=c.pop(),d=c.join("."),f=s(d,zw[d]),h=new x;return f.setItem(u,h,{caption:l}),i.set(a,h),h};for(let[a,l,c]of kh)c.split(" ").some(u=>e.builder.schema[u]&&vn(r,u,e.builder.schema[u]._meta??{}))&&s(a,l);for(let[a,l]of Object.entries(e.builder.schema).sort(([c],[u])=>c.localeCompare(u))){if(!vn(r,a,l._meta??{})||l._meta?.data_element||l._meta?.subbuilder||l._meta?.container)continue;let c=l._meta?.gramlot_component?"components":"html",u=kh.find(([f,,h])=>f.startsWith(c+".")&&h.split(" ").includes(a)),d=u?u[0]:`${c}.other`;s(d,u?u[1]:"Other elements").setItem(a,null,{caption:a,tag:a})}e.SET(".catalogue",n)}prepareWidget(e,{item:t,dragValues:r}){if(e.SET(".sourceDropEffect","copy"),!t.attr.tag)return!1;r["app/widget"]={tag:t.attr.tag}}prepareSource(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","move"),r["app/source"]={path:t}}applyDrop(e,{item:t,path:r,dropValues:n}){if(n["app/clipboard"]){this.beginPaste(e,n["app/clipboard"].path,r);return}if(n["app/source"]){let f=`${te(e)}.${n["app/source"].path}`,h=`${te(e)}.${r}`,p=e.builder.source.getNode(f);if(!p||f===`${te(e)}.pageRoot`)throw new Error("The page root cannot be moved");if(tt(Q(e).GET(".catalogueScope"),p.parentBag),p.resolver)throw new Error("Resolver-backed Source nodes cannot be moved in this trial");if(f===h||h.startsWith(f+"."))throw new Error("A node cannot be moved into itself");let m=t,b=p.parentBag,w=e.builder.source.constructor;if(p.builder!==m.builder)throw new Error("Nodes cannot cross builder dialects");let _=m.getValue(!0),v=_ instanceof w?_.getNodes().filter(D=>D!==p):[];if(_ instanceof w&&_!==b&&_.getNode(p.label))throw new Error("The target already contains this label");let E=m._getMeta("gramlot_component")?.childParameters??{};for(let[D,k]of Object.entries(E)){let C=p.getAttr(D);if(k.required&&C==null)throw new Error(`The moved node requires ${D}`);if(k.enum&&C!=null&&!k.enum.includes(C))throw new Error(`Invalid ${D}`);if(k.unique&&C!=null&&v.some(O=>O.getAttr(D)===C))throw new Error(`${D} is already in use`)}if(m.builder.validateParent(p.nodeTag,m.nodeTag),m.builder.validateChildren(m.nodeTag,[...v.map(D=>D.nodeTag),p.nodeTag]),_===b)b.move(b.getNodes().indexOf(p),v.length);else{let D=_ instanceof w?_:new w(null,m.builder);_ instanceof w||m.builder.promoteNodeValue(m,_,D);let k={label:p.label,tag:p.nodeTag,value:p.getValue(!0),attrs:{...p.getAttr()}};b.popNode(k.label),D.setItem(k.label,k.value,k.attrs,D.getNodes().length,!1,!1,"editor",!1,!0,null,k.tag)}e.SET(".selection",`${r}.${p.label}`);return}let i=n["app/widget"].tag;this.validateCatalogueTag(e,i),t.builder.validateParent(i,t.nodeTag);let s=t.getValue(!0);t.builder.validateChildren(t.nodeTag,[...s instanceof e.builder.source.constructor?s.getNodes().map(f=>f.nodeTag):[],i]);let a=Ct(t,i),l=Object.entries(a).filter(([,f])=>f.required);if(e.SET(".insertion",new x),e.SET(".insertion.parentPath",r),e.SET(".insertion.tag",i),!l.length){this.applyInsert(e);return}let c=Vs(e,"InsertFields");c.getValue(!0).clear();let u=e.builder.wrapSource(c);u.p(`Insert ${i} into ${t.label} [${t.nodeTag}]`,{class:"visual-editor-hint"});let d=u.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[f,h]of l)this.parameterField(e,d,i,f,h,"insertion",h.default);e.SET(".insertionOpen",!0)}showProperties(e,{path:t}){let r=Vs(e,"EditorFields");if(r.getValue(!0).clear(),e.SET(".propertyError",""),e.SET(".properties",new x),!t){e.SET(".propertiesOpen",!1);return}let n=e.builder.source.getNode(`${te(e)}.${t}`);if(!n){e.SET(".propertiesOpen",!1);return}let i=n.parentNode,s=Ct(i,n.nodeTag,n);e.SET(".properties.path",t),this.attributeRows(e,n),e.SET(".propertiesTitle",`${n.label} [${n.nodeTag}]`),e.SET(".propertiesHeight",`${Math.min(300,Math.max(180,80+Math.ceil(Object.keys(s).filter(f=>Yc(f,new Set)==="general").length/2)*38))}px`);let a=e.builder.wrapSource(r);t!=="pageRoot"&&a.p(t,{class:"visual-editor-destination"});let l=new Set(Object.keys(i._getMeta("gramlot_component")?.childParameters??{})),c=new Map(Xc.map(([f])=>[f,[]]));for(let f of Object.entries(s))c.get(Yc(f[0],l)).push(f);e.SET(".parameterTab",Xc.find(([f])=>c.get(f).length)[0]);let u=a.tabContainer({selectedPage:`^${Oe(e)}.parameterTab`,class:"visual-parameter-tabs",tabMode:"underline",height:"100%",min_height:0,flex:1});for(let[f,h]of Xc){if(!c.get(f).length)continue;let p=u.contentPane({pageName:f,title:h,overflow:"auto",padding:"4px",min_height:0,...f==="styles"?{nodeId:Q(e).getAttr("visualEditorId")+"StyleAttributes"}:{}});if(f==="styles"){this.attributeFields(e,p,n,"styles");continue}f==="container"&&p.p(`Child parameters of ${i.nodeTag}`,{class:"visual-editor-hint"}),f==="behaviour"&&Object.hasOwn(s,"action")&&p.p("action: use a named Logic method, for example openCatalogue.",{class:"visual-editor-hint"}),f==="behaviour"&&n.nodeTag==="borderContainer"&&p.p("persist remembers splitter sizes and requires a stable container id.",{class:"visual-editor-hint"});let m=p.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});f==="general"&&n._getMeta("gramlot_component")?.labelbox&&this.labelboxFields(e,m,n,s);let b,w=([,_])=>{let v=Array.isArray(_.dtype)?_.dtype:[_.dtype];return!_.enum&&!v.some(E=>Ws.includes(E))?2:_.dtype==="B"?1:0};for(let[_,v]of[...c.get(f)].sort((E,D)=>w(E)-w(D))){if(n._getMeta("gramlot_component")?.labelbox&&/^(lbl|box)(_|$)/.test(_))continue;let E=m;if(f==="validation"&&/(_if|_error|_warning|_iswarning)$/.test(_)){if(!b){let k=p.details({class:"visual-validation-advanced"});k.summary("Conditions and messages"),b=k.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"})}E=b}let D=_==="_text"?n.getValue(!0):n.getAttr(_);this.parameterField(e,E,n.nodeTag,_,v,"properties",D??v.default)}}let d=u.contentPane({nodeId:Q(e).getAttr("visualEditorId")+"MoreAttributes",pageName:"attributes",title:"More attributes",overflow:"auto",padding:"4px",min_height:0});this.attributeFields(e,d,n),e.SET(".propertiesOpen",!0)}attributeRows(e,t){let r=new x;for(let[n,i]of Object.entries(t.getAttr())){if(n==="_meta")continue;let s=Vc(i),a=s?qs(i,s):"[non-scalar value]";r.setItem(`r${r.length}`,new x({name:n,type:s??"readonly",text:a,original:a}))}e.SET(".properties.attributeRows",r),e.SET(".properties.attributeDraft",new x({name:"",type:"string",text:""})),e.SET(".properties.attributeDraftHidden",!0)}attributeFields(e,t,r,n="attributes"){let i=e.GET(".properties.path"),s=`${Oe(e)}.properties`,a=e.rootBuilder.binding.gramlot.src.renderer,l=new Set(Object.keys(r.parentNode._getMeta("gramlot_component")?.childParameters??{})),c=t.div({class:"visual-editor-attribute-list","aria-label":n==="styles"?"Style attributes":"Node attributes"}),u=c.div({class:"visual-editor-attribute-row visual-editor-attribute-heading"});u.span("Attribute",{class:"visual-editor-attribute-name"});let d=u.div({class:"visual-editor-attribute-value"});d.span("Value"),d.button("+",{action:"beginAttribute",editingPath:i,"aria-label":n==="styles"?"Add style attribute":"Add attribute",title:"Add attribute",class:"visual-editor-attribute-command"});for(let b of e.GET(".properties.attributeRows").getNodes()){let w=b.value.getItem("name"),_=b.value.getItem("type"),v=b.label;if(n==="styles"&&Yc(w,l)!=="styles"&&!a._isStyleContribution(w))continue;let E=_!=="readonly",D=c.div({class:"visual-editor-attribute-row"});D.span(w,{class:"visual-editor-attribute-name",title:w});let k=D.div({class:"visual-editor-attribute-value"});k.input({value:`^${s}.attributeRows.${v}.text`,disabled:!E,"aria-label":`${w} attribute value`,title:E?_:"Non-scalar values are read-only"}),k.button("\xD7",{action:"removeAttribute",attributeRow:v,editingPath:i,disabled:!E,"aria-label":`Remove ${w} attribute`,title:`Remove ${w}`,class:"visual-editor-attribute-command"}),E&&n==="attributes"&&D.dataController({func:"changeAttribute",value:`^${s}.attributeRows.${v}.text`,attributeRow:v,editingPath:i,_userChanges:!0})}let f=c.div({class:"visual-editor-attribute-row",hidden:`^${s}.attributeDraftHidden`,connect_onkeydown:"attributeDraftKey"});f.div({class:"visual-editor-attribute-name"}).input({value:`^${s}.attributeDraft.name`,live:!0,"aria-label":"New attribute name",placeholder:"Attribute name"});let p=f.div({class:"visual-editor-attribute-value"});p.input({value:`^${s}.attributeDraft.text`,live:!0,"aria-label":"New attribute value",placeholder:"Value"});let m=p.select({value:`^${s}.attributeDraft.type`,"aria-label":"New attribute type"});for(let b of xh)m.option(b,{value:b});p.button("\u2713",{action:"addAttribute",editingPath:i,"aria-label":"Apply new attribute",title:"Apply (Enter)",class:"visual-editor-attribute-command"}),p.button("\xD7",{action:"cancelAttribute","aria-label":"Cancel new attribute",title:"Cancel (Escape)",class:"visual-editor-attribute-command"})}beginAttribute(e,{editingPath:t}){let r=Q(e);t===r.GET(".selection")&&(r.SET(".properties.attributeDraft",new x({name:"",type:"string",text:""})),r.SET(".properties.attributeDraftHidden",!1),r.SET(".propertyError",""))}cancelAttribute(e){Q(e).SET(".properties.attributeDraftHidden",!0)}attributeDraftKey(e,t){if(t.isComposing||!["Enter","Escape"].includes(t.key))return;t.preventDefault(),t.stopPropagation();let r=Q(e);t.key==="Escape"?this.cancelAttribute(r):this.addAttribute(r,{editingPath:r.GET(".properties.path")})}addAttribute(e,{editingPath:t}){let r=Q(e);if(t===r.GET(".selection")){r.SET(".propertyError","");try{let n=r.GET(".properties.attributeDraft"),i=n.getItem("name");if(!i||!/^[^\s"'<>/=]+$/.test(i))throw new Error("Enter a valid attribute name.");if(["_meta","__proto__","constructor","prototype"].includes(i))throw new Error("Unsupported attribute name.");let s=r.builder.source.getNode(`${te(r)}.${t}`);if(!s)throw new Error("The selected Source node no longer exists");if(Object.hasOwn(s.getAttr(),i))throw new Error(`Duplicate attribute: ${i}`);let a=Wc(n.getItem("type"),String(n.getItem("text")??""));this.writeAttribute(r,s,t,i,a,!1)}catch(n){r.SET(".propertyError",n.message)}}}changeAttribute(e,{attributeRow:t,editingPath:r,value:n}){this.editAttribute(e,{attributeRow:t,editingPath:r,value:n,remove:!1})}removeAttribute(e,{attributeRow:t,editingPath:r}){this.editAttribute(e,{attributeRow:t,editingPath:r,remove:!0})}editAttribute(e,{attributeRow:t,editingPath:r,value:n,remove:i}){let s=Q(e);if(r===s.GET(".selection")){s.SET(".propertyError","");try{let a=s.GET(".properties.attributeRows").getItem(t);if(!a||a.getItem("type")==="readonly")throw new Error("This attribute is not editable");let l=a.getItem("name");if(["_meta","__proto__","constructor","prototype"].includes(l))throw new Error("Unsupported attribute name.");let c=s.builder.source.getNode(`${te(s)}.${r}`);if(!c)throw new Error("The selected Source node no longer exists");let u=c.getAttr(),d=Vc(u[l]);if(!Object.hasOwn(u,l)||d!==a.getItem("type")||qs(u[l],d)!==a.getItem("original"))throw new Error("Attribute changed; select the node again before editing.");let f=i?null:Wc(d,String(n??""));this.writeAttribute(s,c,r,l,f,i,a)}catch(a){s.SET(".propertyError",a.message)}}}writeAttribute(e,t,r,n,i,s,a=null){let l={...t.getAttr()};s?delete l[n]:l[n]=i;let c=Ct(t.parentNode,t.nodeTag,t);c[n]&&this.validateParameter(t.parentNode,t,n,c[n],s?null:i);let u=e.builder.source.getNode(te(e)),d=e.rootBuilder.binding.gramlot,f=d.src.prepareSource(u.getValue(!0).toTytx(),u.builder);if(f.getNode(r).setAttr(l,!0,!1,!1),tt(e.GET(".catalogueScope"),f),d.src.renderer.validateCandidate(f,{replacingNode:u}),t.setAttr(l,!0,!1,!1),a&&!s){let h=qs(i,a.getItem("type"));a.setItem("original",h),a.setItem("text",h);let p=e.GET(`.properties.types.${n}`);c[n]?.enum?e.SET(`.properties.parameters.${n}`,i):p&&e.SET(`.properties.parameters.${n}.${p}`,i)}else{let h=e.GET(".parameterTab")==="styles"?"styles":"attributes";this.showProperties(e,{path:r}),e.SET(".parameterTab",h)}}toggleLabelboxAttributes(e,{prefix:t}){e.SET(`.properties.${t}Hidden`,!e.GET(`.properties.${t}Hidden`))}labelboxFields(e,t,r,n){for(let i of["lbl","box"]){let s=i==="lbl"?"Label":"Box",a=t.div({class:"visual-labelbox-section",grid_column:"1 / -1"}),l=a.div({class:"visual-labelbox-heading"});i==="lbl"?this.parameterField(e,l,r.nodeTag,"lbl",n.lbl,"properties",r.getAttr("lbl")):l.span(s,{class:"visual-labelbox-title"}),l.button({iconSrc:Ce.properties,title:`Edit ${s.toLowerCase()} attributes`,"aria-label":`Edit ${s.toLowerCase()} attributes`,class:"button--quiet",action:"toggleLabelboxAttributes",prefix:i});let c=Object.entries(n).filter(([f])=>f.startsWith(i+"_"));e.SET(`.properties.${i}Hidden`,!0),e.SET(`.properties.${i}Attribute`,"");let u=a.div({class:"visual-labelbox-attribute",hidden:`^${Oe(e)}.properties.${i}Hidden`}),d=u.select({"aria-label":`${s} attribute`,value:`^${Oe(e)}.properties.${i}Attribute`});d.option("Which attribute?",{value:""});for(let[f]of c)d.option(f.slice(i.length+1),{value:f});u.div({node_label:"attributeValue"}).span(""),u.dataController({func:"renderLabelboxAttribute",_init:!0,parameterName:`^${Oe(e)}.properties.${i}Attribute`,editingPath:e.GET(".properties.path")})}}renderLabelboxAttribute(e,{parameterName:t,editingPath:r}){let n=e.parentBag.getNode("attributeValue");if(n.getValue(!0).clear(),!t||r!==e.GET(".selection"))return;let i=e.builder.source.getNode(`${te(e)}.${r}`),s=Ct(i.parentNode,i.nodeTag,i)[t];this.parameterField(e,e.builder.wrapSource(n),i.nodeTag,t,s,"properties",i.getAttr(t)??s.default,!0)}parameterField(e,t,r,n,i,s,a,l=!1){let c=n==="lbl"?"Label":n==="_text"&&e.builder.schema[r]._meta?.gramlot_component?.command?"caption":n==="_text"?"Text":n,u=`${Oe(e)}.${s}.parameters.${n}`;if(i.enum){e.SET(u,a??"");let b=t.select({lbl:l?null:c,lbl_position:"TL",value:`^${u}`,"aria-label":n});b.option("",{value:""});for(let w of i.enum)b.option(String(w),{value:w});s==="properties"&&t.dataController({func:"changeProperty",value:`^${u}`,_userChanges:!0,parameterName:n,editingPath:e.GET(".properties.path")});return}let d=Array.isArray(i.dtype)?i.dtype:i.dtype?[i.dtype]:[],f=d.filter(b=>Ws.includes(b));if(!f.length){t.p(`${c}: no editor is available for this declared type`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}let h="";if(a==null?h=f.length===1?f[0]:"":typeof a=="boolean"&&f.includes("B")?h="B":typeof a=="string"&&f.includes("T")?h="T":typeof a=="number"?h=f.find(b=>["L","R","N"].includes(b))??"":a instanceof Date?h=f.find(b=>["D","H"].includes(b))??"":f.length===1&&f[0]==="N"&&(h="N"),a!=null&&!h){t.p(`${c}: the current value is not editable with these scalar types`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}e.SET(`${Oe(e)}.${s}.types.${n}`,h);for(let b of f)e.SET(`${u}.${b}`,b===h?a??null:null);let p=!l&&(d.length>1||/^(tooltip|_text|action|placeholder|value)$|(_error|_warning|_if)$/.test(n)),m=t.div({class:"visual-parameter-field",grid_column:p?"1 / -1":"auto",grid_template_columns:d.length>1?"minmax(100px, 1fr) minmax(0, 2fr)":"minmax(0, 1fr)",align_items:"start"});if(d.length>1){let b=m.select({lbl:`${c} type`,lbl_position:"TL",value:`^${Oe(e)}.${s}.types.${n}`,"aria-label":`${n} type`});b.option("Not set",{value:""});for(let w of d)b.option(Ws.includes(w)?w:`${w} (unavailable)`,{value:w,disabled:!Ws.includes(w)});s==="properties"&&m.dataController({func:"changePropertyType",type:`^${Oe(e)}.${s}.types.${n}`,_userChanges:!0,parameterName:n,editingPath:e.GET(".properties.path")})}m.div({node_label:"input"}).span(""),m.dataController({func:"renderParameterInput",_init:!0,type:`^${Oe(e)}.${s}.types.${n}`,parameterName:n,parameterLabel:c,scope:s,compact:l,multiple:d.length>1})}renderParameterInput(e,{type:t,parameterName:r,parameterLabel:n,scope:i,multiple:s,compact:a}){let l=e.parentBag.getNode("input");if(l.getValue(!0).clear(),!t)return;let c=e.builder.wrapSource(l),u=s?`${n} (${t})`:n,d=`^${Oe(e)}.${i}.parameters.${r}.${t}`,f={lbl:a?null:u,lbl_position:"TL",value:d,"aria-label":u};if(t==="B")c.checkbox(f);else if(["L","R","N"].includes(t))c.numberTextBox({...f,dtype:t});else if(t==="D")c.dateTextBox(f);else if(t==="H")c.timeTextBox(f);else if(t==="T"&&/^(lbl|box)_color$/.test(r))c.colorpicker(f);else if(t==="T")c.textbox(f);else throw new Error(`No parameter editor for ${t}`);i==="properties"&&c.dataController({func:"changeProperty",value:d,_userChanges:!0,parameterName:r,editingPath:e.GET(".properties.path")})}changePropertyType(e,{type:t,parameterName:r,editingPath:n}){this.changeProperty(e,{parameterName:r,editingPath:n,value:t?e.GET(`.properties.parameters.${r}.${t}`):null})}changeProperty(e,{value:t,parameterName:r,editingPath:n}){if(n===e.GET(".selection")){e.SET(".propertyError","");try{let i=e.builder.source.getNode(`${te(e)}.${n}`);if(!i)throw new Error("The selected Source node no longer exists");if(r!=="_text"&&Object.is(i.getAttr(r),t))return;let a=Ct(i.parentNode,i.nodeTag,i)[r];if(!a)throw new Error(`Unknown parameter: ${r}`);if(this.validateParameter(i.parentNode,i,r,a,t),r==="_text")i.setValue(t??"");else{let l={...i.getAttr()};t==null||t===""?delete l[r]:l[r]=t,i.setAttr(l,!0,!1,!1)}this.attributeRows(e,i);for(let[l,c]of[["MoreAttributes","attributes"],["StyleAttributes","styles"]]){let u=Vs(e,l);u.getValue(!0).clear(),this.attributeFields(e,e.builder.wrapSource(u),i,c)}}catch(i){e.SET(".propertyError",i.message)}}}validateParameter(e,t,r,n,i){let s=i==null||i==="";if(n.required&&s)throw new Error(`Choose ${r}`);if(!s&&n.enum&&!n.enum.includes(i))throw new Error(`Invalid ${r}`);let a=e.getValue(!0);if(!s&&n.unique&&a instanceof e.builder.source.constructor&&a.getNodes().some(l=>l!==t&&l.getAttr(r)===i))throw new Error(`${r} is already in use`)}validateCatalogueTag(e,t){let r=Q(e).GET(".catalogueScope");if(!vn(r,t,e.builder.schema[t]?._meta??{}))throw new Error(`Tag ${t} is outside the editor catalogue`)}applyInsert(e){if(e.GET(".insertion.clipboard")){this.finishPaste(e);return}let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${te(e)}.${t}`);if(!r)throw new Error("The target Source node is no longer available");let n=e.GET(".insertion.tag");this.validateCatalogueTag(e,n);let i={};for(let[a,l]of Object.entries(Ct(r,n)).filter(([,c])=>c.required)){let c=e.GET(`.insertion.types.${a}`),u=e.GET(`.insertion.parameters.${a}${l.enum?"":c?"."+c:""}`);this.validateParameter(r,null,a,l,u),i[a]=u}let s=r.builder.commandOnNode(r,n,null,i);e.SET(".insertionOpen",!1),e.SET(".selection",`${t}.${s.label}`)}};var Kc={};ee(Kc,{libraries:()=>Xs,loadLibrary:()=>Th});var Tn=(o,e,t)=>`https://cdn.jsdelivr.net/npm/${o}@${e}/${t}`,Xs=Object.freeze({echarts:Object.freeze({packages:{echarts:"6.1.0"},local:"echarts/dist/echarts.esm.min.mjs",url:Tn("echarts","6.1.0","dist/echarts.esm.min.mjs"),integrity:"sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt",format:"module"}),echartsGl:Object.freeze({packages:{"echarts-gl":"2.1.0"},local:"echarts-gl/dist/echarts-gl.min.js",url:null,integrity:null,format:"script",global:"echarts-gl"}),uplot:Object.freeze({packages:{uplot:"1.6.32"},local:"uplot/dist/uPlot.esm.js",url:Tn("uplot","1.6.32","dist/uPlot.esm.js"),integrity:"sha384-iUdBlEO5qc07+gOz+3rq/Besyud+KVIxM+xJEuUBObxLG3C/Dlkz8OYuPUcPrCGP",format:"module"}),uplotStyle:Object.freeze({packages:{uplot:"1.6.32"},local:"uplot/dist/uPlot.min.css",url:Tn("uplot","1.6.32","dist/uPlot.min.css"),integrity:"sha384-IfV0B7MIOYuO95kO9G5ySKPz/85zqFNOAs8iy4tkK5zd9izhJAB8b7lHrwYqqmYE",format:"style"}),xterm:Object.freeze({packages:{"@xterm/xterm":"6.0.0"},local:"@xterm/xterm/lib/xterm.mjs",url:Tn("@xterm/xterm","6.0.0","lib/xterm.mjs"),integrity:"sha384-8Xik+BkzF4UFDtZa8HkUiQ0FE/Xl+03xMuv69uQB3ichDzm8dWs4kPRihQxSZDiY",format:"module"}),xtermFit:Object.freeze({packages:{"@xterm/addon-fit":"0.11.0"},local:"@xterm/addon-fit/lib/addon-fit.mjs",url:Tn("@xterm/addon-fit","0.11.0","lib/addon-fit.mjs"),integrity:"sha384-0/1EW6dUPoaun7dgdlOtb5Wk8x5UQRW6hYM3ihuCCnaA2Xd4HwMFcn378RpxmoAc",format:"module"}),xtermStyle:Object.freeze({packages:{"@xterm/xterm":"6.0.0"},local:"@xterm/xterm/css/xterm.css",url:Tn("@xterm/xterm","6.0.0","css/xterm.css"),integrity:"sha384-n2n7twoohnW+d3myBKaUgl7DSiwidw6MkQy9oesGzkPpMjejKRR3XlnD+5yCdtBD",format:"style"}),plotly:Object.freeze({packages:{"plotly.js-dist-min":"4.2.0"},local:"plotly.js-dist-min",url:null,integrity:null,format:"module"}),vega:Object.freeze({packages:{vega:"6.4.0"},local:"vega",url:null,integrity:null,format:"module"}),writeExcelFile:Object.freeze({packages:{"write-excel-file":"4.1.1"},local:"write-excel-file/browser",url:null,integrity:null,format:"module"}),jodit:Object.freeze({packages:{jodit:"4.18.10"},local:"./components/jodit-engine.js",url:null,integrity:null,format:"module"}),codemirror:Object.freeze({packages:{"@codemirror/autocomplete":"6.20.4","@codemirror/commands":"6.11.1","@codemirror/lang-css":"6.3.1","@codemirror/lang-html":"6.4.12","@codemirror/lang-javascript":"6.2.5","@codemirror/lang-json":"6.0.2","@codemirror/lang-markdown":"6.5.2","@codemirror/lang-python":"6.2.1","@codemirror/lang-sql":"6.10.0","@codemirror/lang-xml":"6.1.0","@codemirror/language":"6.13.1","@codemirror/lint":"6.9.7","@codemirror/search":"6.7.2","@codemirror/state":"6.7.6","@codemirror/view":"6.43.15","@lezer/highlight":"1.2.5","codemirror-lang-typst":"0.6.0"},local:"./components/code-mirror-engine.js",url:null,integrity:null,format:"module"}),prosemirror:Object.freeze({packages:{"prosemirror-commands":"1.6.2","prosemirror-history":"1.4.1","prosemirror-keymap":"1.2.2","prosemirror-markdown":"1.13.1","prosemirror-model":"1.25.12","prosemirror-state":"1.4.3","prosemirror-view":"1.42.6"},local:"./components/prose-mirror-engine.js",url:null,integrity:null,format:"module"}),typst:Object.freeze({packages:{"@myriaddreamin/typst.ts":"0.7.0","@myriaddreamin/typst-ts-web-compiler":"0.7.0","@myriaddreamin/typst-ts-renderer":"0.7.0"},local:"./components/typst-client.js",url:null,integrity:null,format:"module"})});async function Th(o,e,t){if(!Object.hasOwn(Xs,o))throw new Error(`Unknown third-party library: ${o}`);let r=Xs[o],n=r.url!==null&&e.documentElement.getAttribute("data-gramlot-library-source")==="cdn";if(r.format==="style"){if(!n)return(await t()).default;let s=await e.defaultView.fetch(r.url,{integrity:r.integrity});if(!s.ok)throw new Error(`${o}: ${r.url} answered ${s.status}`);return s.text()}let i=n?await import(r.url):await t();return r.format==="script"?e.defaultView[r.global]:i}var Uw=Object.freeze({"@genrojs/bag":Ka,"@genrojs/builders":nl,"@genrojs/toolbox":Fl,"@genrojs/tytx":Va,"decimal.js":ka,"@msgpack/msgpack":Ln,dompurify:yc,"./random-id.js":ol,"./format.js":yl,"./libraries.js":Kc,"./media-frame.js":Oc,"./validation-run.js":El,"./renderer/attributes.js":kl,"./view/labelbox.js":cl,"./stores/column-filter.js":Ml,"./stores/collection-filter.js":Ul,"./stores/id-set.js":Gl,"./stores/bag-collection-store.js":Hl,"./stores/bag-collection-view.js":Yl,"./components/bases.js":bl,"./components/choices.js":il,"./components/choice-field-styles.js":dl,"./components/field-state.js":Cc,"./components/grid-formulas.js":ec,"./components/grid-structure.js":rc,"./components/labelbox.js":xc,"./components/parameters.js":pl,"./components/popup.js":wl,"./components/validation.js":Ac});export{x as Bag,Ue as BagNode,$c as BrowserCameraProvider,gl as ChoiceGroup,Nn as CommandRegistry,Xt as ComponentCollection,Oo as DeviceHandler,Lo as DirectoryResolver,No as DomHandler,Ts as Exposed,Ic as FieldState,Fo as FileSystemController,Rr as FileSystemLogic,wn as FramePage,jo as Gramlot,me as GramlotBuilder,Sr as GramlotHtmlRenderer,Co as GramlotRenderer,fo as GramlotSvgRenderer,Ne as Handler,On as HttpTransport,Ds as IdeLogic,$o as InOut,Ss as IndexLogic,Mo as IndexPage,Ps as Labelbox,Dn as MobileEnvironment,ml as NativeControl,vc as NavigationResolver,Bo as Page,sc as PageBootstrap,Qn as References,pr as RpcError,eo as RpcHandler,Rt as ServerAdapter,Do as SourceHandler,$s as SourceImport,Xo as SourcePicker,zo as TreeStore,Ns as TreeStoreLogic,tr as TreeStoreResolver,_n as UploadTarget,Ro as UtilitiesHandler,Os as VisualEditor,Zc as VisualEditorLogic,Lc as chatCompleted,zc as chatPickAttachments,Uc as chatRemoveAttachment,Pc as chatRender,qc as chatRenderAttachments,Mc as chatReset,Fc as chatResize,Bc as chatSend,As as codeMirrorWithOptions,_h as collectionBuildId,mh as createDOMPurify,Ye as createDecimal,hl as defineCollection,Yt as defineComponent,Hf as fileSystemTree,j as fromTytx,Fa as fromTytxIter,Xs as libraries,Th as loadLibrary,Ow as loadMarkdown,lc as mountIndexPage,_o as parseDateExpression,Uw as sharedModules,Z as sourceTarget,R as toTytx,Bw as verifyCollectionArtifact,Q as visualEditorScope};
1782
1782
  /*! Bundled license information:
1783
1783
 
1784
1784
  decimal.js/decimal.mjs: