markuno_lib 1.2.68 → 1.2.70

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/markcad.js CHANGED
@@ -49,7 +49,7 @@ constructor(p1,p2,x2=null,y2=null){"number"==typeof p1&&"number"==typeof p2&&nul
49
49
  /**
50
50
  * Calcola la differenza delle coordinate x dei punti
51
51
  * @returns {number} Differenza x
52
- */get angle(){return new Punto2(this.dx,this.dy).angle}get dx(){return this.p2.x-this.p1.x}
52
+ */get dx(){return this.p2.x-this.p1.x}
53
53
  /**
54
54
  * Calcola la differenza delle coordinate y dei punti
55
55
  * @returns {number} Differenza y
@@ -151,7 +151,7 @@ constructor(p1,p2,x2=null,y2=null){"number"==typeof p1&&"number"==typeof p2&&nul
151
151
  * @param {string} codice - Il codice sorgente da processare
152
152
  * @param {boolean} tienivuoti - Se true mantiene le righe vuote
153
153
  * @returns {string[]} Array di righe di codice senza commenti
154
- */function getcolonne(value,keepquote=!1){value=String(value||"");const pp=/^(\d+)\.\.(\d+)$/.exec(value);if(pp){let n1=parseInt(pp[1]),n2=parseInt(pp[2]),cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(let i=n1;i<=n2;i++)cl.push(i+"");return cl}if(!/["({[]/.test(value))return value.split(/[,;]/).map((e=>e.trim()));const risultato=[];let buffer="",livelloParentesi=0,inVirgolette=!1;for(let i=0;i<value.length;i++){const char=value[i];if(0===livelloParentesi&&'"'===char&&(0!==i&&"\\"===value[i-1]||(inVirgolette=!inVirgolette)),inVirgolette||("("===char||"["===char||"{"===char?livelloParentesi++:")"!==char&&"]"!==char&&"}"!==char||(livelloParentesi=Math.max(0,livelloParentesi-1))),","!==char&&";"!==char||0!==livelloParentesi||inVirgolette)buffer+=char;else{const trimmed=buffer.trim();risultato.push(trimmed),buffer=""}}const trimmed=buffer.trim();return trimmed&&risultato.push(trimmed),risultato.map((e=>(e=e.trim(),!keepquote&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")"))?e.slice(1,-1):e)))}function hash(obj){let str="";if("string"==typeof obj||"number"==typeof obj)str=obj+"";else if("object"==typeof obj&&obj){const chiaviOrdinati=Object.keys(obj).sort(),separatore="\0";str=chiaviOrdinati.map((key=>`${key}${separatore}${String(obj[key])}`)).join(separatore)}let h1=2166136261,h2=2218511855;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);h1^=char,h1+=h1<<5^2779096485,h2^=h1,h2=((h2<<3)+char^2134516169)>>>0}return h1>>>=0,h1.toString(16)+h2.toString(16)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function getSqDist(p1,p2){let dx=p1.x-p2.x,dy=p1.y-p2.y;return dx*dx+dy*dy}function getSqSegDist(p,p1,p2){let x=p1.x,y=p1.y,dx=p2.x-x,dy=p2.y-y;if(0!==dx||0!==dy){let t=((p.x-x)*dx+(p.y-y)*dy)/(dx*dx+dy*dy);t>1?(x=p2.x,y=p2.y):t>0&&(x+=dx*t,y+=dy*t)}return dx=p.x-x,dy=p.y-y,dx*dx+dy*dy}function simplifyDPStep(points,first,last,sqTolerance,simplified){let index,maxSqDist=sqTolerance;for(let i=first+1;i<last;i++){let sqDist=getSqSegDist(points[i],points[first],points[last]);sqDist>maxSqDist&&(index=i,maxSqDist=sqDist)}maxSqDist>sqTolerance&&(index-first>1&&simplifyDPStep(points,first,index,sqTolerance,simplified),simplified.push(points[index]),last-index>1&&simplifyDPStep(points,index,last,sqTolerance,simplified))}function simplifyDouglasPeucker(points,sqTolerance){let last=points.length-1,simplified=[points[0]];return simplifyDPStep(points,0,last,sqTolerance,simplified),simplified.push(points[last]),simplified}
154
+ */function seedarray(arr,seed){if(arr&&arr.length){let cl=[];for(let i=0;i<arr.length;i++){let a=arr[i];if(a.p)for(let j=0;j<a.p;j++)cl.push(i);else cl.push(i)}return arr[cl[seeder(cl.length,seed)]]}}function seeder(n,seed="seed42"){const rand=function mulberry32(a){return function(){a=(a|=0)+1831565813|0;let t=Math.imul(a^a>>>15,1|a);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}(function xmur3(str){let h=1779033703^str.length;for(let i=0;i<str.length;i++)h=Math.imul(h^str.charCodeAt(i),3432918353),h=h<<13|h>>>19;return function(){return h=Math.imul(h^h>>>16,2246822507),h=Math.imul(h^h>>>13,3266489909),(h^=h>>>16)>>>0}}(String(seed))());return Math.floor(rand()*n)}function getcolonne(value,keepquote=!1){value=String(value||"");const pp=/^(\d+)\.\.(\d+)$/.exec(value);if(pp){let n1=parseInt(pp[1]),n2=parseInt(pp[2]),cl=[];n1>n2&&([n1,n2]=[n2,n1]);for(let i=n1;i<=n2;i++)cl.push(i+"");return cl}if(!/["({[]/.test(value))return value.split(/[,;]/).map((e=>e.trim()));const risultato=[];let buffer="",livelloParentesi=0,inVirgolette=!1;for(let i=0;i<value.length;i++){const char=value[i];if(0===livelloParentesi&&'"'===char&&(0!==i&&"\\"===value[i-1]||(inVirgolette=!inVirgolette)),inVirgolette||("("===char||"["===char||"{"===char?livelloParentesi++:")"!==char&&"]"!==char&&"}"!==char||(livelloParentesi=Math.max(0,livelloParentesi-1))),","!==char&&";"!==char||0!==livelloParentesi||inVirgolette)buffer+=char;else{const trimmed=buffer.trim();risultato.push(trimmed),buffer=""}}const trimmed=buffer.trim();return trimmed&&risultato.push(trimmed),risultato.map((e=>(e=e.trim(),!keepquote&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")"))?e.slice(1,-1):e)))}function hash(obj){let str="";if("string"==typeof obj||"number"==typeof obj)str=obj+"";else if("object"==typeof obj&&obj){const chiaviOrdinati=Object.keys(obj).sort(),separatore="\0";str=chiaviOrdinati.map((key=>`${key}${separatore}${String(obj[key])}`)).join(separatore)}let h1=2166136261,h2=2218511855;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);h1^=char,h1+=h1<<5^2779096485,h2^=h1,h2=((h2<<3)+char^2134516169)>>>0}return h1>>>=0,h1.toString(16)+h2.toString(16)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function getSqDist(p1,p2){let dx=p1.x-p2.x,dy=p1.y-p2.y;return dx*dx+dy*dy}function getSqSegDist(p,p1,p2){let x=p1.x,y=p1.y,dx=p2.x-x,dy=p2.y-y;if(0!==dx||0!==dy){let t=((p.x-x)*dx+(p.y-y)*dy)/(dx*dx+dy*dy);t>1?(x=p2.x,y=p2.y):t>0&&(x+=dx*t,y+=dy*t)}return dx=p.x-x,dy=p.y-y,dx*dx+dy*dy}function simplifyDPStep(points,first,last,sqTolerance,simplified){let index,maxSqDist=sqTolerance;for(let i=first+1;i<last;i++){let sqDist=getSqSegDist(points[i],points[first],points[last]);sqDist>maxSqDist&&(index=i,maxSqDist=sqDist)}maxSqDist>sqTolerance&&(index-first>1&&simplifyDPStep(points,first,index,sqTolerance,simplified),simplified.push(points[index]),last-index>1&&simplifyDPStep(points,index,last,sqTolerance,simplified))}function simplifyDouglasPeucker(points,sqTolerance){let last=points.length-1,simplified=[points[0]];return simplifyDPStep(points,0,last,sqTolerance,simplified),simplified.push(points[last]),simplified}
155
155
  /**
156
156
  * Esegue la semplificazione di un poligono (array di punti) combinando
157
157
  * l’algoritmo di distanza radiale e l’algoritmo di Ramer–Douglas–Peucker.
@@ -1115,4 +1115,4 @@ async function clearmat(){for(const key in _textures)if(_textures[key]){const te
1115
1115
  * @param {THREE.Object3D} gruppo - oggetto root
1116
1116
  * @param {Array<{ mats: string[], name?: string }>} matricole - elenco da evidenziare
1117
1117
  * @returns {Promise<File[]>}
1118
- */async function evidenziaColli(gruppo,matricole,callback){salvaMaterialiOriginali(gruppo);const SIDE=THREE.DoubleSide,mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE});let ii=0;try{for(let mts of matricole)ii++,mts.name||(mts.name=`collo_${ii}`),applicaEvidenziazione(gruppo,mts.mats,mwhite,mgreen),await callback(mts)}catch(err){console.error("Errore durante evidenzia:",err)}finally{ripristinaMaterialiOriginali()}}function TODEG(a,dec=1){let C=10**dec;return Math.round(180*a*C/Math.PI)/C}function TORAD(a,dec=3){let C=10**dec;return Math.round(a*PIF*C)/C}const blocked={window:void 0,self:void 0,globalThis:void 0,document:void 0,Function:void 0,eval:void 0,fetch:void 0,XMLHttpRequest:void 0};function getOggetto(obj,exclude=[]){if(Array.isArray(obj))return obj.map((item=>getOggetto(item,exclude)));if(obj&&"object"==typeof obj){const result={};for(const[key,value]of Object.entries(obj))"function"==typeof value||exclude&&exclude.includes(key)||(result[key]=getOggetto(value,exclude));return result}return obj}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});const params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,log:function addlog(...pars){pars.map((p=>getOggetto(p)))},Math:Math,getcolonne:getcolonne,clean:clean,SP:SP,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects},paramNames=[...Object.keys(params),...Object.keys(blocked)],paramValues=[...Object.values(params),...Object.values(blocked)],fn=new Function(...paramNames,`\n try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...paramValues)}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}function setLineColorMode(white,isdark){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):isdark?(materialline1.color.set(7368816),materialline2.color.set(6316128)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,Vobject,Vscene,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,errorescript,estruso,estrusopat,evalcustomfunction,evidenziaColli,extractTextures,get3dshape,getOggetto,getbb,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getextrude,getface,getfakeshadow,getfakeshadow2,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpannello2,getpoint,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,getthorus,groupfromgeometry,hash,infoestrudi,isfn,ismacro,joinlinestoshapes,mapvertices,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scalaoggetto,scaleunit,setLineColorMode,setorigine,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
1118
+ */async function evidenziaColli(gruppo,matricole,callback){salvaMaterialiOriginali(gruppo);const SIDE=THREE.DoubleSide,mwhite=new THREE.MeshStandardMaterial({color:16777215,roughness:.5,metalness:.4,side:SIDE}),mgreen=new THREE.MeshStandardMaterial({color:36864,roughness:.5,metalness:.4,side:SIDE});let ii=0;try{for(let mts of matricole)ii++,mts.name||(mts.name=`collo_${ii}`),applicaEvidenziazione(gruppo,mts.mats,mwhite,mgreen),await callback(mts)}catch(err){console.error("Errore durante evidenzia:",err)}finally{ripristinaMaterialiOriginali()}}function TODEG(a,dec=1){let C=10**dec;return Math.round(180*a*C/Math.PI)/C}function TORAD(a,dec=3){let C=10**dec;return Math.round(a*PIF*C)/C}const blocked={window:void 0,self:void 0,globalThis:void 0,document:void 0,Function:void 0,eval:void 0,fetch:void 0,XMLHttpRequest:void 0};function getOggetto(obj,exclude=[]){if(Array.isArray(obj))return obj.map((item=>getOggetto(item,exclude)));if(obj&&"object"==typeof obj){const result={};for(const[key,value]of Object.entries(obj))"function"==typeof value||exclude&&exclude.includes(key)||(result[key]=getOggetto(value,exclude));return result}return obj}async function evalcustomfunction(amb,code,values,objects){try{values||(values={}),objects||(objects={});const params={GCAD:!1,...values,A:amb,V:amb.vari,amb:amb,log:function addlog(...pars){pars.map((p=>getOggetto(p)))},Math:Math,getcolonne:getcolonne,clean:clean,SP:SP,seeder:seeder,seedarray:seedarray,Punto2:Punto2,Linea2:Linea2,clamp:clamp,hash:hash,PIF:PIF,getshape:getshape,shapeclip:shapeclip,...objects},paramNames=[...Object.keys(params),...Object.keys(blocked)],paramValues=[...Object.values(params),...Object.values(blocked)],fn=new Function(...paramNames,`\n try {\n return (async () => {\n ${code}\n })();\n } catch (err) {\n err.stack = '[SCRIPT] ' + err.stack;\n throw err;\n }`);return await fn(...paramValues)}catch(error){throw console.error("Errore durante l'esecuzione:",error),error}}function setLineColorMode(white,isdark){white?(materialline1.color.set(16777215),materialline2.color.set(16777215)):isdark?(materialline1.color.set(7368816),materialline2.color.set(6316128)):(materialline1.color.set(3158064),materialline2.color.set(5263440)),materialline1.needsUpdate=!0,materialline2.needsUpdate=!0}export{Linea2,Matrix3D,PIF,Punto2,SIDE,SP,TODEG,TORAD,Vis2d,Vobject,Vscene,addmovpivot,angle2vec,angle3point,blocked,calcolatasks,clamp,clean,creategroup,deletegroup,dxfbulge,edgesfromgeometry,elaborapercorso,errorescript,estruso,estrusopat,evalcustomfunction,evidenziaColli,extractTextures,get3dshape,getOggetto,getbb,getbordi,getbox,getcilindro,getcyl,getdumpmacro,getemitter,getextrude,getface,getfakeshadow,getfakeshadow2,getline,getlinesgeom,getmesh,getmovimento,getnodebyid,getpannello,getpannello2,getpoint,getptsoffset,getpunto,getquota,getreceiver,getriferimento,getshape,getsphere,getsprite,getsubrules,gettarghetta,getthorus,groupfromgeometry,hash,infoestrudi,isfn,ismacro,joinlinestoshapes,mapvertices,materialline1,materialline2,mblack,mblue,mgray1,mgray2,mgreen,mred,mwhite,newgcad,normal2,posiziona,raccordabezier,randombasemat,revolve,ripristinaMaterialiOriginali,salvaMaterialiOriginali,scalaoggetto,scaleunit,seedarray,seeder,setLineColorMode,setorigine,shapeclip,smat,spritemat,svuotanodo,valutagrafica};
package/bin/markuno.js CHANGED
@@ -8,7 +8,7 @@ function testsync(a,b){return a+b}
8
8
  /**
9
9
  * Restituisce il timestamp corrente in millisecondi
10
10
  * @returns {number} Timestamp corrente
11
- */const tk=()=>(new Date).valueOf();function seeder(n,seed="seed42"){const rand=function mulberry32(a){return function(){a=(a|=0)+1831565813|0;let t=Math.imul(a^a>>>15,1|a);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}(function xmur3(str){let h=1779033703^str.length;for(let i=0;i<str.length;i++)h=Math.imul(h^str.charCodeAt(i),3432918353),h=h<<13|h>>>19;return function(){return h=Math.imul(h^h>>>16,2246822507),h=Math.imul(h^h>>>13,3266489909),(h^=h>>>16)>>>0}}(String(seed))());return Math.floor(rand()*n)}function isJsonStr(str){if("string"!=typeof str)return!1;const trimmed=str.trim();return trimmed.startsWith("{")&&trimmed.endsWith("}")||trimmed.startsWith("[")&&trimmed.endsWith("]")}const isObject=value=>!(!value||!Array.isArray(value)&&"object"!=typeof value);function quote(v){if((v=(v||"").trim()).length>1){if(v.startsWith('"')&&v.endsWith('"'))return v;if(v.startsWith("(")&&v.endsWith(")"))return v}return`"${v}"`}function noquote(e){return(e=e.trim()).startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e}function hash(obj){let str="";if("string"==typeof obj||"number"==typeof obj)str=obj+"";else if("object"==typeof obj&&obj){const chiaviOrdinati=Object.keys(obj).sort(),separatore="\0";str=chiaviOrdinati.map((key=>`${key}${separatore}${String(obj[key])}`)).join(separatore)}let h1=2166136261,h2=2218511855;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);h1^=char,h1+=h1<<5^2779096485,h2^=h1,h2=((h2<<3)+char^2134516169)>>>0}return h1>>>=0,h1.toString(16)+h2.toString(16)}
11
+ */const tk=()=>(new Date).valueOf();function seedarray(arr,seed){if(arr&&arr.length){let cl=[];for(let i=0;i<arr.length;i++){let a=arr[i];if(a.p)for(let j=0;j<a.p;j++)cl.push(i);else cl.push(i)}return arr[cl[seeder(cl.length,seed)]]}}function seeder(n,seed="seed42"){const rand=function mulberry32(a){return function(){a=(a|=0)+1831565813|0;let t=Math.imul(a^a>>>15,1|a);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}(function xmur3(str){let h=1779033703^str.length;for(let i=0;i<str.length;i++)h=Math.imul(h^str.charCodeAt(i),3432918353),h=h<<13|h>>>19;return function(){return h=Math.imul(h^h>>>16,2246822507),h=Math.imul(h^h>>>13,3266489909),(h^=h>>>16)>>>0}}(String(seed))());return Math.floor(rand()*n)}function isJsonStr(str){if("string"!=typeof str)return!1;const trimmed=str.trim();return trimmed.startsWith("{")&&trimmed.endsWith("}")||trimmed.startsWith("[")&&trimmed.endsWith("]")}const isObject=value=>!(!value||!Array.isArray(value)&&"object"!=typeof value);function quote(v){if((v=(v||"").trim()).length>1){if(v.startsWith('"')&&v.endsWith('"'))return v;if(v.startsWith("(")&&v.endsWith(")"))return v}return`"${v}"`}function noquote(e){return(e=e.trim()).startsWith('"')&&e.endsWith('"')||e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e}function hash(obj){let str="";if("string"==typeof obj||"number"==typeof obj)str=obj+"";else if("object"==typeof obj&&obj){const chiaviOrdinati=Object.keys(obj).sort(),separatore="\0";str=chiaviOrdinati.map((key=>`${key}${separatore}${String(obj[key])}`)).join(separatore)}let h1=2166136261,h2=2218511855;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);h1^=char,h1+=h1<<5^2779096485,h2^=h1,h2=((h2<<3)+char^2134516169)>>>0}return h1>>>=0,h1.toString(16)+h2.toString(16)}
12
12
  /**
13
13
  * Formatta un messaggio di errore rimuovendo informazioni non necessarie
14
14
  * @param {Error|string} err - L'errore da formattare
@@ -250,7 +250,7 @@ this.amb=amb}
250
250
  * Carica il contenuto esteso della variante
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
- */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)=>{switch(fun){case"dim":{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}case"seed":{let n1=pars[1],cl=getcolonne(pars[2]);return cl[seeder(cl.length,n1)]||""}case"seedvar":{let vv=await dammivariante(amb,mac,pars[2]),n1=pars[1],cl=vv.validkeys();if(pars[3]&&pars[4]){let idcol=muCalc(pars[3])-1;if(idcol>=0){let pcol=getcolonne(pars[4]);cl=cl.filter((e=>{let t=vv.rows[e];if(t&&t.v&&t.v[idcol]){let v=getcolonne(t.v[idcol]);if(v)for(var p of pcol)if(v.includes(p))return!0}return!1}))}}let id=seeder(cl.length,n1);return id>=0&&vv.tovar(cl[id])||""}default: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))}
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)=>{switch(fun){case"dim":{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}case"seed":{let n1=pars[1],cl=getcolonne(pars[2]);return cl[seeder(cl.length,n1)]||""}case"seedvar":{let vv=await dammivariante(amb,mac,pars[2]),n1=pars[1],cl=vv.validkeys();if(pars[3]&&pars[4]){let idcol=muCalc(pars[3])-1;if(idcol>=0){let pcol=getcolonne(pars[4]);cl=cl.filter((e=>{let t=vv.rows[e];if(t&&t.v&&t.v[idcol]){let v=getcolonne(t.v[idcol]);if(v)for(let p of pcol)if(v.includes(p))return!0}return!1}))}}let id=seeder(cl.length,n1);return id>=0&&vv.tovar(cl[id])||""}default: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
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"RET":{const a=await intvaluta(amb,mac,riga.contenuto);amb.vari.savevars(a)}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
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,pars),this.getparametri()}async setparametro(name,value,propaga=!1,pars={}){if(value&&"string"==typeof value&&value.includes("$")&&(value=await intvaluta(this.amb,this,value)),pars||(pars={}),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);pars&&pars[t.cod]&&(t1=pars[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=[]),this.amb.checkscript(tm.linkscript),delete tm.linkscript,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}}
@@ -265,4 +265,4 @@ this.imgpreview={},this.vari=new Variabile,this.ruleset={},this.fndotcallback&&t
265
265
  /** @type {Object.<string, Macro>} */
266
266
  this.macro={},
267
267
  /** @type {Object.<string, Variante>} */
268
- this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}setimgpreview(cod,img){img?this.imgpreview[cod]=img:delete this.imgpreview[cod]}getimgpreview(cod){return this?.imgpreview[cod||""]}setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){const tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(const t of tm)switch(t.tipo){case"_headers":"string"==typeof t.value&&(t.value=headerconvert(t.value)),this.#headers=t.value||{};break;case"_alias":"string"==typeof t.value&&(t.value=aliasconvert(t.value)),this.#alias=t.value||{};break;case"_typos":if("string"==typeof t.value){const tips=fromjson(t.value);for(const tp in tips){const tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips}this.#typos=t.value||{}}}setitem(item,rule,model,ruleset=[],datadelgiorno=0){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.ruleset=toruleset(ruleset),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){let tm;return!this.#headers&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_alias"),this.parseheaderfrominfo(tm)),this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;let ct=riga.contenuto;ct.startsWith("$")&&(ct=await this.vari.valuta(ct));const rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(ct);if(!rr)return void errori.add("Macro non valida:"+ct,riga);let macro=clean(rr[1],!0);macro.includes("$")&&(macro=await this.vari.valuta(macro));const pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;const ky=`${cat}/${name}`;if(!this.macro[ky]){const tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return macro=this.macro[ky],macro?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){const{name:name,cat:cat}=checkmu(cod,this.cat);let n2=name,altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;const key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){const xx=new Variante(this);if(await xx.load(v,this.cat,!0),xx.alias){(await this.getalias())[v]=xx.alias}callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){const mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);const t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){const cc=new CodiceBarra;await cc.compila(articolibarre,titolibarre);for(const x in cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(const v of info.var)await this.varcompila(v,callback);for(const v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){const tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async checkvarianti(cat,vars){if(!cat||!vars?.length)return;cat=checkname(cat),await this.#checkelencovar(cat);const t=this.varelenco[cat],vn=[];for(let v of vars){v=clean(v,!0);const nn=`${cat}/${v}`;this.varianti[nn]||t&&t.includes(v)&&vn.push(v)}if(vn.length&&cbGetVariante){const xv=await cbGetVariante(cat,vn);if(xv&&xv.length)for(const x of xv){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}}async getheaderfromdb(name){const totale=await cbInfo("header",this.cat,name,!this.#deriva);let{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(const r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){llvars=new Set;for(const r of rows)if("p"==r.tipo);else{const nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];const vn=[],t=this.varelenco[this.cat];for(const nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){const vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(const x of vars){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){const getkey=n=>n.includes("/")?n:`${this.cat}/${n}`,cl=[];let k;if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){const vv=macros.split(";");for(const v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){const tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(const x of tm){this.checkscripts(x.content?.linkscript),delete x.content?.linkscript;const m=new Macro(this,x.name);for(const t in x.content){const contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}checkscripts(vv){if(vv&&vv.length)for(let v of vv)this.scripts[v.name]||(this.scripts[v.name]=v.value)}async setruleheader(rule,pars,ruleset){const{name:name,cat:cat}=checkmu(rule,this.cat);ruleset&&ruleset.length&&(this.ruleset=toruleset(ruleset));const ky=`${cat}/${name}`;if(!this.macro[ky]){const totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);const tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){const k2=this.macro[`${cat}/${head.rule}`];if(k2)for(const x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;const mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}async splitteroggetti(name){let data=await this.getvariante(name),cl=[];return data?.rows&&Object.values(data.rows).forEach((v=>{cl.push({tipo:v.v[2]||"",cod:v.v[0]||"",des:v.v[1]||"",macro:v.v[4]||"",sps:parseInt(v.v[3])||0,isshape:parseInt(v.v[5])})})),cl.length||cl.push({tipo:"avob",cod:"__",des:"Vuoto",macro:"",sps:0}),cl}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){const xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){azzera&&mu.azzera();return mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){const mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(/** @type {Ambiente} */amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(const p of pars){const{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){const x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,noquote,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,seeder,setOggetto,sortrows,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
268
+ this.varianti={},this.varelenco={},this.macroelenco={},this.scripts={},this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0)}setimgpreview(cod,img){img?this.imgpreview[cod]=img:delete this.imgpreview[cod]}getimgpreview(cod){return this?.imgpreview[cod||""]}setfndot(fndotcallback){this.fndotcallback=fndotcallback,this.vari.setfndot(fndotcallback)}async#checkelencovar(cat){if(cbInfo&&!this.varelenco[cat]){const tm=await cbInfo("headers",cat,"_varianti");Array.isArray(tm)?this.varelenco[cat]=tm:tm.vars&&(this.varelenco[cat]=tm.vars,tm.alias&&(this.#alias=tm.alias)),this.varelenco[cat]||(this.varelenco[cat]=[])}}parseheaderfrominfo(tm){if(tm&&tm.length>0)for(const t of tm)switch(t.tipo){case"_headers":"string"==typeof t.value&&(t.value=headerconvert(t.value)),this.#headers=t.value||{};break;case"_alias":"string"==typeof t.value&&(t.value=aliasconvert(t.value)),this.#alias=t.value||{};break;case"_typos":if("string"==typeof t.value){const tips=fromjson(t.value);for(const tp in tips){const tq=tips[tp];tq.db&&(tq.db=muClean(muClComments(tq.db))),tq.list&&(tq.list=muClean(muClComments(tq.list)))}t.value=tips}this.#typos=t.value||{}}}setitem(item,rule,model,ruleset=[],datadelgiorno=0){this.item=clean(item,!0),this.rule=clean(rule,!0),this.model=clean(model,!0),this.ruleset=toruleset(ruleset),this.data=datadelgiorno||(new Date).toInt()}async getheader(cod){let tm;return!this.#headers&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_headers"),this.parseheaderfrominfo(tm)),this.#headers||(this.#headers={}),this.#headers[cod]}async getalias(){let tm;return!this.#alias&&cbInfo&&(tm=await cbInfo("headers",this.cat,"_alias"),this.parseheaderfrominfo(tm)),this.#alias||(this.#alias={}),this.#alias}get deriva(){return this.#deriva,this.#deriva||[]}async getmacro(riga){try{if("string"==typeof riga&&(riga={tipo:"M",contenuto:riga}),!riga||!riga.contenuto)return;let ct=riga.contenuto;ct.startsWith("$")&&(ct=await this.vari.valuta(ct));const rr=/^([({}):$\w.\\/]+)[\s;,]*(.*)?$/im.exec(ct);if(!rr)return void errori.add("Macro non valida:"+ct,riga);let macro=clean(rr[1],!0);macro.includes("$")&&(macro=await this.vari.valuta(macro));const pars=getcolonne(rr[2]),{name:name,cat:cat}=checkmu(macro,this.cat);this.cat=cat;const ky=`${cat}/${name}`;if(!this.macro[ky]){const tm=new Macro(this,name);await tm.load()?this.macro[ky]=tm:errori.add(`macro fail to load ${ky}`,riga)}return macro=this.macro[ky],macro?{macro:macro,pars:pars}:(errori.add(`macro non trovata ${ky}`,riga),{})}catch(error){errori.add(geterrdes(error),`ambiente.getmacro: ${riga?.contenuto}`)}}async getvariante(cod){const{name:name,cat:cat}=checkmu(cod,this.cat);let n2=name,altri={};if(cat==this.cat&&this.#alias&&this.#alias[name]&&(altri=this.#alias[name]||{},n2=altri.cod),await this.#checkelencovar(cat),this.varelenco[cat]&&!this.varelenco[cat].includes(name))return;const key=`${cat}/${n2}`;let vv;return this.varianti[key]?vv=this.varianti[key]:(vv=new Variante(this),await vv.load(key,cat),this.varianti[key]=vv),altri&&(altri.des&&(vv.des=altri.des),altri.vdef&&(vv.vdef=altri.vdef)),vv}async varcompila(v,callback){const xx=new Variante(this);if(await xx.load(v,this.cat,!0),xx.alias){(await this.getalias())[v]=xx.alias}callback("variants",{cod:v,des:xx.des||"",alias:xx.alias,info:xx.alias?"":JSON.stringify(getOggetto(xx,["amb"]))})}async macrocompila(v,callback){const mac=new Macro(this,v);await mac.loadAndCompile(`${v}.mu`);const t=mac.getmacro();callback("macros",{cod:v,info:JSON.stringify(t),isgenera:mac.isgenera,isheader:mac.isheader,iscodice:mac.iscodice})}async barrecompila(articolibarre,titolibarre,callback){const cc=new CodiceBarra;await cc.compila(articolibarre,titolibarre);for(const x in cc.barre){callback("barcodes",{cod:x,des:"",info:JSON.stringify(cc.barre[x])})}return cc}async tojson(d){let tm;return cbFunc&&(tm=await cbFunc("json",d)),tm}async compila(info,callback){if(callback){for(const v of info.var)await this.varcompila(v,callback);for(const v of info.mu)await this.macrocompila(v,callback);if(callback("infos",{cod:"info",des:info.cat,info:JSON.stringify({cat:info.cat,md:info.info})}),this.#headers=void 0,this.#alias=void 0,this.#deriva=void 0,this.#typos=void 0,cbInfo){const tm=await cbInfo("headers",this.cat,["_headers","_alias","_deriva","_typos"]);this.parseheaderfrominfo(tm)}this.#headers?callback("infos",{cod:"headers",des:"",info:JSON.stringify(this.#headers)}):logga("missing headers"),this.#alias&&callback("infos",{cod:"alias",des:"",info:JSON.stringify(this.#alias)}),this.#deriva&&callback("infos",{cod:"deriva",des:"",info:JSON.stringify(this.#deriva)}),this.#typos&&callback("infos",{cod:"typos",des:"tipologie",info:JSON.stringify(this.#typos)})}}async checkvarianti(cat,vars){if(!cat||!vars?.length)return;cat=checkname(cat),await this.#checkelencovar(cat);const t=this.varelenco[cat],vn=[];for(let v of vars){v=clean(v,!0);const nn=`${cat}/${v}`;this.varianti[nn]||t&&t.includes(v)&&vn.push(v)}if(vn.length&&cbGetVariante){const xv=await cbGetVariante(cat,vn);if(xv&&xv.length)for(const x of xv){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}}async getheaderfromdb(name){const totale=await cbInfo("header",this.cat,name,!this.#deriva);let{head:head,rows:rows,macros:macros,deriva:deriva,llvars:llvars}=totale;for(const r of rows)r.cod=clean(r.cod),r.alias=clean(r.alias),r.t=clean(r.t);if(!llvars){llvars=new Set;for(const r of rows)if("p"==r.tipo);else{const nn=r.alias?r.alias:r.cod;llvars.add(nn)}llvars=[...llvars]}this.#deriva||(this.#deriva=deriva),await this.#checkelencovar(this.cat),head.cod=clean(head.cod),head.rule=clean(head.rule),head.ruledef=head.ruledef||[];const vn=[],t=this.varelenco[this.cat];for(const nn of llvars)this.varianti[`${this.cat}/${nn}`]||t&&t.includes(nn)&&vn.push(nn);if(vn.length&&cbGetVariante){const vars=await cbGetVariante(this.cat,vn);if(vars&&vars.length)for(const x of vars){const{name:name,content:content}=x,vv=new Variante(this);vv.setheader(name,this.cat),content&&await vv.loadContentExtended(content),this.varianti[vv.key]=vv}}return{head:head,rows:rows,macros:macros}}async getlinkedmacros(rule,macros){const getkey=n=>n.includes("/")?n:`${this.cat}/${n}`,cl=[];let k;if(rule&&(k=getkey(rule),this.macro[k]||cl.push(rule)),macros&&"string"==typeof macros){const vv=macros.split(";");for(const v of vv)k=getkey(v),this.macro[k]||cl.push(v)}if(cl&&cl.length>0&&cbGetMacro){const tm=await cbGetMacro(this.cat,cl);if(tm&&tm.length>0)for(const x of tm){this.checkscripts(x.content?.linkscript),delete x.content?.linkscript;const m=new Macro(this,x.name);for(const t in x.content){const contenuto=x.content[t];m[t]=contenuto}this.macro[m.key]=m}}}checkscripts(vv){if(vv&&vv.length)for(let v of vv)this.scripts[v.name]||(this.scripts[v.name]=v.value)}async setruleheader(rule,pars,ruleset){const{name:name,cat:cat}=checkmu(rule,this.cat);ruleset&&ruleset.length&&(this.ruleset=toruleset(ruleset));const ky=`${cat}/${name}`;if(!this.macro[ky]){const totale=await this.getheaderfromdb(name),{head:head,rows:rows,macros:macros}=totale;await this.getlinkedmacros(head.rule,macros);const tm=new Macro(this,name);if(!head)return void errori.add("Missing rule: "+rule);if(head.rule){const k2=this.macro[`${cat}/${head.rule}`];if(k2)for(const x in k2)["cat","name","key"].includes(x)||(tm[x]=k2[x])}rows&&rows.length&&(tm.head=rows),this.macro[ky]=tm}this.ruleheader=ky;const mc=this.macro[ky];return errori.azzera(),await mc.setparametri(pars),mc}getruleheader(){return this.macro[this.ruleheader]}async setvariante(cod,opz){return await impostavariante(this,null,cod,opz)}async valuta(codice){let output;return"string"==typeof codice&&(codice=muClean(muClComments(codice,this.righevuote))),Array.isArray(codice)&&(logga("m1",codice),output=await muEval(this,null,codice)),output}setinfos(tm){tm&&(this.#headers=tm.headers,this.#alias=tm.alias,this.#deriva=void 0,this.#typos=tm.typos)}async splitteroggetti(name){let data=await this.getvariante(name),cl=[];return data?.rows&&Object.values(data.rows).forEach((v=>{cl.push({tipo:v.v[2]||"",cod:v.v[0]||"",des:v.v[1]||"",macro:v.v[4]||"",sps:parseInt(v.v[3])||0,isshape:parseInt(v.v[5])})})),cl.length||cl.push({tipo:"avob",cod:"__",des:"Vuoto",macro:"",sps:0}),cl}}function toJson(t){return JSON.stringify(t,null,2)}function clamp(n,min=-1/0,max=1/0){return(n=Number(n)||0)<min&&(n=min),n>max&&(n=max),n}function gettipocolonna(cod){return tipicolonna.find((x=>x.cod==cod))?.des||tipicolonna[0].des}function gettipofolder(cod){return tipicolonna.find((x=>x.cod==cod))?.folder||""}function newVariabile(){return new Variabile}async function newVariante(cod,cat,amb){const xx=new Variante(amb);return await xx.load(cod,cat),xx}function newAmbiente(cat,maxmillis=100){return new Ambiente(cat,maxmillis)}function newMacro(amb,name){return new Macro(amb,name)}function muValuta(mu,codice,azzera){azzera&&mu.azzera();return mu.valuta(codice)}function muInit(cat,cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga){const mu=new Ambiente(cat);return setcallbacks(cbGetMacro,cbGetVariante,cbFunc,cbInfo,cbGetFile,cbLogga),mu}function muCompileScript(codice){return codice&&"object"==typeof codice?codice:codice.startsWith("{")&&codice.endsWith("}")||codice.startsWith("[")&&codice.endsWith("]")?JSON.stringify(codice):muClean(muClComments(codice))}async function muEvalScript(/** @type {Ambiente} */amb,codice,pars,reset=!0){if(codice=muCompileScript(codice),reset&&amb.azzera(),pars)for(const p of pars){const{v:v,o:o}=getcouple(p);amb.vari.add(v,o)}return{output:await muEval(amb,null,codice,{}),vari:amb.vari.dictionary,errori:errori}}const tonum=(s,dec=-1)=>{if(!s)return 0;let n=0;if("number"==typeof s)n=s||0;else if("string"==typeof s){const x=(s=s.replaceAll(",",".")).match(/^-?[0-9.]+$/);n=x&&x.length>0?Number(x[0])||0:muCalc(s)}if(dec>=0)switch(dec){case 0:n=Math.round(n);break;case 1:n=Math.round(10*n)/10;break;case 2:n=Math.round(100*n)/100;break;case 3:n=Math.round(1e3*n)/1e3;break;case 4:n=Math.round(1e4*n)/1e4;break;case 5:n=Math.round(1e5*n)/1e5;break;case 6:n=Math.round(1e6*n)/1e6}return n||0};Date.prototype.toInt||(Date.prototype.toInt=function(){return this.getDate()+100*(this.getMonth()+1)+1e4*this.getFullYear()}),Date.prototype.toFloat||(Date.prototype.toFloat=function(){return Math.floor(1e4*this.getDate()+1e6*(this.getMonth()+1)+1e8*this.getFullYear()+100*this.getHours()+this.getMinutes()+.5)/1e4});const mustr={mus:{variants:{cod:"s",des:"s",alias:"s",info:"s",md:"s",__pk:"cod"},extras:{tipo:"s",cod:"s",info:"s",__pk:"tipo, cod"},macros:{cod:"s",des:"s",info:"s",md:"s",def:"s",isgenera:"i",iscodice:"i",isheader:"i",__pk:"cod"},infos:{cod:"s",des:"s",info:"s",__pk:"cod"},barcodes:{cod:"s",des:"s",info:"s",__pk:"cod"}}};export{Ambiente,CodiceBarra,Macro,Variabile,Variante,checkmu,checkname,clamp,clean,dammivariante,errori,fromjson,getOggetto,getcolonne,getcouple,geterrdes,getheaddims,gettipocolonna,gettipofolder,hash,impostavariante,intvaluta,isJsonStr,isObject,muInit as jsTest,logga,muCalc,muClComments,muClean,muCompileScript,muEval,muEvalScript,muGenerate,muInit,muLimits,muParsecode,muValuta,mustr,newAmbiente,newMacro,newVariabile,newVariante,noquote,parselimitifromdb,parselimitifromrule,parsevar,poppars,pushpars,quote,seedarray,seeder,setOggetto,sortrows,testsync,tipicolonna,tipifree,tipiheader,tk,toCadPars,toJson,tonum,xdt};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markuno_lib",
3
- "version": "1.2.68",
3
+ "version": "1.2.70",
4
4
  "description": "Croswil Markuno Language Lib",
5
5
  "author": "Croswil SRL",
6
6
  "license": "SEE LICENSE IN LICENSE.txt",
@@ -18,8 +18,7 @@
18
18
  /**
19
19
  * Calcola la differenza delle coordinate x dei punti
20
20
  * @returns {number} Differenza x
21
- */ get angle(): number;
22
- get dx(): number;
21
+ */ get dx(): number;
23
22
  /**
24
23
  * Calcola la differenza delle coordinate y dei punti
25
24
  * @returns {number} Differenza y
@@ -32,6 +31,7 @@
32
31
  * Calcola la lunghezza della linea
33
32
  * @returns {number} Lunghezza
34
33
  */ get len(): number;
34
+ get angle(): number;
35
35
  /**
36
36
  * Estende la linea di una certa lunghezza o fino all'intersezione con un'altra linea
37
37
  * @param {number|Linea2} l - Lunghezza di estensione o linea da intersecare
@@ -674,6 +674,13 @@ export function revolve(gcad: any, shape: any, orient: any, mat: any, options: a
674
674
  */ export function salvaMaterialiOriginali(gruppo: THREE.Object3D): void;
675
675
  export function scalaoggetto(gcad: any, originale: any, scale?: {}): any;
676
676
  export const scaleunit: 0.001;
677
+ /**
678
+ * Rimuove i commenti dal codice sorgente mantenendo la struttura del codice
679
+ * @param {string} codice - Il codice sorgente da processare
680
+ * @param {boolean} tienivuoti - Se true mantiene le righe vuote
681
+ * @returns {string[]} Array di righe di codice senza commenti
682
+ */ export function seedarray(arr: any, seed: any): string[];
683
+ export function seeder(n: any, seed?: string): number;
677
684
  export function setLineColorMode(white: any, isdark: any): void;
678
685
  export function setorigine(obj: any, x?: number, y?: number, z?: number): any;
679
686
  export function shapeclip(): {
@@ -530,6 +530,7 @@ export function pushpars(amb: any, macro: any, parsfunzione: any, parsinit: any)
530
530
  o: any;
531
531
  }[]>;
532
532
  export function quote(v: any): any;
533
+ export function seedarray(arr: any, seed: any): any;
533
534
  export function seeder(n: any, seed?: string): number;
534
535
  /**
535
536
  * Classe per la gestione degli errori con funzionalità di accumulo e formattazione