@grapesjs/studio-sdk-plugins 1.0.22 → 1.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,31 @@
1
- (function(d,f){typeof exports=="object"&&typeof module<"u"?module.exports=f():typeof define=="function"&&define.amd?define(f):(d=typeof globalThis<"u"?globalThis:d||self,d.StudioSdkPlugins_dataSourceEjs=f())})(this,function(){"use strict";const d="app.grapesjs.com",f="app-stage.grapesjs.com",S=[d,f,"localhost","127.0.0.1",".local-credentialless.webcontainer.io",".local.webcontainer.io","-sandpack.codesandbox.io"],C="license:check:start",L="license:check:end",v=()=>typeof window<"u",w=({isDev:i,isStage:t})=>`${i?"":`https://${t?f:d}`}/api`,P=()=>{const i=v()&&window.location.hostname;return!!i&&(S.includes(i)||S.some(t=>i.endsWith(t)))};async function k({path:i,baseApiUrl:t,method:e="GET",headers:r={},params:s,body:n}){const o=`${t||w({isDev:!1,isStage:!1})}${i}`,l={method:e,headers:{"Content-Type":"application/json",...r}};n&&(l.body=JSON.stringify(n));const p=s?new URLSearchParams(s).toString():"",c=p?`?${p}`:"",h=await fetch(`${o}${c}`,l);if(!h.ok)throw new Error(`HTTP error! status: ${h.status}`);return h.json()}var g=(i=>(i.free="free",i.startup="startup",i.business="business",i.enterprise="enterprise",i))(g||{});const $={[g.free]:0,[g.startup]:10,[g.business]:20,[g.enterprise]:30};function T(i){const t=i;return t.init=e=>r=>i(r,e),t}const M=i=>T(i);async function N({editor:i,plan:t,pluginName:e,licenseKey:r,cleanup:s}){let n="",a=!1;const o=P(),l=c=>{console.warn("Cleanup plugin:",e,"Reason:",c),s()},p=(c={})=>{var I;const{error:h,sdkLicense:y}=c,u=(I=c.plan)==null?void 0:I.category;if(!(y||c.license)||h)l(h||"Invalid license");else if(u){const G=$[t],R=$[u];G>R&&l({pluginRequiredPlan:t,licensePlan:u})}};i.on(C,c=>{n=c==null?void 0:c.baseApiUrl,a=!0}),i.on(L,c=>{p(c)}),setTimeout(async()=>{if(!a){if(o)return;if(r){const c=await O({licenseKey:r,pluginName:e,baseApiUrl:n});c&&p(c)}else l("The `licenseKey` option not provided")}},2e3)}async function O(i){const{licenseKey:t,pluginName:e,baseApiUrl:r}=i;try{return(await k({baseApiUrl:r,path:`/sdk/${t||"na"}`,method:"POST",params:{d:window.location.hostname,pn:e}})).result||{}}catch(s){return console.error("Error during SDK license check:",s),!1}}var m=(i=>(i.variable="data-variable",i.condition="data-condition",i.conditionTrue="data-condition-true-content",i.conditionFalse="data-condition-false-content",i.collection="data-collection",i.collectionItem="data-collection-item",i))(m||{});class _{constructor(t){this.strategy=t,this.requiredHelpers=new Set,this.helperLibrary={}}registerHelper(t){this.helperLibrary[t]&&this.requiredHelpers.add(t)}generateVariable(t){return this.strategy.getVariableSyntax(t)}generateCollectionStart(t){return this.registerHelper("slice"),this.strategy.getCollectionStartSyntax(t)}generateCollectionEnd(){return this.strategy.getCollectionEndSyntax()}generateConditionalStart(t){return this.strategy.getConditionalStartSyntax(t)}generateConditionElse(){return this.strategy.getConditionElseSyntax()}generateConditionalEnd(){return this.strategy.getConditionalEndSyntax()}reset(){this.requiredHelpers.clear()}}function B(i){return typeof i=="object"&&i.type===m.variable}function x({component:i,value:t,getCustomPath:e}){if(B(t)&&!t.collectionId&&e){const r=t.path??"",s=r.split(".");return{...t,path:e({component:i,path:r,paths:s})}}return t}const W=i=>{E(i,m.variable,{toHTML(t){var a;const e=this.tagName,r=this.__attrToString(t),s=(a=this.getDataResolver)==null?void 0:a.call(this),n=x({component:this,value:s,getCustomPath:t==null?void 0:t.getCustomPath});return`<${e}${r?` ${r}`:""}>${t.exporter.generateVariable(n)}</${e}>`}}),E(i,m.condition,{toHTML(t){var p,c;const e=t.exporter,r=t==null?void 0:t.getCustomPath,s=this.components(),[n,a]=(s==null?void 0:s.models)??[],o=(p=this.getDataResolver)==null?void 0:p.call(this),l=((c=this.resolveCondition)==null?void 0:c.call(this,o==null?void 0:o.condition,r))??{};return`
2
- ${e.generateConditionalStart(l)}
3
- ${(n==null?void 0:n.toHTML(t))??""}
4
- ${e.generateConditionElse()}
5
- ${(a==null?void 0:a.toHTML(t))??""}
6
- ${e.generateConditionalEnd()}
7
- `},resolveCondition(t,e){var s,n;if(!t)return{};if(t.operator==="and"||t.operator==="or")return{operator:t.operator,statements:((n=(s=t.statements)==null?void 0:s.map)==null?void 0:n.call(s,a=>{var o;return((o=this.resolveCondition)==null?void 0:o.call(this,a,e))??{}}))??[]};const r={component:this,getCustomPath:e};return{...t,left:x({...r,value:t.left}),right:x({...r,value:t.right})}}}),E(i,m.collection,{toHTML(t){const e=t.exporter,r=this.tagName,s=this.__attrToString(t),n=this.getDataResolver(),a={...n,dataSource:x({component:this,value:n==null?void 0:n.dataSource,getCustomPath:t==null?void 0:t.getCustomPath})},o=this.components().at(0);return`
8
- <${r}${s?` ${s}`:""}>${e.generateCollectionStart(a)}
9
- ${(o==null?void 0:o.toHTML(t))??""}
10
- ${e.generateCollectionEnd()}</${r}>
11
- `}})},E=(i,t,e)=>{const r=i.Components.getType(t);if(!r){console.warn(`Component type ${t} not found`);return}const{model:s}=r;i.Components.addType(t,{model:{...e,toHTML(n={}){var o;const{exporter:a}=n;return a?a.export?a.export({component:this}):((o=e.toHTML)==null?void 0:o.call(this,n))??"":s.prototype.toHTML.call(this,n)??""}}})},j=i=>{const t=i;return t.logicalOperator==="and"||t.logicalOperator==="or"},A=(i,t)=>(i.config.optsHtml={...i.config.optsHtml,exporter:new _(t)},W(i),()=>{i.config.optsHtml.exporter=void 0}),J=(i,t)=>{const e=s=>{const{input:n}=s,{contains:a}=t;(!a||n.includes(a))&&(s.input=t.importer.import(n))},r=i.Parser.events.htmlBefore;return i.on(r,e),()=>{i.off(r,e)}};class H{getVariableSyntax(t){const{defaultValue:e}=t,r=this.getFullPath(t),s=e?` || \`${e}\``:"";return`<%= ${r}${s} %>`}getCollectionStartSyntax(t){const{collectionId:e,dataSource:r,startIndex:s,endIndex:n}=t,a=(r==null?void 0:r.path)||e||"",o=this._sanitizeVariableName(e);let l="";if(s!==void 0||n!==void 0){const p=s??0,c=n!==void 0?n:"";l=`.slice(${p}${c!==""?`, ${c}`:""})`}return`<% ${a}${l}.forEach(function(currentItem, index, arr) {
1
+ (function(g,m){typeof exports=="object"&&typeof module<"u"?module.exports=m():typeof define=="function"&&define.amd?define(m):(g=typeof globalThis<"u"?globalThis:g||self,g.StudioSdkPlugins_dataSourceEjs=m())})(this,function(){"use strict";const g="app.grapesjs.com",m="app-stage.grapesjs.com",C=[g,m,"localhost","127.0.0.1",".local-credentialless.webcontainer.io",".local.webcontainer.io","-sandpack.codesandbox.io"],P="license:check:start",L="license:check:end",v=()=>typeof window<"u",k=({isDev:o,isStage:t})=>`${o?"":`https://${t?m:g}`}/api`,O=()=>{const o=v()&&window.location.hostname;return!!o&&(C.includes(o)||C.some(t=>o.endsWith(t)))};async function T({path:o,baseApiUrl:t,method:e="GET",headers:n={},params:s,body:r}){const a=`${t||k({isDev:!1,isStage:!1})}${o}`,c={method:e,headers:{"Content-Type":"application/json",...n}};r&&(c.body=JSON.stringify(r));const p=s?new URLSearchParams(s).toString():"",l=p?`?${p}`:"",h=await fetch(`${a}${l}`,c);if(!h.ok)throw new Error(`HTTP error! status: ${h.status}`);return h.json()}var y=(o=>(o.free="free",o.startup="startup",o.business="business",o.enterprise="enterprise",o))(y||{});const w={[y.free]:0,[y.startup]:10,[y.business]:20,[y.enterprise]:30};function N(o){const t=o;return t.init=e=>n=>o(n,e),t}const M=o=>N(o);async function B({editor:o,plan:t,pluginName:e,licenseKey:n,cleanup:s}){let r="",i=!1;const a=O(),c=l=>{console.warn("Cleanup plugin:",e,"Reason:",l),s()},p=(l={})=>{var u;const{error:h,sdkLicense:d}=l,f=(u=l.plan)==null?void 0:u.category;if(!(d||l.license)||h)c(h||"Invalid license");else if(f){const S=w[t],b=w[f];S>b&&c({pluginRequiredPlan:t,licensePlan:f})}};o.on(P,l=>{r=l==null?void 0:l.baseApiUrl,i=!0}),o.on(L,l=>{p(l)}),setTimeout(async()=>{if(!i){if(a)return;if(n){const l=await _({licenseKey:n,pluginName:e,baseApiUrl:r});l&&p(l)}else c("The `licenseKey` option not provided")}},2e3)}async function _(o){const{licenseKey:t,pluginName:e,baseApiUrl:n}=o;try{return(await T({baseApiUrl:n,path:`/sdk/${t||"na"}`,method:"POST",params:{d:window.location.hostname,pn:e}})).result||{}}catch(s){return console.error("Error during SDK license check:",s),!1}}var E=(o=>(o.variable="data-variable",o.condition="data-condition",o.conditionTrue="data-condition-true-content",o.conditionFalse="data-condition-false-content",o.collection="data-collection",o.collectionItem="data-collection-item",o))(E||{});class j{constructor(t){this.strategy=t,this.requiredHelpers=new Set,this.helperLibrary={}}registerHelper(t){this.helperLibrary[t]&&this.requiredHelpers.add(t)}generateVariable(t){return this.strategy.getVariableSyntax(t)}generateCollectionStart(t){return this.registerHelper("slice"),this.strategy.getCollectionStartSyntax(t)}generateCollectionEnd(){return this.strategy.getCollectionEndSyntax()}generateConditionalStart(t){return this.strategy.getConditionalStartSyntax(t)}generateConditionElse(){return this.strategy.getConditionElseSyntax()}generateConditionalEnd(){return this.strategy.getConditionalEndSyntax()}reset(){this.requiredHelpers.clear()}}function W(o){return typeof o=="object"&&o.type===E.variable}function x({component:o,value:t,getCustomPath:e}){if(W(t)&&!t.collectionId&&e){const n=t.path??"",s=n.split(".");return{...t,path:e({component:o,path:n,paths:s})}}return t}const A=o=>{I(o,E.variable,{toHTML(t){var i;const e=this.tagName,n=this.__attrToString(t),s=(i=this.getDataResolver)==null?void 0:i.call(this),r=x({component:this,value:s,getCustomPath:t==null?void 0:t.getCustomPath});return`<${e}${n?` ${n}`:""}>${t.exporter.generateVariable(r)}</${e}>`}}),I(o,E.condition,{toHTML(t){var l,h;const e=t.exporter,n=t==null?void 0:t.getCustomPath,s=this.components(),[r,i]=(s==null?void 0:s.models)??[],a=(l=this.getDataResolver)==null?void 0:l.call(this),c=((h=this.resolveCondition)==null?void 0:h.call(this,a==null?void 0:a.condition,n))??{};let p="";return i&&(p=`
2
+ ${e.generateConditionElse()}
3
+ ${i.toHTML(t)??""}`),`
4
+ ${e.generateConditionalStart(c)}
5
+ ${(r==null?void 0:r.toHTML(t))??""}${p}
6
+ ${e.generateConditionalEnd()}
7
+ `},resolveCondition(t,e){var s,r;if(!t)return{};if(t.operator==="and"||t.operator==="or")return{operator:t.operator,statements:((r=(s=t.statements)==null?void 0:s.map)==null?void 0:r.call(s,i=>{var a;return((a=this.resolveCondition)==null?void 0:a.call(this,i,e))??{}}))??[]};const n={component:this,getCustomPath:e};return{...t,left:x({...n,value:t.left}),right:x({...n,value:t.right})}}}),I(o,E.collection,{toHTML(t){const e=t.exporter,n=this.tagName,s=this.__attrToString(t),r=this.getDataResolver(),i={...r,dataSource:x({component:this,value:r==null?void 0:r.dataSource,getCustomPath:t==null?void 0:t.getCustomPath})},a=this.components().at(0);return`
8
+ <${n}${s?` ${s}`:""}>${e.generateCollectionStart(i)}
9
+ ${(a==null?void 0:a.toHTML(t))??""}
10
+ ${e.generateCollectionEnd()}</${n}>
11
+ `}})},I=(o,t,e)=>{const n=o.Components.getType(t);if(!n){console.warn(`Component type ${t} not found`);return}const{model:s}=n;o.Components.addType(t,{model:{...e,toHTML(r={}){var a;const{exporter:i}=r;return i?i.export?i.export({component:this}):((a=e.toHTML)==null?void 0:a.call(this,r))??"":s.prototype.toHTML.call(this,r)??""}}})},J=o=>{const t=o;return t.logicalOperator==="and"||t.logicalOperator==="or"},F=(o,t)=>(o.config.optsHtml={...o.config.optsHtml,exporter:new j(t)},A(o),()=>{o.config.optsHtml.exporter=void 0}),H=(o,t)=>{const e=s=>{const{input:r}=s,{contains:i}=t;(!i||r.includes(i))&&(s.input=t.importer.import(r))},n=o.Parser.events.htmlBefore;return o.on(n,e),()=>{o.off(n,e)}};class U{getVariableSyntax(t){const{defaultValue:e}=t,n=this.getFullPath(t),s=e?` || \`${e}\``:"";return`<%= ${n}${s} %>`}getCollectionStartSyntax(t){const{collectionId:e,dataSource:n,startIndex:s,endIndex:r}=t,i=(n==null?void 0:n.path)||e||"",a=this._sanitizeVariableName(e);let c="";if(s!==void 0||r!==void 0){const p=s??0,l=r!==void 0?r:"";c=`.slice(${p}${l!==""?`, ${l}`:""})`}return`<% ${i}${c}.forEach(function(currentItem, index, arr) {
12
12
  const startIndex = parseInt(${s??0}, 10);
13
13
  const endIndex = startIndex + arr.length;
14
- const ${o}={ currentItem, currentIndex: startIndex + index, remainingItems: endIndex - (startIndex + index)} %>`}_sanitizeVariableName(t){return t.replace(/[^a-zA-Z0-9_$]/g,"_")}getCollectionEndSyntax(){return"<% }) %>"}getConditionalStartSyntax(t){return`<% if (${this._parseCondition(t)}) { %>`}getConditionElseSyntax(){return"<% } else { %>"}getConditionalEndSyntax(){return"<% } %>"}getFullPath({collectionId:t,path:e,variableType:r}){return(t?[this._sanitizeVariableName(t),r,e].filter(Boolean).join("."):e)||""}_parseCondition(t){if(!t)return"";if(j(t)){const e=t.statements.map(r=>this._parseCondition(r));return e.length>1?`(${e.join(`) ${t.logicalOperator} (`)})`:e[0]}else{const e=this._parseValue(t.left),r=this._parseValue(t.right);switch(t.operator){case"equals":return`${e} === ${r}`;case">":case"<":case">=":case"<=":case"=":case"!=":return`${e} ${t.operator} ${r}`;case"contains":return`${e}?.includes(${r})`;case"startsWith":return`${e}?.startsWith(${r})`;case"endsWith":return`${e}?.endsWith(${r})`;case"equalsIgnoreCase":return`${e}?.toLowerCase() === ${r}?.toLowerCase()`;case"trimEquals":return`${e}?.trim() === ${r}?.trim()`;case"isTruthy":return`!!${e}`;case"isFalsy":return`!${e}`;case"isDefined":return`${e} !== undefined`;case"isNull":return`${e} === null`;case"isUndefined":return`${e} === undefined`;case"isArray":return`Array.isArray(${e})`;case"isObject":return`typeof ${e} === 'object' && ${e} !== null && !Array.isArray(${e})`;case"isString":return`typeof ${e} === 'string'`;case"isNumber":return`typeof ${e} === 'number' && !isNaN(${e})`;case"isBoolean":return`typeof ${e} === 'boolean'`;default:return`${e} ${t.operator} ${r}`}}}_parseValue(t){return typeof t=="object"?this.getFullPath(t):typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:String(t)}}const U=["===","==","!==","!=","<=",">=","<",">","&&","||"],D={"===":"=","==":"=","!==":"!=","!=":"!=","<=":"<=",">=":">=","<":"<",">":">","&&":"&&","||":"||"};class V{constructor(){this.messages=[],this.collectionStack=[]}import(t){this.messages=[],this.collectionStack=[];try{const e=this.parseEjsTemplate(t);return this.astToGrapesJS(e)}catch(e){return console.error("Error during import:",e),this.addMessage("error",`Error during import: ${e instanceof Error?e.message:String(e)}`),""}}parseEjsTemplate(t){const e=[];let r=0;for(;r<t.length;){const s=t.indexOf("<%",r);if(s===-1){r<t.length&&e.push(this.createAppendLiteral(t.slice(r)));break}s>r&&e.push(this.createAppendLiteral(t.slice(r,s)));const n=t.indexOf("%>",s);if(n===-1)throw new Error("Unclosed EJS tag");const a=t.slice(s+2,n).trim();if(r=n+2,a.startsWith("=")||a.startsWith("-")){const o=a.slice(1).trim();e.push(this.createAppendExpression(o))}else{if(a.startsWith("#"))continue;if(a.startsWith("if")){const o=this.parseIfStatement(a,t,r);e.push(o),r=o.endPos||r}else if(a.startsWith("for")){const o=this.parseForStatement(a,t,r);e.push(o),r=o.endPos||r}else{if(a.startsWith("}")||a.startsWith("} else"))break;this.addMessage("info",`Unsupported scriptlet content: ${a}`)}}}return{type:"Program",body:e}}createAppendLiteral(t){return{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"__append"},arguments:[{type:"Literal",value:t}]}}}createAppendExpression(t){return{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"__append"},arguments:[this.parseJsExpression(t)]}}}findNextElse(t,e){const r=/<%\s*\}\s*else(?:\s+if\s*\([^)]*\))?\s*\{\s*%>/g;r.lastIndex=e;const s=r.exec(t);return s?{start:s.index,end:t.indexOf("%>",s.index)+2}:null}parseIfStatement(t,e,r){const s=t.match(/if\s*\((.*)\)\s*\{?/);if(!s)throw new Error("Invalid if statement syntax");const n=this.parseJsExpression(s[1]),{body:a,endPos:o}=this.parseTemplateBlock(e,r);let l=null,p=o;const c=this.findNextElse(e,o);if(c){const h=e.slice(c.start,c.end);if(/else\s+if/.test(h)){const y=c.end,u=this.parseIfStatement(h,e,y);l={type:"IfStatement",test:u.test,consequent:u.consequent,alternate:u.alternate},p=u.endPos}else{const y=c.end,{body:u,endPos:b}=this.parseTemplateBlock(e,y);l={type:"BlockStatement",body:u},p=b}}return{type:"IfStatement",test:n,consequent:{type:"BlockStatement",body:a},alternate:l,endPos:p}}parseForStatement(t,e,r){const s=t.match(/for\s*\((.*)\)\s*\{?/);if(!s)throw new Error("Invalid for statement syntax");const n=s[1].split("of");if(n.length!==2)throw new Error("Only for...of loops are supported");const a=n[0].trim().replace(/^let\s+|^const\s+|^var\s+/,""),o=n[1].trim(),{body:l,endPos:p}=this.parseTemplateBlock(e,r);return{type:"ForStatement",init:{type:"VariableDeclaration",kind:"let",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:a},init:this.parseJsExpression(o)}]},test:null,update:null,body:{type:"BlockStatement",body:l},endPos:p}}parseTemplateBlock(t,e){const r=[];let s=e,n=1;for(;s<t.length&&n>0;){const a=t.indexOf("<%",s);if(a===-1){s<t.length&&r.push(this.createAppendLiteral(t.slice(s)));break}a>s&&r.push(this.createAppendLiteral(t.slice(s,a)));const o=t.indexOf("%>",a);if(o===-1)throw new Error("Unclosed EJS tag");const l=t.slice(a+2,o).trim();if(s=o+2,l==="}"){if(n--,n===0)break}else(l.startsWith("if")||l.startsWith("for"))&&n++;if(l.startsWith("=")||l.startsWith("-")){const p=l.slice(1).trim();r.push(this.createAppendExpression(p))}else{if(l.startsWith("#"))continue;if(l.startsWith("} else")){s=a;break}}}return{body:r,endPos:s}}parseJsExpression(t){if(/^(['"]).*\1$/.test(t))return{type:"Literal",value:t.slice(1,-1)};if(/^-?\d+$/.test(t))return{type:"Literal",value:parseInt(t,10)};if(/^-?\d+\.\d+$/.test(t))return{type:"Literal",value:parseFloat(t)};if(t==="true"||t==="false")return{type:"Literal",value:t==="true"};for(const s of U){const n=t.indexOf(s);if(n>0)return{type:s==="&&"||s==="||"?"LogicalExpression":"BinaryExpression",operator:D[s],left:this.parseJsExpression(t.slice(0,n).trim()),right:this.parseJsExpression(t.slice(n+s.length).trim())}}const e=t.indexOf("."),r=t.indexOf("[");if(e>0||r>0){const s=e>0&&(r===-1||e<r)?e:r;let n,a,o=!1;if(s===e)n=t.slice(0,e),a=this.parseJsExpression(t.slice(e+1));else{n=t.slice(0,r);const l=t.indexOf("]",r);if(l===-1)throw new Error("Unclosed bracket in expression");a=this.parseJsExpression(t.slice(r+1,l)),o=!0}return{type:"MemberExpression",object:this.parseJsExpression(n),property:a,computed:o}}return{type:"Identifier",name:t}}astToGrapesJS(t){switch(t.type){case"Program":return this.handleProgram(t);case"VariableDeclaration":return this.handleVariableDeclaration(t);case"ExpressionStatement":return this.handleExpressionStatement(t);case"IfStatement":return this.handleIfStatement(t);case"ForStatement":return this.handleForStatement(t);case"BlockStatement":return this.handleBlockStatement(t);case"Literal":return this.handleLiteral(t);case"Identifier":return this.handleIdentifier(t);case"MemberExpression":return this.handleMemberExpression(t);case"BinaryExpression":return this.handleBinaryExpression(t);case"LogicalExpression":return this.handleLogicalExpression(t);case"CallExpression":return this.handleCallExpression(t);default:return this.addMessage("warning",`Unsupported node type: ${t.type}`),""}}handleProgram(t){let e="";for(const r of t.body)e+=this.astToGrapesJS(r);return e}handleVariableDeclaration(t){return""}handleExpressionStatement(t){return t.expression.type==="CallExpression"&&t.expression.callee.type==="Identifier"&&t.expression.callee.name==="__append"&&t.expression.arguments.length>0?this.astToGrapesJS(t.expression.arguments[0]):""}handleIfStatement(t){const e=this.getConditionExpression(t.test),r=this.astToGrapesJS(t.consequent);let s="";return t.alternate&&(s=this.astToGrapesJS(t.alternate)),`
14
+ const ${a}={ currentItem, currentIndex: startIndex + index, remainingItems: endIndex - (startIndex + index)} %>`}_sanitizeVariableName(t){return t.replace(/[^a-zA-Z0-9_$]/g,"_")}getCollectionEndSyntax(){return"<% }) %>"}getConditionalStartSyntax(t){return`<% if (${this._parseCondition(t)}) { %>`}getConditionElseSyntax(){return"<% } else { %>"}getConditionalEndSyntax(){return"<% } %>"}getFullPath({collectionId:t,path:e,variableType:n}){return(t?[this._sanitizeVariableName(t),n,e].filter(Boolean).join("."):e)||""}_parseCondition(t){if(!t)return"";if(J(t)){const e=t.statements.map(r=>this._parseCondition(r)),n=D[t.logicalOperator];let s=e.length>1?`(${e.join(`)${n}(`)})`:e[0];return t.logicalOperator==="xor"&&(s=`!!(${s})`),s}else{const e=this._parseValue(t.left),n=this._parseValue(t.right);switch(t.operator){case"equals":return`${e} === ${n}`;case">":case"<":case">=":case"<=":case"=":case"!=":return`${e} ${t.operator} ${n}`;case"contains":return`${e}?.includes(${n})`;case"startsWith":return`${e}?.startsWith(${n})`;case"endsWith":return`${e}?.endsWith(${n})`;case"equalsIgnoreCase":return`${e}?.toLowerCase() === ${n}?.toLowerCase()`;case"trimEquals":return`${e}?.trim() === ${n}?.trim()`;case"isTruthy":return`!!${e}`;case"isFalsy":return`!${e}`;case"isDefined":return`${e} !== undefined`;case"isNull":return`${e} === null`;case"isUndefined":return`${e} === undefined`;case"isArray":return`Array.isArray(${e})`;case"isObject":return`typeof ${e} === 'object' && ${e} !== null && !Array.isArray(${e})`;case"isString":return`typeof ${e} === 'string'`;case"isNumber":return`typeof ${e} === 'number' && !isNaN(${e})`;case"isBoolean":return`typeof ${e} === 'boolean'`;default:return`${e} ${t.operator} ${n}`}}}_parseValue(t){return typeof t=="object"?this.getFullPath(t):typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:String(t)}}const D={and:"&&",or:"||",xor:"^"},V=["===","==","!==","!=","<=",">=","<",">","&&","||"],q={"===":"=","==":"=","!==":"!=","!=":"!=","<=":"<=",">=":">=","<":"<",">":">","&&":"&&","||":"||"};class G{constructor(){this.messages=[],this.collectionStack=[]}import(t){this.messages=[],this.collectionStack=[];try{const e=this.parseEjsTemplate(t);return this.astToGrapesJS(e)}catch(e){return console.error("Error during import:",e),this.addMessage("error",`Error during import: ${e instanceof Error?e.message:String(e)}`),""}}parseEjsTemplate(t){const e=[];let n=0;for(;n<t.length;){const s=t.indexOf("<%",n);if(s===-1){n<t.length&&e.push(this.createAppendLiteral(t.slice(n)));break}s>n&&e.push(this.createAppendLiteral(t.slice(n,s)));const r=t.indexOf("%>",s);if(r===-1)throw new Error("Unclosed EJS tag");const i=t.slice(s+2,r).trim();if(n=r+2,i.startsWith("=")||i.startsWith("-")){const a=i.slice(1).trim();e.push(this.createAppendExpression(a))}else{if(i.startsWith("#"))continue;if(i.startsWith("if")){const a=this.parseIfStatement(i,t,n);e.push(a),n=a.endPos||n}else if(i.startsWith("for")){const a=this.parseForStatement(i,t,n);e.push(a),n=a.endPos||n}else{const a=i.match(/([\w][\w.-]*[\w])\s*\.\s*forEach\s*\(\s*(\w+)\s*=>\s*\{?/);if(a){const c=a[1],p=a[2],l=this.parseForEachStatement(c,p,t,n);e.push(l),n=l.endPos||n}else this.addMessage("info",`Unsupported scriptlet content: ${i}`)}}}return{type:"Program",body:e}}createAppendLiteral(t){return{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"__append"},arguments:[{type:"Literal",value:t}]}}}createAppendExpression(t){return{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"__append"},arguments:[this.parseJsExpression(t)]}}}parseIfStatement(t,e,n){const s=t.match(/if\s*\((.*)\)\s*\{?/);if(!s)throw new Error("Invalid if statement syntax");const r=this.parseJsExpression(s[1]),{body:i,endPos:a}=this.parseTemplateBlock(e,n);let c=null,p=a;const l=e.indexOf("<%",p);if(l===p){const h=e.indexOf("%>",l);if(h!==-1){const d=e.slice(l+2,h).trim(),f=h+2-l;if(d.startsWith("} else if")){p=l+f;const $=d.substring(d.indexOf("if")).trim(),u=this.parseIfStatement($,e,p);c={type:"IfStatement",test:u.test,consequent:u.consequent,alternate:u.alternate},p=u.endPos}else if(d.startsWith("} else")){p=l+f;const{body:$,endPos:u}=this.parseTemplateBlock(e,p);c={type:"BlockStatement",body:$},p=u;const S=e.indexOf("<%",p),b=e.indexOf("%>",S);S===p&&e.slice(S+2,b).trim()==="}"&&(p=b+2)}else d==="}"&&(p=l+f)}}return{type:"IfStatement",test:r,consequent:{type:"BlockStatement",body:i},alternate:c,endPos:p}}parseForStatement(t,e,n){const s=t.match(/for\s*\((.*)\)\s*\{?/);if(!s)throw new Error("Invalid for statement syntax");const r=s[1].split("of");if(r.length!==2)throw new Error("Only for...of loops are supported");const i=r[0].trim().replace(/^let\s+|^const\s+|^var\s+/,""),a=r[1].trim(),{body:c,endPos:p}=this.parseTemplateBlock(e,n);return{type:"ForStatement",init:{type:"VariableDeclaration",kind:"let",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:i},init:this.parseJsExpression(a)}]},test:null,update:null,body:{type:"BlockStatement",body:c},endPos:(()=>{const l=e.indexOf("<%",p),h=e.indexOf("%>",l);return l===p&&e.slice(l+2,h).trim()==="}"?h+2:p})()}}parseForEachStatement(t,e,n,s){const{body:r,endPos:i}=this.parseTemplateBlock(n,s);return{type:"ForEachStatement",collection:this.parseJsExpression(t),itemIdentifier:{type:"Identifier",name:e},body:{type:"BlockStatement",body:r},endPos:(()=>{const a=n.indexOf("<%",i),c=n.indexOf("%>",a);return a===i&&n.slice(a+2,c).trim()==="}"?c+2:i})()}}parseTemplateBlock(t,e){const n=[];let s=e;for(;s<t.length;){const r=t.indexOf("<%",s);if(r===-1){s<t.length&&n.push(this.createAppendLiteral(t.slice(s))),s=t.length;break}r>s&&n.push(this.createAppendLiteral(t.slice(s,r)));const i=t.indexOf("%>",r);if(i===-1)throw new Error("Unclosed EJS tag within block");const a=t.slice(r+2,i).trim();if(a==="}"||a.startsWith("} else")){s=r;break}if(s=i+2,a.startsWith("=")||a.startsWith("-")){const c=a.slice(1).trim();n.push(this.createAppendExpression(c))}else{if(a.startsWith("#"))continue;if(a.startsWith("if")){const c=this.parseIfStatement(a,t,s);n.push(c),s=c.endPos||s}else if(a.startsWith("for")){const c=this.parseForStatement(a,t,s);n.push(c),s=c.endPos||s}else{const c=a.match(/([\w][\w.-]*[\w])\s*\.\s*forEach\s*\(\s*(\w+)\s*=>\s*\{?/);if(c){const p=c[1],l=c[2],h=this.parseForEachStatement(p,l,t,s);n.push(h),s=h.endPos||s}else this.addMessage("info",`Unsupported scriptlet content within block: ${a}`)}}}return{body:n,endPos:s}}parseJsExpression(t){if(/^(['"]).*\1$/.test(t))return{type:"Literal",value:t.slice(1,-1)};if(/^-?\d+$/.test(t))return{type:"Literal",value:parseInt(t,10)};if(/^-?\d+\.\d+$/.test(t))return{type:"Literal",value:parseFloat(t)};if(t==="true"||t==="false")return{type:"Literal",value:t==="true"};for(const s of V){const r=t.lastIndexOf(s);if(r>0&&t[r-1]!=="!"&&t[r-1]!=="="&&t[r-1]!=="<"&&t[r-1]!==">")return{type:s==="&&"||s==="||"?"LogicalExpression":"BinaryExpression",operator:q[s],left:this.parseJsExpression(t.slice(0,r).trim()),right:this.parseJsExpression(t.slice(r+s.length).trim())}}const e=t.indexOf("."),n=t.indexOf("[");if(e>0&&(n===-1||e<n)||n>0&&(e===-1||n<e)){const s=e>0&&(n===-1||e<n)?e:n;let r,i,a=!1;if(s===e)r=t.slice(0,e),i={type:"Identifier",name:t.slice(e+1)},a=!1;else{r=t.slice(0,n);const c=t.indexOf("]",n);if(c===-1)throw new Error("Unclosed bracket in expression");const p=t.slice(n+1,c);i=/^(['"]).*\1$/.test(p)||/^-?\d+(\.\d+)?$/.test(p)?this.parseJsExpression(p):{type:"Identifier",name:p},a=!0}return{type:"MemberExpression",object:this.parseJsExpression(r),property:i,computed:a}}return{type:"Identifier",name:t}}astToGrapesJS(t){switch(t.type){case"Program":return this.handleProgram(t);case"VariableDeclaration":return this.handleVariableDeclaration(t);case"ExpressionStatement":return this.handleExpressionStatement(t);case"IfStatement":return this.handleIfStatement(t);case"ForStatement":return this.handleForStatement(t);case"ForEachStatement":return this.handleForEachStatement(t);case"BlockStatement":return this.handleBlockStatement(t);case"Literal":return this.handleLiteral(t);case"Identifier":return this.handleIdentifier(t);case"MemberExpression":return this.handleMemberExpression(t);case"BinaryExpression":return this.handleBinaryExpression(t);case"LogicalExpression":return this.handleLogicalExpression(t);case"CallExpression":return this.handleCallExpression(t);default:return this.addMessage("warning",`Unsupported node type: ${t.type}`),""}}handleProgram(t){let e="";for(const n of t.body)e+=this.astToGrapesJS(n);return e}handleVariableDeclaration(t){return""}handleExpressionStatement(t){return t.expression.type==="CallExpression"&&t.expression.callee.type==="Identifier"&&t.expression.callee.name==="__append"&&t.expression.arguments.length>0?this.astToGrapesJS(t.expression.arguments[0]):""}handleIfStatement(t){const e=this.getConditionExpression(t.test),n=this.astToGrapesJS(t.consequent);let s="";return t.alternate&&(s=this.astToGrapesJS(t.alternate)),`
15
15
  <data-condition data-gjs-data-resolver='${JSON.stringify({condition:e})}'>
16
- <data-condition-true-content>${r}</data-condition-true-content>
16
+ <data-condition-true-content>${n}</data-condition-true-content>
17
17
  <data-condition-false-content>${s}</data-condition-false-content>
18
18
  </data-condition>
19
- `}handleForStatement(t){var a;if(((a=t.init)==null?void 0:a.type)!=="VariableDeclaration"||t.init.declarations.length===0)return this.addMessage("warning","Unsupported for loop init format"),"";const e=t.init.declarations[0];if(e.id.type!=="Identifier")return this.addMessage("warning","Unsupported for loop variable declaration id"),"";let r="";if(e.init)r=this.getExpressionString(e.init);else return this.addMessage("warning","For loop collection is undefined"),"";r.startsWith("data.")||(r=`data.${r}`);const s=`collection-${Math.random().toString(36).substring(2,10)}`;this.collectionStack.push(s);const n=this.astToGrapesJS(t.body);return this.collectionStack.pop(),`
20
- <data-collection data-gjs-data-resolver='${JSON.stringify({dataSource:{type:"data-variable",path:r},collectionId:s})}'>
19
+ `}handleForStatement(t){var a;if(((a=t.init)==null?void 0:a.type)!=="VariableDeclaration"||t.init.declarations.length===0)return this.addMessage("warning","Unsupported for loop init format"),"";const e=t.init.declarations[0];if(e.id.type!=="Identifier")return this.addMessage("warning","Unsupported for loop variable declaration id"),"";let n="";if(e.init)n=this.getExpressionString(e.init);else return this.addMessage("warning","For loop collection is undefined"),"";const s=e.id.name,r=s;this.collectionStack.push(s);const i=this.astToGrapesJS(t.body);return this.collectionStack.pop(),`
20
+ <data-collection data-gjs-data-resolver='${JSON.stringify({dataSource:{type:"data-variable",path:n},collectionId:r})}'>
21
21
  <data-collection-item>
22
- ${n}
22
+ ${i}
23
23
  </data-collection-item>
24
24
  </data-collection>
25
- `}handleBlockStatement(t){let e="";for(const r of t.body)e+=this.astToGrapesJS(r);return e}handleLiteral(t){return String(t.value??"")}handleIdentifier(t){let e={path:t.name};if(this.collectionStack.length>0&&t.name==="item"){const r=this.collectionStack[this.collectionStack.length-1];e={path:t.name,collectionId:r,variableType:"currentItem"}}return`<data-variable data-gjs-data-resolver='${JSON.stringify(e)}'></data-variable>`}handleMemberExpression(t,e={}){let s={path:this.getExpressionString(t),...e};if(this.collectionStack.length>0){let n=t;const a=[];let o=!1;for(;n.type==="MemberExpression";)if(n.property.type==="Identifier"?a.unshift(n.property.name):n.property.type==="Literal"&&n.computed&&a.unshift(`[${n.property.value}]`),n=n.object,n.type==="Identifier"&&n.name==="item"){o=!0;break}if(o&&n.type==="Identifier"&&n.name==="item"){const l=this.collectionStack[this.collectionStack.length-1],p=a.join(".").replace(/\.\[/g,"[");s={...s,collectionId:l,variableType:"currentItem",path:p}}}return`<data-variable data-gjs-data-resolver='${JSON.stringify(s)}'></data-variable>`}handleBinaryExpression(t){return`${this.getExpressionString(t.left)} ${t.operator} ${this.getExpressionString(t.right)}`}handleLogicalExpression(t){return t.operator==="||"&&t.right.type==="Literal"?this.handleMemberExpression(t.left,{defaultValue:t.right.value}):`${this.getExpressionString(t.left)} ${t.operator} ${this.getExpressionString(t.right)}`}handleCallExpression(t){var e;if(t.callee.type==="Identifier"&&t.callee.name==="include"){const r=((e=t.arguments[0])==null?void 0:e.type)==="Literal"?String(t.arguments[0].value):"";return this.addMessage("info",`Partial includes are not fully supported: ${r}`),""}return""}getConditionExpression(t){if(t.type==="Identifier")return{logicalOperator:"and",statements:[{left:{type:"data-variable",path:t.name},operator:"isTruthy"}]};if(t.type==="MemberExpression"){let e=this.getExpressionString(t),r="isTruthy";return e.startsWith("!!")?(r="isTruthy",e=e.slice(2)):e.startsWith("!")&&(r="isFalsy",e=e.slice(1)),{logicalOperator:"and",statements:[{left:{type:"data-variable",path:e},operator:r}]}}if(t.type==="BinaryExpression"||t.type==="LogicalExpression"){const e=this.getConditionExpression(t.left),r=this.getConditionExpression(t.right);return`${e} ${t.operator} ${r}`}return t.type==="Literal"?typeof t.value=="string"?`'${t.value}'`:String(t.value??""):this.getExpressionString(t)}getExpressionString(t){switch(t.type){case"Identifier":return t.name;case"Literal":return String(t.value??"");case"MemberExpression":{const e=this.getExpressionString(t.object),r=this.getExpressionString(t.property);return t.computed?`${e}[${r}]`:`${e}.${r}`}case"BinaryExpression":{const e=this.getExpressionString(t.left),r=this.getExpressionString(t.right);return`${e} ${t.operator} ${r}`}case"LogicalExpression":{const e=this.getExpressionString(t.left),r=this.getExpressionString(t.right);return`${e} ${t.operator} ${r}`}default:return this.addMessage("warning",`Unsupported expression type for getExpressionString: ${t.type}`),""}}addMessage(t,e){this.messages.push({type:t,message:e})}}const q="dataSourceEjs",F=g.startup;return M(function(i,t={}){const e=A(i,new H),r=J(i,{contains:"<%",importer:new V});N({editor:i,licenseKey:t.licenseKey,plan:F,pluginName:q,cleanup:()=>{e(),r()}})})});
25
+ `}handleForEachStatement(t){const e=this.getExpressionString(t.collection),n=t.itemIdentifier.name,s=n;this.collectionStack.push(n);const r=this.astToGrapesJS(t.body);return this.collectionStack.pop(),`
26
+ <data-collection data-gjs-data-resolver='${JSON.stringify({dataSource:{type:"data-variable",path:e},collectionId:s})}'>
27
+ <data-collection-item>
28
+ ${r}
29
+ </data-collection-item>
30
+ </data-collection>
31
+ `}handleBlockStatement(t){let e="";for(const n of t.body)e+=this.astToGrapesJS(n);return e}handleLiteral(t){return String(t.value??"")}handleIdentifier(t){let e={path:t.name};if(this.collectionStack.length>0){const n=this.collectionStack[this.collectionStack.length-1];t.name===n&&(e={collectionId:n,variableType:"currentItem"})}return`<data-variable data-gjs-data-resolver='${JSON.stringify(e)}'></data-variable>`}handleMemberExpression(t,e={}){let s={path:this.getExpressionString(t),...e};if(this.collectionStack.length>0){const r=this.collectionStack[this.collectionStack.length-1];let i=t;const a=[];for(;i.type==="MemberExpression";)i.property.type==="Identifier"&&!i.computed?a.unshift(i.property.name):i.property.type==="Literal"&&i.computed?a.unshift(String(i.property.value)):a.unshift(this.getExpressionString(i.property)),i=i.object;if(i.type==="Identifier"&&i.name===r){const c=a.join(".");s={...e,collectionId:r,variableType:"currentItem",path:c}}}return`<data-variable data-gjs-data-resolver='${JSON.stringify(s)}'></data-variable>`}handleBinaryExpression(t){return`${this.getExpressionString(t.left)} ${t.operator} ${this.getExpressionString(t.right)}`}handleLogicalExpression(t){return t.operator==="||"&&t.right.type==="Literal"?this.handleMemberExpression(t.left,{defaultValue:t.right.value}):`${this.getExpressionString(t.left)} ${t.operator} ${this.getExpressionString(t.right)}`}handleCallExpression(t){var e;if(t.callee.type==="Identifier"&&t.callee.name==="include"){const n=((e=t.arguments[0])==null?void 0:e.type)==="Literal"?String(t.arguments[0].value):"";return this.addMessage("info",`Partial includes are not fully supported: ${n}`),""}return""}getConditionExpression(t){if(t.type==="Identifier")return{logicalOperator:"and",statements:[{left:{type:"data-variable",path:t.name},operator:"isTruthy"}]};if(t.type==="MemberExpression"){let e=this.getExpressionString(t),n="isTruthy";return e.startsWith("!!")?(n="isTruthy",e=e.slice(2)):e.startsWith("!")&&(n="isFalsy",e=e.slice(1)),{logicalOperator:"and",statements:[{left:{type:"data-variable",path:e},operator:n}]}}if(t.type==="BinaryExpression"||t.type==="LogicalExpression"){const e=this.getConditionExpression(t.left),n=this.getConditionExpression(t.right);return`${e} ${t.operator} ${n}`}return t.type==="Literal"?typeof t.value=="string"?`'${t.value}'`:String(t.value??""):this.getExpressionString(t)}getExpressionString(t){switch(t.type){case"Identifier":return t.name;case"Literal":return String(t.value??"");case"MemberExpression":{const e=this.getExpressionString(t.object),n=this.getExpressionString(t.property);return t.computed?`${e}[${n}]`:`${e}.${n}`}case"BinaryExpression":{const e=this.getExpressionString(t.left),n=this.getExpressionString(t.right);return`${e} ${t.operator} ${n}`}case"LogicalExpression":{const e=this.getExpressionString(t.left),n=this.getExpressionString(t.right);return`${e} ${t.operator} ${n}`}default:return this.addMessage("warning",`Unsupported expression type for getExpressionString: ${t.type}`),""}}addMessage(t,e){this.messages.push({type:t,message:e})}}const R="dataSourceEjs",K=y.startup;return M(function(o,t={}){const e=F(o,new U),n=H(o,{contains:"<%",importer:new G});B({editor:o,licenseKey:t.licenseKey,plan:K,pluginName:R,cleanup:()=>{e(),n()}})})});
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -1,14 +1,14 @@
1
1
  import { Operator } from '@studio/editor/src/components/DataConditionPicker/statementTypes';
2
2
  import { ConditionType, DataCollectionResolverProps, DataVariableResolverProps, IDataSourceExporter } from '@studio/editor/src/typeConfigs/dataSources';
3
3
  export declare class HandlebarsExporter implements IDataSourceExporter {
4
- getHelperId(operator: Operator, typeHint?: 'string' | 'number' | 'any'): string;
4
+ getHelperId(operator: Operator): string;
5
5
  getFullPath({ collectionId, path }: DataVariableResolverProps): string;
6
6
  getVariableSyntax(props: DataVariableResolverProps): string;
7
7
  getCollectionStartSyntax(options: DataCollectionResolverProps): string;
8
8
  getCollectionEndSyntax(): string;
9
9
  getConditionalStartSyntax(condition?: ConditionType): string;
10
10
  private _parseCondition;
11
- private _getTypeHint;
11
+ private getExpressionStr;
12
12
  private _parseValue;
13
13
  private _sanitizeVariableName;
14
14
  getConditionElseSyntax(): string;
@@ -7,6 +7,15 @@ export declare class HandlebarsImporter {
7
7
  private handleProgram;
8
8
  private handleContentStatement;
9
9
  private handleMustacheStatement;
10
+ private processPathWithCollectionContext;
11
+ private handleDirectCollectionReference;
12
+ private isSpecialIterationVariable;
13
+ private setSpecialVariableResolver;
14
+ private setCurrentItemResolver;
15
+ private handleRelativePathReference;
16
+ private calculateParentLevel;
17
+ private resolveRelativePath;
18
+ private handleParentReferenceFallback;
10
19
  private handleBlockStatement;
11
20
  private handleConditionalBlock;
12
21
  private handleEachBlock;
@@ -0,0 +1,16 @@
1
+ import { Operator } from '@studio/editor/src/components/DataConditionPicker/statementTypes';
2
+ export declare const ANYTYPE_OPERATION: {
3
+ equals: string;
4
+ isTruthy: string;
5
+ isFalsy: string;
6
+ isDefined: string;
7
+ isNull: string;
8
+ isUndefined: string;
9
+ isArray: string;
10
+ isObject: string;
11
+ isString: string;
12
+ isNumber: string;
13
+ isBoolean: string;
14
+ isDefaultValue: string;
15
+ };
16
+ export declare const OPERATORS_MAP: Record<Operator, string>;
@@ -1,20 +1,20 @@
1
- "use strict";const I=require("handlebars/dist/cjs/handlebars"),b="app.grapesjs.com",x="app-stage.grapesjs.com",y=[b,x,"localhost","127.0.0.1",".local-credentialless.webcontainer.io",".local.webcontainer.io","-sandpack.codesandbox.io"],P="license:check:start",T="license:check:end",k=()=>typeof window<"u",L=({isDev:r,isStage:t})=>`${r?"":`https://${t?x:b}`}/api`,w=()=>{const r=k()&&window.location.hostname;return!!r&&(y.includes(r)||y.some(t=>r.endsWith(t)))};async function N({path:r,baseApiUrl:t,method:n="GET",headers:e={},params:a,body:s}){const o=`${t||L({isDev:!1,isStage:!1})}${r}`,u={method:n,headers:{"Content-Type":"application/json",...e}};s&&(u.body=JSON.stringify(s));const l=a?new URLSearchParams(a).toString():"",c=l?`?${l}`:"",h=await fetch(`${o}${c}`,u);if(!h.ok)throw new Error(`HTTP error! status: ${h.status}`);return h.json()}var p=(r=>(r.free="free",r.startup="startup",r.business="business",r.enterprise="enterprise",r))(p||{});const $={[p.free]:0,[p.startup]:10,[p.business]:20,[p.enterprise]:30};function H(r){const t=r;return t.init=n=>e=>r(e,n),t}const M=r=>H(r);async function _({editor:r,plan:t,pluginName:n,licenseKey:e,cleanup:a}){let s="",i=!1;const o=w(),u=c=>{console.warn("Cleanup plugin:",n,"Reason:",c),a()},l=(c={})=>{var S;const{error:h,sdkLicense:C}=c,m=(S=c.plan)==null?void 0:S.category;if(!(C||c.license)||h)u(h||"Invalid license");else if(m){const E=$[t],v=$[m];E>v&&u({pluginRequiredPlan:t,licensePlan:m})}};r.on(P,c=>{s=c==null?void 0:c.baseApiUrl,i=!0}),r.on(T,c=>{l(c)}),setTimeout(async()=>{if(!i){if(o)return;if(e){const c=await j({licenseKey:e,pluginName:n,baseApiUrl:s});c&&l(c)}else u("The `licenseKey` option not provided")}},2e3)}async function j(r){const{licenseKey:t,pluginName:n,baseApiUrl:e}=r;try{return(await N({baseApiUrl:e,path:`/sdk/${t||"na"}`,method:"POST",params:{d:window.location.hostname,pn:n}})).result||{}}catch(a){return console.error("Error during SDK license check:",a),!1}}var d=(r=>(r.variable="data-variable",r.condition="data-condition",r.conditionTrue="data-condition-true-content",r.conditionFalse="data-condition-false-content",r.collection="data-collection",r.collectionItem="data-collection-item",r))(d||{});class B{constructor(t){this.strategy=t,this.requiredHelpers=new Set,this.helperLibrary={}}registerHelper(t){this.helperLibrary[t]&&this.requiredHelpers.add(t)}generateVariable(t){return this.strategy.getVariableSyntax(t)}generateCollectionStart(t){return this.registerHelper("slice"),this.strategy.getCollectionStartSyntax(t)}generateCollectionEnd(){return this.strategy.getCollectionEndSyntax()}generateConditionalStart(t){return this.strategy.getConditionalStartSyntax(t)}generateConditionElse(){return this.strategy.getConditionElseSyntax()}generateConditionalEnd(){return this.strategy.getConditionalEndSyntax()}reset(){this.requiredHelpers.clear()}}function O(r){return typeof r=="object"&&r.type===d.variable}function g({component:r,value:t,getCustomPath:n}){if(O(t)&&!t.collectionId&&n){const e=t.path??"",a=e.split(".");return{...t,path:n({component:r,path:e,paths:a})}}return t}const D=r=>{f(r,d.variable,{toHTML(t){var i;const n=this.tagName,e=this.__attrToString(t),a=(i=this.getDataResolver)==null?void 0:i.call(this),s=g({component:this,value:a,getCustomPath:t==null?void 0:t.getCustomPath});return`<${n}${e?` ${e}`:""}>${t.exporter.generateVariable(s)}</${n}>`}}),f(r,d.condition,{toHTML(t){var l,c;const n=t.exporter,e=t==null?void 0:t.getCustomPath,a=this.components(),[s,i]=(a==null?void 0:a.models)??[],o=(l=this.getDataResolver)==null?void 0:l.call(this),u=((c=this.resolveCondition)==null?void 0:c.call(this,o==null?void 0:o.condition,e))??{};return`
2
- ${n.generateConditionalStart(u)}
3
- ${(s==null?void 0:s.toHTML(t))??""}
4
- ${n.generateConditionElse()}
5
- ${(i==null?void 0:i.toHTML(t))??""}
6
- ${n.generateConditionalEnd()}
7
- `},resolveCondition(t,n){var a,s;if(!t)return{};if(t.operator==="and"||t.operator==="or")return{operator:t.operator,statements:((s=(a=t.statements)==null?void 0:a.map)==null?void 0:s.call(a,i=>{var o;return((o=this.resolveCondition)==null?void 0:o.call(this,i,n))??{}}))??[]};const e={component:this,getCustomPath:n};return{...t,left:g({...e,value:t.left}),right:g({...e,value:t.right})}}}),f(r,d.collection,{toHTML(t){const n=t.exporter,e=this.tagName,a=this.__attrToString(t),s=this.getDataResolver(),i={...s,dataSource:g({component:this,value:s==null?void 0:s.dataSource,getCustomPath:t==null?void 0:t.getCustomPath})},o=this.components().at(0);return`
8
- <${e}${a?` ${a}`:""}>${n.generateCollectionStart(i)}
1
+ "use strict";const L=require("handlebars/dist/cjs/handlebars"),C="app.grapesjs.com",b="app-stage.grapesjs.com",y=[C,b,"localhost","127.0.0.1",".local-credentialless.webcontainer.io",".local.webcontainer.io","-sandpack.codesandbox.io"],k="license:check:start",T="license:check:end",N=()=>typeof window<"u",_=({isDev:r,isStage:t})=>`${r?"":`https://${t?b:C}`}/api`,w=()=>{const r=N()&&window.location.hostname;return!!r&&(y.includes(r)||y.some(t=>r.endsWith(t)))};async function H({path:r,baseApiUrl:t,method:e="GET",headers:n={},params:a,body:s}){const o=`${t||_({isDev:!1,isStage:!1})}${r}`,c={method:e,headers:{"Content-Type":"application/json",...n}};s&&(c.body=JSON.stringify(s));const h=a?new URLSearchParams(a).toString():"",l=h?`?${h}`:"",u=await fetch(`${o}${l}`,c);if(!u.ok)throw new Error(`HTTP error! status: ${u.status}`);return u.json()}var d=(r=>(r.free="free",r.startup="startup",r.business="business",r.enterprise="enterprise",r))(d||{});const P={[d.free]:0,[d.startup]:10,[d.business]:20,[d.enterprise]:30};function M(r){const t=r;return t.init=e=>n=>r(n,e),t}const O=r=>M(r);async function R({editor:r,plan:t,pluginName:e,licenseKey:n,cleanup:a}){let s="",i=!1;const o=w(),c=l=>{console.warn("Cleanup plugin:",e,"Reason:",l),a()},h=(l={})=>{var $;const{error:u,sdkLicense:E}=l,m=($=l.plan)==null?void 0:$.category;if(!(E||l.license)||u)c(u||"Invalid license");else if(m){const v=P[t],I=P[m];v>I&&c({pluginRequiredPlan:t,licensePlan:m})}};r.on(k,l=>{s=l==null?void 0:l.baseApiUrl,i=!0}),r.on(T,l=>{h(l)}),setTimeout(async()=>{if(!i){if(o)return;if(n){const l=await A({licenseKey:n,pluginName:e,baseApiUrl:s});l&&h(l)}else c("The `licenseKey` option not provided")}},2e3)}async function A(r){const{licenseKey:t,pluginName:e,baseApiUrl:n}=r;try{return(await H({baseApiUrl:n,path:`/sdk/${t||"na"}`,method:"POST",params:{d:window.location.hostname,pn:e}})).result||{}}catch(a){return console.error("Error during SDK license check:",a),!1}}var p=(r=>(r.variable="data-variable",r.condition="data-condition",r.conditionTrue="data-condition-true-content",r.conditionFalse="data-condition-false-content",r.collection="data-collection",r.collectionItem="data-collection-item",r))(p||{});class D{constructor(t){this.strategy=t,this.requiredHelpers=new Set,this.helperLibrary={}}registerHelper(t){this.helperLibrary[t]&&this.requiredHelpers.add(t)}generateVariable(t){return this.strategy.getVariableSyntax(t)}generateCollectionStart(t){return this.registerHelper("slice"),this.strategy.getCollectionStartSyntax(t)}generateCollectionEnd(){return this.strategy.getCollectionEndSyntax()}generateConditionalStart(t){return this.strategy.getConditionalStartSyntax(t)}generateConditionElse(){return this.strategy.getConditionElseSyntax()}generateConditionalEnd(){return this.strategy.getConditionalEndSyntax()}reset(){this.requiredHelpers.clear()}}function j(r){return typeof r=="object"&&r.type===p.variable}function g({component:r,value:t,getCustomPath:e}){if(j(t)&&!t.collectionId&&e){const n=t.path??"",a=n.split(".");return{...t,path:e({component:r,path:n,paths:a})}}return t}const V=r=>{f(r,p.variable,{toHTML(t){var i;const e=this.tagName,n=this.__attrToString(t),a=(i=this.getDataResolver)==null?void 0:i.call(this),s=g({component:this,value:a,getCustomPath:t==null?void 0:t.getCustomPath});return`<${e}${n?` ${n}`:""}>${t.exporter.generateVariable(s)}</${e}>`}}),f(r,p.condition,{toHTML(t){var l,u;const e=t.exporter,n=t==null?void 0:t.getCustomPath,a=this.components(),[s,i]=(a==null?void 0:a.models)??[],o=(l=this.getDataResolver)==null?void 0:l.call(this),c=((u=this.resolveCondition)==null?void 0:u.call(this,o==null?void 0:o.condition,n))??{};let h="";return i&&(h=`
2
+ ${e.generateConditionElse()}
3
+ ${i.toHTML(t)??""}`),`
4
+ ${e.generateConditionalStart(c)}
5
+ ${(s==null?void 0:s.toHTML(t))??""}${h}
6
+ ${e.generateConditionalEnd()}
7
+ `},resolveCondition(t,e){var a,s;if(!t)return{};if(t.operator==="and"||t.operator==="or")return{operator:t.operator,statements:((s=(a=t.statements)==null?void 0:a.map)==null?void 0:s.call(a,i=>{var o;return((o=this.resolveCondition)==null?void 0:o.call(this,i,e))??{}}))??[]};const n={component:this,getCustomPath:e};return{...t,left:g({...n,value:t.left}),right:g({...n,value:t.right})}}}),f(r,p.collection,{toHTML(t){const e=t.exporter,n=this.tagName,a=this.__attrToString(t),s=this.getDataResolver(),i={...s,dataSource:g({component:this,value:s==null?void 0:s.dataSource,getCustomPath:t==null?void 0:t.getCustomPath})},o=this.components().at(0);return`
8
+ <${n}${a?` ${a}`:""}>${e.generateCollectionStart(i)}
9
9
  ${(o==null?void 0:o.toHTML(t))??""}
10
- ${n.generateCollectionEnd()}</${e}>
11
- `}})},f=(r,t,n)=>{const e=r.Components.getType(t);if(!e){console.warn(`Component type ${t} not found`);return}const{model:a}=e;r.Components.addType(t,{model:{...n,toHTML(s={}){var o;const{exporter:i}=s;return i?i.export?i.export({component:this}):((o=n.toHTML)==null?void 0:o.call(this,s))??"":a.prototype.toHTML.call(this,s)??""}}})},V=(r,t)=>(r.config.optsHtml={...r.config.optsHtml,exporter:new B(t)},D(r),()=>{r.config.optsHtml.exporter=void 0}),q=(r,t)=>{const n=a=>{const{input:s}=a,{contains:i}=t;(!i||s.includes(i))&&(a.input=t.importer.import(s))},e=r.Parser.events.htmlBefore;return r.on(e,n),()=>{r.off(e,n)}};class U{getHelperId(t,n){return{equals:`${n==="string"?"str":n==="number"?"num":"any"}Equals`,isTruthy:"isTruthy",isFalsy:"isFalsy",isDefined:"isDefined",isNull:"isNull",isUndefined:"isUndefined",isArray:"isArray",isObject:"isObject",isString:"isString",isNumber:"isNumber",isBoolean:"isBoolean",isDefaultValue:"isDefaultValue",">":"numGt","<":"numLt",">=":"numGte","<=":"numLte","=":"numEq","!=":"numNeq",contains:"strContains",startsWith:"strStartsWith",endsWith:"strEndsWith",equalsIgnoreCase:"strEqualsIgnoreCase",trimEquals:"strTrimEquals"}[t]||t}getFullPath({collectionId:t,path:n}){let e=n;return t&&(e=[this._sanitizeVariableName(t),n].filter(Boolean).join(".")),e||""}getVariableSyntax(t){const{defaultValue:n}=t,e=this.getFullPath(t);return n?`{{#if ${e}}}{{{${e}}}}{{else}}${n}{{/if}}`:`{{{${e}}}}`}getCollectionStartSyntax(t){const{collectionId:n,dataSource:e}=t,a=e==null?void 0:e.path;let s="";if(t.startIndex!==void 0||t.endIndex!==void 0){const l=t.startIndex??0,c=t.endIndex!==void 0?t.endIndex:"";c!==""?s=` (slice ${a} ${l} ${c})`:s=` (slice ${a} ${l})`}const o=` as |${this._sanitizeVariableName(n)}|`;return`{{#each ${s||a}${o}}}`}getCollectionEndSyntax(){return"{{/each}}"}getConditionalStartSyntax(t){if(!t)return"";const n=t,e=t;if(e.statements&&e.logicalOperator==="and"||e.logicalOperator==="or"){const{statements:a}=e,s=e.logicalOperator,i=a.map(u=>this._parseCondition(u)).join(", ");return`{{#if ${a.length>1?`(${s} ${i})`:i}}}`}else return`{{#if ${this._parseCondition(n)}}}`}_parseCondition(t){if(!t)return"";const n=t,e=t;if(e.statements&&e.logicalOperator==="and"||e.logicalOperator==="or"){const{statements:a}=e,s=e.logicalOperator,i=e.statements.map(o=>this._parseCondition(o)).join(" ");return a.length>1?`(${s} ${i})`:i}else{const a=this.getHelperId(n.operator,this._getTypeHint(t)),s=this._parseValue(n.left),i=this._parseValue(n.right);return`(${a} ${s} ${i})`}}_getTypeHint(t){return["contains","startsWith","endsWith","equalsIgnoreCase","trimEquals"].includes(t.operator)?"string":[">","<",">=","<=","=","!="].includes(t.operator)?"number":"any"}_parseValue(t){return typeof t=="object"?this.getFullPath(t):typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:String(t)}_sanitizeVariableName(t){return t.replace(/[^a-zA-Z0-9_$]/g,"_")}getConditionElseSyntax(){return"{{else}}"}getConditionalEndSyntax(){return"{{/if}}"}}class W{constructor(){this.messages=[],this.collectionStack=[]}import(t){this.messages=[],this.collectionStack=[];const n=this.parse(t);return this.astToGrapesJS(n)}parse(t){try{return I.parse(t)}catch(n){if(n instanceof Error&&n.message.includes("Parse error")){const e=n.message.match(/line (\d+)/),a=e?parseInt(e[1]):0,s=n.message.match(/column (\d+)/),i=s?parseInt(s[1]):0;throw new Error(`Handlebars syntax error at line ${a}, column ${i}: ${n.message}`)}throw n}}astToGrapesJS(t){switch(t.type){case"Program":return this.handleProgram(t);case"ContentStatement":return this.handleContentStatement(t);case"MustacheStatement":return this.handleMustacheStatement(t);case"BlockStatement":return this.handleBlockStatement(t);case"PartialStatement":return this.handlePartialStatement(t);case"CommentStatement":return this.handleCommentStatement(t);case"ElementNode":return this.handleElementNode(t);case"TextNode":return this.handleTextNode(t);default:return this.addMessage("warning",`Unsupported node type: ${t.type}`,t.loc),""}}handleProgram(t){let n="";if(t.body)for(const e of t.body)n+=this.astToGrapesJS(e);return n}handleContentStatement(t){return t.value||""}handleMustacheStatement(t,n={}){const e=this.getExpressionString(t.path),a=n;if(this.collectionStack.length>0)if(e.startsWith("@")){const s=e.split("/");let i=0;const o=s[s.length-1];for(let l=0;l<s.length-1;l++)s[l]===".."&&i++;const u=Math.max(0,this.collectionStack.length-1-i);if(u>=0&&u<this.collectionStack.length){const l=this.collectionStack[u];o==="index"||o==="@index"?(a.collectionId=l,a.variableType="currentIndex"):o==="key"||o==="@key"?(a.collectionId=l,a.variableType="currentKey"):o==="first"||o==="@first"?(a.collectionId=l,a.variableType="isFirst"):o==="last"||o==="@last"?(a.collectionId=l,a.variableType="isLast"):a.path=e}else a.path=e}else{const s=e.split("/");let i=0;for(;s[0]==="..";)i++,s.shift();const o=s.join("/"),u=this.collectionStack.length-1-i;if(u>=0&&u<this.collectionStack.length){const l=this.collectionStack[u];o==="this"?(a.collectionId=l,a.variableType="currentItem"):(a.collectionId=l,a.variableType="currentItem",a.path=o.startsWith("this.")?o.split(".").slice(1).join("."):o)}else a.path=`globalData.${s.join(".")}`}else a.path=e;return`<data-variable data-gjs-data-resolver='${JSON.stringify(a)}'></data-variable>`}handleBlockStatement(t){const n=t.path.original;switch(n){case"if":case"unless":return this.handleConditionalBlock(t,n);case"each":return this.handleEachBlock(t);default:return this.addMessage("warning",`Unsupported block helper: ${n}`,t.loc),this.handleGenericBlock(t)}}handleConditionalBlock(t,n){const s={logicalOperator:"and",statements:[{left:{type:"data-variable",path:this.getExpressionString(t.params[0])},operator:n==="unless"?"isFalsy":"isTruthy"}]},i=this.handleProgram(t.program),o=t.inverse?this.handleProgram(t.inverse):"";return t.params[0].type==="PathExpression"?this.handleMustacheStatement(t.program.body[0],{defaultValue:o}):`
10
+ ${e.generateCollectionEnd()}</${n}>
11
+ `}})},f=(r,t,e)=>{const n=r.Components.getType(t);if(!n){console.warn(`Component type ${t} not found`);return}const{model:a}=n;r.Components.addType(t,{model:{...e,toHTML(s={}){var o;const{exporter:i}=s;return i?i.export?i.export({component:this}):((o=e.toHTML)==null?void 0:o.call(this,s))??"":a.prototype.toHTML.call(this,s)??""}}})},B=(r,t)=>(r.config.optsHtml={...r.config.optsHtml,exporter:new D(t)},V(r),()=>{r.config.optsHtml.exporter=void 0}),U=(r,t)=>{const e=a=>{const{input:s}=a,{contains:i}=t;(!i||s.includes(i))&&(a.input=t.importer.import(s))},n=r.Parser.events.htmlBefore;return r.on(n,e),()=>{r.off(n,e)}},x={equals:"equals",isTruthy:"isTruthy",isFalsy:"isFalsy",isDefined:"isDefined",isNull:"isNull",isUndefined:"isUndefined",isArray:"isArray",isObject:"isObject",isString:"isString",isNumber:"isNumber",isBoolean:"isBoolean",isDefaultValue:"isDefaultValue"},W={">":"numGt","<":"numLt",">=":"numGte","<=":"numLte","=":"numEq","!=":"numNeq"},q={contains:"strContains",startsWith:"strStartsWith",endsWith:"strEndsWith",equalsIgnoreCase:"strEqualsIgnoreCase",trimEquals:"strTrimEquals"},G={...x,...W,...q};class F{getHelperId(t){return G[t]||t}getFullPath({collectionId:t,path:e}){let n=e;return t&&(n=[this._sanitizeVariableName(t),e].filter(Boolean).join(".")),n||""}getVariableSyntax(t){const{defaultValue:e}=t,n=this.getFullPath(t);return e?`{{#if ${n}}}{{{${n}}}}{{else}}${e}{{/if}}`:`{{{${n}}}}`}getCollectionStartSyntax(t){const{collectionId:e,dataSource:n}=t,a=n==null?void 0:n.path;let s="";if(t.startIndex!==void 0||t.endIndex!==void 0){const h=t.startIndex??0,l=t.endIndex!==void 0?t.endIndex:"";l!==""?s=` (slice ${a} ${h} ${l})`:s=` (slice ${a} ${h})`}const o=` as |${this._sanitizeVariableName(e)}|`;return`{{#each ${s||a}${o}}}`}getCollectionEndSyntax(){return"{{/each}}"}getConditionalStartSyntax(t){if(!t)return"";const e=t,n=t;if(n.statements&&n.logicalOperator==="and"||n.logicalOperator==="or"){const{statements:a}=n,s=n.logicalOperator,i=a.map(c=>this._parseCondition(c)).join(" ");return`{{#if ${a.length>1?`(${s} ${i})`:i}}}`}else return`{{#if ${this._parseCondition(e)}}}`}_parseCondition(t){if(!t)return"";const e=t,n=t;if(n.statements&&n.logicalOperator==="and"||n.logicalOperator==="or"){const{statements:a}=n,s=n.logicalOperator,i=n.statements.map(o=>this._parseCondition(o)).join(" ");return a.length>1?`(${s} ${i})`:i}else{const a=e.operator,s=this.getHelperId(a),i=this._parseValue(e.left),o=this._parseValue(e.right);return this.getExpressionStr(s,i,o)}}getExpressionStr(t,e,n){return x[t]?t==="isTruthy"?e:t==="isFalsy"?`!${e}`:`${t} ${e}`:`(${t} ${e} ${n})`}_parseValue(t){return typeof t=="object"?this.getFullPath(t):typeof t=="string"?`'${t.replace(/'/g,"\\'")}'`:String(t)}_sanitizeVariableName(t){return t.replace(/[^a-zA-Z0-9_$]/g,"_")}getConditionElseSyntax(){return"{{else}}"}getConditionalEndSyntax(){return"{{/if}}"}}class J{constructor(){this.messages=[],this.collectionStack=[]}import(t){this.messages=[],this.collectionStack=[];const e=this.parse(t);return this.astToGrapesJS(e)}parse(t){try{return L.parse(t)}catch(e){if(e instanceof Error&&e.message.includes("Parse error")){const n=e.message.match(/line (\d+)/),a=n?parseInt(n[1]):0,s=e.message.match(/column (\d+)/),i=s?parseInt(s[1]):0;throw new Error(`Handlebars syntax error at line ${a}, column ${i}: ${e.message}`)}throw e}}astToGrapesJS(t){switch(t.type){case"Program":return this.handleProgram(t);case"ContentStatement":return this.handleContentStatement(t);case"MustacheStatement":return this.handleMustacheStatement(t);case"BlockStatement":return this.handleBlockStatement(t);case"PartialStatement":return this.handlePartialStatement(t);case"CommentStatement":return this.handleCommentStatement(t);case"ElementNode":return this.handleElementNode(t);case"TextNode":return this.handleTextNode(t);default:return this.addMessage("warning",`Unsupported node type: ${t.type}`,t.loc),""}}handleProgram(t){let e="";if(t.body)for(const n of t.body)e+=this.astToGrapesJS(n);return e}handleContentStatement(t){return t.value||""}handleMustacheStatement(t,e={}){const n=this.getExpressionString(t.path),a={...e};return this.collectionStack.length>0?this.processPathWithCollectionContext(n,a):a.path=n,`<data-variable data-gjs-data-resolver='${JSON.stringify(a)}'></data-variable>`}processPathWithCollectionContext(t,e){t.startsWith("@")?this.handleDirectCollectionReference(t,e):this.handleRelativePathReference(t,e)}handleDirectCollectionReference(t,e){if(this.isSpecialIterationVariable(t)){this.setSpecialVariableResolver(this.collectionStack[this.collectionStack.length-1],t,e);return}const[n,...a]=t.substring(1).split("/"),s=a.join(".");this.collectionStack.includes(n)?this.setCurrentItemResolver(n,s,e):this.handleParentReferenceFallback(t,e)}isSpecialIterationVariable(t){return["index","@index","key","@key"].includes(t)}setSpecialVariableResolver(t,e,n){n.collectionId=t;const a={index:"currentIndex","@index":"currentIndex",key:"currentKey","@key":"currentKey"};n.variableType=a[e]}setCurrentItemResolver(t,e,n){n.collectionId=t,n.variableType="currentItem",e&&(n.path=e)}handleRelativePathReference(t,e){const n=S(t),{parentLevel:a,remainingPathParts:s}=this.calculateParentLevel(n),i=s.join("."),o=this.collectionStack.length-1-a;o>=0&&o<this.collectionStack.length?this.resolveRelativePath(i,o,e):e.path=s.join(".")}calculateParentLevel(t){const e=this.collectionStack.findLastIndex(s=>s===t[0]);if(e!==-1)return{parentLevel:this.collectionStack.length-1-e,remainingPathParts:t.slice(1)};let n=0;const a=[...t];for(;a[0]==="..";)n++,a.shift();return{parentLevel:n,remainingPathParts:a}}resolveRelativePath(t,e,n){const a=this.collectionStack[e];n.collectionId=a,n.variableType="currentItem",t!=="this"&&(n.path=t.startsWith("this.")?t.split(".").slice(1).join("."):t)}handleParentReferenceFallback(t,e){const n=S(t),{parentLevel:a,remainingPathParts:s}=this.calculateParentLevel(n),i=s.join("."),o=this.collectionStack.length-1-a;o>=0&&o<this.collectionStack.length?this.resolveRelativePath(i,o,e):e.path=s.join(".")}handleBlockStatement(t){const e=t.path.original;switch(e){case"if":case"unless":return this.handleConditionalBlock(t,e);case"each":return this.handleEachBlock(t);default:return this.addMessage("warning",`Unsupported block helper: ${e}`,t.loc),this.handleGenericBlock(t)}}handleConditionalBlock(t,e){const s={logicalOperator:"and",statements:[{left:{type:"data-variable",path:this.getExpressionString(t.params[0])},operator:e==="unless"?"isFalsy":"isTruthy"}]},i=this.handleProgram(t.program),o=t.inverse?this.handleProgram(t.inverse):"";return`
12
12
  <data-condition data-gjs-data-resolver='${JSON.stringify({condition:s})}'>
13
13
  <data-condition-true-content>${i}</data-condition-true-content>
14
14
  <data-condition-false-content>${o}</data-condition-false-content>
15
15
  </data-condition>
16
- `}handleEachBlock(t){const n=this.getExpressionString(t.params[0]),e=`collection-${Math.random().toString(36).substring(2,10)}`;this.collectionStack.push(e);const a=this.handleProgram(t.program);return this.collectionStack.pop(),`
17
- <data-collection data-gjs-data-resolver='${JSON.stringify({dataSource:{type:"data-variable",path:n},collectionId:e})}'>
16
+ `}handleEachBlock(t){var s,i,o;const e=this.getExpressionString(t.params[0]);let n;t.params.length>=3&&t.params[1]==="as"&&((s=t.params[2])==null?void 0:s.type)==="PathExpression"?n=t.params[2].original:(o=(i=t.program)==null?void 0:i.blockParams)!=null&&o.length?n=t.program.blockParams[0]:n=`collection-${Math.random().toString(36).substring(2,10)}`,this.collectionStack.push(n);const a=this.handleProgram(t.program);return this.collectionStack.pop(),`
17
+ <data-collection data-gjs-data-resolver='${JSON.stringify({dataSource:{type:"data-variable",path:e},collectionId:n})}'>
18
18
  <data-collection-item>${a}</data-collection-item>
19
19
  </data-collection>
20
- `}handleCommentStatement(t){return`<!--${t.value}-->`}handleElementNode(t){let n="";if(t.attributes)for(const a of t.attributes)a.value.type==="TextNode"?n+=` ${a.name}="${a.value.chars}"`:(this.addMessage("warning",`Complex attribute values not fully supported: ${a.name}`,t.loc),n+=` ${a.name}="${this.getExpressionString(a.value)}"`);let e="";if(t.children)for(const a of t.children)e+=this.astToGrapesJS(a);return`<${t.tag}${n}>${e}</${t.tag}>`}handleTextNode(t){return t.chars||""}handlePartialStatement(t){return this.addMessage("warning",`Partials are not fully supported: ${t.name.original}`,t.loc),`{{> ${t.name.original}}}`}handleGenericBlock(t){const n=this.handleProgram(t.program);return`<!-- Unsupported block: ${t.path.original} -->${n}`}getExpressionString(t){return t.type==="PathExpression"?t.original:t.type==="StringLiteral"?t.value:t.type==="NumberLiteral"?t.value.toString():t.type==="BooleanLiteral"?t.value?"true":"false":t.type==="SubExpression"?this.getExpressionString(t.params[0]):t.type==="Hash"?`{${t.pairs.map(e=>`${e.key}=${this.getExpressionString(e.value)}`).join(", ")}}`:(this.addMessage("warning",`Complex expression type not fully supported: ${t.type}`,t.loc),"")}addMessage(t,n,e){this.messages.push({type:t,message:n,location:e?{line:e.start.line,column:e.start.column}:void 0})}}const A="dataSourceHandlebars",G=p.startup,R=function(r,t={}){const n=V(r,new U),e=q(r,{contains:"{{",importer:new W});_({editor:r,licenseKey:t.licenseKey,plan:G,pluginName:A,cleanup:()=>{n(),e()}})},F=M(R);module.exports=F;
20
+ `}handleCommentStatement(t){return`<!--${t.value}-->`}handleElementNode(t){let e="";if(t.attributes)for(const a of t.attributes)a.value.type==="TextNode"?e+=` ${a.name}="${a.value.chars}"`:(this.addMessage("warning",`Complex attribute values not fully supported: ${a.name}`,t.loc),e+=` ${a.name}="${this.getExpressionString(a.value)}"`);let n="";if(t.children)for(const a of t.children)n+=this.astToGrapesJS(a);return`<${t.tag}${e}>${n}</${t.tag}>`}handleTextNode(t){return t.chars||""}handlePartialStatement(t){return this.addMessage("warning",`Partials are not fully supported: ${t.name.original}`,t.loc),`{{> ${t.name.original}}}`}handleGenericBlock(t){const e=this.handleProgram(t.program);return`<!-- Unsupported block: ${t.path.original} -->${e}`}getExpressionString(t){return t.type==="PathExpression"?t.original:t.type==="StringLiteral"?t.value:t.type==="NumberLiteral"?t.value.toString():t.type==="BooleanLiteral"?t.value?"true":"false":t.type==="SubExpression"?this.getExpressionString(t.params[0]):t.type==="Hash"?`{${t.pairs.map(n=>`${n.key}=${this.getExpressionString(n.value)}`).join(", ")}}`:(this.addMessage("warning",`Complex expression type not fully supported: ${t.type}`,t.loc),"")}addMessage(t,e,n){this.messages.push({type:t,message:e,location:n?{line:n.start.line,column:n.start.column}:void 0})}}const S=r=>{if(r==null||r==="")return[];if(r===".")return["this"];if(r===".."||r==="../")return[".."];if(r.startsWith("../")){const i=r.substring(3);return["..",...S(i)]}const t=[];let e=0,n=r.replace(/\[(?:(['"])(.*?)\1|([^\]]*))\]/g,(i,o,c,h)=>{const l=c!==void 0?c:h||"";return t[e]=l,`__HANDLEBARS_PLACEHOLDER_${e++}__`});n=n.replace(/\//g,".");const a=n.split("."),s=[];for(const i of a){const o=/^__HANDLEBARS_PLACEHOLDER_(\d+)__$/.exec(i);if(o){const c=parseInt(o[1],10);s.push(t[c])}else i!==""&&s.push(i)}return s},K="dataSourceHandlebars",z=d.startup,Y=function(r,t={}){const e=B(r,new F),n=U(r,{contains:"{{",importer:new J});R({editor:r,licenseKey:t.licenseKey,plan:z,pluginName:K,cleanup:()=>{e(),n()}})},Z=O(Y);module.exports=Z;