markuno_lib 1.2.38 → 1.2.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/marked.js CHANGED
@@ -18,4 +18,4 @@ inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)("])","~|])")(),
18
18
  /**
19
19
  * GFM + Line Breaks Inline Grammar
20
20
  */
21
- inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()});const basealias={s:"subtitle",k:"keywords",g:"gruppo",e:"editore",y:"datapub",d:"datapub",p:"priority",a:"autore",u:"base",t:"title",l:"link",i:"img","#":"title"};const aliasInfo=new class AliasInfo{constructor(){this.alias=JSON.parse(JSON.stringify(basealias)),this.check()}check(){let rr=new Set,checkr=x=>{x&&x.length>2&&!rr.has(x)&&rr.add(x)};for(let x in this.alias)this.alias[x]?(checkr(x),checkr(this.alias[x])):delete this.alias[x];this.retoalias=function retroalias(alias){let retro={};for(let x in alias)alias[x]&&(retro[alias[x]]=x);return retro}(this.alias),rr=[...rr],rr=`^\\s*\\:(${rr.join("|")}|\\w{1,2})\\:(.*)$`,this.regex=rr}add(sigla,valore){return sigla&&(this.alias[sigla]=valore,this.check()),this}removeAll(){return this.alias={},this.check(),this}setmappa(mappa){this.alias={};for(let x in mappa)this.alias[x]=mappa[x];this.alias["#"]||(this.alias["#"]="title"),this.check()}parse(data,info,mappa){mappa&&this.setmappa();let xx=data,res={};info&&(res=Object.assign(res,info),res.info=!0);let rr=/^\s*#\s+(.*?)\s*$/im.exec(xx);rr&&(res[this.alias["#"]]=rr[1].toLowerCase());for(let i=0;i<20;i++){let rr=/:::(.*)([^]+?):::/im.exec(xx);if(!rr)break;{let id=rr[1];id||(id=i+""),res.comments||(res.comments=[]),res.comments.push({k:id,v:rr[2]}),xx=xx.substr(rr.index+rr[0].length)}}xx=data;let regex=new RegExp(this.regex,"im");for(let i=0;i<50;i++){let rr=regex.exec(xx);if(!(rr&&rr.length>=2))break;{xx=xx.substr(rr.index+rr[0].length),res.info=!0;let rr2=(rr[2]||"").trim(),oname=this.alias[rr[1].toLowerCase()];oname||(oname=rr[1].toLowerCase()),"l"==oname||"link"==oname?(res[oname]||(res[oname]=[]),res[oname].push(rr2)):res[oname]=rr2}}return res}};var tokenize=(src,easylen,noheader=!1)=>{function _parsetable(tokens,src){let v2,tb={type:"table",headers:[],align:[],cells:[],cols:0},vv=src.split("\n"),fl=!1;function checkcols(cols){if(tb.cols<cols){for(let i=tb.cols;i<cols;i++){tb.align[i]="left",tb.headers[i]=[];for(let r of tb.cells)r[i]=[]}tb.cols=cols}}for(let v1 of vv)if(v1=v1.trim(),v1.length)if(v1.length>2&&v1.startsWith("|")&&v1.endsWith("|")&&(v1=v1.slice(1,-1)),v2=v1.split("|"),checkcols(v2.length),0==fl&&/^[- :]+\|[- :|]*$/im.test(v1)){for(let i=0;i<v2.length;i++){let v=v2[i],x1=v.slice(0,1),x2=v.slice(-1);tb.align[i]=":"==x1&&":"==x2?"center":":"==x2?"right":"left"}fl=!0}else{let r=[];for(let i=0;i<v2.length;i++){let v=v2[i];if(fl){let t=[];_tokenize(t,v,!1),r.push(t)}else _tokenize(tb.headers[i],v,!1)}fl&&tb.cells.push(r)}tokens.push(tb)}function _pushtoken(tokens,src){let cc=/^([\d.]+)\s*/.exec(src),num="",title="";cc&&(num=cc[1],src=src.substring(cc.index+cc[0].length)),cc=/^([\w\s]*?):.*$/gim.exec(src),cc&&(title=cc[1],src=src.substring(cc.index+cc[1].length)),tokens.push({type:"list_item_start",num:num}),title&&(tokens.push({type:"list_title_start"}),_tokenize(tokens,title,!1),tokens.push({type:"list_title_end"})),src=src.replace(/\n +/gim,"<br>"),_tokenize(tokens,src,!1),tokens.push({type:"list_item_end"})}function _parselista(tokens,ordered,space,src){let counter=[space];for(tokens.push({type:"list_start",ordered:ordered});;){let cap=/^( *)([*\-+])[\s$]/im.exec(src);if(!cap){_pushtoken(tokens,src);break}{cap.index&&_pushtoken(tokens,src.substring(0,cap.index));let sl=cap[1].length;if(sl>counter[counter.length-1])tokens.push({type:"list_start",ordered:ordered}),counter.push(sl);else for(;;){let sp=counter[counter.length-1];if(1==counter.length||sp<=sl)break;tokens.push({type:"list_end"}),counter.pop()}src=src.substring(cap.index+cap[0].length)}}for(let c of counter)tokens.push({type:"list_end"})}const _tokenize=(tokens,src,top,bq)=>{let cap;for(src=src.replace(/^ +$/gm,"");src;){if(easylen){let ll=0;for(let t of tokens)t.text||t.html?ll=ll+t.text.length+2:ll+=3;if(ll>easylen)break}if((cap=rules.newline.exec(src))&&(src=src.substring(cap[0].length),cap[0].length>1&&tokens.push({type:"space"})),cap=rules.formula.exec(src))src=src.substring(cap[0].length),tokens.push({type:"code",lang:"math",text:cap[2]||""});else if(cap=/^(\s*`{3})(.*)([^]+?)(`{3})/gim.exec(src)){cap.index>0&&_tokenize(tokens,src.substring(0,cap.index),top);let txt=(cap[3]||"").replace(/^\n/,"").replace(/\n+$/,"");tokens.push({type:"code",lang:cap[2],text:txt}),src=src.substring(cap.index+cap[0].length)}else if(cap=rules.heading.exec(src))src=src.substring(cap[0].length),tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});else if(top&&(cap=/^(.*?\|.*\n[-: ]+\|[-| :]*\n.*?\|[^]*?)\n\n/gim.exec(src)))cap.index>0&&_tokenize(tokens,src.substring(0,cap.index),top),_parsetable(tokens,cap[1]),src=src.substring(cap.index+cap[0].length);else if(top&&(cap=/^\|.*\|\s*(?:\n\|.*\|)+/gim.exec(src)))cap.index>0&&_tokenize(tokens,src.substring(0,cap.index),top),_parsetable(tokens,cap[0]),src=src.substring(cap.index+cap[0].length);else if(cap=rules.lheading.exec(src))src=src.substring(cap[0].length),tokens.push({type:"heading",depth:"="===cap[2]?1:2,text:cap[1]});else if(cap=rules.hr.exec(src))src=src.substring(cap[0].length),tokens.push({type:"hr"});else if(cap=rules.blockquote.exec(src))src=src.substring(cap[0].length),tokens.push({type:"blockquote_start"}),_tokenize(tokens,cap[0].replace(/^ *> ?/gm,""),top,!0),tokens.push({type:"blockquote_end"});else if(cap=/^[\s-:]*?\|[\s-:|]*/im.exec(src),cap||!(cap=/^( *)([*\-+])[\s$]/im.exec(src))){if(cap=rules.html.exec(src))src=src.substring(cap[0].length),tokens.push({type:"html",pre:"pre"===cap[1]||"script"===cap[1]||"style"===cap[1],text:cap[0]});else if(!bq&&top&&(cap=rules.def.exec(src)))src=src.substring(cap[0].length),tokens.push({type:"code",text:`??${cap[0]}??${rules.def}??`});else if(top&&(cap=rules.paragraph.exec(src)))src=src.substring(cap[0].length),tokens.push({type:"paragraph",text:"\n"===cap[1].charAt(cap[1].length-1)?cap[1].slice(0,-1):cap[1]});else if(cap=rules.text.exec(src))src=src.substring(cap[0].length),tokens.push({type:"text",text:cap[0]});else if(src)throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}else{cap.index>0&&_tokenize(tokens,src.substring(0,cap.index)),src=src.substring(cap.index+cap[0].length);let res=/([^]*?)(\n\n|\n\s*[#>])/im.exec(src+"\n\n");if(res){_parselista(tokens,"*"==cap[2],cap[1].length,res[1]),src=src.substring(res[1].length)}else tokens.push({type:"text??",text:cap[0]})}}return tokens};let rules=block.tables;return src=function removeInfo(src,title=!1){let tm=src.replace(/:::([^]+?):::/gim,"").replace(new RegExp(aliasInfo.regex,"gim"),"").replace(/^\s*#\s+/im,"# ").replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");if(title){const rg=/(^\s*#\s+(.*)?\s*)$/im;let rr=rg.exec(tm);rr&&0==rr.index&&(tm=tm.replace(rg,""))}return tm}(src,noheader),_tokenize([],src,!0)};const controls={string:/(".*?[^\\]"|'.*?[^\\]'|`[^]*?[^\\]`|""|''|``)/m,puntuaction:/(-[-=]?|,|;|\+[+=]?|!=?=?|<<?=?|>>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3})/g,parentesis:/(\(|\)|\[|\]|\{|\})/g,ingraffe:/([^$])(\{)(.*?)(\})/g,regex:/\/.*?[^\\]\/[gimu]*/m,numbers:/\b((?:(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+)n?|\d+n|NaN|Infinity)\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?)/gi,js:{comments:/(?:(?:^|[^\\:])(\/\/.*)|(?:^|[^\\])(\/\*[\s\S]*?(?:\*\/)))/m,keyword:/(\b)(import|require|endif|include|define|float|int|real|char|bool|as|true|false|async|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)(\b)/g,keyword2:/(\.\w+|\w+:)/g},json:{string:/(".*?[^\\]")/m,string1:/(".*?[^\\]"\s*:)/m},html:{script:/(<script[\s\S]*?>)([^]*?)(<\/script>)/im,tag:/<(!DOCTYPE|\/?\w+)([^]*?)(\/?>)/im,intag:/(\b)([\w-]+)(=)/g,comments:/<!--[^]*?-->/im},bash:{comments:/# .*/,keyword1:/(^ *|; *)(\w+)(\b)/g,keyword:/(\b)(sudo *[\w-]+)(\b)/g},mu:{comments:/(?:(?:^|[^\\:])(\/\/.*)|(?:^|[^\\])(\/\*[\s\S]*?(?:\*\/)))/m,keyword1:/(#)(\w+)(\b)/g,keyword2:/(\$\(?(\w+|\.|:|\)))/g},sql:{keyword:".",keyword2:/(\b)(FROM|USING|FTS5|NVARCHAR|INTEGER|REAL|BLOB|DELETE|UPDATE|BEGIN|END|ADD|CREATE|CONSTRAINT|ALTER|COLUMN|TABLE|ALL|ASC|BETWEEN|CASE|CHECK|COLUMN|INDEX|VIEW|PROCEDURE|DESC|DISTINTC|DROP|OUTER|INNER|LEFT|JOIN|INSERT|INTO|[NOT ]*NULL|LIMIT|SELECT|ORDER BY|UNION|WHERE)(\b)/gi,keyword1:/(\b)(COLLATE|NOCASE|DEFAULT|IF [NOT ]*EXISTS|PRIMARY KEY|VALUES|AS)(\b)/gi,comments:/(?:(?:^|[^\\:])(\/\/.*)|(?:^|[^\\])(\/\*[\s\S]*?(?:\*\/))|(--\s.*))/m}};function elang(str,lang,punct,codes){let data;return codes&&(data=codes.length,codes.push(str)),`<pre class="elang relative">${xelang(str,lang,punct)}<div class="absolute top-1 right-1"><button class="mu-internal-copy" data-copy="${data}">📋</button></div></pre>`}const escapeTag=str=>str.replace(/[<>]/g,(tag=>({"<":"&lt;",">":"&gt;"}[tag]))),escapeHTML=str=>str.replace(/[&<>'"]/g,(tag=>({"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"}[tag]))),unescapeHTML=str=>str.replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&gt;/g,">").replace(/&lt;/g,"<");function xelang(str,lang,punct){let gspan=(str,cls)=>(cls&&(cls=cls.replace(/(\b)(\w+)(\b)/g,"$1_$2$3")),`☉☊${cls||""}☊☉${(str=escapeTag(str))||""}☉☋`),regex=code=>{if(controls[lang]){let x=controls[lang][code];if("."==x)return;if(x)return x}let x=controls[code];return"."==x?void 0:x},out=[],r=0,ids=[];if(lang){controls[lang]||(lang="js");let rg=regex("script");if(rg){let st1=[];for(;;){let res=rg.exec(str);if(!res)break;res.index>0&&st1.push(str.substr(0,res.index)),st1.push(`★★K${ids.length}★★`),ids.push(xelang(res[1],lang)+xelang(res[2],"js")+xelang(res[3],lang)),str=str.substr(res.index+res[0].length)}str.length&&st1.push(str),str=st1.join("")}for(let r of[{r:"comments",s:"C"}]){let rg=regex(r.r);if(rg){let st1=[];for(;;){let res=rg.exec(str);if(!res)break;if(res.index>0&&st1.push(str.substr(0,res.index)),st1.push(`★★${r.s}${ids.length}★★`),"html"==lang){let tm=res[0].replace(/</g,"&lt;").replace(/>/g,"&gt;");ids.push(tm)}else ids.push(res[0]);str=str.substr(res.index+res[0].length)}str.length&&st1.push(str),str=st1.join("")}}for(let r of[{r:"string2",s:"A"},{r:"string1",s:"B"},{r:"string",s:"S"},{r:"tag",s:"T"},{r:"regex",s:"R"}]){let rg=regex(r.r);if(rg){let st1=[];for(;;){let res=rg.exec(str);if(!res)break;if(res.index>0&&st1.push(str.substr(0,res.index)),st1.push(`★★${r.s}${ids.length}★★`),"T"==r.s){let tm=res[2].replace(regex("intag"),((p,p1,p2,p3)=>p1+gspan(p2,"intag")+gspan(p3,"punc")));ids.push(gspan("<","punc")+res[1]+tm+gspan(res[3],"punc"))}else if("`"==res[0][0]){let tm=res[0].replace(/(\${)(.*?)(})/gm,((p,p1,p2,p3)=>gspan(p1,"punc")+gspan(p2,"word")+gspan(p3,"punc")));ids.push(tm)}else ids.push(res[0]);str=str.substr(res.index+res[0].length)}str.length&&st1.push(str),str=st1.join("")}}let vv=str.split("\n"),r=0;for(let v of vv)r++,v=v.replace(regex("keyword"),((p,p1,p2,p3)=>gspan(p1,"tag")+gspan(p2,"keys")+p3)).replace(regex("keyword1"),((p,p1,p2,p3)=>p1+gspan(p2,"keys1 keys")+p3)).replace(regex("keyword2"),(p=>gspan(p,"keys2 keys"))).replace(regex("numbers"),(p=>gspan(p,"number"))).replace(regex("ingraffe"),((p,p1,p2,p3,p4)=>p1+gspan(p2,"punc")+gspan(p3,"word")+gspan(p4,"punc"))).replace(regex("puntuaction"),(p=>gspan(p,"punc"))).replace(/★★T(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"tag"))).replace(/★★S(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"string"))).replace(/★★B(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"string string1"))).replace(/★★A(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"string string2"))).replace(/★★R(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"regex"))).replace(/★★C(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"comment"))).replace(/★★K(\d+)★★/gu,((m,p)=>ids[Number(p)])),punct?out.push(gspan((" "+r).substr(-4),"rowid")+gspan(v)):out.push(gspan(v))}else{let vv=str.split("\n");for(let v of vv)r++,punct?out.push(`${gspan((" "+r).substr(-4),"rowid")}${gspan(v)}`):out.push(gspan(v))}let xx=out.join("\n");return xx=xx.replace(/☉☋/gmu,"</span>").replace(/☉☊([^]*?)☊☉/gmu,((p,p1)=>{if(p1){let v1=p1.split(" "),aa=[];for(let v of v1)aa.push(`elang_${lang}${v}`),aa.push(`elang${v}`);return`<span class="${aa.join(" ")}">`}return"<span>"})),xx}class Render{constructor(baseurl,easy,callback){this.baseurl=baseurl,this.easy=easy,this.callback=callback}code(code,lang,codes){if(this.easy)return"";lang||(lang="js");let punct=lang==lang.toUpperCase();return elang(code,lang=lang.toLowerCase(),punct,codes)}blockquote(quote){return this.easy?quote:`<blockquote>\n${quote}</blockquote>\n`}html(html){return html}heading(text,level,raw){return"."==text||"*"==text?"":this.easy?`${text} `:`<h${level}>${text}</h${level}>`}hr(){return this.easy?"":'<div class="my-4"><hr/></div>'}list(body,ordered){let type=ordered?"ol":"ul";return`<${type}>\n${body}</${type}>\n`}listtitle(body){return`<span class="listtitle">${body}</span>`}listitem(text,num){return num?`<li attr-num="${num||""}">${text}</li>\n`:`<li>${text}</li>\n`}paragraph(text){return this.easy?text:`<p>${text}</p>\n`}table(header,body){return this.easy?"":`<table>\n<thead>\n${header}\n</thead>\n<tbody>\n${body}\n</tbody>\n</table>\n\n`}tablerow(content){return`<tr>\n${content}</tr>\n`}tablecell(content,header,align){if(header)return`<th style="text-align:center;">${content}</th>\n`;return`<td style="${align?"text-align:"+align+";":""}">${content}</td>`}colorbase(text){return`<span class='tilde'>${text}</span>`}formula(text,full=!1){if(this.easy)return"";let aa=`<img class='inline px-2' src='https://math.croswil.com/f?${text=text.replace(/<\/?em>/g," ").replace(/\r/g,"").replace("/\n/g"," ")}' alt='${text}'/>`;return full?`<div class='flex justify-center'><div>${aa}</div></div>`:aa}coloralt(text){return`<span class='tilde2'>${text}</span>`}strong(text){return"<strong>"+text+"</strong>"}ico(text){return`<span class="font-ico">${text}</span>`}em(text){return"<em>"+text+"</em>"}codespan(text){return"<code>"+text+"</code>"}br(){return"<br>"}del(text){return`<del>${text}</del>`}link(href,title,text){if(this.easy)return"("+text+")";let out;if("/"==href.substr(0,1)&&this.baseurl&&(href=this.baseurl+href.substr(1)),href.startsWith("!"))out=`<button class="mu-internal-link" data-href="${href=href.slice(1)}">${text}</button>`;else{let target="";href.startsWith(".")?href=href.slice(1):target='target="_blank"',out=`<a ${target} href='${href}' title='${title||""}'>${text}</a>`}return out}image(href,title,text){if(this.easy)return"";let v=text.split("|"),out="",iswebm=!1,ismp4=!1,ismp3=!1;if((href=(href=href.replace("https://www.youtube.com/watch?v=","https://youtu.be/")).replace("https://youtu.be","https://www.youtube.com/embed")).endsWith(".mp3")?(href=href.slice(0,-4),ismp3=!0):href.endsWith(".mp4")?(href=href.slice(0,-4),ismp4=!0):href.endsWith(".webm")?(href=href.slice(0,-5),iswebm=!0):href.endsWith(".video")&&(href=href.slice(0,-6),iswebm=!0,ismp4=!0),ismp3)out=`\n <audio controls ${v.length>=1?' width="'+v[1]+'"':""}\n class="mx-auto my-2 ${v.length>=2?v[2]:""}" \n >\n <source src="${href}.mp3" type="audio/mpeg">\n Il tuo browser non supporta l'elemento audio.\n </audio>\n `;else if(ismp4||iswebm)out=`\n<video ${v.length>=1?' width="'+v[1]+'"':""}\nclass="border rounded-lg shadow-xl ${v.length>=2?v[2]:""}" \ncontrols controlsList="nodownload" >\n ${iswebm?'<source src="'+href+'.webm" type="video/webm" >':""}\n ${ismp4?'<source src="'+href+'.mp4" type="video/mp4" >':""}\n \n Your browser does not support the video tag.\n</video>`;else{if(href.indexOf("https://www.youtu")>=0){let hh=href.split("/embed/")[1]?.split("?")[0];return out=`\n\n<div style="width: 94%; box-shadow: 6px 6px 10px hsl(206.5, 0%, 75%); margin: 3%;">\n <div style="position: relative; padding-bottom: 56.15%; height: 0; overflow: hidden;">\n <iframe \n style="position: absolute; top: 0; left:0; width: 100%; height: 100%; border: 0;"\n loading="lazy";\n srcdoc="<style>\n * {\n padding: 0;\n margin: 0;\n overflow: hidden;\n }\n \n body, html {\n height: 100%;\n }\n \n img, svg {\n position: absolute;\n width: 100%;\n top: 0;\n bottom: 0;\n margin: auto;\n }\n \n svg {\n filter: drop-shadow(1px 1px 10px hsl(206.5, 70.7%, 8%));\n transition: all 250ms ease-in-out;\n }\n \n body:hover svg {\n filter: drop-shadow(1px 1px 10px hsl(206.5, 0%, 10%));\n transform: scale(2);\n }\n </style>\n <a href='https://www.youtube.com/embed/${hh}?autoplay=1'>\n <img src='https://img.youtube.com/vi/${hh}/hqdefault.jpg' alt='${title||"video"}'>\n <svg xmlns='http://www.w3.org/2000/svg' width='64' height='64' viewBox='0 0 24 24' fill='none' stroke='#ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-play-circle'><circle cx='12' cy='12' r='10'></circle><polygon points='10 8 16 12 10 16 10 8'></polygon></svg>\n </a>\n "\n src="https://www.youtube.com/embed/${hh}" \n title="${title||"video"}"\n frameborder="0"\n allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" \n allowfullscreen>\n </iframe>\n </div>\n </div> \n \n`,out}this.callback&&"function"==typeof this.callback&&(href=this.callback({type:"img",href:href})),"/"==href.substr(0,1)&&this.baseurl&&(href=this.baseurl+href.substr(1)),out='<img src="'+href+'" alt="'+v[0]+'"',v.length>1&&(v[1].length&&(out+=' width="'+v[1]+'"'),v.length>2&&(out+=' class="'+v[2]+'"')),v[0]&&(out+=' title="'+v[0]+'"'),out+="/>"}return out}text(text){return text}}const irules=inline.gfm;let tokenparser=(res,render,maxlen=0)=>{let totl=0,checklen=body=>{if(maxlen>0&&body.length>maxlen-totl){let q=(body=body.substring(0,maxlen-totl)).lastIndexOf(" ");q>0&&(body=body.substring(0,q))}return body},next=()=>token=tokens.pop(),parseText=()=>{let body=token.text;for(;"text"===(tokens[tokens.length-1]||0).type;)body+="\n"+next().text;return output(checklen(body))},outputLink=(cap,link)=>{let href=escape(link.href),title=link.title?escape(link.title):null;return"!"!==cap[0].charAt(0)?render.link(href,title,output(cap[1])):render.image(href,title,escape(cap[1]))};const output=src=>{let link,text,href,cap,out="";for(;src;)if(cap=irules.escape.exec(src))src=src.substring(cap[0].length),out+=cap[1];else if(cap=irules.autolink.exec(src))src=src.substring(cap[0].length),"@"===cap[2]?(text=":"===cap[1].charAt(6)?cap[1].substring(7):cap[1],href=`mailto:${text}`):(text=escape(cap[1]),href=text),out+=render.link(href,null,text);else if(inLink||!(cap=irules.url.exec(src))){if(cap=irules.tag.exec(src))!inLink&&/^<a /i.test(cap[0])?inLink=!0:inLink&&/^<\/a>/i.test(cap[0])&&(inLink=!1),src=src.substring(cap[0].length),out+=cap[0];else if(cap=irules.link.exec(src))src=src.substring(cap[0].length),inLink=!0,out+=outputLink(cap,{href:cap[2],title:cap[3]}),inLink=!1;else if((cap=irules.reflink.exec(src))||(cap=irules.nolink.exec(src))){if(src=src.substring(cap[0].length),link=(cap[2]||cap[1]).replace(/\s+/g," "),link=links[link.toLowerCase()],!link||!link.href){out+=cap[0].charAt(0),src=cap[0].substring(1)+src;continue}inLink=!0,out+=outputLink(cap,link),inLink=!1}else if(cap=irules.formula.exec(src))src=src.substring(cap[0].length),out+=render.formula(output(cap[1]));else if(cap=irules.ico.exec(src))src=src.substring(cap[0].length),out+=render.ico(output(cap[2]||cap[1]));else if(cap=irules.strong.exec(src))src=src.substring(cap[0].length),out+=render.strong(output(cap[2]||cap[1]));else if(cap=irules.em.exec(src))src=src.substring(cap[0].length),out+=render.em(output(cap[2]||cap[1]));else if(cap=irules.code.exec(src))src=src.substring(cap[0].length),out+=render.codespan(escape(cap[2],!0));else if(cap=irules.br.exec(src))src=src.substring(cap[0].length),out+=render.br();else if(cap=irules.del.exec(src))src=src.substring(cap[0].length),out+=render.del(output(cap[1]));else if(cap=irules.coloralt.exec(src))src=src.substring(cap[0].length),out+=render.coloralt(output(cap[1]));else if(cap=irules.colorbase.exec(src))src=src.substring(cap[0].length),out+=render.colorbase(output(cap[1]));else if(cap=irules.text.exec(src))src=src.substring(cap[0].length),out+=render.text(cap[0]);else if(src)throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}else src=src.substring(cap[0].length),text=escape(cap[1]),href=text,out+=render.link(href,null,text);return out};let token,tok=()=>{switch(token.type){case"space":return"";case"hr":return render.hr();case"heading":return render.heading(output(checklen(token.text)),token.depth,token.text);case"code":return"math"==token.lang?render.formula(token.text,!0):render.code(token.text,token.lang,codes);case"table":{let row,cell,j,header="",body=[];cell=[];for(let i=0;i<token.headers.length;i++)cell.push(render.tablecell(tokenparser(token.headers[i],render,0).out,!0,token.align[i]));header=render.tablerow(cell.join(""));for(let i=0;i<token.cells.length;i++){for(row=token.cells[i],cell=[],j=0;j<row.length;j++)cell.push(render.tablecell(tokenparser(row[j],render,0).out,!1,token.align[j]));body.push(render.tablerow(cell.join("")))}return render.table(header,body.join(""))}case"blockquote_start":{let body="";for(;"blockquote_end"!==next().type;)body+=tok();return render.blockquote(body)}case"list_start":{let body="",ordered=token.ordered;for(;"list_end"!==next().type;)body+=tok();return render.list(body,ordered)}case"list_title_start":{let body="";for(;"list_title_end"!==next().type;)body+=tok();return render.listtitle(body)}case"list_item_start":{let body="",num=token.num;for(;"list_item_end"!==next().type;)body+="text"===token.type?parseText():tok();return render.listitem(body,num)}case"html":return render.html(token.text);case"paragraph":return render.paragraph(output(checklen(token.text)));case"text":return render.paragraph(parseText());default:console.log("missing",token.type)}},tokens=res.reverse(),inLink=!1,links={},codes=[],out=[];for(;next();){let t=tok();if(totl+=t.length,t&&out.push(t),maxlen>0&&totl>maxlen)break}return{out:out.join(""),codes:codes}};function __parselist(tt,tm){let rr;function pb(exp,cl,callback){if(rr=exp.exec(tt),rr){__parselist(tt.slice(0,rr.index),tm);let t=rr[1];return t.startsWith("\n")&&(tm.push({class:"",text:"\n"}),t=t.slice(1)),tm.push({class:cl,text:callback?callback(t):t}),__parselist(tt.slice(rr.index+rr[1].length),tm),!0}return!1}tt&&"string"==typeof tt&&(pb(/^(:{3}\s*$[^]+?:{3}\s*$)/gim,"comment")||pb(/^(\s*`{3}[^]+?`{3}\s*$)/gim,"code")||pb(/^(\s*:\w+:.*)$/gim,"comment")||(tt=tt.replace(/ {2,}\n/gim," "),pb(/^(\s*#{1,6}\s+.*)/gim,"title")||pb(/(\n\s*\n)/gim,"break")||pb(/^(\s*>\s+[^]*?\n\n)/gim,"cite")||pb(/^(\s*>\s+.*)/gim,"cite")||pb(/^(.*?\|[^]*?\n\n)/gim,"table")||pb(/^( *\*| *-|-{1,8})[ $]/gim,"list")||pb(/^( ([\d]+[.]*)+)[ $]/gim,"list",(r=>{let vv=r.split(".");vv.shift();let cl=[];for(let v of vv)v.length&&cl.push(" ");return cl.push("-"),cl.join("")}))||tm.push({class:"",text:tt})))}function parselist(text,title=""){let tm=[];__parselist(text,tm);let counter=[],space=0;for(let ii=0;ii<tm.length;ii++){let t=tm[ii];if("list"==t.class){let sl=t.text.replace("\n","").length;if(sl>space)counter.push({space:sl,id:1}),space=sl;else for(;;){let c=counter[counter.length-1];if(1==counter.length||c.space<=sl){space=c.space,c.id++;break}counter.pop()}let cl=[],cl1=[];for(let c of counter)cl1.push(" "),cl.push(c.id);cl1.pop(),t.old=t.text,t.text.indexOf("-")>=0?t.text=cl1.join("")+"- "+cl.join(".")+".":t.text=cl1.join("")+"* ",cl=[];for(let j=ii+1;j<tm.length&&""==tm[j].class;j++)cl.push(tm[j].text);t.title=title,t.data=t.text+cl.join("")}else""!=t.class&&("title"==t.class&&(title=t.text),counter=[],space=0)}let cl=[],cards=[];for(let t of tm)"list"==t.class&&cards.push({title:t.title,lev:t.text,data:t.data}),cl.push(t.text);return{txt:cl.join(""),cards:cards,tm:tm}}function parserow$1(tt,tm,classe=""){let rr;function parse3(exp,cl){return rr=exp.exec(tt),!!rr&&(parserow$1(tt.slice(0,rr.index),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[1]}),parserow$1(rr[2],tm,`${classe} ${cl}`),tm.push({class:`${classe} ${cl}`,text:rr[3]}),parserow$1(tt.slice(rr.index+rr[1].length+rr[2].length+rr[3].length),tm,classe),!0)}(function parse1(exp,cl){return rr=exp.exec(tt),!!rr&&(parserow$1(tt.slice(0,rr.index),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[1]}),parserow$1(tt.slice(rr.index+rr[1].length),tm,classe),!0)})(/(`.*?`)/gim,"code2")||parse3(/(\*{3})([^]+?)(\*{3})/gim,"grassetto italico")||parse3(/(\*{2})([^]+?)(\*{2})/gim,"grassetto")||parse3(/(\*{1})([^]+?)(\*{1})/gim,"italico")||parse3(/(_{3})([^]+?)(_{3})/gim,"grassetto italico")||parse3(/(_{2})([^]+?)(_{2})/gim,"grassetto")||parse3(/(_{1})([^]+?)(_{1})/gim,"italico")||parse3(/(~{3})([^]+?)(~{3})/gim,"barrato")||parse3(/(~{2})([^]+?)(~{2})/gim,"tilde2")||parse3(/(~{1})([^]+?)(~{1})/gim,"tilde")||tm.push({class:classe,text:tt})}function parseblock$1(tt,tm){let rr;function pb(exp,cl,row=!1){return rr=exp.exec(tt),!!rr&&(parseblock$1(tt.slice(0,rr.index),tm),row?parserow$1(rr[1],tm,cl):tm.push({class:cl,text:rr[1]}),parseblock$1(tt.slice(rr.index+rr[1].length),tm),!0)}if(!(pb(/^(:{3}[^]+?:{3})/gim,"comment")||pb(/^(\s*`{3}[^]+?`{3})/gim,"code")||pb(/^(\s*:\w+:.*)$/gim,"comment")||pb(/^(\s*#{1,6} +.*)$/gim,"title",!0)||pb(/^(\s*>\s+[^]*?\n\n)/gim,"cite",!0)||pb(/^(\s*>\s+.*)/gim,"cite",!0)||pb(/^(.*?\|.*\n[-: ]+\|[-| :]*\n.*?\|[^]*?\n\n)/gim,"tabella",!0)||pb(/^(\n{2,})/gim,"break",!0)||pb(/^( *\*| *-|-{1,8})[ $]/gim,"list",!0)||pb(/(^\s*[\d.]+)[\s$]/gim,"list",!0))){if(rr=/(!*\[)(.*?)(\]\s*\()(.*?)(\))/.exec(tt),rr)return parserow$1(tt.slice(0,rr.index),tm,""),tm.push({class:"grassetto",text:rr[1]}),tm.push({class:"linkdes",text:rr[2]}),tm.push({class:"grassetto",text:rr[3]}),tm.push({class:"linkval",text:rr[4]}),tm.push({class:"grassetto",text:rr[5]}),void parserow$1(tt.slice(rr.index+rr[1].length+rr[2].length+rr[3].length+rr[4].length+rr[5].length),tm,"");parserow$1(tt,tm,"")}}function parsetext(tt){"number"==typeof tt&&(tt=String(tt)),tt&&"string"==typeof tt||(tt=" "),tt.endsWith("\n")&&(tt+=" ");let tm=[];return parseblock$1(tt,tm),tm}function parserow(tt,tm,classe=""){let rr;function parse1(exp,cl){return rr=exp.exec(tt),!!rr&&(parserow(tt.slice(0,rr.index),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[1]}),parserow(tt.slice(rr.index+rr[1].length),tm,classe),!0)}parse1(/(\/\/.*)$/gim,"commento2")||function parse2(exp,cl){if(rr=exp.exec(tt),rr){let ii=rr.index+rr[1].length;return parserow(tt.slice(0,ii),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[2]}),parserow(tt.slice(ii+rr[2].length),tm,classe),!0}return!1}(/(#let.? +)([\w_.]+)/gi,"variabile")||parse1(/(#(select|cases|endselect|ifdef|log|msg|endif|cvar|cache|look|lookb|elseifdef|variante|forvar|for|endfor|continue|break|inc|macro|default|lets|letv|lett|cat|func))/gim,"comando")||parse1(/(#(if\s*|elseif\s*))/gim,"comando")||parse1(/(#(else|let|i |m |f |j |case|def ))/gim,"comando")||parse1(/(\$[{(]?[\w_.]+)/gim,"variabile")||parse1(/({.+?\})/gim,"formula")||parse1(/([})(])/gim,"variabile")||parse1(/([\d.:,;\\,]+)/gim,"digit")||tm.push({class:classe,text:tt})}function parseblock(tt,tm){let rr;(function pb(exp,cl,row=!1){return rr=exp.exec(tt),!!rr&&(parseblock(tt.slice(0,rr.index),tm),row?parserow(rr[1],tm,cl):tm.push({class:cl,text:rr[1]}),parseblock(tt.slice(rr.index+rr[1].length),tm),!0)})(/(\/\*[^]+?\*\/)/gim,"comment")||parserow(tt,tm,"")}function parserule(tt){tt||(tt=" "),tt.endsWith("\n")&&(tt+=" ");let tm=[];return parseblock(tt,tm),tm}function formatrule(code){let lines=code.split("\n"),formattedCode=[],indentLevel=0,next=0;for(let i=0;i<lines.length;i++){let line=lines[i].trim(),indent=" ".repeat(indentLevel>=0?indentLevel+next:next);next=0;let command="";line.split("//")[0].trim().endsWith("\\")&&(next=1),(line.startsWith("#")||line.startsWith("!"))&&(command=line.substring(1).split(" ")[0].toUpperCase(),line=line.substring(0,1)+command+line.substring(command.length+1)),"IF"==command||"IFDEF"==command||"IFNDEF"==command?line.indexOf("#",2)<0?indentLevel++:line=line.replace(/#([\w]+)/g,((match,m1)=>"#"+m1.toUpperCase())):["FOR","FORVAR","DO","SELECT"].includes(command)?indentLevel++:["ENDIF","LOOP","ENDFOR","ENDSELECT"].includes(command)&&(indentLevel--,indent=" ".repeat(indentLevel>=0?indentLevel:0)),["ELSEIF","ELSE","ELSEIFDEF","ELSEIFNDEF","CASE","CASES","DEFAULT"].includes(command)&&indentLevel>0?formattedCode.push(" ".repeat(indentLevel-1)+line):formattedCode.push(indent+line)}return formattedCode.join("\n")}function getcolonne(value){if((value=value+""||"").includes('"')){return value.split(/[,;](?=(?:(?:[^"]*["]){2})*[^"]*$)/).map((part=>part.trim().replace(/(^["'])|(["']$)/g,"").replace(/=\s*["']/g,"=")))}return value.split(/[,;]/).map((p=>p.trim()))}function formatvariante(str){let cl=[],ll=[];for(let c of str.split("\n")){let tm=getcolonne(c);for(let i=0;i<tm.length;i++){let t=tm[i]||"";(t.includes(",")||t.includes(";"))&&(t=`"${t}"`,tm[i]=t);let l=t.length;(!ll[i]||ll[i]<l)&&(ll[i]=l)}cl.push(getcolonne(c))}let res=[];for(let c of cl){let tm=[];for(let i=0;i<ll.length;i++)tm[i]=(c[i]||"").padEnd(ll[i]);res.push(tm.join(" , "))}return res.join("\n")}function markunoFormatCodeMirror(CodeMirror){CodeMirror.defineMode("markuno",(function(){return{startState:function(){return{inComment:!1}},token:function(stream,state){return state.inComment?(stream.skipTo("*/")?(stream.next(),stream.next(),state.inComment=!1):stream.skipToEnd(),"comment"):stream.match(/\/\/.*/)?"comment":stream.sol()&&stream.match(/^\s*\.[a-zA-Z0-9_]+(?=\s|$)/)?"def":state.expectMacroArg?stream.eatSpace()?null:stream.match(/^[^\s#,(){}]+/)?(state.expectMacroArg=!1,"builtin"):(stream.next(),state.expectMacroArg=!1,null):stream.sol()&&stream.match(/^\s*#([mif])\b/i)?(state.expectMacroArg=!0,"def"):stream.match("/*")?(stream.skipTo("*/")?(stream.next(),stream.next()):state.inComment=!0,"comment"):stream.match(/^\s*#(select|cache|cvar|lookb|look|cases|endselect|log|msg|ifdef|ifndef|elseif|elseifndef|endif|elseifdef|variante|forvar|for|endfor|continue|break|inc|macro|default|lets|lett|cat|func|push|pop|letv|let|letm|lett|else)/i)||stream.match(/^\s*#(if\s*|elseif\s*|j |case|def )/i)||stream.match(/#(else|let|letv|lett|letm|cvar|cache|lookb|look)/i)?"keyword":!state.inCommand&&stream.match(/^\s*#[\w_.]+/i)?"string":stream.match(/^\s*![\w_.]+/i)?"builtin":stream.match(/[<>!=+\-*/\\%]+/)?"operator":stream.match(/\$\[[\w_.]+/)||stream.match(/\$\{[\w_.]+/)||stream.match(/\$\([\w_.]+/)||stream.match(/\$[\w_.]+/)||stream.match(/[}\])]/)?"string":stream.match(/\{.+?\}/)?"variable-3":stream.match(/[\d.:,;\\]+/)?"number":(stream.next(),null)}}}))}function parsevars(v,vars){let r=v;if(vars)for(let x in vars){let v2=vars[x]||`..${x}..`;r=r.replace(new RegExp(`\\[${x}\\]`,"gim"),v2)}return r}const parseinfomd=(data,info,mappa)=>aliasInfo.parse(data,info,mappa),mark=(xx,baseurl,notitle=!1,parsedlist=!1,callback)=>{let res;if(parsedlist)res=tokenize(xx,0,notitle);else{let{txt:txt}=parselist(xx);res=tokenize(txt,0,notitle)}return tokenparser(res,new Render(baseurl,!1,callback))},markeasy=(xx,maxlen=400,notitle=!1)=>{let res=tokenize(xx,maxlen,notitle);return tokenparser(res,new Render,maxlen).out};export{Render,aliasInfo,elang,escapeHTML,formatrule,formatvariante,mark,markeasy,markunoFormatCodeMirror,parseinfomd,parselist,parserule,parsetext,tokenparser as parsetokens,parsevars,tokenize,unescapeHTML};
21
+ inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()});const basealias={s:"subtitle",k:"keywords",g:"gruppo",e:"editore",y:"datapub",d:"datapub",p:"priority",a:"autore",u:"base",t:"title",l:"link",i:"img","#":"title"};const aliasInfo=new class AliasInfo{constructor(){this.alias=JSON.parse(JSON.stringify(basealias)),this.check()}check(){let rr=new Set,checkr=x=>{x&&x.length>2&&!rr.has(x)&&rr.add(x)};for(let x in this.alias)this.alias[x]?(checkr(x),checkr(this.alias[x])):delete this.alias[x];this.retoalias=function retroalias(alias){let retro={};for(let x in alias)alias[x]&&(retro[alias[x]]=x);return retro}(this.alias),rr=[...rr],rr=`^\\s*\\:(${rr.join("|")}|\\w{1,2})\\:(.*)$`,this.regex=rr}add(sigla,valore){return sigla&&(this.alias[sigla]=valore,this.check()),this}removeAll(){return this.alias={},this.check(),this}setmappa(mappa){this.alias={};for(let x in mappa)this.alias[x]=mappa[x];this.alias["#"]||(this.alias["#"]="title"),this.check()}parse(data,info,mappa){mappa&&this.setmappa();let xx=data,res={};info&&(res=Object.assign(res,info),res.info=!0);let rr=/^\s*#\s+(.*?)\s*$/im.exec(xx);rr&&(res[this.alias["#"]]=rr[1].toLowerCase());for(let i=0;i<20;i++){let rr=/:::(.*)([^]+?):::/im.exec(xx);if(!rr)break;{let id=rr[1];id||(id=i+""),res.comments||(res.comments=[]),res.comments.push({k:id,v:rr[2]}),xx=xx.substr(rr.index+rr[0].length)}}xx=data;let regex=new RegExp(this.regex,"im");for(let i=0;i<50;i++){let rr=regex.exec(xx);if(!(rr&&rr.length>=2))break;{xx=xx.substr(rr.index+rr[0].length),res.info=!0;let rr2=(rr[2]||"").trim(),oname=this.alias[rr[1].toLowerCase()];oname||(oname=rr[1].toLowerCase()),"l"==oname||"link"==oname?(res[oname]||(res[oname]=[]),res[oname].push(rr2)):res[oname]=rr2}}return res}};var tokenize=(src,easylen,noheader=!1)=>{function _parsetable(tokens,src){let v2,tb={type:"table",headers:[],align:[],cells:[],cols:0},vv=src.split("\n"),fl=!1;function checkcols(cols){if(tb.cols<cols){for(let i=tb.cols;i<cols;i++){tb.align[i]="left",tb.headers[i]=[];for(let r of tb.cells)r[i]=[]}tb.cols=cols}}for(let v1 of vv)if(v1=v1.trim(),v1.length)if(v1.length>2&&v1.startsWith("|")&&v1.endsWith("|")&&(v1=v1.slice(1,-1)),v2=v1.split("|"),checkcols(v2.length),0==fl&&/^[- :]+\|[- :|]*$/im.test(v1)){for(let i=0;i<v2.length;i++){let v=v2[i],x1=v.slice(0,1),x2=v.slice(-1);tb.align[i]=":"==x1&&":"==x2?"center":":"==x2?"right":"left"}fl=!0}else{let r=[];for(let i=0;i<v2.length;i++){let v=v2[i];if(fl){let t=[];_tokenize(t,v,!1),r.push(t)}else _tokenize(tb.headers[i],v,!1)}fl&&tb.cells.push(r)}tokens.push(tb)}function _pushtoken(tokens,src){let cc=/^([\d.]+)\s*/.exec(src),num="",title="";cc&&(num=cc[1],src=src.substring(cc.index+cc[0].length)),cc=/^([\w\s]*?):.*$/gim.exec(src),cc&&(title=cc[1],src=src.substring(cc.index+cc[1].length)),tokens.push({type:"list_item_start",num:num}),title&&(tokens.push({type:"list_title_start"}),_tokenize(tokens,title,!1),tokens.push({type:"list_title_end"})),src=src.replace(/\n +/gim,"<br>"),_tokenize(tokens,src,!1),tokens.push({type:"list_item_end"})}function _parselista(tokens,ordered,space,src){let counter=[space];for(tokens.push({type:"list_start",ordered:ordered});;){let cap=/^( *)([*\-+])[\s$]/im.exec(src);if(!cap){_pushtoken(tokens,src);break}{cap.index&&_pushtoken(tokens,src.substring(0,cap.index));let sl=cap[1].length;if(sl>counter[counter.length-1])tokens.push({type:"list_start",ordered:ordered}),counter.push(sl);else for(;;){let sp=counter[counter.length-1];if(1==counter.length||sp<=sl)break;tokens.push({type:"list_end"}),counter.pop()}src=src.substring(cap.index+cap[0].length)}}for(let c of counter)tokens.push({type:"list_end"})}const _tokenize=(tokens,src,top,bq)=>{let cap;for(src=src.replace(/^ +$/gm,"");src;){if(easylen){let ll=0;for(let t of tokens)t.text||t.html?ll=ll+t.text.length+2:ll+=3;if(ll>easylen)break}if((cap=rules.newline.exec(src))&&(src=src.substring(cap[0].length),cap[0].length>1&&tokens.push({type:"space"})),cap=rules.formula.exec(src))src=src.substring(cap[0].length),tokens.push({type:"code",lang:"math",text:cap[2]||""});else if(cap=/^(\s*`{3})(.*)([^]+?)(`{3})/gim.exec(src)){cap.index>0&&_tokenize(tokens,src.substring(0,cap.index),top);let txt=(cap[3]||"").replace(/^\n/,"").replace(/\n+$/,"");tokens.push({type:"code",lang:cap[2],text:txt}),src=src.substring(cap.index+cap[0].length)}else if(cap=rules.heading.exec(src))src=src.substring(cap[0].length),tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});else if(top&&(cap=/^(.*?\|.*\n[-: ]+\|[-| :]*\n.*?\|[^]*?)\n\n/gim.exec(src)))cap.index>0&&_tokenize(tokens,src.substring(0,cap.index),top),_parsetable(tokens,cap[1]),src=src.substring(cap.index+cap[0].length);else if(top&&(cap=/^\|.*\|\s*(?:\n\|.*\|)+/gim.exec(src)))cap.index>0&&_tokenize(tokens,src.substring(0,cap.index),top),_parsetable(tokens,cap[0]),src=src.substring(cap.index+cap[0].length);else if(cap=rules.lheading.exec(src))src=src.substring(cap[0].length),tokens.push({type:"heading",depth:"="===cap[2]?1:2,text:cap[1]});else if(cap=rules.hr.exec(src))src=src.substring(cap[0].length),tokens.push({type:"hr"});else if(cap=rules.blockquote.exec(src))src=src.substring(cap[0].length),tokens.push({type:"blockquote_start"}),_tokenize(tokens,cap[0].replace(/^ *> ?/gm,""),top,!0),tokens.push({type:"blockquote_end"});else if(cap=/^[\s-:]*?\|[\s-:|]*/im.exec(src),cap||!(cap=/^( *)([*\-+])[\s$]/im.exec(src))){if(cap=rules.html.exec(src))src=src.substring(cap[0].length),tokens.push({type:"html",pre:"pre"===cap[1]||"script"===cap[1]||"style"===cap[1],text:cap[0]});else if(!bq&&top&&(cap=rules.def.exec(src)))src=src.substring(cap[0].length),tokens.push({type:"code",text:`??${cap[0]}??${rules.def}??`});else if(top&&(cap=rules.paragraph.exec(src)))src=src.substring(cap[0].length),tokens.push({type:"paragraph",text:"\n"===cap[1].charAt(cap[1].length-1)?cap[1].slice(0,-1):cap[1]});else if(cap=rules.text.exec(src))src=src.substring(cap[0].length),tokens.push({type:"text",text:cap[0]});else if(src)throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}else{cap.index>0&&_tokenize(tokens,src.substring(0,cap.index)),src=src.substring(cap.index+cap[0].length);let res=/([^]*?)(\n\n|\n\s*[#>])/im.exec(src+"\n\n");if(res){_parselista(tokens,"*"==cap[2],cap[1].length,res[1]),src=src.substring(res[1].length)}else tokens.push({type:"text??",text:cap[0]})}}return tokens};let rules=block.tables;return src=function removeInfo(src,title=!1){let tm=src.replace(/:::([^]+?):::/gim,"").replace(new RegExp(aliasInfo.regex,"gim"),"").replace(/^\s*#\s+/im,"# ").replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");if(title){const rg=/(^\s*#\s+(.*)?\s*)$/im;let rr=rg.exec(tm);rr&&0==rr.index&&(tm=tm.replace(rg,""))}return tm}(src,noheader),_tokenize([],src,!0)};const controls={string:/(".*?[^\\]"|'.*?[^\\]'|`[^]*?[^\\]`|""|''|``)/m,puntuaction:/(-[-=]?|,|;|\+[+=]?|!=?=?|<<?=?|>>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3})/g,parentesis:/(\(|\)|\[|\]|\{|\})/g,ingraffe:/([^$])(\{)(.*?)(\})/g,regex:/\/.*?[^\\]\/[gimu]*/m,numbers:/\b((?:(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+)n?|\d+n|NaN|Infinity)\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee][+-]?\d+)?)/gi,js:{comments:/(?:(?:^|[^\\:])(\/\/.*)|(?:^|[^\\])(\/\*[\s\S]*?(?:\*\/)))/m,keyword:/(\b)(import|require|endif|include|define|float|int|real|char|bool|as|true|false|async|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)(\b)/g,keyword2:/(\.\w+|\w+:)/g},json:{string:/(".*?[^\\]")/m,string1:/(".*?[^\\]"\s*:)/m},html:{script:/(<script[\s\S]*?>)([^]*?)(<\/script>)/im,tag:/<(!DOCTYPE|\/?\w+)([^]*?)(\/?>)/im,intag:/(\b)([\w-]+)(=)/g,comments:/<!--[^]*?-->/im},bash:{comments:/# .*/,keyword1:/(^ *|; *)(\w+)(\b)/g,keyword:/(\b)(sudo *[\w-]+)(\b)/g},mu:{comments:/(?:(?:^|[^\\:])(\/\/.*)|(?:^|[^\\])(\/\*[\s\S]*?(?:\*\/)))/m,keyword1:/(#)(\w+)(\b)/g,keyword2:/(\$\(?(\w+|\.|:|\)))/g},sql:{keyword:".",keyword2:/(\b)(FROM|USING|FTS5|NVARCHAR|INTEGER|REAL|BLOB|DELETE|UPDATE|BEGIN|END|ADD|CREATE|CONSTRAINT|ALTER|COLUMN|TABLE|ALL|ASC|BETWEEN|CASE|CHECK|COLUMN|INDEX|VIEW|PROCEDURE|DESC|DISTINTC|DROP|OUTER|INNER|LEFT|JOIN|INSERT|INTO|[NOT ]*NULL|LIMIT|SELECT|ORDER BY|UNION|WHERE)(\b)/gi,keyword1:/(\b)(COLLATE|NOCASE|DEFAULT|IF [NOT ]*EXISTS|PRIMARY KEY|VALUES|AS)(\b)/gi,comments:/(?:(?:^|[^\\:])(\/\/.*)|(?:^|[^\\])(\/\*[\s\S]*?(?:\*\/))|(--\s.*))/m}};function elang(str,lang,punct,codes){let data;return codes&&(data=codes.length,codes.push(str)),`<pre class="elang relative">${xelang(str,lang,punct)}<div class="absolute top-1 right-1"><button class="mu-internal-copy" data-copy="${data}">📋</button></div></pre>`}const escapeTag=str=>str.replace(/[<>]/g,(tag=>({"<":"&lt;",">":"&gt;"}[tag]))),escapeHTML=str=>str.replace(/[&<>'"]/g,(tag=>({"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"}[tag]))),unescapeHTML=str=>str.replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&gt;/g,">").replace(/&lt;/g,"<");function xelang(str,lang,punct){let gspan=(str,cls)=>(cls&&(cls=cls.replace(/(\b)(\w+)(\b)/g,"$1_$2$3")),`☉☊${cls||""}☊☉${(str=escapeTag(str))||""}☉☋`),regex=code=>{if(controls[lang]){let x=controls[lang][code];if("."==x)return;if(x)return x}let x=controls[code];return"."==x?void 0:x},out=[],r=0,ids=[];if(lang){controls[lang]||(lang="js");let rg=regex("script");if(rg){let st1=[];for(;;){let res=rg.exec(str);if(!res)break;res.index>0&&st1.push(str.substr(0,res.index)),st1.push(`★★K${ids.length}★★`),ids.push(xelang(res[1],lang)+xelang(res[2],"js")+xelang(res[3],lang)),str=str.substr(res.index+res[0].length)}str.length&&st1.push(str),str=st1.join("")}for(let r of[{r:"comments",s:"C"}]){let rg=regex(r.r);if(rg){let st1=[];for(;;){let res=rg.exec(str);if(!res)break;if(res.index>0&&st1.push(str.substr(0,res.index)),st1.push(`★★${r.s}${ids.length}★★`),"html"==lang){let tm=res[0].replace(/</g,"&lt;").replace(/>/g,"&gt;");ids.push(tm)}else ids.push(res[0]);str=str.substr(res.index+res[0].length)}str.length&&st1.push(str),str=st1.join("")}}for(let r of[{r:"string2",s:"A"},{r:"string1",s:"B"},{r:"string",s:"S"},{r:"tag",s:"T"},{r:"regex",s:"R"}]){let rg=regex(r.r);if(rg){let st1=[];for(;;){let res=rg.exec(str);if(!res)break;if(res.index>0&&st1.push(str.substr(0,res.index)),st1.push(`★★${r.s}${ids.length}★★`),"T"==r.s){let tm=res[2].replace(regex("intag"),((p,p1,p2,p3)=>p1+gspan(p2,"intag")+gspan(p3,"punc")));ids.push(gspan("<","punc")+res[1]+tm+gspan(res[3],"punc"))}else if("`"==res[0][0]){let tm=res[0].replace(/(\${)(.*?)(})/gm,((p,p1,p2,p3)=>gspan(p1,"punc")+gspan(p2,"word")+gspan(p3,"punc")));ids.push(tm)}else ids.push(res[0]);str=str.substr(res.index+res[0].length)}str.length&&st1.push(str),str=st1.join("")}}let vv=str.split("\n"),r=0;for(let v of vv)r++,v=v.replace(regex("keyword"),((p,p1,p2,p3)=>gspan(p1,"tag")+gspan(p2,"keys")+p3)).replace(regex("keyword1"),((p,p1,p2,p3)=>p1+gspan(p2,"keys1 keys")+p3)).replace(regex("keyword2"),(p=>gspan(p,"keys2 keys"))).replace(regex("numbers"),(p=>gspan(p,"number"))).replace(regex("ingraffe"),((p,p1,p2,p3,p4)=>p1+gspan(p2,"punc")+gspan(p3,"word")+gspan(p4,"punc"))).replace(regex("puntuaction"),(p=>gspan(p,"punc"))).replace(/★★T(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"tag"))).replace(/★★S(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"string"))).replace(/★★B(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"string string1"))).replace(/★★A(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"string string2"))).replace(/★★R(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"regex"))).replace(/★★C(\d+)★★/gu,((m,p)=>gspan(ids[Number(p)],"comment"))).replace(/★★K(\d+)★★/gu,((m,p)=>ids[Number(p)])),punct?out.push(gspan((" "+r).substr(-4),"rowid")+gspan(v)):out.push(gspan(v))}else{let vv=str.split("\n");for(let v of vv)r++,punct?out.push(`${gspan((" "+r).substr(-4),"rowid")}${gspan(v)}`):out.push(gspan(v))}let xx=out.join("\n");return xx=xx.replace(/☉☋/gmu,"</span>").replace(/☉☊([^]*?)☊☉/gmu,((p,p1)=>{if(p1){let v1=p1.split(" "),aa=[];for(let v of v1)aa.push(`elang_${lang}${v}`),aa.push(`elang${v}`);return`<span class="${aa.join(" ")}">`}return"<span>"})),xx}class Render{constructor(baseurl,easy,callback){this.baseurl=baseurl,this.easy=easy,this.callback=callback}code(code,lang,codes){if(this.easy)return"";lang||(lang="js");let punct=lang==lang.toUpperCase();return elang(code,lang=lang.toLowerCase(),punct,codes)}blockquote(quote){return this.easy?quote:`<blockquote>\n${quote}</blockquote>\n`}html(html){return html}heading(text,level,raw){return"."==text||"*"==text?"":this.easy?`${text} `:`<h${level}>${text}</h${level}>`}hr(){return this.easy?"":'<div class="my-4"><hr/></div>'}list(body,ordered){let type=ordered?"ol":"ul";return`<${type}>\n${body}</${type}>\n`}listtitle(body){return`<span class="listtitle">${body}</span>`}listitem(text,num){return num?`<li attr-num="${num||""}">${text}</li>\n`:`<li>${text}</li>\n`}paragraph(text){return this.easy?text:`<p>${text}</p>\n`}table(header,body){return this.easy?"":`<table>\n<thead>\n${header}\n</thead>\n<tbody>\n${body}\n</tbody>\n</table>\n\n`}tablerow(content){return`<tr>\n${content}</tr>\n`}tablecell(content,header,align){if(header)return`<th style="text-align:center;">${content}</th>\n`;return`<td style="${align?"text-align:"+align+";":""}">${content}</td>`}colorbase(text){return`<span class='tilde'>${text}</span>`}formula(text,full=!1){if(this.easy)return"";let aa=`<img class='inline px-2' src='https://math.croswil.com/f?${text=text.replace(/<\/?em>/g," ").replace(/\r/g,"").replace("/\n/g"," ")}' alt='${text}'/>`;return full?`<div class='flex justify-center'><div>${aa}</div></div>`:aa}coloralt(text){return`<span class='tilde2'>${text}</span>`}strong(text){return"<strong>"+text+"</strong>"}ico(text){return`<span class="font-ico">${text}</span>`}em(text){return"<em>"+text+"</em>"}codespan(text){return"<code>"+text+"</code>"}br(){return"<br>"}del(text){return`<del>${text}</del>`}link(href,title,text){if(this.easy)return"("+text+")";let out;if("/"==href.substr(0,1)&&this.baseurl&&(href=this.baseurl+href.substr(1)),href.startsWith("!"))out=`<button class="mu-internal-link" data-href="${href=href.slice(1)}">${text}</button>`;else{let target="";href.startsWith(".")?href=href.slice(1):target='target="_blank"',out=`<a ${target} href='${href}' title='${title||""}'>${text}</a>`}return out}image(href,title,text){if(this.easy)return"";let v=text.split("|"),out="",iswebm=!1,ismp4=!1,ismp3=!1;if((href=(href=href.replace("https://www.youtube.com/watch?v=","https://youtu.be/")).replace("https://youtu.be","https://www.youtube.com/embed")).endsWith(".mp3")?(href=href.slice(0,-4),ismp3=!0):href.endsWith(".mp4")?(href=href.slice(0,-4),ismp4=!0):href.endsWith(".webm")?(href=href.slice(0,-5),iswebm=!0):href.endsWith(".video")&&(href=href.slice(0,-6),iswebm=!0,ismp4=!0),ismp3)out=`\n <audio controls ${v.length>=1?' width="'+v[1]+'"':""}\n class="mx-auto my-2 ${v.length>=2?v[2]:""}" \n >\n <source src="${href}.mp3" type="audio/mpeg">\n Il tuo browser non supporta l'elemento audio.\n </audio>\n `;else if(ismp4||iswebm)out=`\n<video ${v.length>=1?' width="'+v[1]+'"':""}\nclass="border rounded-lg shadow-xl ${v.length>=2?v[2]:""}" \ncontrols controlsList="nodownload" >\n ${iswebm?'<source src="'+href+'.webm" type="video/webm" >':""}\n ${ismp4?'<source src="'+href+'.mp4" type="video/mp4" >':""}\n \n Your browser does not support the video tag.\n</video>`;else{if(href.indexOf("https://www.youtu")>=0){let hh=href.split("/embed/")[1]?.split("?")[0];return out=`\n\n<div style="width: 94%; box-shadow: 6px 6px 10px hsl(206.5, 0%, 75%); margin: 3%;">\n <div style="position: relative; padding-bottom: 56.15%; height: 0; overflow: hidden;">\n <iframe \n style="position: absolute; top: 0; left:0; width: 100%; height: 100%; border: 0;"\n loading="lazy";\n srcdoc="<style>\n * {\n padding: 0;\n margin: 0;\n overflow: hidden;\n }\n \n body, html {\n height: 100%;\n }\n \n img, svg {\n position: absolute;\n width: 100%;\n top: 0;\n bottom: 0;\n margin: auto;\n }\n \n svg {\n filter: drop-shadow(1px 1px 10px hsl(206.5, 70.7%, 8%));\n transition: all 250ms ease-in-out;\n }\n \n body:hover svg {\n filter: drop-shadow(1px 1px 10px hsl(206.5, 0%, 10%));\n transform: scale(2);\n }\n </style>\n <a href='https://www.youtube.com/embed/${hh}?autoplay=1'>\n <img src='https://img.youtube.com/vi/${hh}/hqdefault.jpg' alt='${title||"video"}'>\n <svg xmlns='http://www.w3.org/2000/svg' width='64' height='64' viewBox='0 0 24 24' fill='none' stroke='#ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-play-circle'><circle cx='12' cy='12' r='10'></circle><polygon points='10 8 16 12 10 16 10 8'></polygon></svg>\n </a>\n "\n src="https://www.youtube.com/embed/${hh}" \n title="${title||"video"}"\n frameborder="0"\n allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" \n allowfullscreen>\n </iframe>\n </div>\n </div> \n \n`,out}this.callback&&"function"==typeof this.callback&&(href=this.callback({type:"img",href:href})),"/"==href.substr(0,1)&&this.baseurl&&(href=this.baseurl+href.substr(1)),out='<img src="'+href+'" alt="'+v[0]+'"',v.length>1&&(v[1].length&&(out+=' width="'+v[1]+'"'),v.length>2&&(out+=' class="'+v[2]+'"')),v[0]&&(out+=' title="'+v[0]+'"'),out+="/>"}return out}text(text){return text}}const irules=inline.gfm;let tokenparser=(res,render,maxlen=0)=>{let totl=0,checklen=body=>{if(maxlen>0&&body.length>maxlen-totl){let q=(body=body.substring(0,maxlen-totl)).lastIndexOf(" ");q>0&&(body=body.substring(0,q))}return body},next=()=>token=tokens.pop(),parseText=()=>{let body=token.text;for(;"text"===(tokens[tokens.length-1]||0).type;)body+="\n"+next().text;return output(checklen(body))},outputLink=(cap,link)=>{let href=escape(link.href),title=link.title?escape(link.title):null;return"!"!==cap[0].charAt(0)?render.link(href,title,output(cap[1])):render.image(href,title,escape(cap[1]))};const output=src=>{let link,text,href,cap,out="";for(;src;)if(cap=irules.escape.exec(src))src=src.substring(cap[0].length),out+=cap[1];else if(cap=irules.autolink.exec(src))src=src.substring(cap[0].length),"@"===cap[2]?(text=":"===cap[1].charAt(6)?cap[1].substring(7):cap[1],href=`mailto:${text}`):(text=escape(cap[1]),href=text),out+=render.link(href,null,text);else if(inLink||!(cap=irules.url.exec(src))){if(cap=irules.tag.exec(src))!inLink&&/^<a /i.test(cap[0])?inLink=!0:inLink&&/^<\/a>/i.test(cap[0])&&(inLink=!1),src=src.substring(cap[0].length),out+=cap[0];else if(cap=irules.link.exec(src))src=src.substring(cap[0].length),inLink=!0,out+=outputLink(cap,{href:cap[2],title:cap[3]}),inLink=!1;else if((cap=irules.reflink.exec(src))||(cap=irules.nolink.exec(src))){if(src=src.substring(cap[0].length),link=(cap[2]||cap[1]).replace(/\s+/g," "),link=links[link.toLowerCase()],!link||!link.href){out+=cap[0].charAt(0),src=cap[0].substring(1)+src;continue}inLink=!0,out+=outputLink(cap,link),inLink=!1}else if(cap=irules.formula.exec(src))src=src.substring(cap[0].length),out+=render.formula(output(cap[1]));else if(cap=irules.ico.exec(src))src=src.substring(cap[0].length),out+=render.ico(output(cap[2]||cap[1]));else if(cap=irules.strong.exec(src))src=src.substring(cap[0].length),out+=render.strong(output(cap[2]||cap[1]));else if(cap=irules.em.exec(src))src=src.substring(cap[0].length),out+=render.em(output(cap[2]||cap[1]));else if(cap=irules.code.exec(src))src=src.substring(cap[0].length),out+=render.codespan(escape(cap[2],!0));else if(cap=irules.br.exec(src))src=src.substring(cap[0].length),out+=render.br();else if(cap=irules.del.exec(src))src=src.substring(cap[0].length),out+=render.del(output(cap[1]));else if(cap=irules.coloralt.exec(src))src=src.substring(cap[0].length),out+=render.coloralt(output(cap[1]));else if(cap=irules.colorbase.exec(src))src=src.substring(cap[0].length),out+=render.colorbase(output(cap[1]));else if(cap=irules.text.exec(src))src=src.substring(cap[0].length),out+=render.text(cap[0]);else if(src)throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}else src=src.substring(cap[0].length),text=escape(cap[1]),href=text,out+=render.link(href,null,text);return out};let token,tok=()=>{switch(token.type){case"space":return"";case"hr":return render.hr();case"heading":return render.heading(output(checklen(token.text)),token.depth,token.text);case"code":return"math"==token.lang?render.formula(token.text,!0):render.code(token.text,token.lang,codes);case"table":{let row,cell,j,header="",body=[];cell=[];for(let i=0;i<token.headers.length;i++)cell.push(render.tablecell(tokenparser(token.headers[i],render,0).out,!0,token.align[i]));header=render.tablerow(cell.join(""));for(let i=0;i<token.cells.length;i++){for(row=token.cells[i],cell=[],j=0;j<row.length;j++)cell.push(render.tablecell(tokenparser(row[j],render,0).out,!1,token.align[j]));body.push(render.tablerow(cell.join("")))}return render.table(header,body.join(""))}case"blockquote_start":{let body="";for(;"blockquote_end"!==next().type;)body+=tok();return render.blockquote(body)}case"list_start":{let body="",ordered=token.ordered;for(;"list_end"!==next().type;)body+=tok();return render.list(body,ordered)}case"list_title_start":{let body="";for(;"list_title_end"!==next().type;)body+=tok();return render.listtitle(body)}case"list_item_start":{let body="",num=token.num;for(;"list_item_end"!==next().type;)body+="text"===token.type?parseText():tok();return render.listitem(body,num)}case"html":return render.html(token.text);case"paragraph":return render.paragraph(output(checklen(token.text)));case"text":return render.paragraph(parseText());default:console.log("missing",token.type)}},tokens=res.reverse(),inLink=!1,links={},codes=[],out=[];for(;next();){let t=tok();if(totl+=t.length,t&&out.push(t),maxlen>0&&totl>maxlen)break}return{out:out.join(""),codes:codes}};function __parselist(tt,tm){let rr;function pb(exp,cl,callback){if(rr=exp.exec(tt),rr){__parselist(tt.slice(0,rr.index),tm);let t=rr[1];return t.startsWith("\n")&&(tm.push({class:"",text:"\n"}),t=t.slice(1)),tm.push({class:cl,text:callback?callback(t):t}),__parselist(tt.slice(rr.index+rr[1].length),tm),!0}return!1}tt&&"string"==typeof tt&&(pb(/^(:{3}\s*$[^]+?:{3}\s*$)/gim,"comment")||pb(/^(\s*`{3}[^]+?`{3}\s*$)/gim,"code")||pb(/^(\s*:\w+:.*)$/gim,"comment")||(tt=tt.replace(/ {2,}\n/gim," "),pb(/^(\s*#{1,6}\s+.*)/gim,"title")||pb(/(\n\s*\n)/gim,"break")||pb(/^(\s*>\s+[^]*?\n\n)/gim,"cite")||pb(/^(\s*>\s+.*)/gim,"cite")||pb(/^(.*?\|[^]*?\n\n)/gim,"table")||pb(/^( *\*| *-|-{1,8})[ $]/gim,"list")||pb(/^( ([\d]+[.]*)+)[ $]/gim,"list",(r=>{let vv=r.split(".");vv.shift();let cl=[];for(let v of vv)v.length&&cl.push(" ");return cl.push("-"),cl.join("")}))||tm.push({class:"",text:tt})))}function parselist(text,title=""){let tm=[];__parselist(text,tm);let counter=[],space=0;for(let ii=0;ii<tm.length;ii++){let t=tm[ii];if("list"==t.class){let sl=t.text.replace("\n","").length;if(sl>space)counter.push({space:sl,id:1}),space=sl;else for(;;){let c=counter[counter.length-1];if(1==counter.length||c.space<=sl){space=c.space,c.id++;break}counter.pop()}let cl=[],cl1=[];for(let c of counter)cl1.push(" "),cl.push(c.id);cl1.pop(),t.old=t.text,t.text.indexOf("-")>=0?t.text=cl1.join("")+"- "+cl.join(".")+".":t.text=cl1.join("")+"* ",cl=[];for(let j=ii+1;j<tm.length&&""==tm[j].class;j++)cl.push(tm[j].text);t.title=title,t.data=t.text+cl.join("")}else""!=t.class&&("title"==t.class&&(title=t.text),counter=[],space=0)}let cl=[],cards=[];for(let t of tm)"list"==t.class&&cards.push({title:t.title,lev:t.text,data:t.data}),cl.push(t.text);return{txt:cl.join(""),cards:cards,tm:tm}}function parserow$1(tt,tm,classe=""){let rr;function parse3(exp,cl){return rr=exp.exec(tt),!!rr&&(parserow$1(tt.slice(0,rr.index),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[1]}),parserow$1(rr[2],tm,`${classe} ${cl}`),tm.push({class:`${classe} ${cl}`,text:rr[3]}),parserow$1(tt.slice(rr.index+rr[1].length+rr[2].length+rr[3].length),tm,classe),!0)}(function parse1(exp,cl){return rr=exp.exec(tt),!!rr&&(parserow$1(tt.slice(0,rr.index),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[1]}),parserow$1(tt.slice(rr.index+rr[1].length),tm,classe),!0)})(/(`.*?`)/gim,"code2")||parse3(/(\*{3})([^]+?)(\*{3})/gim,"grassetto italico")||parse3(/(\*{2})([^]+?)(\*{2})/gim,"grassetto")||parse3(/(\*{1})([^]+?)(\*{1})/gim,"italico")||parse3(/(_{3})([^]+?)(_{3})/gim,"grassetto italico")||parse3(/(_{2})([^]+?)(_{2})/gim,"grassetto")||parse3(/(_{1})([^]+?)(_{1})/gim,"italico")||parse3(/(~{3})([^]+?)(~{3})/gim,"barrato")||parse3(/(~{2})([^]+?)(~{2})/gim,"tilde2")||parse3(/(~{1})([^]+?)(~{1})/gim,"tilde")||tm.push({class:classe,text:tt})}function parseblock$1(tt,tm){let rr;function pb(exp,cl,row=!1){return rr=exp.exec(tt),!!rr&&(parseblock$1(tt.slice(0,rr.index),tm),row?parserow$1(rr[1],tm,cl):tm.push({class:cl,text:rr[1]}),parseblock$1(tt.slice(rr.index+rr[1].length),tm),!0)}if(!(pb(/^(:{3}[^]+?:{3})/gim,"comment")||pb(/^(\s*`{3}[^]+?`{3})/gim,"code")||pb(/^(\s*:\w+:.*)$/gim,"comment")||pb(/^(\s*#{1,6} +.*)$/gim,"title",!0)||pb(/^(\s*>\s+[^]*?\n\n)/gim,"cite",!0)||pb(/^(\s*>\s+.*)/gim,"cite",!0)||pb(/^(.*?\|.*\n[-: ]+\|[-| :]*\n.*?\|[^]*?\n\n)/gim,"tabella",!0)||pb(/^(\n{2,})/gim,"break",!0)||pb(/^( *\*| *-|-{1,8})[ $]/gim,"list",!0)||pb(/(^\s*[\d.]+)[\s$]/gim,"list",!0))){if(rr=/(!*\[)(.*?)(\]\s*\()(.*?)(\))/.exec(tt),rr)return parserow$1(tt.slice(0,rr.index),tm,""),tm.push({class:"grassetto",text:rr[1]}),tm.push({class:"linkdes",text:rr[2]}),tm.push({class:"grassetto",text:rr[3]}),tm.push({class:"linkval",text:rr[4]}),tm.push({class:"grassetto",text:rr[5]}),void parserow$1(tt.slice(rr.index+rr[1].length+rr[2].length+rr[3].length+rr[4].length+rr[5].length),tm,"");parserow$1(tt,tm,"")}}function parsetext(tt){"number"==typeof tt&&(tt=String(tt)),tt&&"string"==typeof tt||(tt=" "),tt.endsWith("\n")&&(tt+=" ");let tm=[];return parseblock$1(tt,tm),tm}function parserow(tt,tm,classe=""){let rr;function parse1(exp,cl){return rr=exp.exec(tt),!!rr&&(parserow(tt.slice(0,rr.index),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[1]}),parserow(tt.slice(rr.index+rr[1].length),tm,classe),!0)}parse1(/(\/\/.*)$/gim,"commento2")||function parse2(exp,cl){if(rr=exp.exec(tt),rr){let ii=rr.index+rr[1].length;return parserow(tt.slice(0,ii),tm,classe),tm.push({class:`${classe} ${cl}`,text:rr[2]}),parserow(tt.slice(ii+rr[2].length),tm,classe),!0}return!1}(/(#let.? +)([\w_.]+)/gi,"variabile")||parse1(/(#(select|setdef|cases|endselect|ifdef|log|msg|endif|cvar|cache|look|lookb|elseifdef|variante|forvar|for|endfor|continue|break|inc|macro|default|lets|letv|lett|cat|func))/gim,"comando")||parse1(/(#(if\s*|elseif\s*))/gim,"comando")||parse1(/(#(else|let|i |m |f |j |case|def ))/gim,"comando")||parse1(/(\$[{(]?[\w_.]+)/gim,"variabile")||parse1(/({.+?\})/gim,"formula")||parse1(/([})(])/gim,"variabile")||parse1(/([\d.:,;\\,]+)/gim,"digit")||tm.push({class:classe,text:tt})}function parseblock(tt,tm){let rr;(function pb(exp,cl,row=!1){return rr=exp.exec(tt),!!rr&&(parseblock(tt.slice(0,rr.index),tm),row?parserow(rr[1],tm,cl):tm.push({class:cl,text:rr[1]}),parseblock(tt.slice(rr.index+rr[1].length),tm),!0)})(/(\/\*[^]+?\*\/)/gim,"comment")||parserow(tt,tm,"")}function parserule(tt){tt||(tt=" "),tt.endsWith("\n")&&(tt+=" ");let tm=[];return parseblock(tt,tm),tm}function formatrule(code){let lines=code.split("\n"),formattedCode=[],indentLevel=0,next=0;for(let i=0;i<lines.length;i++){let line=lines[i].trim(),indent=" ".repeat(indentLevel>=0?indentLevel+next:next);next=0;let command="";line.split("//")[0].trim().endsWith("\\")&&(next=1),(line.startsWith("#")||line.startsWith("!"))&&(command=line.substring(1).split(" ")[0].toUpperCase(),line=line.substring(0,1)+command+line.substring(command.length+1)),"IF"==command||"IFDEF"==command||"IFNDEF"==command?line.indexOf("#",2)<0?indentLevel++:line=line.replace(/#([\w]+)/g,((match,m1)=>"#"+m1.toUpperCase())):["FOR","FORVAR","DO","SELECT"].includes(command)?indentLevel++:["ENDIF","LOOP","ENDFOR","ENDSELECT"].includes(command)&&(indentLevel--,indent=" ".repeat(indentLevel>=0?indentLevel:0)),["ELSEIF","ELSE","ELSEIFDEF","ELSEIFNDEF","CASE","CASES","DEFAULT"].includes(command)&&indentLevel>0?formattedCode.push(" ".repeat(indentLevel-1)+line):formattedCode.push(indent+line)}return formattedCode.join("\n")}function getcolonne(value){if((value=value+""||"").includes('"')){return value.split(/[,;](?=(?:(?:[^"]*["]){2})*[^"]*$)/).map((part=>part.trim().replace(/(^["'])|(["']$)/g,"").replace(/=\s*["']/g,"=")))}return value.split(/[,;]/).map((p=>p.trim()))}function formatvariante(str){let cl=[],ll=[];for(let c of str.split("\n")){let tm=getcolonne(c);for(let i=0;i<tm.length;i++){let t=tm[i]||"";(t.includes(",")||t.includes(";"))&&(t=`"${t}"`,tm[i]=t);let l=t.length;(!ll[i]||ll[i]<l)&&(ll[i]=l)}cl.push(getcolonne(c))}let res=[];for(let c of cl){let tm=[];for(let i=0;i<ll.length;i++)tm[i]=(c[i]||"").padEnd(ll[i]);res.push(tm.join(" , "))}return res.join("\n")}function markunoFormatCodeMirror(CodeMirror){CodeMirror.defineMode("markuno",(function(){return{startState:function(){return{inComment:!1}},token:function(stream,state){return state.inComment?(stream.skipTo("*/")?(stream.next(),stream.next(),state.inComment=!1):stream.skipToEnd(),"comment"):stream.match(/\/\/.*/)?"comment":stream.sol()&&stream.match(/^\s*\.[a-zA-Z0-9_]+(?=\s|$)/)?"def":state.expectMacroArg?stream.eatSpace()?null:stream.match(/^[^\s#,(){}]+/)?(state.expectMacroArg=!1,"builtin"):(stream.next(),state.expectMacroArg=!1,null):stream.sol()&&stream.match(/^\s*#([mif])\b/i)?(state.expectMacroArg=!0,"def"):stream.match("/*")?(stream.skipTo("*/")?(stream.next(),stream.next()):state.inComment=!0,"comment"):stream.match(/^\s*#(select|cache|cvar|lookb|look|cases|endselect|log|msg|ifdef|ifndef|elseif|elseifndef|endif|elseifdef|variante|forvar|for|endfor|continue|break|inc|macro|default|lets|lett|cat|func|push|pop|letv|let|letm|lett|else)/i)||stream.match(/^\s*#(if\s*|elseif\s*|j |case|def )/i)||stream.match(/#(else|let|letv|lett|letm|cvar|cache|lookb|look)/i)?"keyword":!state.inCommand&&stream.match(/^\s*#[\w_.]+/i)?"string":stream.match(/^\s*![\w_.]+/i)?"builtin":stream.match(/[<>!=+\-*/\\%]+/)?"operator":stream.match(/\$\[[\w_.]+/)||stream.match(/\$\{[\w_.]+/)||stream.match(/\$\([\w_.]+/)||stream.match(/\$[\w_.]+/)||stream.match(/[}\])]/)?"string":stream.match(/\{.+?\}/)?"variable-3":stream.match(/[\d.:,;\\]+/)?"number":(stream.next(),null)}}}))}function parsevars(v,vars){let r=v;if(vars)for(let x in vars){let v2=vars[x]||`..${x}..`;r=r.replace(new RegExp(`\\[${x}\\]`,"gim"),v2)}return r}const parseinfomd=(data,info,mappa)=>aliasInfo.parse(data,info,mappa),mark=(xx,baseurl,notitle=!1,parsedlist=!1,callback)=>{let res;if(parsedlist)res=tokenize(xx,0,notitle);else{let{txt:txt}=parselist(xx);res=tokenize(txt,0,notitle)}return tokenparser(res,new Render(baseurl,!1,callback))},markeasy=(xx,maxlen=400,notitle=!1)=>{let res=tokenize(xx,maxlen,notitle);return tokenparser(res,new Render,maxlen).out};export{Render,aliasInfo,elang,escapeHTML,formatrule,formatvariante,mark,markeasy,markunoFormatCodeMirror,parseinfomd,parselist,parserule,parsetext,tokenparser as parsetokens,parsevars,tokenize,unescapeHTML};
package/bin/markuno.js CHANGED
@@ -115,12 +115,12 @@ function setOggetto(objDestinazione,objSorgente){"object"==typeof objDestinazion
115
115
  /**
116
116
  * Converte la lista degli errori in stringa
117
117
  * @returns {string} Rappresentazione testuale degli errori
118
- */toString(){const cl=[];for(const e of this.err){const m="object"==typeof e.msg?JSON.stringify(e.msg):e.msg||"";cl.push(`${e.row?e.row+":":""}${m}`)}return cl.join("\n")}},toNum=(n,dec=-1)=>{const num="string"==typeof n?parseFloat(n)||0:n;if(dec<0)return num||0;const factor=Math.pow(10,dec);return Math.round(num*factor)/factor||0};function getheaddims(dims){let res;try{res="object"==typeof dims&&dims?dims:JSON.parse(dims||"{}")}catch(error){res={}}return res||(res={}),res.l||(res.l={visible:1,val:1e3,min:0,max:1e4}),res.a||(res.a={visible:1,val:1e3,min:0,max:1e4}),res.p||(res.p={visible:1,val:1e3,min:0,max:1e4}),res}function sortrows(rows){const k2=Object.keys(rows).sort(),out={};for(let i=0;i<k2.length;i++){const k=k2[i],kk=rows[k];i+1<k2.length&&k2[i+1].startsWith(k+".")?kk.hasliv=1:delete kk.hasliv,out[k]=kk}return out}const REGEX_PARENTESI=/(?<!\w)\(/g,REGEX_NUMERO=/^-?[0-9.]+$/,REGEX_FUNZIONE=/^(\w+)(!)?\[(.*)?\]$/,REGEX_RANDOM=/^(rnd|random|cas)\(/i,REGEX_CLAMP=/^clamp\(/i,REGEX_ROUND=/^(dec|round)\(/i,REGEX_DIGIT=/[0-9.]/,REGEX_OPERATOR=/[+\-*/^%]/,REGEX_ALPHA=/[a-zA-Z]/i;function valutaparentesi(expression){for(expression=(expression+"").trim();;){const tm=REGEX_PARENTESI.exec(expression);if(!tm)break;{const{i:i,res:res}=parsevar(expression,tm.index+1,"(",")");if(i<=0)break;expression=expression.substring(0,tm.index)+valutaparentesi(res[0])+(i>=0?expression.substring(i+1):"")}}return function operatoricomparazione(expression){let left,right;const operators={"||":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"|":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"&&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"<<=":()=>clean(left)<=clean(right),">>=":()=>clean(left)>=clean(right),"===":()=>clean(left)==clean(right),"==":()=>clean(left)==clean(right),"!!":()=>clean(left)!=clean(right),"<<":()=>clean(left)<clean(right),">>":()=>clean(left)>clean(right),"<=":()=>muCalcbase(left)<=muCalcbase(right),">=":()=>muCalcbase(left)>=muCalcbase(right),"<":()=>muCalcbase(left)<muCalcbase(right),">":()=>muCalcbase(left)>muCalcbase(right),"=":()=>muCalcbase(left)==muCalcbase(right),"!":()=>muCalcbase(left)!=muCalcbase(right)};let operatorIndex=-1,op="";for(const operator in operators)if(operatorIndex=expression.indexOf(operator),operatorIndex>=0){op=operator;break}return-1!==operatorIndex?(left=expression.slice(0,operatorIndex),right=expression.slice(operatorIndex+op.length),operators[op]&&operators[op]()?1:0):muCalcbase(expression)}(expression=function valutainsiemi(expression){if(expression.includes("[")){function resinisiemi(rr){const v1=rr[1],fl=!!rr[2],vv=getcolonne(rr[3]);for(const v of vv)if(v==v1)return fl?"0":"1";return fl?"1":"0"}for(;;){const rr=REGEX_FUNZIONE.exec(expression);if(!rr)break;{const tm=resinisiemi(rr);expression=expression.substring(0,rr.index)+tm+expression.substring(rr.index+rr[0].length)}}}return expression}(expression))}const mathFunctions={sqr:x=>Math.sqrt(x),sqrt:x=>Math.sqrt(x),int:x=>Math.floor(x),floor:x=>Math.floor(x),round:x=>Math.round(x),abs:x=>Math.abs(x),sin:x=>Math.sin(x*(Math.PI/180)),cos:x=>Math.cos(x*(Math.PI/180)),tan:x=>Math.tan(x*(Math.PI/180)),atan:x=>Math.atan(x*(Math.PI/180)),atan2:(x,y)=>Math.atan2(x,y)*(Math.PI/180),asin:x=>Math.asin(x*(Math.PI/180)),acos:x=>Math.acos(x*(Math.PI/180))};function muCalcbase(expression){let index=0;function parseOperator(){const op=expression[index];return REGEX_OPERATOR.test(op)?(index++,op):null}function parsePrimary(){if(REGEX_DIGIT.test(expression[index]))return function parseNumber(){const start=index;for(;index<expression.length&&REGEX_DIGIT.test(expression[index]);)index++;return Number(expression.slice(start,index))}();if("("===expression[index]){index++;const result=parseExpr();return")"===expression[index]&&index++,result}return REGEX_ALPHA.test(expression[index])?function parseFunctions(){const ex=expression.slice(index);if(!ex)return 0;for(const[name,func]of Object.entries(mathFunctions)){const match=new RegExp(`^(${name})\\(`,"i").exec(ex);if(match){index+=match[0].length;const result=func(parseExpr());return")"===expression[index]&&index++,result}}let fn;if(fn=REGEX_RANDOM.exec(ex),fn){index+=fn[0].length;let min=0,max=1;return")"!==expression[index]&&(min=parseExpr(),","===expression[index]?(index++,max=parseExpr()):(max=min,min=0)),")"===expression[index]&&index++,Math.random()*(max-min)+min}if(fn=REGEX_CLAMP.exec(ex),fn){index+=fn[0].length;const a=parseExpr();","===expression[index]&&index++;const b=parseExpr();","===expression[index]&&index++;const c=parseExpr();return")"===expression[index]&&index++,Math.min(Math.max(a,b),c)}if(fn=REGEX_ROUND.exec(ex),fn){index+=fn[0].length;const value=parseExpr();let decimals=0;return","===expression[index]&&(index++,decimals=parseExpr()),")"===expression[index]&&index++,parseFloat(value.toFixed(decimals))}return index++,parseExpr()}():0}function parseFactor(){let left=parsePrimary();for(;index<expression.length&&/[/*^%]/.test(expression[index]);){const op=parseOperator(),right=parsePrimary();"*"===op?left*=right:"/"===op?left=right?left/right:0:"%"===op?left=right?left%right:0:"^"===op&&(left=Math.pow(left,right))}return left}function parseExpr(){let left=parseFactor();for(;index<expression.length&&/[+-]/.test(expression[index]);){const op=parseOperator(),right=parseFactor();"+"===op?left+=right:"-"===op&&(left-=right)}return left}return expression=expression.replace(/\s/g,""),parseExpr()}
118
+ */toString(){const cl=[];for(const e of this.err){const m="object"==typeof e.msg?JSON.stringify(e.msg):e.msg||"";cl.push(`${e.row?e.row+":":""}${m}`)}return cl.join("\n")}},toNum=(n,dec=-1)=>{const num="string"==typeof n?parseFloat(n)||0:n;if(dec<0)return num||0;const factor=Math.pow(10,dec);return Math.round(num*factor)/factor||0};function getheaddims(dims){let res;try{res="object"==typeof dims&&dims?dims:JSON.parse(dims||"{}")}catch(error){res={}}return res||(res={}),res.l||(res.l={visible:1,val:1e3,min:0,max:1e4}),res.a||(res.a={visible:1,val:1e3,min:0,max:1e4}),res.p||(res.p={visible:1,val:1e3,min:0,max:1e4}),res}function sortrows(rows){const k2=Object.keys(rows).sort(),out={};for(let i=0;i<k2.length;i++){const k=k2[i],kk=rows[k];i+1<k2.length&&k2[i+1].startsWith(k+".")?kk.hasliv=1:delete kk.hasliv,out[k]=kk}return out}const REGEX_PARENTESI=/(?<!\w)\(/g,REGEX_NUMERO=/^-?[0-9.]+$/,REGEX_FUNZIONE=/^(\w+)(!)?\[(.*)?\]$/,REGEX_RANDOM=/^(rnd|random|cas)\(/i,REGEX_CLAMP=/^clamp\(/i,REGEX_ROUND=/^(dec|round)\(/i,REGEX_DIGIT=/[0-9.]/,REGEX_OPERATOR=/[+\-*/^%]/,REGEX_ALPHA=/[a-zA-Z]/i;function valutaparentesi(expression){for(expression=(expression+"").trim();;){const tm=REGEX_PARENTESI.exec(expression);if(!tm)break;{const{i:i,res:res}=parsevar(expression,tm.index+1,"(",")");if(i<=0)break;expression=expression.substring(0,tm.index)+valutaparentesi(res[0])+(i>=0?expression.substring(i+1):"")}}return function operatoricomparazione(expression){let left,right;const operators={"||":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"|":()=>valutaparentesi(left)||valutaparentesi(right)?1:0,"&&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"&":()=>valutaparentesi(left)&&valutaparentesi(right)?1:0,"<<=":()=>clean(left)<=clean(right),">>=":()=>clean(left)>=clean(right),"===":()=>clean(left)==clean(right),"==":()=>clean(left)==clean(right),"!!":()=>clean(left)!=clean(right),"<<":()=>clean(left)<clean(right),">>":()=>clean(left)>clean(right),"<=":()=>muCalcbase(left)<=muCalcbase(right),">=":()=>muCalcbase(left)>=muCalcbase(right),"<":()=>muCalcbase(left)<muCalcbase(right),">":()=>muCalcbase(left)>muCalcbase(right),"=":()=>muCalcbase(left)==muCalcbase(right),"!":()=>muCalcbase(left)!=muCalcbase(right)};let operatorIndex=-1,op="";for(const operator in operators)if(operatorIndex=expression.indexOf(operator),operatorIndex>=0){op=operator;break}return-1!==operatorIndex?(left=expression.slice(0,operatorIndex),right=expression.slice(operatorIndex+op.length),operators[op]&&operators[op]()?1:0):muCalcbase(expression)}(expression=function valutainsiemi(expression){if(expression.includes("[")){function resinisiemi(rr){const v1=rr[1],fl=!!rr[2],vv=getcolonne(rr[3]);for(const v of vv)if(v==v1)return fl?"0":"1";return fl?"1":"0"}for(;;){const rr=REGEX_FUNZIONE.exec(expression);if(!rr)break;{const tm=resinisiemi(rr);expression=expression.substring(0,rr.index)+tm+expression.substring(rr.index+rr[0].length)}}}return expression}(expression))}const mathFunctions={sqrt:x=>Math.sqrt(x),sqr:x=>Math.sqrt(x),pow:(x,y)=>Math.pow(x,y),int:x=>Math.floor(x),floor:x=>Math.floor(x),round:x=>Math.round(x),dec:(x,d=0)=>Number.parseFloat(x).toFixed(d),abs:x=>Math.abs(x),sin:x=>Math.sin(x*Math.PI/180),cos:x=>Math.cos(x*Math.PI/180),tan:x=>Math.tan(x*Math.PI/180),asin:x=>180*Math.asin(x)/Math.PI,acos:x=>180*Math.acos(x)/Math.PI,atan:x=>180*Math.atan(x)/Math.PI,atan2:(x,y)=>180*Math.atan2(x,y)/Math.PI,log:x=>Math.log(x),log10:x=>Math.log10(x),min:(x,y)=>Math.min(x,y),max:(x,y)=>Math.max(x,y),clamp:(x,min,max)=>Math.max(min,Math.min(max,x)),rnd:()=>Math.random(),cas:(a,b)=>Math.floor(Math.random()*(b-a+1))+a};function muCalcbase(expression){let index=0;function parseOperator(){const op=expression[index];return REGEX_OPERATOR.test(op)?(index++,op):null}function parsePrimary(){if(REGEX_DIGIT.test(expression[index]))return function parseNumber(){const start=index;for(;index<expression.length&&REGEX_DIGIT.test(expression[index]);)index++;return Number(expression.slice(start,index))}();if("("===expression[index]){index++;const result=parseExpr();return")"===expression[index]&&index++,result}return REGEX_ALPHA.test(expression[index])?function parseFunctions(){const ex=expression.slice(index);if(!ex)return 0;for(const[name,func]of Object.entries(mathFunctions)){const match=new RegExp(`^(${name})\\(`,"i").exec(ex);if(match){index+=match[0].length;const result=func(parseExpr());return")"===expression[index]&&index++,result}}let fn;if(fn=REGEX_RANDOM.exec(ex),fn){index+=fn[0].length;let min=0,max=1;return")"!==expression[index]&&(min=parseExpr(),","===expression[index]?(index++,max=parseExpr()):(max=min,min=0)),")"===expression[index]&&index++,Math.random()*(max-min)+min}if(fn=REGEX_CLAMP.exec(ex),fn){index+=fn[0].length;const a=parseExpr();","===expression[index]&&index++;const b=parseExpr();","===expression[index]&&index++;const c=parseExpr();return")"===expression[index]&&index++,Math.min(Math.max(a,b),c)}if(fn=REGEX_ROUND.exec(ex),fn){index+=fn[0].length;const value=parseExpr();let decimals=0;return","===expression[index]&&(index++,decimals=parseExpr()),")"===expression[index]&&index++,parseFloat(value.toFixed(decimals))}return index++,parseExpr()}():0}function parseFactor(){let left=parsePrimary();for(;index<expression.length&&/[/*^%]/.test(expression[index]);){const op=parseOperator(),right=parsePrimary();"*"===op?left*=right:"/"===op?left=right?left/right:0:"%"===op?left=right?left%right:0:"^"===op&&(left=Math.pow(left,right))}return left}function parseExpr(){let left=parseFactor();for(;index<expression.length&&/[+-]/.test(expression[index]);){const op=parseOperator(),right=parseFactor();"+"===op?left+=right:"-"===op&&(left-=right)}return left}return expression=expression.replace(/\s/g,""),parseExpr()}
119
119
  /**
120
120
  * Valuta un'espressione matematica o logica e restituisce il risultato
121
121
  * @param {string|number} expression - L'espressione da valutare
122
122
  * @returns {number} Il risultato della valutazione dell'espressione
123
- * @description
123
+ * @description
124
124
  * Supporta operazioni matematiche di base, funzioni trigonometriche,
125
125
  * operatori di confronto e operazioni logiche.
126
126
  * Le funzioni supportate includono: sqrt, floor, abs, sin, cos, random, clamp, round
@@ -142,13 +142,13 @@ function setOggetto(objDestinazione,objSorgente){"object"==typeof objDestinazion
142
142
  */dump(isstr=!1){let cl=[];for(const t in this.dictionary)cl.push({cod:t,val:this.dictionary[t]});return cl=cl.sort(((a,b)=>a.cod>b.cod)),isstr?cl.map((e=>`${e.cod} = ${isObject(e.val)?JSON.stringify(e.val,null,2):e.val}`)):cl}
143
143
  /**
144
144
  * Aggiunge o rimuove una variabile
145
- */add(key,value){"number"==typeof value&&(value=String(value));const sanitizedKey=Variabile.sanitizeKey(key);if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();0===value||value?this.dictionary[lowercaseKey]=value:delete this.dictionary[lowercaseKey]}else logga(`Invalid key: ${key}`)}
145
+ */add(key,value){if("number"==typeof value&&(value=String(value)),key.includes("*")){const sanitizedKey=Variabile.sanitizeKey(key.split("*")[0]);if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();let cl=Object.keys(this.dictionary).filter((e=>e.startsWith(lowercaseKey)));for(let c of cl)value?this.dictionary[c]=value:delete this.dictionary[c]}}else{const sanitizedKey=Variabile.sanitizeKey(key);if(Variabile.isValidKey(sanitizedKey)){const lowercaseKey=sanitizedKey.toLowerCase();0===value||value?this.dictionary[lowercaseKey]=value:delete this.dictionary[lowercaseKey]}else logga(`Invalid key: ${key}`)}}removeallvars(exclude){if(Array.isArray(exclude)){let tm=Object.keys(this.dictionary);for(let t of tm)exclude.includes(t)||delete this.dictionary[t]}else this.dictionary={}}
146
146
  /**
147
147
  * Valuta un'espressione con supporto per callback asincroni
148
148
  */valutasync(str){return valutabase(this,str)}async valuta(ex,callback){this.stl={};let tm=await async function valutafunc(sh,ex,callback){if(ex){for(let ii=0;ii<20;ii++){const i1=ex.lastIndexOf("$[");if(!(i1>=0)){ex=valutabase(sh,ex);break}{const{i:i,res:res}=parsevar(ex,i1+2,"[","]"),t1=valutabase(sh,ex.substring(0,i1)),t2=res?res[0].startsWith(".")?valutabase(sh,res.join(":")):valutabase(sh,res[0]):"",t3=i>=0?valutabase(sh,ex.substring(i+1)):"";let t4=valutaquadra(sh,t2);if("object"==typeof t4&&(t4=callback?await callback(t4?.fun,t4.pars):`** fun: ${t4.fun} ** `),isObject(t4))return t4;ex=t1+t4+t3}}return ex}return""}(this,ex,callback);return isObject(tm)||(tm=(ex=>{for(;;){const i1=ex.indexOf("{");if(!(i1>=0))break;{const{i:i,res:res}=parsevar(ex,i1+1,"{","}");if(i<0)return ex;ex=ex.substring(0,i1)+muCalc(res[0])+(i>=0?ex.substring(i+1):"")}}return ex})(tm)),tm}async parametrokeyval(p){if("string"!=typeof p)return{};if(!(p=p.trim()))return{};let k,v,q,isnum=!1;return p.startsWith("#")&&(isnum=!0,p=p.slice(1)),q=p.indexOf("="),q>0?(k=clean(p.slice(0,q)),v=p.slice(q+1)):(q=p.indexOf(":"),q>0?(k=clean(p.slice(0,q)),v=p.slice(q+1),v=this.var(v)):(k=clean(p),v=this.var(k))),v&&"string"==typeof v&&v.includes("$")&&(v=await this.valuta(v)),["l","a","p"].includes(k)&&(isnum=!0),isnum&&(v=muCalc(v)),{k:k,v:v}}}class CodiceBarra{constructor(){this.barre={}}azzera(){this.barre={}}oriented(t,l,a,p){switch(t=(t||"1").substr(0,1).toLowerCase()){case"0":break;case"l":return{t:"l",x:l};case"a":return{t:"a",x:a};case"p":return{t:"p",x:p};case"2":return{t:t,x:l,y:p,z:a};case"5":return{t:t,x:l,y:a,z:p};case"4":return{t:t,x:p,y:l,z:a};case"3":return{t:t,x:a,y:p,z:l};case"6":return{t:t,x:p,y:a,z:l};default:return{t:"1",x:a,y:l,z:p}}}async getcode(codicebarratot,l,a,p,callback){let[codicebarra,modello]=codicebarratot.split(":");modello=modello||"";const getcode0=async(codicebarra,liv)=>{let barra=this.barre[codicebarra];if(!barra&&callback&&(barra=await callback(codicebarra),barra||(barra={t:"1",r:[]}),this.barre[codicebarra]=barra,barra.coderr&&"errore"!=barra.coderr||(barra.coderr=`#err_${codicebarra}`)),!barra||0==barra.r.length)return{extra:{err:"missing codicebarra"},c:`#err_${codicebarra}`,fm:10};const{t:t,x:x,y:y,z:z}=this.oriented(codicebarra,l,a,p),extra={barra:codicebarra,fm:barra.fm,t:t,liv:liv,items:barra.r.length,err:""};let bx=barra.r;if(z){const t2=bx.filter((e=>e.z===z||!e.z));t2.length>0?bx=t2:extra.err=`spessore non coerente: ${z}`}if("l"==t||"a"==t||"p"==t){const t=bx.find((e=>e.x>=x));if(t)return{c:t.c,fm:t.x==x?0:1,x1:t.x,x:x,extra:extra}}else{let t=bx.find((e=>e.x==x&&e.y==y));if(t)return{c:t.c,fm:0,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra};if(0!=barra.fm&&(t=bx.find((e=>e.x>=x&&e.y==y)),t))return{c:t.c,fm:1,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra};if(0!=barra.fm&&2!=barra.fm&&(t=bx.find((e=>e.x>=x&&e.y>=y)),t))return{c:t.c,fm:2,x:x,y:y,z:z,x1:t.x,y1:t.y,z1:t.z,extra:extra}}return barra.codalt&&liv<5?await getcode0(barra.codalt,liv+1):{c:barra.coderr,fm:9,x:x,y:y,z:z,extra:extra}};return await getcode0(codicebarra,0)}compila(vettore,headers){headers||(headers={});const barre={};if(Array.isArray(vettore)){for(const r of vettore)if(r.cod=clean(r.cod),r.barcode=clean(r.barcode),r.barcode.length>2&&"+"==r.barcode[0]){r.barcode=r.barcode.substr(1);const tm=this.oriented(r.barcode.substr(0,1),r.l,r.a,r.p);tm.c=r.modello?{c:r.cod,m:r.modello}:r.cod,barre[r.barcode]||(barre[r.barcode]={t:r.barcode.substr(0,1),r:[]},headers[r.barcode]&&(barre[r.barcode]=Object.assign(headers[r.barcode],barre[r.barcode]))),barre[r.barcode].r.push(tm)}for(const x in barre){barre[x].r.sort(((a,b)=>a.y?1e4*(a.x-b.x)+(a.y-b.y):a.x-b.x))}}this.barre=barre}}
149
149
  /**
150
150
  * Costanti e espressioni regolari utilizzate nel modulo
151
- */const keys="IFDEF|IFNDEF|CACHE|CVAR|LOOK|LOOKB|SELECT|CASES|CASE|LOG|MSG|DEFAULT|ELSEIFDEF|ELSEIFNDEF|ELSEIF|ELSE|ENDIF|ENDSELECT|PUSH|POP|FUNC|MACRO|LETS|LETO|LETM|LETT|LETV|LETM|LET|DEF|DO|VARIANTE|FORVAR|FOR|LOOP|ENDFOR|BREAK|EXIT|EXITFOR|CONTINUE|IF|INC|I|F|M|J|:P".split("|");function toCadPars(str){const t0=muClComments(str),t2=[];for(const row of t0){const t1=row.includes("(")||row.includes("[")?[row]:getcolonne(row,!0);let fl=!1;for(const t of t1)!t.startsWith('"')&&t.includes("=")?(t2.push(t),fl=!0):fl&&(t2[t2.length-1]+=","+t)}const pars={};for(const x of t2){let{v:v,o:o}=getcouple(x,"=",!1);o=o||"",v&&(/^[-+]?\d*\.?\d+$/.test(o)&&(o=parseFloat(o)),pars[v]=o)}return pars}
151
+ */const keys="IFDEF|IFNDEF|SETDEF|CACHE|CVAR|LOOK|LOOKB|SELECT|CASES|CASE|LOG|MSG|DEFAULT|ELSEIFDEF|ELSEIFNDEF|ELSEIF|ELSE|ENDIF|ENDSELECT|PUSH|POP|FUNC|MACRO|LETS|LETO|LETM|LETT|LETV|LETM|LET|DEF|DO|VARIANTE|FORVAR|FOR|LOOP|ENDFOR|BREAK|EXIT|EXITFOR|CONTINUE|IF|INC|I|F|M|J|:P".split("|");function toCadPars(str){const t0=muClComments(str),t2=[];for(const row of t0){const t1=row.includes("(")||row.includes("[")?[row]:getcolonne(row,!0);let fl=!1;for(const t of t1)!t.startsWith('"')&&t.includes("=")?(t2.push(t),fl=!0):fl&&(t2[t2.length-1]+=","+t)}const pars={};for(const x of t2){let{v:v,o:o}=getcouple(x,"=",!1);o=o||"",v&&(/^[-+]?\d*\.?\d+$/.test(o)&&(o=parseFloat(o)),pars[v]=o)}return pars}
152
152
  /**
153
153
  * Rimuove i commenti dal codice sorgente mantenendo la struttura del codice
154
154
  * @param {string} codice - Il codice sorgente da processare
@@ -251,9 +251,9 @@ this.amb=amb}
251
251
  * @param {Object|string} content - Contenuto da caricare, può essere un oggetto o una stringa
252
252
  * @returns {Promise<void>} Promise che si risolve al completamento del caricamento
253
253
  */async loadContentExtended(content){if("object"==typeof content){for(const x in content)["rows","des","h","alias","obbligo"].includes(x)&&(this[x]=content[x]);"string"==typeof content.def&&content.def.length&&(this.vdef=getcolonne(content.def.trim().toLowerCase())),content.filter&&content.filter.length&&(this.limits=parselimitifromdb(content.filter))}else await this._loadContent(muClComments(content,!1))}todata(){return{name:this.name,des:this.des,alias:this.alias,obbligo:this.obbligo,h:this.h,rows:this.rows,limits:this.limits,key:this.key}}}const _nofunc={};async function getcbfunc(tm,cmd,pars,vari,amb,output){if(cbFunc){if(_nofunc[cmd])return"";let a=await cbFunc(cmd,pars,vari,amb,output);return isObject(a)||(a=(a||"").trim(),"!"==a&&(_nofunc[cmd]=!0,a="")),a}return tm}async function intvaluta(amb,mac,str){return await amb.vari.valuta(str,(async(fun,pars)=>{if("dim"===fun){let dm=muCalc(pars[1]),vv=await dammivariante(amb,mac,pars[2]),col=parseInt(pars[3])||2;return vv&&vv.fromdim?vv.fromdim(dm,col):dm}return await getcbfunc(`**fun:${fun}**`,fun,pars,amb.vari,amb)}))}async function dammivariante(amb,macro,ky){let tm;return tm=macro&&macro?.localvar&&macro.localvar[ky]?macro.localvar[ky]:await amb.getvariante(ky),tm}async function impostavariante(amb,macro,a,b,head){let tm,ky=a;if((b=b||"")&&"string"==typeof b){const k=b.indexOf(":");k>=0&&(k>0&&(ky=clean(b.slice(0,k))),b=b.slice(k+1))}
254
- /** @type {Variante} */if(head&&head.alias&&(ky=head.alias),macro&&macro.paralias&&macro.paralias[a]&&(ky=macro.paralias[a]),tm=await dammivariante(amb,macro,ky),tm)if(head&&head.t){head.des||(head.des=tm.des);let x8=head?.filtra||"";if(x8.includes("$")&&(x8=await amb.vari.valuta(x8)),"m"===head.t){let col=2;if(b.includes(":")){const xx=b.split(":");col=parseInt(xx[1]),b=xx[0]}tm.limita(x8),b=tm.fromdim(parseFloat(b),col)}else{tm.limita(x8);const b1=tm.firstvalid(b,getcolonne(head.def));b=tm.tovar(b1)}}else tm.resetfilter(),b=tm.firstvalid(b),b=tm.tovar(b);else head&&head.t&&head.t;return amb.vari.add(a,b),b}async function pushpars(amb,macro,parsfunzione,parsinit){const fatti={},vals=[];if(parsfunzione)for(const x of parsfunzione){const{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}if(parsinit)for(const x of parsinit){const{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}return vals}function poppars(amb,tm){if(tm)for(const x of tm)amb.vari.add(x.v,x.o)}const outpush=(output,a)=>{null!=a&&null!=a&&("object"==typeof a?output.push(JSON.stringify(a,null,2)):"string"==typeof a&&a.startsWith("_ ")&&output.length>0&&"string"==typeof output[output.length-1]?output[output.length-1]+=a.slice(2):output.push(...a.split("\n")))};async function muEval(amb,mac,codice,options){if(!Array.isArray(codice))return errori.add("codice is not a valid parsed array"),[];options||(options={}),options.id||(options.id="_"),options._stackmacro||(options._stackmacro=0),options.limited||(options.limited=!1),amb||errori.add("amb deve essere definito");const vari=amb.vari;amb.maxdelays,amb.cat;const output=[];let macro,pars,xid;tk();for(let ii=0;ii<codice.length;){let riga=codice[ii];switch(riga.tipo){case"IFDEF":case"IFNDEF":case"IF":{const tm="IF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"IFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);riga.next?(codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)):errori.add("Troppo tempo",riga)}break;case"SELECT":riga.next?(codice[riga.next].t1=await intvaluta(amb,mac,riga.contenuto),ii=riga.next-1):errori.add("manca endselect",riga);break;case"CASE":case"CASES":case"DEFAULT":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{let vv,tm=1;const _getvv=async()=>{let vv=await intvaluta(amb,mac,riga.contenuto);return vv=vv.includes(":")&&!vv.includes(",")?vv.split(":").map((e=>(e||"").trim())):getcolonne(vv),vv};if("CASE"==riga.tipo){tm=0,vv=await _getvv();const tmx=muCalc(riga.t1||"");vv.find((v=>muCalc(v)==tmx))&&(tm=1)}else if("CASES"==riga.tipo){tm=0,vv=await _getvv();const tmx=riga.t1||"";vv.find((v=>v==tmx))&&(tm=1)}codice[riga.next].jlast=tm?1:0,codice[riga.next].t1=riga.t1,tm||(ii=riga.next-1)}else errori.add("manca select",riga);break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{const tm="ELSE"==riga.tipo?1:"ELSEIF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"ELSEIFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)}else errori.add("manca endif",riga);break;case"ENDIF":case"ENDSELECT":case"CACHE":case"CVAR":break;case"PUSH":vari.push();break;case"POP":vari.pop();break;case"INC":case"I":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else if(({macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{}),macro){options._inc=!0,options._stackmacro++;const saved={},parametri=macro.parametri?._;if(parametri&&parametri.length)for(const x of parametri){const x1=clean(x.split("=")[0]||"",!0);x1&&(saved[x1]=vari.dictionary[x1])}await macro.impostaparametri(parametri,pars);const rs1=await muEval(amb,macro,macro.codice,options);for(const v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];output.push(...rs1),options._stackmacro--,options._inc=!1}break;case"MACRO":case"M":case"FUNC":case"F":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{let{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){const ismacro=!!options.grafica||["F","FUNC"].includes(riga.tipo),optid=options.id||"",parametri=macro.parametri?._,saved={};if(ismacro)vari.push();else{if(macro.head)for(const x of macro.head)saved[x.cod]=amb.vari.var(x.cod);if(parametri&&parametri.length)for(const x of parametri){const x1=(x.split("=")[0]||"").trim().toLowerCase();x1&&(saved[x1]=vari.dictionary[x1])}}if(macro.codice.length){if(options._stackmacro++,options.grafica&&"function"==typeof options.grafica){let f="",xid="";pars&&pars.length?(f=pars.find((e=>e.startsWith("#id"))),f?(f=await vari.valuta(f.slice(4)),f.startsWith("#")?options.id=f:options.id=hash(`${ii}${macro.name}${optid}${f}`),pars=pars.filter((e=>!e.startsWith("#id"))),xid=options.id):options.id=hash(`z${optid}${ii}`)):options.id=hash(`z${optid}${ii}`);let tm=amb.pick.key;amb.pick.key=options.id;const out=await options.grafica({tipo:riga.tipo,id:xid,pars:pars,parametri:parametri,macro:macro,options:options,vari:amb.vari,amb:amb});amb.pick.key=tm,output.push(out)}else{await macro.impostaparametri(parametri,pars);let tm=amb.vari.var("_rootnode");amb.vari.add("_rootnode","0");const rs1=await muEval(amb,macro,macro.codice,options);amb.vari.add("_rootnode",tm),output.push(...rs1)}options._stackmacro--}if(ismacro)vari.pop();else for(const v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];options.id=optid}else errori.add("Macro non trovata!",riga)}break;case"LET":case"LETS":{let i=riga.contenuto.indexOf("="),j=-1;if(i>=0&&(j=riga.contenuto.indexOf("=",i+1)),j<0){const v=riga.contenuto;if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i).trim());let b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}else{const vv=getcolonne(riga.contenuto);for(const v of vv)if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i));let b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}}break;case"LETT":{const i=riga.contenuto.indexOf("=");if(i>0){const a=await intvaluta(amb,mac,riga.contenuto.slice(0,i).trim()),b=await intvaluta(amb,mac,riga.contenuto.slice(i+1).trim());vari.add(a,b)}}break;case"LOOK":case"LOOKB":{const cc=getcolonne(await intvaluta(amb,mac,riga.contenuto)),base=muCalc(cc[1]),col=muCalc(cc[3]),ww=await dammivariante(amb,macro,cc[2]);if(ww&&ww.rows){const rr=Object.values(ww.rows).reduce(((t,e)=>{const val=parseInt(e.v[col?col-1:0]);return val&&("LOOKB"==riga.tipo?val<=base&&val>t.v&&(t.v=val,t.c=e.v[0]):val>=base&&val<t.v&&(t.v=val,t.c=e.v[0])),t}),{v:"LOOKB"==riga.tipo?0:1/0,c:""});rr&&rr.c&&(amb.vari.add(cc[0],ww.tovar(rr.c)),options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:cc[0],valore:ww.tovar(rr.c),riga:riga}))}else amb.vari.add(cc[0],`${base},no,no`)}break;case"LETV":case"LETM":case"DEF":{const tm=getcolonne(riga.contenuto);if(tm)for(const x of tm){let{v:v,o:o,fl:fl}=getcouple(x);if(fl){v=await vari.valuta(v),o=await intvaluta(amb,mac,o);const valore=await impostavariante(amb,mac,v.trim().toLowerCase(),o.trim().toLowerCase(),"LETM"==riga.tipo?{t:"m"}:{t:"v"});options._stackmacro<=0&&options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:v,valore:valore,riga:riga})}}}break;case"DO":{const valido=(riga.contenuto||"").trim();let fl=!0;valido&&!muCalc(await intvaluta(amb,mac,valido))&&(fl=!1),riga.next&&(fl||(ii=riga.next+1))}break;case"VARIANTE":case"FORVAR":case"FOR":{let vv,valido,elenco,v;if(options.oldstyle?(vv=riga.contenuto.split(","),v=vv[2]||"i",elenco=vv[0],valido=vv[1]):(vv=getcolonne(riga.contenuto||""),v=vv[0]||"",elenco=clean(vv[1],!0),valido=vv[2]||""),v=v.includes("$")?await intvaluta(amb,mac,v):v||"","FORVAR"==riga.tipo||"VARIANTE"==riga.tipo){const tm=await intvaluta(amb,mac,elenco),xx=tm?await dammivariante(amb,mac,tm):void 0;xx?elenco=xx.tovec():(elenco=[],errori.add("getvariante not found!",riga))}else{const txx=await intvaluta(amb,mac,elenco||"");elenco=elenco?getcolonne(txx):void 0}elenco=elenco||[];const nc=0;if(riga.next){codice[riga.next].for={v:v,elenco:elenco,nc:nc,valido:valido};let voce,fl=!0;v&&elenco.length>0?nc>=elenco.length?fl=!1:(voce=elenco[nc],vari.add(v,voce),valido&&(fl=!muCalc(await intvaluta(amb,mac,valido)))):fl=!1,fl||(ii=riga.next-1)}else errori.add("manca endfor/loop",riga)}break;case"LOOP":{let fl=!0;riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))&&(fl=!1),fl&&(ii=riga.prev-1);break}case"ENDFOR":if(!riga.contenuto||muCalc(await intvaluta(amb,mac,riga.contenuto)))if(riga.for){const{v:v,elenco:elenco,valido:valido}=riga.for;if(v&&elenco.length>0&&riga.for.nc<500)for(;;){if(riga.for.nc++,riga.for.nc<elenco.length){if(vari.add(v,elenco[riga.for.nc]),valido&&muCalc(await intvaluta(amb,mac,valido)))continue;ii=riga.prev;break}break}}else errori.add("manca istruzione for",riga);break;case"BREAK":case"EXIT":case"EXITFOR":riga.next?riga.contenuto.trim()?muCalc(await intvaluta(amb,mac,riga.contenuto))&&(ii=riga.next):ii=riga.next:errori.add("break outside loop",riga);break;case"CONTINUE":riga.next?riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))||(ii=riga.next-1):errori.add("continue outside loop",riga);break;case"MSG":case"LOG":{const tm99=await intvaluta(amb,mac,riga.contenuto);logga(tm99),errori.add(tm99)}break;default:{let tm;if(riga.contenuto.startsWith("!")){tm=await intvaluta(amb,mac,riga.contenuto);let a="";const rr=/^!(.\w+)[\s;,]\s*(.+)?$/gim.exec(tm);if(rr)if(rr[1].startsWith("."))await getcbfunc(tm,tm.slice(1),[],vari,amb),a="";else{const cmd=rr[1].toLowerCase(),pars=getcolonne(rr[2]||"");a=await getcbfunc(tm,cmd,pars,vari,amb)}a&&outpush(output,a)}else options.parsefnpunto&&"function"==typeof options.parsefnpunto&&riga.contenuto.startsWith(".")?await options.parsefnpunto({dati:riga.contenuto,output:output,id:options.id,vari:amb.vari,amb:amb}):(tm=await intvaluta(amb,mac,riga.contenuto),outpush(output,tm))}}ii++}return output}async function muGenerate(macro,amb,genera,callback,isTestmode=0){if(macro.isgenera&&callback){const output={counter:0,keys:{},isTestmode:isTestmode};if(genera){if(!macro.genera[genera])return!1;await muGenerate_0(macro,amb,genera,callback,output)}else for(const gg in macro.genera)await muGenerate_0(macro,amb,gg,callback,output);return!0}}async function muGenerate_0(mac,amb,genera,callback,output){const xgen=mac.genera[genera];if(xgen){output.counter2=0;const working_variant={};async function processavariante(liv){if(output.isTestmode&&output.counter>output.isTestmode)return;if(liv<xgen.vars.length){const xx=xgen.vars[liv];if(!working_variant[xx]){const xvar=await dammivariante(amb,mac,xx),keys=xvar?Object.keys(xvar.rows):void 0;if(keys&&keys.length>0){for(const k of keys)amb.vari.add(xvar.name,xvar.tovar(k)),working_variant[xx]=!0,await processavariante(liv+1),working_variant[xx]=!1;return}logga("manca la variante",xx)}}for(const x of xgen.calcola)mac.formula[x]&&await muEval(amb,mac,mac.formula[x],{limited:!0});for(const x of xgen.exclude)if(mac.formula[x]){const vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});if(vvv)for(const v of vvv){if(muCalc(v))return}}const out1=await muEval(amb,mac,xgen.codice,{limited:!0,localvar:mac.localvar}),bb={};for(const x of xgen.bom)if(mac.formula[x]){let vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});vvv=vvv.join("\n").split("\n");for(const v of vvv)if(v){const tm=getcolonne(v);bb[x]||(bb[x]=[]);const t={};for(let i=0;i<tm.length;i++)t[`c${i}`]=tm[i];bb[x].push(t)}}await async function docallback(callback,out1,bom,xgen,genera,output){let fl=!0;for(const x of out1){const tm=getcolonne(x);if(tm[0]&&!output[tm[0]]){output[tm[0]]=1,output.counter++,output.counter2++;const o={__id:output.counter};for(let i=0;i<tm.length;i++){let key=xgen.head[i]?xgen.head[i]:`c${i}`;"#"==key[0]?(key=key.substr(1),o[key]=Math.round(1e3*muCalc(tm[i]))/1e3):o[key]=tm[i]}await callback(genera,o,fl?bom:void 0,output.counter,output.counter2),fl=!1}}}(callback,out1,bb,xgen,genera,output)}await processavariante(0)}}const DIMS=["l","a","p"],rx1=/^\{(:?(var|valid|formula|genera|header|v|f|g|h))[\s|}]/im,tipifree=["s","g","h","p","q"],tipiheader=[{cod:"t",des:"Variante"},{cod:"q",des:"V.Query"},{cod:"f",des:"Valore Fisso"},{cod:"g",des:"Gruppo"},{cod:"s",des:"Libero"},{cod:"m",des:"Misura"},{cod:"c",des:"Check (no/si)"},{cod:"z",des:"Check (si/no)"},{cod:"h",des:"Hidden"},{cod:"p",des:"Programmato"}],tipicolonna=[{cod:"",des:"Libero"},{cod:"a",des:"Area"},{cod:"t",des:"Thumb",folder:"thumbs"},{cod:"i",des:"Image",folder:"textures"},{cod:"x",des:"3D file",folder:"3d"},{cod:"f",des:"Funzione",folder:"script"}];function valutaCondizioniTestata(vari,str){const vv=str.split("\n");for(const v of vv)if(v.trim()){if(muCalc(vari.valutasync(v)))return!0}return!1}class Macro{constructor(amb,_name){const{name:name,cat:cat}=checkmu(_name,amb.cat||"");this.name=name,this.cat=cat,
254
+ /** @type {Variante} */if(head&&head.alias&&(ky=head.alias),macro&&macro.paralias&&macro.paralias[a]&&(ky=macro.paralias[a]),tm=await dammivariante(amb,macro,ky),tm)if(head&&head.t){head.des||(head.des=tm.des);let x8=head?.filtra||"";if(x8.includes("$")&&(x8=await amb.vari.valuta(x8)),"m"===head.t){let col=2;if(b.includes(":")){const xx=b.split(":");col=parseInt(xx[1]),b=xx[0]}tm.limita(x8),b=tm.fromdim(parseFloat(b),col)}else{tm.limita(x8);const b1=tm.firstvalid(b,getcolonne(head.def));b=tm.tovar(b1)}}else tm.resetfilter(),b=tm.firstvalid(b),b=tm.tovar(b);else head&&head.t&&head.t;return amb.vari.add(a,b),b}async function pushpars(amb,macro,parsfunzione,parsinit){const fatti={},vals=[];if(parsfunzione)for(const x of parsfunzione){const{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}if(parsinit)for(const x of parsinit){const{v:v,o:o,fl:fl}=getcouple(x);fatti[v]||(fatti[v]=!0,vals.push({v:v,o:amb.vari.var[v]}),fl&&await impostavariante(amb,macro,v,o))}return vals}function poppars(amb,tm){if(tm)for(const x of tm)amb.vari.add(x.v,x.o)}const outpush=(output,a)=>{null!=a&&null!=a&&("object"==typeof a?output.push(JSON.stringify(a,null,2)):"string"==typeof a&&a.startsWith("_ ")&&output.length>0&&"string"==typeof output[output.length-1]?output[output.length-1]+=a.slice(2):output.push(...a.split("\n")))};async function muEval(amb,mac,codice,options){if(!Array.isArray(codice))return errori.add("codice is not a valid parsed array"),[];options||(options={}),options.id||(options.id="_"),options._stackmacro||(options._stackmacro=0),options.limited||(options.limited=!1),amb||errori.add("amb deve essere definito");const vari=amb.vari;amb.maxdelays,amb.cat;const output=[];let macro,pars,xid;tk();for(let ii=0;ii<codice.length;){let riga=codice[ii];switch(riga.tipo){case"IFDEF":case"IFNDEF":case"IF":{const tm="IF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"IFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);riga.next?(codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)):errori.add("Troppo tempo",riga)}break;case"SELECT":riga.next?(codice[riga.next].t1=await intvaluta(amb,mac,riga.contenuto),ii=riga.next-1):errori.add("manca endselect",riga);break;case"CASE":case"CASES":case"DEFAULT":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{let vv,tm=1;const _getvv=async()=>{let vv=await intvaluta(amb,mac,riga.contenuto);return vv=vv.includes(":")&&!vv.includes(",")?vv.split(":").map((e=>(e||"").trim())):getcolonne(vv),vv};if("CASE"==riga.tipo){tm=0,vv=await _getvv();const tmx=muCalc(riga.t1||"");vv.find((v=>muCalc(v)==tmx))&&(tm=1)}else if("CASES"==riga.tipo){tm=0,vv=await _getvv();const tmx=riga.t1||"";vv.find((v=>v==tmx))&&(tm=1)}codice[riga.next].jlast=tm?1:0,codice[riga.next].t1=riga.t1,tm||(ii=riga.next-1)}else errori.add("manca select",riga);break;case"ELSEIF":case"ELSEIFDEF":case"ELSEIFNDEF":case"ELSE":if(riga.next)if(riga.jlast)riga.jlast=0,ii=riga.last-1;else{const tm="ELSE"==riga.tipo?1:"ELSEIF"==riga.tipo?muCalc(await intvaluta(amb,mac,riga.contenuto)):"ELSEIFDEF"==riga.tipo?""!=await intvaluta(amb,mac,riga.contenuto):""==await intvaluta(amb,mac,riga.contenuto);codice[riga.next].jlast=tm?1:0,tm||(ii=riga.next-1)}else errori.add("manca endif",riga);break;case"ENDIF":case"ENDSELECT":case"CACHE":case"CVAR":break;case"PUSH":vari.push();break;case"POP":vari.pop();break;case"INC":case"I":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else if(({macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{}),macro){options._inc=!0,options._stackmacro++;const saved={},parametri=macro.parametri?._;if(parametri&&parametri.length)for(const x of parametri){const x1=clean(x.split("=")[0]||"",!0);x1&&(saved[x1]=vari.dictionary[x1])}await macro.impostaparametri(parametri,pars);const rs1=await muEval(amb,macro,macro.codice,options);for(const v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];output.push(...rs1),options._stackmacro--,options._inc=!1}break;case"MACRO":case"M":case"FUNC":case"F":if(options._stackmacro>500)errori.add("stack chiamate macro troppo profondo!",riga);else{let{macro:macro,pars:pars,xid:xid}=await amb.getmacro(riga)||{};if(macro){const ismacro=!!options.grafica||["F","FUNC"].includes(riga.tipo),optid=options.id||"",parametri=macro.parametri?._,saved={};if(ismacro)vari.push();else{if(macro.head)for(const x of macro.head)saved[x.cod]=amb.vari.var(x.cod);if(parametri&&parametri.length)for(const x of parametri){const x1=(x.split("=")[0]||"").trim().toLowerCase();x1&&(saved[x1]=vari.dictionary[x1])}}if(macro.codice.length){if(options._stackmacro++,options.grafica&&"function"==typeof options.grafica){let f="",xid="";pars&&pars.length?(f=pars.find((e=>e.startsWith("#id"))),f?(f=await vari.valuta(f.slice(4)),f.startsWith("#")?options.id=f:options.id=hash(`${ii}${macro.name}${optid}${f}`),pars=pars.filter((e=>!e.startsWith("#id"))),xid=options.id):options.id=hash(`z${optid}${ii}`)):options.id=hash(`z${optid}${ii}`);let tm=amb.pick.key;amb.pick.key=options.id;const out=await options.grafica({tipo:riga.tipo,id:xid,pars:pars,parametri:parametri,macro:macro,options:options,vari:amb.vari,amb:amb});amb.pick.key=tm,output.push(out)}else{await macro.impostaparametri(parametri,pars);let tm=amb.vari.var("_rootnode");amb.vari.add("_rootnode","0");const rs1=await muEval(amb,macro,macro.codice,options);amb.vari.add("_rootnode",tm),output.push(...rs1)}options._stackmacro--}if(ismacro)vari.pop();else for(const v in saved)saved[v]?vari.dictionary[v]=saved[v]:delete vari.dictionary[v];options.id=optid}else errori.add("Macro non trovata!",riga)}break;case"SETDEF":{let cl=getcolonne(riga.contenuto.toLowerCase()),tm=await dammivariante(amb,macro,cl[0]),prf=cl[1]||"def_",filtra=cl[2];if(prf.endsWith("_")||(prf+="_"),tm&&tm.rows){cl=Object.keys(tm.rows),filtra&&(cl=cl.filter((e=>e.startsWith(filtra))));for(let c of cl){let ky=`${prf}${c}`;if(!vari.dictionary[ky]){function torow(tm){const cl=[];if(tm)for(const t of tm.v.slice(1))"string"==typeof t&&(t.includes(",")||t.includes(";"))?cl.push(quote(t)):cl.push(t||"");return cl.join(",")}vari.add(ky,await intvaluta(amb,mac,torow(tm.rows[c])))}}}}break;case"LET":case"LETS":{let i=riga.contenuto.indexOf("="),j=-1;if(i>=0&&(j=riga.contenuto.indexOf("=",i+1)),j<0){const v=riga.contenuto;if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i).trim());let b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}else{const vv=getcolonne(riga.contenuto);for(const v of vv)if(i=v.indexOf("="),i>0){const a=await intvaluta(amb,mac,v.slice(0,i));let b=v.slice(i+1).trim();b="LET"==riga.tipo?muCalc(await intvaluta(amb,mac,b))||"":await intvaluta(amb,mac,b),vari.add(a,b)}}}break;case"LETT":{const i=riga.contenuto.indexOf("=");if(i>0){const a=await intvaluta(amb,mac,riga.contenuto.slice(0,i).trim()),b=await intvaluta(amb,mac,riga.contenuto.slice(i+1).trim());vari.add(a,b)}}break;case"LOOK":case"LOOKB":{const cc=getcolonne(await intvaluta(amb,mac,riga.contenuto)),base=muCalc(cc[1]),col=muCalc(cc[3]),ww=await dammivariante(amb,macro,cc[2]);if(ww&&ww.rows){const rr=Object.values(ww.rows).reduce(((t,e)=>{const val=parseInt(e.v[col?col-1:0]);return val&&("LOOKB"==riga.tipo?val<=base&&val>t.v&&(t.v=val,t.c=e.v[0]):val>=base&&val<t.v&&(t.v=val,t.c=e.v[0])),t}),{v:"LOOKB"==riga.tipo?0:1/0,c:""});rr&&rr.c&&(amb.vari.add(cc[0],ww.tovar(rr.c)),options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:cc[0],valore:ww.tovar(rr.c),riga:riga}))}else amb.vari.add(cc[0],`${base},no,no`)}break;case"LETV":case"LETM":case"DEF":{const tm=getcolonne(riga.contenuto);if(tm)for(const x of tm){let{v:v,o:o,fl:fl}=getcouple(x);if(fl){v=await vari.valuta(v),o=await intvaluta(amb,mac,o);const valore=await impostavariante(amb,mac,v.trim().toLowerCase(),o.trim().toLowerCase(),"LETM"==riga.tipo?{t:"m"}:{t:"v"});options._stackmacro<=0&&options.checkheader&&"function"==typeof options.checkheader&&await options.checkheader({variante:v,valore:valore,riga:riga})}}}break;case"DO":{const valido=(riga.contenuto||"").trim();let fl=!0;valido&&!muCalc(await intvaluta(amb,mac,valido))&&(fl=!1),riga.next&&(fl||(ii=riga.next+1))}break;case"VARIANTE":case"FORVAR":case"FOR":{let vv,valido,elenco,v;if(options.oldstyle?(vv=riga.contenuto.split(","),v=vv[2]||"i",elenco=vv[0],valido=vv[1]):(vv=getcolonne(riga.contenuto||""),v=vv[0]||"",elenco=clean(vv[1],!0),valido=vv[2]||""),v=v.includes("$")?await intvaluta(amb,mac,v):v||"","FORVAR"==riga.tipo||"VARIANTE"==riga.tipo){const tm=await intvaluta(amb,mac,elenco),xx=tm?await dammivariante(amb,mac,tm):void 0;xx?elenco=xx.tovec():(elenco=[],errori.add("getvariante not found!",riga))}else{const txx=await intvaluta(amb,mac,elenco||"");elenco=elenco?getcolonne(txx):void 0}elenco=elenco||[];const nc=0;if(riga.next){codice[riga.next].for={v:v,elenco:elenco,nc:nc,valido:valido};let voce,fl=!0;v&&elenco.length>0?nc>=elenco.length?fl=!1:(voce=elenco[nc],vari.add(v,voce),valido&&(fl=!muCalc(await intvaluta(amb,mac,valido)))):fl=!1,fl||(ii=riga.next-1)}else errori.add("manca endfor/loop",riga)}break;case"LOOP":{let fl=!0;riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))&&(fl=!1),fl&&(ii=riga.prev-1);break}case"ENDFOR":if(!riga.contenuto||muCalc(await intvaluta(amb,mac,riga.contenuto)))if(riga.for){const{v:v,elenco:elenco,valido:valido}=riga.for;if(v&&elenco.length>0&&riga.for.nc<500)for(;;){if(riga.for.nc++,riga.for.nc<elenco.length){if(vari.add(v,elenco[riga.for.nc]),valido&&muCalc(await intvaluta(amb,mac,valido)))continue;ii=riga.prev;break}break}}else errori.add("manca istruzione for",riga);break;case"BREAK":case"EXIT":case"EXITFOR":riga.next?riga.contenuto.trim()?muCalc(await intvaluta(amb,mac,riga.contenuto))&&(ii=riga.next):ii=riga.next:errori.add("break outside loop",riga);break;case"CONTINUE":riga.next?riga.contenuto&&!muCalc(await intvaluta(amb,mac,riga.contenuto))||(ii=riga.next-1):errori.add("continue outside loop",riga);break;case"MSG":case"LOG":{const tm99=await intvaluta(amb,mac,riga.contenuto);logga(tm99),errori.add(tm99)}break;default:{let tm;if(riga.contenuto.startsWith("!")){tm=await intvaluta(amb,mac,riga.contenuto);let a="";const rr=/^!(.\w+)[\s;,]\s*(.+)?$/gim.exec(tm);if(rr)if(rr[1].startsWith("."))await getcbfunc(tm,tm.slice(1),[],vari,amb),a="";else{const cmd=rr[1].toLowerCase(),pars=getcolonne(rr[2]||"");a=await getcbfunc(tm,cmd,pars,vari,amb)}a&&outpush(output,a)}else options.parsefnpunto&&"function"==typeof options.parsefnpunto&&riga.contenuto.startsWith(".")?await options.parsefnpunto({dati:riga.contenuto,output:output,id:options.id,vari:amb.vari,amb:amb}):(tm=await intvaluta(amb,mac,riga.contenuto),outpush(output,tm))}}ii++}return output}async function muGenerate(macro,amb,genera,callback,isTestmode=0){if(macro.isgenera&&callback){const output={counter:0,keys:{},isTestmode:isTestmode};if(genera){if(!macro.genera[genera])return!1;await muGenerate_0(macro,amb,genera,callback,output)}else for(const gg in macro.genera)await muGenerate_0(macro,amb,gg,callback,output);return!0}}async function muGenerate_0(mac,amb,genera,callback,output){const xgen=mac.genera[genera];if(xgen){output.counter2=0;const working_variant={};async function processavariante(liv){if(output.isTestmode&&output.counter>output.isTestmode)return;if(liv<xgen.vars.length){const xx=xgen.vars[liv];if(!working_variant[xx]){const xvar=await dammivariante(amb,mac,xx),keys=xvar?Object.keys(xvar.rows):void 0;if(keys&&keys.length>0){for(const k of keys)amb.vari.add(xvar.name,xvar.tovar(k)),working_variant[xx]=!0,await processavariante(liv+1),working_variant[xx]=!1;return}logga("manca la variante",xx)}}for(const x of xgen.calcola)mac.formula[x]&&await muEval(amb,mac,mac.formula[x],{limited:!0});for(const x of xgen.exclude)if(mac.formula[x]){const vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});if(vvv)for(const v of vvv){if(muCalc(v))return}}const out1=await muEval(amb,mac,xgen.codice,{limited:!0,localvar:mac.localvar}),bb={};for(const x of xgen.bom)if(mac.formula[x]){let vvv=await muEval(amb,mac,mac.formula[x],{limited:!0});vvv=vvv.join("\n").split("\n");for(const v of vvv)if(v){const tm=getcolonne(v);bb[x]||(bb[x]=[]);const t={};for(let i=0;i<tm.length;i++)t[`c${i}`]=tm[i];bb[x].push(t)}}await async function docallback(callback,out1,bom,xgen,genera,output){let fl=!0;for(const x of out1){const tm=getcolonne(x);if(tm[0]&&!output[tm[0]]){output[tm[0]]=1,output.counter++,output.counter2++;const o={__id:output.counter};for(let i=0;i<tm.length;i++){let key=xgen.head[i]?xgen.head[i]:`c${i}`;"#"==key[0]?(key=key.substr(1),o[key]=Math.round(1e3*muCalc(tm[i]))/1e3):o[key]=tm[i]}await callback(genera,o,fl?bom:void 0,output.counter,output.counter2),fl=!1}}}(callback,out1,bb,xgen,genera,output)}await processavariante(0)}}const DIMS=["l","a","p"],rx1=/^\{(:?(var|valid|formula|genera|header|v|f|g|h))[\s|}]/im,tipifree=["s","g","h","p","q"],tipiheader=[{cod:"t",des:"Variante"},{cod:"q",des:"V.Query"},{cod:"f",des:"Valore Fisso"},{cod:"g",des:"Gruppo"},{cod:"s",des:"Libero"},{cod:"m",des:"Misura"},{cod:"c",des:"Check (no/si)"},{cod:"z",des:"Check (si/no)"},{cod:"h",des:"Hidden"},{cod:"p",des:"Programmato"}],tipicolonna=[{cod:"",des:"Libero"},{cod:"a",des:"Area"},{cod:"t",des:"Thumb",folder:"thumbs"},{cod:"i",des:"Image",folder:"textures"},{cod:"x",des:"3D file",folder:"3d"},{cod:"f",des:"Funzione",folder:"script"}];function valutaCondizioniTestata(vari,str){const vv=str.split("\n");for(const v of vv)if(v.trim()){if(muCalc(vari.valutasync(v)))return!0}return!1}class Macro{constructor(amb,_name){const{name:name,cat:cat}=checkmu(_name,amb.cat||"");this.name=name,this.cat=cat,
255
255
  /** @type {Ambiente} */
256
- this.amb=amb,this.azzera()}azzera(){this.key=`${this.cat}/${this.name}`,this.localvar={},this.head=[],this.frontend=!1,this.valid=[],this.parametri={},this.paralias={},this.formula={},this.settings={},this.errori=[],this.codice=[],this.genera={}}get isgenera(){return Object.keys(this.genera).length||0}get iscodice(){return this.codice.length||0}get isheader(){return this.head?.length||0}geterrori(){const cl=[];return this.errori.forEach((e=>cl.push({e:e}))),cl}getparametri(){const s={};if(this.dims&&DIMS.forEach((k=>{const t=muCalc(this.amb.vari.var(k));t&&(s[k]=String(t))})),this.head){for(const x of this.head)if(!x._h){let tm=this.amb.vari.var(x.cod);tipifree.includes(x.t)||"string"==typeof tm&&(tm=tm.split(",")[0]),s[x.cod]=tm}}else if(this.parametri?._)for(const x of this.parametri._){const x1=(x.split("=")[0]||"").trim().toLowerCase();let tm=this.amb.vari.var[x1];tm=(tm||"").split(",")[0],s[x1]=tm}return s}async setparametri(pars){const ff={},ruleset=this.amb.ruleset||{};pars||(pars={}),this.dims&&DIMS.forEach((e=>{let t=pars[e]||this.dims[e].val;t=parseFloat(t)||0,this.dims[e].visible&&(t<this.dims[e].min&&(t=this.dims[e].min),t>this.dims[e].max&&(t=this.dims[e].max)),pars[e]=String(t)}));for(const x of this.head){const tm=ruleset[x.cod];tm&&(tm.islock?(x.visible="0",pars[x.cod]=tm.opz,x._islock=!0):pars[x.cod]||(pars[x.cod]=tm.opz)),"g"!=x.t&&("z"!=x.t||pars[x.cod]||(pars[x.cod]="1"),x._v=pars[x.cod]||"",ff[x.cod]=!0)}for(const x in pars)ff[x]||(ff[x]=!0,await impostavariante(this.amb,this,x,pars[x]));return this.head?.length>0&&await this.setparametro(this.head[0].cod,pars[this.head[0].cod]||void 0,!0),this.getparametri()}async setparametro(name,value,propaga=!1){if(value&&"string"==typeof value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),this.head){const _imposta=async(riga,vv,id,propaga)=>{const nn=riga?.cod;if(riga.valid&&!riga._h1){const t0=!valutaCondizioniTestata(this.amb.vari,riga.valid);if(riga._h!=t0&&(riga._h=t0,["g","g1","g2"].includes(riga.t)))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;tm1._h1=riga._h}}}if(riga._h||riga._h1)return this.amb.vari.add(nn,""),riga._v=void 0,"";{if(delete riga._h2,riga.visible){const t0=!valutaCondizioniTestata(this.amb.vari,riga.visible);if(t0&&(riga._h2=t0),["g","g1","g2"].includes(riga.t))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;riga._h2?tm1._h3=riga._h2:delete tm1._h3}}}let tx=this.amb.vari.var(nn)||"";"thlm".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0]);let txold=tx;if("z"!=riga.t||tx||(this.amb.vari.add(nn,"1"),tx="1"),"m"==riga.t&&riga.spars){const vspars=getcolonne(riga.spars);tx=parseFloat(tx||vspars[0])||0,vspars[1]&&parseFloat(tx)<vspars[1]&&(tx=parseFloat(vspars[1])||0),vspars[2]&&parseFloat(tx)>vspars[2]&&(tx=parseFloat(vspars[2])||0),tx=String(tx),this.amb.vari.add(nn,tx)}const tmimposta=await impostavariante(this.amb,this,nn,vv||riga._v||tx,riga);if(riga._v=void 0,tx=this.amb.vari.var(nn)||"","thl".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0],this.amb&&this.amb.deriva&&this.amb.deriva.length>0)){const t2=this.amb.deriva.filter((e=>e.cod==nn&&((!e.item||e.item==this.amb.item)&&((!e.model||e.model==this.amb.model)&&((!e.rule||e.rule==this.amb.rule)&&(!e.opz||e.opz==tx))))));t2.length&&t2.forEach((e=>{let t=this.head.find((h=>h.cod==e.tocod));if(t){let t1=this.amb.vari.var(t.cod);"string"==typeof t1&&(t1=t1.split(",")[0],t1&&t1!=txold||(t._v=e.toopz||tx,t._d=1))}}))}return tmimposta}};let tm,i0=-1;if("#dim"==name)propaga=1;else{if(i0=this.head.findIndex((e=>e.cod===name)),i0<0)return;const hh=this.head[i0];tm=await _imposta(hh,value,i0),propaga&&delete hh._d}if(propaga)for(let i=i0+1;i<this.head.length;i++)await _imposta(this.head[i],void 0,i);return tm}return await impostavariante(this.amb,this,name,value)}async impostaparametri(parimposta,parcall,ismacro=!1,progettokeys){if(this.head){this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]);for(const i of this.head)i._v="",delete i._h,delete i._h1,delete i._h2,i.alias&&(this.paralias[i.cod]=i.alias)}progettokeys||(progettokeys={}),parimposta||(parimposta=[]),parcall||(parcall=[]);for(const x of[...parimposta,...parcall]){const i=x.indexOf("=");if(i>0){let a=clean(x.substr(0,i));a.includes("$")&&(a=await intvaluta(this.amb,this,a));let t,b=x.substr(i+1);b.includes("$")&&(b=await intvaluta(this.amb,this,b)),this.head&&(t=this.head.find((e=>e.cod==a)))?t._v=b:await impostavariante(this.amb,this,a,b)}}if(this.head){let fl=!0;for(const h of this.head){let fl2=await this.checkvalid(h.valid);ismacro&&(fl2=!0),["g","g1","g2"].includes(h.t)?fl=fl2:fl&&fl2&&await this.setparametro(h.cod,progettokeys[h.cod]||h._v)}}}async checkvalid(formula){if(!formula)return!0;return!!muCalc(await intvaluta(this.amb,this,formula))}getmacrostr(){return JSON.stringify(this.getmacro())}getmacro(){return getOggetto(this,["amb"])}setmacro(vv){if(setOggetto(this,fromjson(vv,{})),this.localvar)for(const x in this.localvar){const vv=new Variante;setOggetto(vv,this.localvar[x]),this.localvar[x]=vv}}async load(xname,xcat){let name,cat;try{let tm;if(({name:name,cat:cat}=checkmu(xname||this.name,xcat||this.cat||"")),this.name||(this.name=name),this.cat||(this.cat=cat),this.azzera(),cbGetMacro&&(tm=await cbGetMacro(cat,name),"string"==typeof tm&&(tm.startsWith("{")||tm.startsWith("["))&&(tm=fromjson(tm)),tm&&tm.head&&!Array.isArray(tm.head)&&(tm.head=[]),tm.head&&(tm.dims=getheaddims(tm.dims))),tm){if("string"==typeof tm)await this.parsedata(tm);else for(const x in tm)this[x]=tm[x];return!0}errori.add(`missing cbGetFile: ${cat}/${name}`)}catch(error){errori.add(geterrdes(error),`macro.load: ${name}/${cat}`)}}async loadAndCompile(file,_cat,acapo=!1){let res;const{name:name,cat:cat}=checkmu(file,this.cat||_cat);return this.azzera(),cbGetFile&&(res=await cbGetFile(cat,name)),res?(await this.parsedata(res,acapo),this.getmacro()):void errori.add(`missing cbGetFile: ${name}/${cat}`)}async#loadinclude(file,flin,stak,pp){let res;const{name:name,cat:cat}=checkmu(file,this.cat);if(cbGetFile&&(res=await cbGetFile(cat,name)),!res)return[];if(res.includes("$1")&&pp&&pp.length>0)for(let i=1;i<pp.length;i++)res=res.replaceAll(`$${i}`,pp[i]);let tm=muClComments(res);const t2=[];flin&&(tm=tm.filter((t=>!/^\{(:?(var|valid|formula|header|genera|v|f|h))[\s|}]/im.test(t))));for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]);if(!stak.includes(pp[0])){stak.push(pp[0]);const t3=await this.loadinclude(pp[0],flin,stak,pp);Array.isArray(t3)&&t2.push(...t3),stak.pop()}}else t2.push(t)}}return t2}async parsedata(res,acapo=!1){if(this.azzera(),!res)return;const t2=[];let tm=muClComments(res),flin=!1;const lochead=[];for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]),t3=await this.#loadinclude(pp[0],flin,[pp[0]],pp);Array.isArray(t3)&&t2.push(...t3)}else t2.push(t)}}flin=!1;let out=this.codice;for(const t of t2){const rr=rx1.exec(t);if(rr)if(rr[1].startsWith(":"))out=this.codice;else switch(rr[1]){case"genera":case"g":{let r2=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(getcolonne(r2[2])[0]);this.genera[name]=[],out=this.genera[name]}else out=this.errori,out.push(t)}break;case"valid":out=this.valid;break;case"var":case"v":{const r2=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t);if(r2){const nn=getcolonne(r2[2]),name=checkname(nn[0]);this.localvar[name]={name:name,des:nn[1]||"",rows:[]},out=this.localvar[name].rows}else out=this.errori,out.push(t)}break;case"formula":case"f":{const r2=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(r2[2]);this.formula[name]=[],out=this.formula[name]}else out=this.errori,out.push(t)}break;case"h":case"header":out=lochead;break;default:this.errori.push(t),out=this.errori}else t.startsWith("{")&&(out=this.codice),out.push(t)}this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,acapo);for(const f in this.formula)this.formula[f]=this.cleanfiltraparametri(f,this.formula[f],acapo);for(const f in this.localvar){const vv=new Variante,v=this.localvar[f];vv.setheader(f,this.cat),vv.rows={};for(const x of v.rows){const c=getcolonne(x),k=c[0].trim().toLowerCase();vv.rows[k]={annulla:0,v:c}}v.des&&(vv.des=v.des),this.localvar[f]=vv}tm=this.valid,this.valid=[];for(const t of tm){let p=getcouple(t,",");p={v:p.v,msg:p.o},p.v&&(p.v.startsWith("#")?this.formula[p.v.substring(1)]&&this.valid.push(p):this.valid.push(p))}tm=lochead;const head=[];for(const t of tm){const rr=/^\s*([\w\-_]+)+[;,\s]\s*(.*)?$/im.exec(t);if(rr){const pp=getcolonne(rr[2]),c=clean(rr[1]);let ht;if(c){ht=head.find((e=>e.cod==c)),ht||(ht={cod:c,t:"t"},head.push(ht));for(const tp of pp){const p=getcouple(tp);switch(p.v){case"t":ht.t=p.o;break;case"def":case"default":ht.def=p.o;break;case"valid":case"colonna":case"hidden":p.o.startsWith("#")?this.formula[p.o.substring(1)]&&(ht[p.v]=p.o):ht[p.v]=p.o;break;default:ht[p.v]=p.o}}}}}this.head=head,tm=this.genera;const genera={};for(const kk in tm)if(Array.isArray(tm[kk])){const gen={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]},regx=/^\s*[!:]\s*(\w+)\s*(.*)$/i;for(const k2 of tm[kk]){const rr=regx.exec(clean(k2));if(rr)switch(rr[1]){case"calcola":case"c":gen.calcola=[...gen.calcola,...getcolonne(rr[2])];break;case"exclude":case"e":case"escludi":gen.exclude=[...gen.exclude,...getcolonne(rr[2])];break;case"bom":case"db":gen.bom=[...gen.bom,...getcolonne(rr[2])];break;case"vars":case"v":gen.vars=[...gen.vars,...getcolonne(rr[2])];break;case"head":case"h":gen.head=getcolonne(rr[2]);break;default:this.errori.push(`genera ${kk} => ${k2}`)}else gen.codice.push(k2)}gen.codice=muClean(gen.codice,!0),genera[kk]=gen}this.genera=genera}cleanfiltraparametri(key,codice,acapo){if(this.paralias||(this.paralias={}),codice&&codice.length){let fl=!1;const getparalias=dati=>{const cl=[],co=getcolonne(dati);for(const c of co)if(c.includes(":")){const v=c.split(":");this.paralias[v[0]]=v[1],cl.push(v[0])}else cl.push(c);return cl};for(let i=0;i<codice.length;i++){const rr=/^:p[;,\s]+(.*)?$/im.exec(codice[i]);if(rr)codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[1]);else{const rr=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(codice[i]);rr&&(codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[2]))}}fl&&(codice=codice.filter((e=>null!=e)))}return codice=muClean(codice,acapo)}}function parsevariabili(text){let fl=!1;const tk=[];for(;;){const m=/\$([{[(])/m.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}{fl=!0;const classe="["==m[1]?"inline":"variabile";m.index>0&&tk.push({class:"",text:text.substring(0,m.index)});const{i:i}=parsevar(text,m.index+2,m[1],null);if(!(i>m.index)){tk.push({class:classe,text:text.substring(m.index)});break}tk.push({class:classe,text:text.substring(m.index,i+1)}),text=text.substring(i+1)}}return{fl:fl,tk:tk}}function parseexp(text,exp,callback){if(!callback)throw new Error("missing callback");let fl=!1;const tk=[];for(;;){const m=exp.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}m.index>0&&tk.push({class:"",text:text.substring(0,m.index)}),tk.push(...callback(m)),fl=!0,text=text.substring(m.index+m[0].length)}return{fl:fl,tk:tk}}
256
+ this.amb=amb,this.azzera()}azzera(){this.key=`${this.cat}/${this.name}`,this.localvar={},this.head=[],this.frontend=!1,this.valid=[],this.parametri={},this.paralias={},this.formula={},this.settings={},this.errori=[],this.codice=[],this.genera={}}get isgenera(){return Object.keys(this.genera).length||0}get iscodice(){return this.codice.length||0}get isheader(){return this.head?.length||0}geterrori(){const cl=[];return this.errori.forEach((e=>cl.push({e:e}))),cl}getparametri(op={}){const{noderiva:noderiva}=op,s={};if(this.dims&&DIMS.forEach((k=>{const t=muCalc(this.amb.vari.var(k));t&&(s[k]=String(t))})),this.head){for(const x of this.head)if(!x._h){if(noderiva&&x._d&&x._d.cod)continue;let tm=this.amb.vari.var(x.cod);tipifree.includes(x.t)||"string"==typeof tm&&(tm=tm.split(",")[0]),s[x.cod]=tm}}else if(this.parametri?._)for(const x of this.parametri._){const x1=(x.split("=")[0]||"").trim().toLowerCase();let tm=this.amb.vari.var[x1];tm=(tm||"").split(",")[0],s[x1]=tm}return s}async setparametri(pars){const ff={},ruleset=this.amb.ruleset||{};pars||(pars={}),this.dims&&DIMS.forEach((e=>{let t=pars[e]||this.dims[e].val;t=parseFloat(t)||0,this.dims[e].visible&&(t<this.dims[e].min&&(t=this.dims[e].min),t>this.dims[e].max&&(t=this.dims[e].max)),pars[e]=String(t)}));for(const x of this.head){const tm=ruleset[x.cod];tm&&(tm.islock?(x.visible="0",pars[x.cod]=tm.opz,x._islock=!0):pars[x.cod]||(pars[x.cod]=tm.opz)),"g"!=x.t&&("z"!=x.t||pars[x.cod]||(pars[x.cod]="1"),x._v=pars[x.cod]||"",ff[x.cod]=!0)}for(const x in pars)ff[x]||(ff[x]=!0,await impostavariante(this.amb,this,x,pars[x]));return this.head?.length>0&&await this.setparametro(this.head[0].cod,pars[this.head[0].cod]||void 0,!0),this.getparametri()}async setparametro(name,value,propaga=!1){if(value&&"string"==typeof value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),this.head){const _imposta=async(riga,vv,id,propaga)=>{const nn=riga?.cod;if(riga.valid&&!riga._h1){const t0=!valutaCondizioniTestata(this.amb.vari,riga.valid);if(riga._h!=t0&&(riga._h=t0,["g","g1","g2"].includes(riga.t)))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;tm1._h1=riga._h}}}if(riga._h||riga._h1)return this.amb.vari.add(nn,""),riga._v=void 0,"";{if(delete riga._h2,riga.visible){const t0=!valutaCondizioniTestata(this.amb.vari,riga.visible);if(t0&&(riga._h2=t0),["g","g1","g2"].includes(riga.t))for(let i=id+1;i<this.head.length;i++){const tm1=this.head[i];if(tm1){if(["g","g1","g2"].includes(tm1.t))break;riga._h2?tm1._h3=riga._h2:delete tm1._h3}}}let tx=this.amb.vari.var(nn)||"";"thlm".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0]);let txold=tx;if("z"!=riga.t||tx||(this.amb.vari.add(nn,"1"),tx="1"),"m"==riga.t&&riga.spars){const vspars=getcolonne(riga.spars);tx=parseFloat(tx||vspars[0])||0,vspars[1]&&parseFloat(tx)<vspars[1]&&(tx=parseFloat(vspars[1])||0),vspars[2]&&parseFloat(tx)>vspars[2]&&(tx=parseFloat(vspars[2])||0),tx=String(tx),this.amb.vari.add(nn,tx)}const tmimposta=await impostavariante(this.amb,this,nn,vv||riga._v||tx,riga);if(riga._v=void 0,tx=this.amb.vari.var(nn)||"","thl".includes(riga.t)&&"string"==typeof tx&&(tx=tx.split(",")[0],this.amb&&this.amb.deriva&&this.amb.deriva.length>0)){const t2=this.amb.deriva.filter((e=>e.cod==nn&&((!e.item||e.item==this.amb.item)&&((!e.model||e.model==this.amb.model)&&((!e.rule||e.rule==this.amb.rule)&&(!e.opz||e.opz==tx))))));t2.length&&t2.forEach((e=>{let t=this.head.find((h=>h.cod==e.tocod));if(t){let t1=this.amb.vari.var(t.cod);"string"==typeof t1&&(t1=t1.split(",")[0],t1&&t1!=txold&&t1!=tx?delete t._d:(t._v=e.toopz||tx,t._d={cod:riga.cod,opz:e.toopz}))}}))}return tmimposta}};let tm,i0=-1;if("#dim"==name)propaga=1;else{if(i0=this.head.findIndex((e=>e.cod===name)),i0<0)return;const hh=this.head[i0];tm=await _imposta(hh,value,i0),propaga&&delete hh._d}if(propaga)for(let i=i0+1;i<this.head.length;i++)await _imposta(this.head[i],void 0,i);return tm}return await impostavariante(this.amb,this,name,value)}isderivato(hd){return"string"==typeof hd&&(hd=this.head.find((e=>e.cod==hd))),!!(hd&&hd._d&&hd._d.cod)}async impostaparametri(parimposta,parcall,ismacro=!1,progettokeys){if(this.head){this.paralias||(this.paralias={}),Array.isArray(this.head)||(this.head=[]);for(const i of this.head)i._v="",delete i._h,delete i._h1,delete i._h2,i.alias&&(this.paralias[i.cod]=i.alias)}progettokeys||(progettokeys={}),parimposta||(parimposta=[]),parcall||(parcall=[]);for(const x of[...parimposta,...parcall]){const i=x.indexOf("=");if(i>0){let a=clean(x.substr(0,i));a.includes("$")&&(a=await intvaluta(this.amb,this,a));let t,b=x.substr(i+1);b.includes("$")&&(b=await intvaluta(this.amb,this,b)),this.head&&(t=this.head.find((e=>e.cod==a)))?t._v=b:await impostavariante(this.amb,this,a,b)}}if(this.head){let fl=!0;for(const h of this.head){let fl2=await this.checkvalid(h.valid);ismacro&&(fl2=!0),["g","g1","g2"].includes(h.t)?fl=fl2:fl&&fl2&&await this.setparametro(h.cod,progettokeys[h.cod]||h._v)}}}async checkvalid(formula){if(!formula)return!0;return!!muCalc(await intvaluta(this.amb,this,formula))}getmacrostr(){return JSON.stringify(this.getmacro())}getmacro(){return getOggetto(this,["amb"])}setmacro(vv){if(setOggetto(this,fromjson(vv,{})),this.localvar)for(const x in this.localvar){const vv=new Variante;setOggetto(vv,this.localvar[x]),this.localvar[x]=vv}}async load(xname,xcat){let name,cat;try{let tm;if(({name:name,cat:cat}=checkmu(xname||this.name,xcat||this.cat||"")),this.name||(this.name=name),this.cat||(this.cat=cat),this.azzera(),cbGetMacro&&(tm=await cbGetMacro(cat,name),"string"==typeof tm&&(tm.startsWith("{")||tm.startsWith("["))&&(tm=fromjson(tm)),tm&&tm.head&&!Array.isArray(tm.head)&&(tm.head=[]),tm.head&&(tm.dims=getheaddims(tm.dims))),tm){if("string"==typeof tm)await this.parsedata(tm);else for(const x in tm)this[x]=tm[x];return!0}errori.add(`missing cbGetFile: ${cat}/${name}`)}catch(error){errori.add(geterrdes(error),`macro.load: ${name}/${cat}`)}}async loadAndCompile(file,_cat,acapo=!1){let res;const{name:name,cat:cat}=checkmu(file,this.cat||_cat);return this.azzera(),cbGetFile&&(res=await cbGetFile(cat,name)),res?(await this.parsedata(res,acapo),this.getmacro()):void errori.add(`missing cbGetFile: ${name}/${cat}`)}async#loadinclude(file,flin,stak,pp){let res;const{name:name,cat:cat}=checkmu(file,this.cat);if(cbGetFile&&(res=await cbGetFile(cat,name)),!res)return[];if(res.includes("$1")&&pp&&pp.length>0)for(let i=1;i<pp.length;i++)res=res.replaceAll(`$${i}`,pp[i]);let tm=muClComments(res);const t2=[];flin&&(tm=tm.filter((t=>!/^\{(:?(var|valid|formula|header|genera|v|f|h))[\s|}]/im.test(t))));for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]);if(!stak.includes(pp[0])){stak.push(pp[0]);const t3=await this.loadinclude(pp[0],flin,stak,pp);Array.isArray(t3)&&t2.push(...t3),stak.pop()}}else t2.push(t)}}return t2}async parsedata(res,acapo=!1){if(this.azzera(),!res)return;const t2=[];let tm=muClComments(res),flin=!1;const lochead=[];for(const t of tm){const rr=rx1.exec(t);if(rr)flin=!rr[1].startsWith(":"),t2.push(t);else{const r1=/^\s*\{i\s(.+)?\}/im.exec(t);if(r1){const pp=getcolonne(r1[1]),t3=await this.#loadinclude(pp[0],flin,[pp[0]],pp);Array.isArray(t3)&&t2.push(...t3)}else t2.push(t)}}flin=!1;let out=this.codice;for(const t of t2){const rr=rx1.exec(t);if(rr)if(rr[1].startsWith(":"))out=this.codice;else switch(rr[1]){case"genera":case"g":{let r2=/^\s*\{(genera|g)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(getcolonne(r2[2])[0]);this.genera[name]=[],out=this.genera[name]}else out=this.errori,out.push(t)}break;case"valid":out=this.valid;break;case"var":case"v":{const r2=/^\s*\{(var|v)\s+(.+)?\}/im.exec(t);if(r2){const nn=getcolonne(r2[2]),name=checkname(nn[0]);this.localvar[name]={name:name,des:nn[1]||"",rows:[]},out=this.localvar[name].rows}else out=this.errori,out.push(t)}break;case"formula":case"f":{const r2=/^\s*\{(formula|f)\s+(.+)?\}/im.exec(t);if(r2){const name=checkname(r2[2]);this.formula[name]=[],out=this.formula[name]}else out=this.errori,out.push(t)}break;case"h":case"header":out=lochead;break;default:this.errori.push(t),out=this.errori}else t.startsWith("{")&&(out=this.codice),out.push(t)}this.parametri={},this.codice=this.cleanfiltraparametri("_",this.codice,acapo);for(const f in this.formula)this.formula[f]=this.cleanfiltraparametri(f,this.formula[f],acapo);for(const f in this.localvar){const vv=new Variante,v=this.localvar[f];vv.setheader(f,this.cat),vv.rows={};for(const x of v.rows){const c=getcolonne(x),k=c[0].trim().toLowerCase();vv.rows[k]={annulla:0,v:c}}v.des&&(vv.des=v.des),this.localvar[f]=vv}tm=this.valid,this.valid=[];for(const t of tm){let p=getcouple(t,",");p={v:p.v,msg:p.o},p.v&&(p.v.startsWith("#")?this.formula[p.v.substring(1)]&&this.valid.push(p):this.valid.push(p))}tm=lochead;const head=[];for(const t of tm){const rr=/^\s*([\w\-_]+)+[;,\s]\s*(.*)?$/im.exec(t);if(rr){const pp=getcolonne(rr[2]),c=clean(rr[1]);let ht;if(c){ht=head.find((e=>e.cod==c)),ht||(ht={cod:c,t:"t"},head.push(ht));for(const tp of pp){const p=getcouple(tp);switch(p.v){case"t":ht.t=p.o;break;case"def":case"default":ht.def=p.o;break;case"valid":case"colonna":case"hidden":p.o.startsWith("#")?this.formula[p.o.substring(1)]&&(ht[p.v]=p.o):ht[p.v]=p.o;break;default:ht[p.v]=p.o}}}}}this.head=head,tm=this.genera;const genera={};for(const kk in tm)if(Array.isArray(tm[kk])){const gen={codice:[],head:"",calcola:[],bom:[],vars:[],exclude:[]},regx=/^\s*[!:]\s*(\w+)\s*(.*)$/i;for(const k2 of tm[kk]){const rr=regx.exec(clean(k2));if(rr)switch(rr[1]){case"calcola":case"c":gen.calcola=[...gen.calcola,...getcolonne(rr[2])];break;case"exclude":case"e":case"escludi":gen.exclude=[...gen.exclude,...getcolonne(rr[2])];break;case"bom":case"db":gen.bom=[...gen.bom,...getcolonne(rr[2])];break;case"vars":case"v":gen.vars=[...gen.vars,...getcolonne(rr[2])];break;case"head":case"h":gen.head=getcolonne(rr[2]);break;default:this.errori.push(`genera ${kk} => ${k2}`)}else gen.codice.push(k2)}gen.codice=muClean(gen.codice,!0),genera[kk]=gen}this.genera=genera}cleanfiltraparametri(key,codice,acapo){if(this.paralias||(this.paralias={}),codice&&codice.length){let fl=!1;const getparalias=dati=>{const cl=[],co=getcolonne(dati);for(const c of co)if(c.includes(":")){const v=c.split(":");this.paralias[v[0]]=v[1],cl.push(v[0])}else cl.push(c);return cl};for(let i=0;i<codice.length;i++){const rr=/^:p[;,\s]+(.*)?$/im.exec(codice[i]);if(rr)codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[1]);else{const rr=/^!(parametri|pars|p)[;,\s]+(.*)?$/im.exec(codice[i]);rr&&(codice[i]=null,fl=!0,this.parametri[key]=getparalias(rr[2]))}}fl&&(codice=codice.filter((e=>null!=e)))}return codice=muClean(codice,acapo)}}function parsevariabili(text){let fl=!1;const tk=[];for(;;){const m=/\$([{[(])/m.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}{fl=!0;const classe="["==m[1]?"inline":"variabile";m.index>0&&tk.push({class:"",text:text.substring(0,m.index)});const{i:i}=parsevar(text,m.index+2,m[1],null);if(!(i>m.index)){tk.push({class:classe,text:text.substring(m.index)});break}tk.push({class:classe,text:text.substring(m.index,i+1)}),text=text.substring(i+1)}}return{fl:fl,tk:tk}}function parseexp(text,exp,callback){if(!callback)throw new Error("missing callback");let fl=!1;const tk=[];for(;;){const m=exp.exec(text);if(!m){text&&fl&&tk.push({class:"",text:text});break}m.index>0&&tk.push({class:"",text:text.substring(0,m.index)}),tk.push(...callback(m)),fl=!0,text=text.substring(m.index+m[0].length)}return{fl:fl,tk:tk}}
257
257
  /**
258
258
  * Analizza il codice sorgente e restituisce un array di token con classi CSS
259
259
  * @param {string} tt - Il codice sorgente da analizzare
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markuno_lib",
3
- "version": "1.2.38",
3
+ "version": "1.2.39",
4
4
  "description": "Croswil Markuno Language Lib",
5
5
  "author": "Croswil SRL",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -114,9 +114,10 @@ export class Macro {
114
114
  get iscodice(): any;
115
115
  get isheader(): number;
116
116
  geterrori(): any[];
117
- getparametri(): {};
117
+ getparametri(op?: {}): {};
118
118
  setparametri(pars: any): Promise<{}>;
119
119
  setparametro(name: any, value: any, propaga?: boolean): Promise<any>;
120
+ isderivato(hd: any): boolean;
120
121
  impostaparametri(parimposta: any, parcall: any, ismacro: boolean, progettokeys: any): Promise<void>;
121
122
  checkvalid(formula: any): Promise<boolean>;
122
123
  getmacrostr(): string;
@@ -159,6 +160,7 @@ export class Variabile {
159
160
  /**
160
161
  * Aggiunge o rimuove una variabile
161
162
  */ add(key: any, value: any): void;
163
+ removeallvars(exclude: any): void;
162
164
  /**
163
165
  * Valuta un'espressione con supporto per callback asincroni
164
166
  */ valutasync(str: any): any;