UNPKG

@silexlabs/grapesjs-data-source

Version:
16 lines 208 kB
/*! @silexlabs/grapesjs-data-source - 0.3.0 */ !function(e,t){'object'==typeof exports&&'object'==typeof module?module.exports=t():'function'==typeof define&&define.amd?define([],t):'object'==typeof exports?exports["@silexlabs/grapesjs-data-source"]=t():e["@silexlabs/grapesjs-data-source"]=t()}('undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:this,(()=>(()=>{var e={365:e=>{e.exports=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];var o=[],r='string'==typeof e?[e]:e.slice();r[r.length-1]=r[r.length-1].replace(/\r?\n([\t ]*)$/,'');for(var i=0;i<r.length;i++){var s;(s=r[i].match(/\n[\t ]+/g))&&o.push.apply(o,s)}if(o.length){var a=Math.min.apply(Math,o.map((function(e){return e.length-1}))),l=new RegExp("\n[\t ]{"+a+"}",'g');for(i=0;i<r.length;i++)r[i]=r[i].replace(l,'\n')}r[0]=r[0].replace(/^\r?\n/,'');var d=r[0];for(i=0;i<t.length;i++)d+=t[i]+r[i+1];return d}}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.n=e=>{var t=e&&e.__esModule?()=>e['default']:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{'undefined'!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:'Module'}),Object.defineProperty(e,'__esModule',{value:!0})};var o={};return(()=>{"use strict";n.r(o),n.d(o,{BinaryOperator:()=>E,COMMAND_ADD_DATA_SOURCE:()=>x,COMMAND_PREVIEW_ACTIVATE:()=>y,COMMAND_PREVIEW_DEACTIVATE:()=>m,COMMAND_PREVIEW_REFRESH:()=>v,COMMAND_PREVIEW_TOGGLE:()=>b,COMMAND_REFRESH:()=>g,COMPONENT_NAME_PREFIX:()=>ao,COMPONENT_STATE_CHANGED:()=>s,DATA_SOURCE_CHANGED:()=>i,DATA_SOURCE_DATA_LOAD_CANCEL:()=>d,DATA_SOURCE_DATA_LOAD_END:()=>l,DATA_SOURCE_DATA_LOAD_START:()=>a,DATA_SOURCE_ERROR:()=>r,DATA_SOURCE_READY:()=>t,FIXED_TOKEN_ID:()=>e,NOTIFICATION_GROUP:()=>so,PREVIEW_ACTIVATED:()=>h,PREVIEW_DEACTIVATED:()=>f,PREVIEW_RENDER_END:()=>c,PREVIEW_RENDER_ERROR:()=>u,PREVIEW_RENDER_START:()=>p,Properties:()=>k,UnariOperator:()=>$,addDataSource:()=>Pn,addFilters:()=>Wn,buildPageQueries:()=>Nn,builtinTypeIds:()=>w,builtinTypes:()=>_,clearPreviewData:()=>Bn,createDataSource:()=>io,default:()=>kr,fromStored:()=>Gn,getAllDataSources:()=>Rn,getCompletion:()=>Vn,getDataSource:()=>Ln,getExpressionResultType:()=>Jn,getOrCreatePersistantId:()=>Zn,getPageExpressions:()=>Qn,getPageQuery:()=>jn,getPersistantId:()=>Yn,getPreviewData:()=>zn,getState:()=>Xn,getStateIds:()=>eo,getStateVariableName:()=>oo,getValue:()=>Hn,loadPreviewData:()=>Dn,refreshDataSources:()=>Un,removeDataSource:()=>Mn,removeFilters:()=>Kn,removeState:()=>no,setPreviewData:()=>qn,setPreviewIndex:()=>Fn,setState:()=>to,toExpression:()=>ro,version:()=>Sr});const e='fixed',t='data-source:ready',r='data-source:error',i='data-source:changed',s='component:state:changed',a='data-source:data-load:start',l='data-source:data-load:end',d='data-source:data-load:cancel',p='data-source:start:preview',c='data-source:start:end',u='data-source:start:error',h='data-source:preview:activated',f='data-source:preview:deactivated',g='data-source:refresh',y='data-source:preview:activate',m='data-source:preview:deactivate',v='data-source:preview:refresh',b='data-source:preview:toggle',x='data-source:add',w=['String','Int','Float','Boolean','ID','Unknown'],_=w.map((e=>({id:e,label:e,fields:[]})));var $,E,k;!function(e){e["TRUTHY"]="truthy",e["FALSY"]="falsy",e["EMPTY_ARR"]="empty array",e["NOT_EMPTY_ARR"]="not empty array"}($||($={})),function(e){e["EQUAL"]="==",e["NOT_EQUAL"]="!=",e["GREATER_THAN"]=">",e["LESS_THAN"]="<",e["GREATER_THAN_OR_EQUAL"]=">=",e["LESS_THAN_OR_EQUAL"]="<="}(E||(E={})),function(e){e["innerHTML"]="innerHTML",e["condition"]="condition",e["condition2"]="condition2",e["__data"]="__data"}(k||(k={}));const S='publicStates',T='privateStates',A='id-plugin-data-source',C='nameForDataSource';function I(e){var t;return null!==(t=e.get(A))&&void 0!==t?t:null}function O(e){const t=e.get(A);if(t)return t;const n=`${e.ccid}-${Math.round(1e4*Math.random())}`;return e.set(A,n),n}function j(e,t){return t?I(t)===e?t:j(e,t.parent()):null}const N=[];function R(e,t){N.forEach((n=>n(e,t)))}function L(e,t=!0,n){var o;try{const r=(null!==(o=e.get(t?S:T))&&void 0!==o?o:[]).sort(((e,t)=>{var n,o;return Number(null!==(n=t.hidden)&&void 0!==n&&n)-Number(null!==(o=e.hidden)&&void 0!==o&&o)})).map((e=>e.id));if(n){const e=r.indexOf(n);return e<0?r:r.slice(0,e)}return r}catch(e){return console.error('Error while getting state ids',e),[]}}function P(e,t=!0){var n;return(null!==(n=e.get(t?S:T))&&void 0!==n?n:[]).map((e=>({label:e.label,hidden:e.hidden,expression:e.expression})))}function M(e,t,n=!0){var o,r;const i=null!==(r=(null!==(o=e.get(n?S:T))&&void 0!==o?o:[]).find((e=>e.id===t)))&&void 0!==r?r:null;return i?{label:i.label,hidden:i.hidden,expression:i.expression}:null}function U(e,t,n,o=!0,r=-1){var i,s;const a=o?S:T,l=null!==(i=e.get(a))&&void 0!==i?i:[],d=null!==(s=l.find((e=>e.id===t)))&&void 0!==s?s:null;if(d?e.set(a,l.map((e=>e.id!==t?e:Object.assign({id:t},n)))):e.set(a,[...l,Object.assign({id:t},n)]),r>=0){const n=[...e.get(a)],o=n.find((e=>e.id===t));o&&r<n.length&&(n.splice(n.indexOf(o),1),n.splice(r,0,o),e.set(a,n))}R({label:n.label,hidden:n.hidden,expression:n.expression},e)}function D(e,t,n=!0){var o;const r=n?S:T,i=(null!==(o=e.get(r))&&void 0!==o?o:[]).filter((e=>e.id!==t));e.set(r,i),R(null,e)}let z=null;function q(){if(!z)throw new Error('DataSourceRegistry not initialized. Call initializeDataSourceRegistry first.');return z}function F(){return[...q().dataSources]}function B(e){const t=q();t.dataSources.push(e),e.connect().then((()=>{t.editor.trigger(i)})).catch((e=>{console.error('Failed to connect data source:',e),t.editor.trigger(i)}))}function H(e){const t=q(),n=t.dataSources.indexOf(e);n>-1&&(t.dataSources.splice(n,1),t.editor.trigger(i))}function Q(e){return q().dataSources.find((t=>t.id===e))}function V(e){const t=q();t.dataSources=[...e],t.editor.trigger(i)}const G=globalThis,J=G.ShadowRoot&&(void 0===G.ShadyCSS||G.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,W=Symbol(),K=new WeakMap;class Y{constructor(e,t,n){if(this._$cssResult$=!0,n!==W)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(J&&void 0===e){const n=void 0!==t&&1===t.length;n&&(e=K.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&K.set(t,e))}return e}toString(){return this.cssText}}const Z=(e,...t)=>{const n=1===e.length?e[0]:t.reduce(((t,n,o)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+e[o+1]),e[0]);return new Y(n,e,W)},X=(e,t)=>{if(J)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const n of t){const t=document.createElement("style"),o=G.litNonce;void 0!==o&&t.setAttribute("nonce",o),t.textContent=n.cssText,e.appendChild(t)}},ee=J?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const n of e.cssRules)t+=n.cssText;return(e=>new Y("string"==typeof e?e:e+"",void 0,W))(t)})(e):e,{is:te,defineProperty:ne,getOwnPropertyDescriptor:oe,getOwnPropertyNames:re,getOwnPropertySymbols:ie,getPrototypeOf:se}=Object,ae=globalThis,le=ae.trustedTypes,de=le?le.emptyScript:"",pe=ae.reactiveElementPolyfillSupport,ce=(e,t)=>e,ue={toAttribute(e,t){switch(t){case Boolean:e=e?de:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=null!==e;break;case Number:n=null===e?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch(e){n=null}}return n}},he=(e,t)=>!te(e,t),fe={attribute:!0,type:String,converter:ue,reflect:!1,useDefault:!1,hasChanged:he};Symbol.metadata??=Symbol("metadata"),ae.litPropertyMetadata??=new WeakMap;class ge extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=fe){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const n=Symbol(),o=this.getPropertyDescriptor(e,n,t);void 0!==o&&ne(this.prototype,e,o)}}static getPropertyDescriptor(e,t,n){const{get:o,set:r}=oe(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:o,set(t){const i=o?.call(this);r?.call(this,t),this.requestUpdate(e,i,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??fe}static _$Ei(){if(this.hasOwnProperty(ce("elementProperties")))return;const e=se(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(ce("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ce("properties"))){const e=this.properties,t=[...re(e),...ie(e)];for(const n of t)this.createProperty(n,e[n])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const n=this._$Eu(e,t);void 0!==n&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const e of n)t.unshift(ee(e))}else void 0!==e&&t.push(ee(e));return t}static _$Eu(e,t){const n=t.attribute;return!1===n?void 0:"string"==typeof n?n:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return X(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){const n=this.constructor.elementProperties.get(e),o=this.constructor._$Eu(e,n);if(void 0!==o&&!0===n.reflect){const r=(void 0!==n.converter?.toAttribute?n.converter:ue).toAttribute(t,n.type);this._$Em=e,null==r?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(e,t){const n=this.constructor,o=n._$Eh.get(e);if(void 0!==o&&this._$Em!==o){const e=n.getPropertyOptions(o),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:ue;this._$Em=o;const i=r.fromAttribute(t,e.type);this[o]=i??this._$Ej?.get(o)??i,this._$Em=null}}requestUpdate(e,t,n,o=!1,r){if(void 0!==e){const i=this.constructor;if(!1===o&&(r=this[e]),n??=i.getPropertyOptions(e),!((n.hasChanged??he)(r,t)||n.useDefault&&n.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:o,wrapped:r},i){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,i??t??this[e]),!0!==r||void 0!==i)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===o&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,n]of e){const{wrapped:e}=n,o=this[t];!0!==e||this._$AL.has(t)||void 0===o||this.C(t,void 0,n,o)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach((e=>this._$ET(e,this[e]))),this._$EM()}updated(e){}firstUpdated(e){}}ge.elementStyles=[],ge.shadowRootOptions={mode:"open"},ge[ce("elementProperties")]=new Map,ge[ce("finalized")]=new Map,pe?.({ReactiveElement:ge}),(ae.reactiveElementVersions??=[]).push("2.1.2");const ye=globalThis,me=ye.trustedTypes,ve=me?me.createPolicy("lit-html",{createHTML:e=>e}):void 0,be="$lit$",xe=`lit$${Math.random().toFixed(9).slice(2)}$`,we="?"+xe,_e=`<${we}>`,$e=document,Ee=()=>$e.createComment(""),ke=e=>null===e||"object"!=typeof e&&"function"!=typeof e,Se=Array.isArray,Te=e=>Se(e)||"function"==typeof e?.[Symbol.iterator],Ae="[ \t\n\f\r]",Ce=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ie=/-->/g,Oe=/>/g,je=RegExp(`>|${Ae}(?:([^\\s"'>=/]+)(${Ae}*=${Ae}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),Ne=/'/g,Re=/"/g,Le=/^(?:script|style|textarea|title)$/i,Pe=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),Me=Pe(1),Ue=(Pe(2),Pe(3),Symbol.for("lit-noChange")),De=Symbol.for("lit-nothing"),ze=new WeakMap,qe=$e.createTreeWalker($e,129);function Fe(e,t){if(!Se(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==ve?ve.createHTML(t):t}const Be=(e,t)=>{const n=e.length-1,o=[];let r,i=2===t?"<svg>":3===t?"<math>":"",s=Ce;for(let t=0;t<n;t++){const n=e[t];let a,l,d=-1,p=0;for(;p<n.length&&(s.lastIndex=p,l=s.exec(n),null!==l);)p=s.lastIndex,s===Ce?"!--"===l[1]?s=Ie:void 0!==l[1]?s=Oe:void 0!==l[2]?(Le.test(l[2])&&(r=RegExp("</"+l[2],"g")),s=je):void 0!==l[3]&&(s=je):s===je?">"===l[0]?(s=r??Ce,d=-1):void 0===l[1]?d=-2:(d=s.lastIndex-l[2].length,a=l[1],s=void 0===l[3]?je:'"'===l[3]?Re:Ne):s===Re||s===Ne?s=je:s===Ie||s===Oe?s=Ce:(s=je,r=void 0);const c=s===je&&e[t+1].startsWith("/>")?" ":"";i+=s===Ce?n+_e:d>=0?(o.push(a),n.slice(0,d)+be+n.slice(d)+xe+c):n+xe+(-2===d?t:c)}return[Fe(e,i+(e[n]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),o]};class He{constructor({strings:e,_$litType$:t},n){let o;this.parts=[];let r=0,i=0;const s=e.length-1,a=this.parts,[l,d]=Be(e,t);if(this.el=He.createElement(l,n),qe.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(o=qe.nextNode())&&a.length<s;){if(1===o.nodeType){if(o.hasAttributes())for(const e of o.getAttributeNames())if(e.endsWith(be)){const t=d[i++],n=o.getAttribute(e).split(xe),s=/([.?@])?(.*)/.exec(t);a.push({type:1,index:r,name:s[2],strings:n,ctor:"."===s[1]?We:"?"===s[1]?Ke:"@"===s[1]?Ye:Je}),o.removeAttribute(e)}else e.startsWith(xe)&&(a.push({type:6,index:r}),o.removeAttribute(e));if(Le.test(o.tagName)){const e=o.textContent.split(xe),t=e.length-1;if(t>0){o.textContent=me?me.emptyScript:"";for(let n=0;n<t;n++)o.append(e[n],Ee()),qe.nextNode(),a.push({type:2,index:++r});o.append(e[t],Ee())}}}else if(8===o.nodeType)if(o.data===we)a.push({type:2,index:r});else{let e=-1;for(;-1!==(e=o.data.indexOf(xe,e+1));)a.push({type:7,index:r}),e+=xe.length-1}r++}}static createElement(e,t){const n=$e.createElement("template");return n.innerHTML=e,n}}function Qe(e,t,n=e,o){if(t===Ue)return t;let r=void 0!==o?n._$Co?.[o]:n._$Cl;const i=ke(t)?void 0:t._$litDirective$;return r?.constructor!==i&&(r?._$AO?.(!1),void 0===i?r=void 0:(r=new i(e),r._$AT(e,n,o)),void 0!==o?(n._$Co??=[])[o]=r:n._$Cl=r),void 0!==r&&(t=Qe(e,r._$AS(e,t.values),r,o)),t}class Ve{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:n}=this._$AD,o=(e?.creationScope??$e).importNode(t,!0);qe.currentNode=o;let r=qe.nextNode(),i=0,s=0,a=n[0];for(;void 0!==a;){if(i===a.index){let t;2===a.type?t=new Ge(r,r.nextSibling,this,e):1===a.type?t=new a.ctor(r,a.name,a.strings,this,e):6===a.type&&(t=new Ze(r,this,e)),this._$AV.push(t),a=n[++s]}i!==a?.index&&(r=qe.nextNode(),i++)}return qe.currentNode=$e,o}p(e){let t=0;for(const n of this._$AV)void 0!==n&&(void 0!==n.strings?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}}class Ge{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,o){this.type=2,this._$AH=De,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Qe(this,e,t),ke(e)?e===De||null==e||""===e?(this._$AH!==De&&this._$AR(),this._$AH=De):e!==this._$AH&&e!==Ue&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):Te(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==De&&ke(this._$AH)?this._$AA.nextSibling.data=e:this.T($e.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:n}=e,o="number"==typeof n?this._$AC(e):(void 0===n.el&&(n.el=He.createElement(Fe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===o)this._$AH.p(t);else{const e=new Ve(o,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=ze.get(e.strings);return void 0===t&&ze.set(e.strings,t=new He(e)),t}k(e){Se(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let n,o=0;for(const r of e)o===t.length?t.push(n=new Ge(this.O(Ee()),this.O(Ee()),this,this.options)):n=t[o],n._$AI(r),o++;o<t.length&&(this._$AR(n&&n._$AB.nextSibling,o),t.length=o)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e&&e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}}class Je{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,o,r){this.type=1,this._$AH=De,this._$AN=void 0,this.element=e,this.name=t,this._$AM=o,this.options=r,n.length>2||""!==n[0]||""!==n[1]?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=De}_$AI(e,t=this,n,o){const r=this.strings;let i=!1;if(void 0===r)e=Qe(this,e,t,0),i=!ke(e)||e!==this._$AH&&e!==Ue,i&&(this._$AH=e);else{const o=e;let s,a;for(e=r[0],s=0;s<r.length-1;s++)a=Qe(this,o[n+s],t,s),a===Ue&&(a=this._$AH[s]),i||=!ke(a)||a!==this._$AH[s],a===De?e=De:e!==De&&(e+=(a??"")+r[s+1]),this._$AH[s]=a}i&&!o&&this.j(e)}j(e){e===De?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class We extends Je{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===De?void 0:e}}class Ke extends Je{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==De)}}class Ye extends Je{constructor(e,t,n,o,r){super(e,t,n,o,r),this.type=5}_$AI(e,t=this){if((e=Qe(this,e,t,0)??De)===Ue)return;const n=this._$AH,o=e===De&&n!==De||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,r=e!==De&&(n===De||o);o&&this.element.removeEventListener(this.name,this,n),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class Ze{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){Qe(this,e)}}const Xe={M:be,P:xe,A:we,C:1,L:Be,R:Ve,D:Te,V:Qe,I:Ge,H:Je,N:Ke,U:Ye,B:We,F:Ze},et=ye.litHtmlPolyfillSupport;et?.(He,Ge),(ye.litHtmlVersions??=[]).push("3.3.0");const tt=(e,t,n)=>{const o=n?.renderBefore??t;let r=o._$litPart$;if(void 0===r){const e=n?.renderBefore??null;o._$litPart$=r=new Ge(t.insertBefore(Ee(),e),e,void 0,n??{})}return r._$AI(e),r},nt=globalThis;class ot extends ge{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=tt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}}ot._$litElement$=!0,ot["finalized"]=!0,nt.litElementHydrateSupport?.({LitElement:ot});const rt=nt.litElementPolyfillSupport;rt?.({LitElement:ot});(nt.litElementVersions??=[]).push("4.2.2");const it=`\n query IntrospectionQuery {\n __schema {\n queryType {\n name\n }\n types {\n ...FullType\n }\n }\n }\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: false) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: false) {\n name\n description\n }\n possibleTypes {\n ...TypeRef\n }\n }\n fragment InputValue on __InputValue {\n name\n description\n type {\n ...TypeRef\n }\n defaultValue\n }\n fragment TypeRef on __Type {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n }\n`;var st=n(365),at=n.n(st),lt=void 0&&(void 0).__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o["throw"](e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}))};const dt=`\n query TypeNamesQuery {\n __schema {\n queryType {\n name\n }\n types {\n name\n kind\n }\n }\n }\n`,pt=`\n fragment SelectiveType on __Type {\n name\n kind\n fields(includeDeprecated: false) {\n name\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n defaultValue\n }\n type {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n ofType {\n kind\n name\n possibleTypes {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n`,ct=100,ut=5;class ht{constructor(e){this.type='graphql',this.method='POST',this.headers={},this.backendType='generic',this.types=[],this.queryables=[],this.queryType='',this.ready=!1,this.eventListeners={},this.id=e.id.toString(),this.label=e.label,this.url=e.url,this.type=e.type,this.method=e.method||'POST',this.headers=e.headers||{},this.queryable=e.queryable,this.readonly=e.readonly,this.hidden=e.hidden,this.backendType=e.backendType||'generic',this.disabledTypes=e.disabledTypes}on(e,t){this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(t)}off(e,t){this.eventListeners[e]&&(this.eventListeners[e]=t?this.eventListeners[e].filter((e=>e!==t)):[])}trigger(e,...t){this.eventListeners[e]&&this.eventListeners[e].forEach((e=>e(...t)))}fetchTypeNames(){return lt(this,void 0,void 0,(function*(){var e,t,n;try{const o=yield this.call(dt);if(!(null===(t=null===(e=o.data)||void 0===e?void 0:e.__schema)||void 0===t?void 0:t.types))throw new Error(`Invalid response: ${JSON.stringify(o)}`);const r=(null===(n=o.data.__schema.queryType)||void 0===n?void 0:n.name)||'Query';return{types:o.data.__schema.types.filter((e=>!e.name.startsWith('__'))),queryTypeName:r}}catch(e){throw console.error('[GraphQL] Failed to fetch type names:',e.message),new Error(`Failed to fetch type names: ${e.message}`)}}))}static getDefaultEnabledTypes(e,t,n='Query'){const o=t.map((e=>e.name)),r=t.filter((e=>'SCALAR'===e.kind)).map((e=>e.name));switch(e){case'gitlab':{const e=['Project','Namespace','User','Group','Repository','Commit','Branch','MergeRequest','Issue','Pipeline','Job','Release','Milestone','Label','Note','Discussion','Snippet','Board','Epic','Vulnerability','Package','ContainerRepository','Environment','Deployment','CiRunner','Topic','PageInfo'],t=[...r,n,...e,...o.filter((t=>!t.endsWith('Input')&&!t.endsWith('Enum')&&(t.endsWith('Connection')||t.endsWith('Edge')||e.some((e=>t.startsWith(e))))))];return o.filter((e=>t.includes(e)))}case'wordpress':{const e=t.filter((e=>'INPUT_OBJECT'===e.kind)).map((e=>e.name)),n=['RootMutation','Settings','DiscussionSettings','GeneralSettings','ReadingSettings','WritingSettings','Plugin','Theme','UserRole','Avatar','ContentTemplate','DefaultTemplate'],r=[/^Create.+Input$/,/^Update.+Input$/,/^Delete.+Input$/,/^Register.+Input$/,/^Reset.+Input$/,/^Restore.+Input$/,/^Send.+Input$/,/Payload$/,/^RootQueryToPlugin/,/^RootQueryToTheme/,/^RootQueryToUserRole/,/Plugin(?:Connection|Edge|PageInfo|Status)/,/Theme(?:Connection|Edge|PageInfo)/,/UserRole(?:Connection|Edge|PageInfo)/,/Enqueued/,/Script(?!$)/,/Stylesheet/,/Revision/,/Comment/,/Commenter/,/PostFormat/,/^RootQueryToContentNode/],i=t=>!!e.includes(t)||(!!n.includes(t)||r.some((e=>e.test(t))));return o.filter((e=>!i(e)))}case'strapi':{const e=t.filter((e=>'INPUT_OBJECT'===e.kind)).map((e=>e.name)),n=['Mutation','GenericMorph'],r=[/Payload$/,/^UsersPermissions/,/^UploadFolder/,/^I18N/,/EntityResponse$/,/EntityResponseCollection$/,/^ContentType/,/^Admin/],i=t=>!!e.includes(t)||(!!n.includes(t)||r.some((e=>e.test(t))));return o.filter((e=>!i(e)))}case'supabase':{const e=t.filter((e=>'INPUT_OBJECT'===e.kind)).map((e=>e.name)),n=['Mutation','Cursor'],r=[/InsertInput$/,/UpdateInput$/,/DeleteInput$/,/InsertResponse$/,/UpdateResponse$/,/DeleteResponse$/,/OrderBy$/,/OrderByDirection$/,/Filter$/,/FilterInput$/,/Edge$/],i=t=>!!e.includes(t)||(!!n.includes(t)||r.some((e=>e.test(t))));return o.filter((e=>!i(e)))}default:return[...o]}}triggerError(e){throw console.error('GraphQL error:',e),this.trigger(r,e,this),new Error(e)}loadData(){return lt(this,void 0,void 0,(function*(){var e,t,n,o,r,i;try{let s,a;if(this.disabledTypes&&this.disabledTypes.length>0){const o=yield this.call(dt);if(!(null===(t=null===(e=o.data)||void 0===e?void 0:e.__schema)||void 0===t?void 0:t.types))return this.triggerError(`Invalid lightweight response: ${JSON.stringify(o)}`);const r=o.data.__schema.types.map((e=>e.name)).filter((e=>!e.startsWith('__'))),i=(null===(n=o.data.__schema.queryType)||void 0===n?void 0:n.name)||'Query',l=o.data.__schema.types.filter((e=>'SCALAR'===e.kind&&!e.name.startsWith('__'))).map((e=>e.name)),d=r.filter((e=>!this.disabledTypes.includes(e)));!d.includes(i)&&r.includes(i)&&d.push(i);for(const e of l)d.includes(e)||d.push(e);const p='gitlab'===this.backendType?ut:ct,c=[];for(let e=0;e<d.length;e+=p)c.push(d.slice(e,e+p));const u=yield Promise.all(c.map((e=>lt(this,void 0,void 0,(function*(){try{const t=`\n query BatchTypeIntrospection {\n${e.map((e=>` ${`type_${e.replace(/[^a-zA-Z0-9_]/g,'_')}`}: __type(name: "${e}") { ...SelectiveType }`)).join('\n')}\n }\n ${pt}\n `,n=yield this.call(t),o=[];for(const[e,t]of Object.entries(n.data||{}))e.startsWith('type_')&&null!==t&&o.push(t);return o}catch(e){return console.warn('[GraphQL] Failed to fetch batch:',e.message),[]}})))));s=u.flat(),a=i}else{const e=yield this.call(it);if(!(null===(r=null===(o=e.data)||void 0===o?void 0:o.__schema)||void 0===r?void 0:r.types))return this.triggerError(`Invalid response: ${JSON.stringify(e)}`);s=e.data.__schema.types,a=null===(i=e.data.__schema.queryType)||void 0===i?void 0:i.name}if(!a)return this.triggerError('Invalid response, queryType not found');const l=s.map((e=>e.name)).concat(w),d=s.find((e=>e.name===a));if(!d)return this.triggerError(`Query type "${a}" not found in schema. Make sure to enable it.`);const p=s.filter((e=>!e.name.startsWith('__'))).filter((e=>{var t;return!(null===(t=null==d?void 0:d.fields)||void 0===t?void 0:t.find((t=>t.name===e.name)))})).map((e=>this.graphQLToType(l,e,'SCALAR',!1))).concat(_),c=(d.fields||[]).map((e=>({type:Object.assign(Object.assign({},s.find((t=>t.name===this.getOfTypeProp('name',e.type,e.name)))),{name:e.name}),kind:this.ofKindToKind(e.type)}))).filter((({type:e})=>void 0!==e.fields)).map((({type:e,kind:t})=>this.graphQLToType(l,e,t,!0))),u=(d.fields||[]).filter((e=>{const t=this.getOfTypeProp('name',e.type,e.name);return s.some((e=>e.name===t))||w.includes(t)})).map((e=>this.graphQLToField(e)));return[c.concat(p),u,a]}catch(e){return this.triggerError(`GraphQL introspection failed: ${e.message}`)}}))}graphQLToField(e){var t;const n=this.ofKindToKind(e.type);return{id:e.name,dataSourceId:this.id,label:e.name,typeIds:this.graphQLToTypes(e),kind:n?this.graphQLToKind(n):'unknown',arguments:null===(t=e.args)||void 0===t?void 0:t.map((e=>({name:e.name,typeId:this.getOfTypeProp('name',e.type,e.name),defaultValue:e.defaultValue})))}}getOfTypeProp(e,t,n){const o=this.getOfTypePropRecursive(e,t);if(o)return o;if(n)return n;throw new Error(`Type ${JSON.stringify(t)} has no property ${e} and no default was provided`)}getOfTypePropRecursive(e,t){if(!t)throw console.error('Invalid type',t),new Error('Invalid type');if(t.ofType){const n=this.getOfTypePropRecursive(e,t.ofType);if(n)return n}return t[e]}graphQLToTypes(e){const t=this.getOfTypeProp('possibleTypes',e.type,[]);if(t.length>0)return t.map((e=>e.name));return[this.getOfTypeProp('name',e.type,e.name)]}graphQLToKind(e){switch(e){case'LIST':return'list';case'OBJECT':return'object';case'SCALAR':return'scalar';default:throw new Error(`Unable to find a valid kind for ${e}`)}}validKind(e){return['LIST','OBJECT','SCALAR'].includes(e)}ofKindToKind(e){if(e.possibleTypes){const t=e.possibleTypes.reduce(((t,n)=>{if(!t)return n.kind;if(t!==n.kind)throw new Error(`Unable to find a valid kind for ${e.kind}. Union types with different kind is not supported`);return t}),null);return t||(console.error('Unable to find a valid kind (1)',e),null)}return this.validKind(e.kind)?e.kind:e.ofType?this.ofKindToKind(e.ofType):null}graphQLToType(e,t,n,o){var r,i,s;const a=this.queryable;return{id:t.name,dataSourceId:this.id,label:t.name,fields:null!==(s=null===(i=null===(r=t.fields)||void 0===r?void 0:r.filter((t=>e.includes(this.getOfTypeProp('name',t.type,t.name)))))||void 0===i?void 0:i.map((e=>this.graphQLToField(e))))&&void 0!==s?s:[],queryable:o&&(!a||a.includes(t.name))}}connect(){return lt(this,void 0,void 0,(function*(){try{const[e,n,o]=yield this.loadData();if(0===e.length)return this.triggerError('No types found in GraphQL schema');if(0===n.length)return this.triggerError('No fields found in GraphQL schema');if(!o)return this.triggerError('No query type found in GraphQL schema');this.types=e,this.queryables=n,this.queryType=o,this.ready?this.trigger(i,this):(this.ready=!0,this.trigger(t,this))}catch(e){return this.triggerError(`GraphQL connection failed: ${e.message}`)}}))}isConnected(){return this.ready}getTypes(){if(!this.ready)throw console.error('DataSource is not ready. Attempted to get types before ready status was achieved.'),new Error('DataSource is not ready. Ensure it is connected and ready before querying.');if(0===this.types.length)throw console.error('No types available. It seems the data source may not be connected or the schema is incomplete.',this.ready),new Error('No types found. The data source may not be connected or there might be an issue with the schema.');return this.types}getQueryables(){return this.queryables}call(e){return lt(this,void 0,void 0,(function*(){var t;const n=this.url;if(!n)return this.triggerError('Missing GraphQL URL');const o=this.headers;if(!o)return this.triggerError('Missing GraphQL headers');const r=Object.keys(o).find((e=>'content-type'===e.toLowerCase()));o[r||'Content-Type']=o[r||'Content-Type']||'application/json';const i=null!==(t=this.method)&&void 0!==t?t:'POST',s=yield fetch(n,Object.assign({method:i,headers:o},'POST'===i?{body:JSON.stringify({query:e})}:{}));return(null==s?void 0:s.ok)?s.json():(console.error('GraphQL call failed',null==s?void 0:s.status,null==s?void 0:s.statusText,e),this.triggerError(`GraphQL call failed with \`${null==s?void 0:s.statusText}\` and status ${null==s?void 0:s.status}`))}))}getQuery(e){return this.getQueryRecursive({token:{dataSourceId:this.id,fieldId:'query',kind:'object',typeIds:[this.queryType]},children:e})}getQueryRecursive(t,n='',o=''){const r=o?`...on ${o}`:`${t.token.fieldId}${function(e){const t=e?`(${Object.keys(e).map((t=>({key:t,value:e[t]}))).filter((({value:e})=>!Nt(e))).map((({key:e,value:t})=>`${e}: ${t}`)).join(', ')})`:'';return'()'===t?'':t}(t.token.options)}`;switch(t.token.kind){case'scalar':return t.token.fieldId===e?'':n+r;case'object':case'list':{const e=this.getTypes().filter((e=>{var n;return null===(n=t.token.typeIds)||void 0===n?void 0:n.includes(e.id)}));if(0===e.length)throw new Error(`Type not found for ${t.token.fieldId} (${t.token.typeIds})`);if(e.length>1)throw new Error(`Multiple types found for ${t.token.fieldId}`);const o=e[0],i=t.children.map((e=>{const t=o.fields.find((t=>t.id===e.token.fieldId));return t?{fieldType:t,child:e}:null})).filter((e=>null!==e)),s=i.filter((({fieldType:e})=>e.typeIds.length>1)).map((({child:e})=>({query:this.getQueryRecursive(e,n+' ',e.token.typeIds[0]),child:e}))).map((({query:e,child:t})=>at()` ${n}${t.token.fieldId} { ${e} } `)).join('\n'),a=i.filter((({fieldType:e})=>1===e.typeIds.length)).map((({child:e})=>this.getQueryRecursive(e,n+' '))).join('\n');return at()`${n}${r} { ${n} __typename ${a} ${s} ${n}}`}default:throw console.error('Unable to build GraphQL query',t),new Error(`Unable to build GraphQL query: unable to build tree ${JSON.stringify(t)}`)}}fetchValues(e){return lt(this,void 0,void 0,(function*(){return(yield this.call(e)).data}))}}const ft='Data source';function gt(e){const t=e.parent(),n=null==t?void 0:t.getName(),o=null==t?void 0:t.get('tagName'),r=n?`${n} (${o})`:o,i=e.cid,s=e.get('tagName'),a=e.getClasses(),l=a.length?`.${a.join('.')}`:'';return`${r} > ${e.getName()} (${s}#${i}${l})`}function yt(e,t){switch(t.type){case'property':{const e=function(e,t){const n=e.join(', ').toLowerCase();return'list'===t?` (${n}[])`:'object'===t?` (${n}{})`:` (${n})`}(t.typeIds,t.kind);return`${t.label} ${e}`}case'filter':return t.label;case'state':return function(e,t){var n;const o=j(t.componentId,e),r=null!==(n=null==o?void 0:o.get(C))&&void 0!==n?n:'';return`${r?r+' ':''}${t.label||t.storedStateId}`}(e,t);default:throw console.error('Unknown token type (reading type)',t),new Error('Unknown token type')}}function mt(e,t,n,o){return n.reduce(((n,r)=>{var i,s,a,l;let d;switch(r.type){case'filter':d='Filters';break;case'property':if(r.dataSourceId)if(o.length>0)try{const e=It(o,t);d=null!==(s=null!==(i=null==e?void 0:e.label)&&void 0!==i?i:null==e?void 0:e.id)&&void 0!==s?s:'Unknown'}catch(e){console.error('Error while getting expression result type in groupByType',{expression:o,component:t}),d='Unknown'}else{const t=Q(r.dataSourceId);if(!t)throw console.error('Data source not found',r.dataSourceId),e.runCommand('notifications:add',{type:'error',group:ft,message:`Data source not found: ${r.dataSourceId}`}),new Error(`Data source not found: ${r.dataSourceId}`);d=t.label||(null===(l=(a=t).get)||void 0===l?void 0:l.call(a,'label'))||r.dataSourceId}else d='Fields';break;case'state':{const e=j(r.componentId,t),n='body'===(null==e?void 0:e.get('tagName'))?'Website':null==e?void 0:e.getName();d=n?`${n}'s states`:'States';break}default:throw console.error('Unknown token type (reading type)',r),new Error('Unknown token type')}return n[d]||(n[d]=[]),n[d].push(r),n}),{})}function vt(t){return{type:'property',propType:'field',fieldId:e,label:'Fixed value',kind:'scalar',typeIds:['String'],options:{value:t},optionsForm:()=>Me` <label>Value <input type="text" name="value" .value=${t}> </label> `}}function bt(e){return JSON.stringify(Object.assign({},e))}function xt(e){switch(e.type){case'property':return`property__${e.dataSourceId||''}__${e.fieldId}__${e.kind}__${e.typeIds.join(',')}`;case'filter':return`filter____${e.id}`;case'state':return`state__${e.componentId}__${e.storedStateId}`;default:throw console.error('Unknown token type (reading type)',e),new Error('Unknown token type')}}function wt(e,t,n){return Tt(JSON.parse(t),n)}function _t(t){try{return'string'==typeof t&&(t=JSON.parse(t)),function(t){if('string'==typeof t)throw new Error('json must be parsed');return!!Array.isArray(t)&&t.every((t=>{var n;if('object'!=typeof t)return!1;if(!t.type)return!1;switch(t.type){case'property':if(!t.fieldId)return!1;if(t.fieldId===e&&!(null===(n=t.options)||void 0===n?void 0:n.value))return!1;break;case'state':if(!t.componentId)return!1;if(!t.storedStateId)return!1;break;case'filter':if(!t.id)return!1}return!0}))}(t)?t:null}catch(e){return null}}function $t(e,t,n){if(!e)return null;if(e.kind!==t)throw console.error(`Field is not a ${t}`,e),new Error(`Field ${e.label} is not a ${t}`);return Object.assign(Object.assign({},e),{kind:n})}function Et(e,t){if(void 0===e)throw new Error('el option must be set');if('string'==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Element ${e} not found`);return t}if('function'==typeof e){const t=e();if(!t)throw new Error('el option must be a returned by the provided function');return t}if(e instanceof HTMLElement)return e;throw new Error(`${t} must be a string or an HTMLElement or a function`)}function kt(e=Math.random().toString(36).slice(2,8)){return{id:`ds-${e}`,label:'New data source',type:'graphql',url:'',method:'POST',headers:{},readonly:!1}}function St(e={},t){const n=Object.assign(Object.assign({},kt(t)),e);if('graphql'===n.type)return new ht(n);throw new Error(`Unknown data source type: ${n.type}`)}function Tt(e,t){var n;if(!e||'object'!=typeof e)throw console.error('Invalid token: not an object',e),new Error('Invalid token: expected an object');if(!e.type)throw console.error('Invalid token: missing type property',e),new Error('Invalid token: missing type property');switch(e.type){case'filter':{if(e.optionsForm)return e;const t=an().find((t=>t.id===e.id));if(!t)throw console.error('Filter not found',e),new Error(`Filter ${e.id} not found`);return Object.assign(Object.assign(Object.assign({},t),e),{type:'filter'})}case'property':{if(e.optionsForm)return e;const o=Ct(e,t);if(!o)throw console.error('Field not found for token',e),new Error(`Field ${e.fieldId} not found`);return Object.assign(Object.assign(Object.assign({},null!==(n=Ot(o))&&void 0!==n?n:{}),e),{type:'property',propType:'field'})}case'state':return e;default:throw console.error('Unknown token type (reading type)',e),new Error('Unknown token type')}}function At(e,t,n){var o,r,i;switch(e.type){case'filter':try{const n=function(e,t){if('filter'!==e.type)throw new Error('Token is not a filter');const n=t.find((t=>t.id===e.id));if(!n)throw console.error('Filter not found',e),new Error(`Filter ${e.id} not found`);return Object.assign(Object.assign(Object.assign({},e),n),{options:e.options})}(e,an());try{if(n.validate(t))return n.output(t,null!==(o=n.options)&&void 0!==o?o:{})}catch(n){return console.warn('Filter validate error:',n,{token:e,prev:t}),null}return null}catch(o){return console.error('Error while getting filter result type',{token:e,prev:t,component:n}),null}case'property':try{return Ct(e,n.getId())}catch(t){return console.error('Error while getting property result type',{token:e,component:n}),null}case'state':{const o=j(e.componentId,n);if(!o){console.warn('Component not found for state',e);return rn().editor.runCommand('notifications:add',{type:'error',group:ft,message:`Component not found for state: ${e.storedStateId}`,componentId:n.getId()}),null}const s=null===(r=M(o,e.storedStateId,e.exposed))||void 0===r?void 0:r.expression;if(!s){console.warn('State is not defined on component',{component:o,token:e});return rn().editor.runCommand('notifications:add',{type:'error',group:ft,message:`State '${e.storedStateId}' is not defined on component '${o.getName()||o.get('id')}'`,componentId:o.getId()}),null}try{const t=It(s,o);return t?Object.assign(Object.assign({},t),{kind:null!==(i=e.forceKind)&&void 0!==i?i:t.kind}):null}catch(r){return console.error('Error while getting expression result type in tokenToField',{expression:s,parent:o,component:n,token:e,prev:t}),null}}default:throw console.error('Unknown token type (reading type)',e),new Error('Unknown token type')}}function Ct(e,t){var n,o;const r=rn(),i=r.cachedTypes.length>0?r.cachedTypes:[],s=[];for(const a of e.typeIds){const l=i.find((t=>t.id===a&&(!e.dataSourceId||t.dataSourceId===e.dataSourceId)));l?s.push(l.label):(r.editor.runCommand('notifications:add',{type:'error',group:ft,message:`Type not found ${null!==(n=e.dataSourceId)&&void 0!==n?n:''}.${a}`,componentId:t}),console.error(`Type not found ${null!==(o=e.dataSourceId)&&void 0!==o?o:''}.${a}`))}const a=e.options?Object.entries(e.options).map((([e,t])=>({typeId:'JSON',name:e,defaultValue:t}))):void 0;return{id:e.fieldId,label:s.length>0?s.join(', '):e.label,typeIds:e.typeIds,kind:e.kind,dataSourceId:e.dataSourceId,arguments:a,previewIndex:e.previewIndex}}function It(e,t){return e.reduce(((e,n)=>At(Tt(n,t.getId()),e,t)),null)}function Ot(e){return e.arguments&&e.arguments.length>0?{optionsForm:(t=e.arguments.map((e=>({name:e.name,value:e.defaultValue}))),(e,n,o)=>Me` ${t.map((e=>{var t,n;const r=null!==(n=null!==(t=o[e.name])&&void 0!==t?t:e.value)&&void 0!==n?n:'';return Me`<label>${e.name}</label><input type="text" name=${e.name} .value=${r}>`}))} `),options:e.arguments.reduce(((e,t)=>(e[t.name]=t.defaultValue,e)),{})}:null;var t}function jt(e,t){if(!e&&!t)return{error:!1,result:void 0};if(Nt(e)&&Nt(t))return{error:!1,result:void 0};if(!e||!t)return{error:!0,result:void 0};if(Nt(e)||Nt(t))return{error:!0,result:void 0};const n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return{error:!0,result:void 0};for(const o of n)if(e[o]!==t[o])return{error:!0,result:void 0};return{error:!1,result:e}}function Nt(e){if(null==e)return!0;const t='string'==typeof e,n=t&&function(e){if('string'!=typeof e)return!1;if(0===e.length)return!1;try{JSON.parse(e)}catch(e){return!1}return!0}(e);if(t&&!n)return''===e;const o=n?JSON.parse(e):e;return null===o||(Array.isArray(o)?0===o.length:'object'==typeof o&&0===Object.values(o).filter((e=>!!e)).length)}function Rt(e,t){return void 0===t.previewIndex?e:Array.isArray(e)?e[t.previewIndex]:e}function Lt(t,n,o=null){if(0===t.length)return o;const r=t.map((e=>Object.assign({},e))),[i,...s]=r;switch(i.type){case'state':return function(e,t,n,o){var r;const i=Pt(e,n.component,n);if(!i)throw new Error(`Unable to resolve state: ${JSON.stringify(e)}`);const s=null===(r=i[i.length-1])||void 0===r?void 0:r.previewIndex;'items'===e.storedStateId&&void 0!==s&&(i[0].isItems=!0);return Lt([...i,...t],n,o)}(i,s,n,o);case'property':return function(t,n,o,r){var i;if(t.fieldId===e)return Lt(n,o,null===(i=t.options)||void 0===i?void 0:i.value);let s;if(null==r){if(!t.dataSourceId)throw new Error(`Data source ID is missing for token: ${JSON.stringify(t)}`);s=o.previewData[t.dataSourceId]}else s=r;let a=s?s[t.fieldId]:null;if(o.resolvePreviewIndex){const e=n[0];e&&'filter'===e.type||(a=Rt(a,t))}n.length>0&&!o.resolvePreviewIndex&&'filter'!==n[0].type&&(a=Rt(a,t));return t.isItems&&void 0!==t.previewIndex&&n.length>0&&(a=[a]),Lt(n,o,a)}(i,s,n,o);case'filter':return function(e,t,n,o){var r;const i=Object.entries(e.options).reduce(((e,[t,o])=>{const r=_t(o);return e[t]=r?Lt(r,n,null):o,e}),{}),s=n.filters.find((t=>t.id===e.id));if(!s)throw new Error(`Filter not found: ${e.id}`);let a;try{a=s.apply(o,i)}catch(e){return console.warn(`Filter "${s.id}" error:`,e,{filter:s.id,prevValues:o,options:i,valueType:typeof o,isArray:Array.isArray(o),isNull:null===o}),null}t.length>0&&'filter'===(null===(r=t[0])||void 0===r?void 0:r.type)||!(n.resolvePreviewIndex||t.length>0)||(a=Rt(a,e));return Lt(t,n,a)}(i,s,n,o);default:throw new Error(`Unsupported token type: ${JSON.stringify(i)}`)}}function Pt(e,t,n){const o=j(e.componentId,t);if(!o)return console.error('Component not found for state',e,t.get('id-plugin-data-source')),null;const r=M(o,e.storedStateId,e.exposed);return(null==r?void 0:r.expression)?r.expression.flatMap((e=>{var r;return'state'===e.type?null!==(r=Pt(Tt(e,t.getId()),o,n))&&void 0!==r?r:[]:e})):(console.warn('State is not defined on component',o.getId(),e,r),null)}function Mt(e,t){const n=[],o=t.getMainComponent();return o&&o.onAll((e=>{P(e,!0).concat(P(e,!1)).forEach((t=>{t.expression&&n.push({expression:t.expression,component:e})})),Object.values(e.getAttributes()).forEach((t=>{const o=_t(t);o&&n.push({expression:o,component:e})}))})),n}function Ut(e,{expression:t,component:n},o){if(0===t.length)return[];const r=t[0];switch(r.type){case'property':{if(r.dataSourceId!==o)return[];const i=Ut(e,{expression:t.slice(1),component:n},o);return 0===i.length?[{token:r,children:[]}]:i.flatMap((t=>function(e,t,n,o){const r=e.dataSources.find((e=>e.id===o));if(!r)throw new Error(`Data source not found ${o}`);if(!r.isConnected())throw new Error(`Data source ${o} is not ready (not connected)`);const i=r.getTypes().filter((e=>t.typeIds.includes(e.id))),s=i.flatMap((e=>e.fields.map((e=>e.typeIds)).flat()));return s.length>0&&n.typeIds.some((e=>s.includes(e)))}(e,r,t.token,o)?{token:r,children:[t]}:[{token:r,children:[]},t]))}case'filter':{const i=Object.values(r.options).map((e=>_t(e))).filter((e=>!!e&&e.length>0)).flatMap((t=>Ut(e,{expression:t,component:n},o))),s=Ut(e,{expression:t.slice(1),component:n},o);return 0===s.length?i:s.flatMap((e=>[e,...i]))}case'state':{const t=Pt(r,n,e);if(!t)throw e.editor.runCommand('notifications:add',{type:'error',group:ft,message:`Unable to resolve state <pre>${JSON.stringify(r)}</pre>`,componentId:n.getId()}),new Error(`Unable to resolve state ${JSON.stringify(r)}. State defined on component ${gt(n)}`);return Ut(e,{expression:t,component:n},o)}default:throw e.editor.runCommand('notifications:add',{type:'error',group:ft,message:`Invalid expression <pre>${JSON.stringify(t)}</pre>`,componentId:n.getId()}),new Error(`Invalid expression ${JSON.stringify(t)}. Expression used on component ${gt(n)}`)}}function Dt(e,t,n){return 0===t.length?[]:t.flatMap((t=>Ut(e,t,n))).reduce(((e,t)=>{const n=e.find((e=>e[0].token.fieldId===t.token.fieldId&&(!t.token.dataSourceId||e[0].token.dataSourceId===t.token.dataSourceId)));return n?n.push(t):e.push([t]),e}),[]).map((n=>{try{return n.reduce(((e,t)=>zt(e,t)))}catch(o){throw e.editor.runCommand('notifications:add',{type:'error',group:ft,message:`Unable to merge trees <pre>${JSON.stringify(n)}</pre>`,componentId:t[0].component.getId()}),o}}))}function zt(e,t){if(e.token.dataSourceId!==t.token.dataSourceId)throw console.error('Unable to merge trees',e,t),new Error(`Unable to build GraphQL query: unable to merge trees ${JSON.stringify(e)} and ${JSON.stringify(t)}`);const n=e.children.filter((e=>t.children.find((t=>e.token.fieldId===t.token.fieldId&&jt(e.token.options,t.token.options).error)))).map((e=>{const n=t.children.find((t=>e.token.fieldId===t.token.fieldId));return`${e.token.fieldId} appears twice with different options: ${JSON.stringify(e.token.options)} vs ${JSON.stringify(null==n?void 0:n.token.options)}`}));if(n.length>0)throw console.error('Unable to merge trees',n),new Error(`Unable to build GraphQL query: unable to merge trees: \n* ${n.join('\n* ')}`);const o=e.