@fluxscape/runtime 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/api/cloudfile.d.ts +12 -0
- package/dist/api/cloudfile.d.ts.map +1 -0
- package/dist/api/cloudstore.d.ts +87 -0
- package/dist/api/cloudstore.d.ts.map +1 -0
- package/dist/api/configservice.d.ts +15 -0
- package/dist/api/configservice.d.ts.map +1 -0
- package/dist/api/queryutils.d.ts +20 -0
- package/dist/api/queryutils.d.ts.map +1 -0
- package/dist/api/records.d.ts +32 -0
- package/dist/api/records.d.ts.map +1 -0
- package/dist/async-pool.d.ts +2 -0
- package/dist/async-pool.d.ts.map +1 -0
- package/dist/collection.d.ts +17 -0
- package/dist/collection.d.ts.map +1 -0
- package/dist/edgetriggeredinput.d.ts +2 -0
- package/dist/edgetriggeredinput.d.ts.map +1 -0
- package/dist/editorconnection.activewarnings.d.ts +7 -0
- package/dist/editorconnection.activewarnings.d.ts.map +1 -0
- package/dist/editorconnection.d.ts +39 -0
- package/dist/editorconnection.d.ts.map +1 -0
- package/dist/editormodeleventshandler.d.ts +2 -0
- package/dist/editormodeleventshandler.d.ts.map +1 -0
- package/dist/events.d.ts +31 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/eventsender.d.ts +10 -0
- package/dist/eventsender.d.ts.map +1 -0
- package/dist/guid.d.ts +2 -0
- package/dist/guid.d.ts.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.es.js +10463 -0
- package/dist/index.es.js.map +1 -0
- package/dist/index.iife.js +25 -0
- package/dist/index.iife.js.map +1 -0
- package/dist/javascriptnodeparser.d.ts +27 -0
- package/dist/javascriptnodeparser.d.ts.map +1 -0
- package/dist/model.d.ts +64 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/models/componentmodel.d.ts +47 -0
- package/dist/models/componentmodel.d.ts.map +1 -0
- package/dist/models/graphmodel.d.ts +44 -0
- package/dist/models/graphmodel.d.ts.map +1 -0
- package/dist/models/nodemodel.d.ts +40 -0
- package/dist/models/nodemodel.d.ts.map +1 -0
- package/dist/node.d.ts +70 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/nodecontext.d.ts +91 -0
- package/dist/nodecontext.d.ts.map +1 -0
- package/dist/nodedefinition.d.ts +93 -0
- package/dist/nodedefinition.d.ts.map +1 -0
- package/dist/nodelibraryexport.d.ts +81 -0
- package/dist/nodelibraryexport.d.ts.map +1 -0
- package/dist/noderegister.d.ts +12 -0
- package/dist/noderegister.d.ts.map +1 -0
- package/dist/nodes/componentinputs.d.ts +39 -0
- package/dist/nodes/componentinputs.d.ts.map +1 -0
- package/dist/nodes/componentinstance.d.ts +8 -0
- package/dist/nodes/componentinstance.d.ts.map +1 -0
- package/dist/nodes/componentoutputs.d.ts +34 -0
- package/dist/nodes/componentoutputs.d.ts.map +1 -0
- package/dist/nodes/std-library/and.d.ts +27 -0
- package/dist/nodes/std-library/and.d.ts.map +1 -0
- package/dist/nodes/std-library/booleantostring.d.ts +53 -0
- package/dist/nodes/std-library/booleantostring.d.ts.map +1 -0
- package/dist/nodes/std-library/condition.d.ts +71 -0
- package/dist/nodes/std-library/condition.d.ts.map +1 -0
- package/dist/nodes/std-library/counter.d.ts +98 -0
- package/dist/nodes/std-library/counter.d.ts.map +1 -0
- package/dist/nodes/std-library/data/cloudfilenode.d.ts +41 -0
- package/dist/nodes/std-library/data/cloudfilenode.d.ts.map +1 -0
- package/dist/nodes/std-library/data/dbcollectionnode2.d.ts +100 -0
- package/dist/nodes/std-library/data/dbcollectionnode2.d.ts.map +1 -0
- package/dist/nodes/std-library/data/dbconfig.d.ts +24 -0
- package/dist/nodes/std-library/data/dbconfig.d.ts.map +1 -0
- package/dist/nodes/std-library/data/dbmodelcrudbase.d.ts +6 -0
- package/dist/nodes/std-library/data/dbmodelcrudbase.d.ts.map +1 -0
- package/dist/nodes/std-library/data/dbmodelnode-addrelation.d.ts +30 -0
- package/dist/nodes/std-library/data/dbmodelnode-addrelation.d.ts.map +1 -0
- package/dist/nodes/std-library/data/dbmodelnode-removerelation.d.ts +31 -0
- package/dist/nodes/std-library/data/dbmodelnode-removerelation.d.ts.map +1 -0
- package/dist/nodes/std-library/data/dbmodelnode2.d.ts +120 -0
- package/dist/nodes/std-library/data/dbmodelnode2.d.ts.map +1 -0
- package/dist/nodes/std-library/data/deletedbmodelpropertiesnode.d.ts +29 -0
- package/dist/nodes/std-library/data/deletedbmodelpropertiesnode.d.ts.map +1 -0
- package/dist/nodes/std-library/data/filterdbmodelsnode.d.ts +95 -0
- package/dist/nodes/std-library/data/filterdbmodelsnode.d.ts.map +1 -0
- package/dist/nodes/std-library/data/modelcrudbase.d.ts +4 -0
- package/dist/nodes/std-library/data/modelcrudbase.d.ts.map +1 -0
- package/dist/nodes/std-library/data/modelnode2.d.ts +114 -0
- package/dist/nodes/std-library/data/modelnode2.d.ts.map +1 -0
- package/dist/nodes/std-library/data/newdbmodelpropertiesnode.d.ts +43 -0
- package/dist/nodes/std-library/data/newdbmodelpropertiesnode.d.ts.map +1 -0
- package/dist/nodes/std-library/data/newmodelnode.d.ts +29 -0
- package/dist/nodes/std-library/data/newmodelnode.d.ts.map +1 -0
- package/dist/nodes/std-library/data/restnode.d.ts +133 -0
- package/dist/nodes/std-library/data/restnode.d.ts.map +1 -0
- package/dist/nodes/std-library/data/setdbmodelpropertiesnode.d.ts +72 -0
- package/dist/nodes/std-library/data/setdbmodelpropertiesnode.d.ts.map +1 -0
- package/dist/nodes/std-library/data/setmodelpropertiesnode.d.ts +25 -0
- package/dist/nodes/std-library/data/setmodelpropertiesnode.d.ts.map +1 -0
- package/dist/nodes/std-library/datetostring.d.ts +59 -0
- package/dist/nodes/std-library/datetostring.d.ts.map +1 -0
- package/dist/nodes/std-library/expression.d.ts +101 -0
- package/dist/nodes/std-library/expression.d.ts.map +1 -0
- package/dist/nodes/std-library/inverter.d.ts +31 -0
- package/dist/nodes/std-library/inverter.d.ts.map +1 -0
- package/dist/nodes/std-library/or.d.ts +27 -0
- package/dist/nodes/std-library/or.d.ts.map +1 -0
- package/dist/nodes/std-library/runtasks.d.ts +117 -0
- package/dist/nodes/std-library/runtasks.d.ts.map +1 -0
- package/dist/nodes/std-library/simplejavascript.d.ts +86 -0
- package/dist/nodes/std-library/simplejavascript.d.ts.map +1 -0
- package/dist/nodes/std-library/stringformat.d.ts +40 -0
- package/dist/nodes/std-library/stringformat.d.ts.map +1 -0
- package/dist/nodes/std-library/stringmapper.d.ts +71 -0
- package/dist/nodes/std-library/stringmapper.d.ts.map +1 -0
- package/dist/nodes/std-library/substring.d.ts +50 -0
- package/dist/nodes/std-library/substring.d.ts.map +1 -0
- package/dist/nodes/std-library/uniqueid.d.ts +28 -0
- package/dist/nodes/std-library/uniqueid.d.ts.map +1 -0
- package/dist/nodes/std-library/user/setuserproperties.d.ts +73 -0
- package/dist/nodes/std-library/user/setuserproperties.d.ts.map +1 -0
- package/dist/nodes/std-library/user/user.d.ts +102 -0
- package/dist/nodes/std-library/user/user.d.ts.map +1 -0
- package/dist/nodes/std-library/variables/boolean.d.ts +47 -0
- package/dist/nodes/std-library/variables/boolean.d.ts.map +1 -0
- package/dist/nodes/std-library/variables/number.d.ts +47 -0
- package/dist/nodes/std-library/variables/number.d.ts.map +1 -0
- package/dist/nodes/std-library/variables/string.d.ts +47 -0
- package/dist/nodes/std-library/variables/string.d.ts.map +1 -0
- package/dist/nodes/std-library/variables/variablebase.d.ts +43 -0
- package/dist/nodes/std-library/variables/variablebase.d.ts.map +1 -0
- package/dist/nodescope.d.ts +29 -0
- package/dist/nodescope.d.ts.map +1 -0
- package/dist/outputproperty.d.ts +30 -0
- package/dist/outputproperty.d.ts.map +1 -0
- package/dist/projectsettings.d.ts +5 -0
- package/dist/projectsettings.d.ts.map +1 -0
- package/dist/runtime.d.ts +65 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/services/services.d.ts +6 -0
- package/dist/services/services.d.ts.map +1 -0
- package/dist/timerscheduler.d.ts +29 -0
- package/dist/timerscheduler.d.ts.map +1 -0
- package/dist/utils.d.ts +8 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/variants.d.ts +11 -0
- package/dist/variants.d.ts.map +1 -0
- package/package.json +19 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
var Runtime=function(exports){"use strict";class CloudFile{constructor({name:t,url:n}){this.name=t,this.url=n}getUrl(){return this.url}getName(){return this.name}toString(){return this.url}}var R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(t,n,o){return Function.prototype.apply.call(t,n,o)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ReflectOwnKeys=function(t){return Object.getOwnPropertyNames(t)};function ProcessEmitWarning(e){console&&console.warn&&console.warn(e)}var NumberIsNaN=Number.isNaN||function(t){return t!==t};function EventEmitter(){EventEmitter.init.call(this)}EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:!0,get(){return defaultMaxListeners},set(e){if(typeof e!="number"||e<0||NumberIsNaN(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");defaultMaxListeners=e}}),EventEmitter.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||NumberIsNaN(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function _getMaxListeners(e){return e._maxListeners===void 0?EventEmitter.defaultMaxListeners:e._maxListeners}EventEmitter.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter.prototype.emit=function(t){for(var n=[],o=1;o<arguments.length;o++)n.push(arguments[o]);var r=t==="error",s=this._events;if(s!==void 0)r=r&&s.error===void 0;else if(!r)return!1;if(r){var a;if(n.length>0&&(a=n[0]),a instanceof Error)throw a;var u=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw u.context=a,u}var l=s[t];if(l===void 0)return!1;if(typeof l=="function")ReflectApply(l,this,n);else for(var d=l.length,p=arrayClone(l,d),o=0;o<d;++o)ReflectApply(p[o],this,n);return!0};function _addListener(e,t,n,o){var r,s,a;if(checkListener(n),s=e._events,s===void 0?(s=e._events=Object.create(null),e._eventsCount=0):(s.newListener!==void 0&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),a=s[t]),a===void 0)a=s[t]=n,++e._eventsCount;else if(typeof a=="function"?a=s[t]=o?[n,a]:[a,n]:o?a.unshift(n):a.push(n),r=_getMaxListeners(e),r>0&&a.length>r&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,ProcessEmitWarning(u)}return e}EventEmitter.prototype.addListener=function(t,n){return _addListener(this,t,n,!1)},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.prependListener=function(t,n){return _addListener(this,t,n,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(e,t,n){var o={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},r=onceWrapper.bind(o);return r.listener=n,o.wrapFn=r,r}EventEmitter.prototype.once=function(t,n){return checkListener(n),this.on(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.prependOnceListener=function(t,n){return checkListener(n),this.prependListener(t,_onceWrap(this,t,n)),this},EventEmitter.prototype.removeListener=function(t,n){var o,r,s,a,u;if(checkListener(n),r=this._events,r===void 0)return this;if(o=r[t],o===void 0)return this;if(o===n||o.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,o.listener||n));else if(typeof o!="function"){for(s=-1,a=o.length-1;a>=0;a--)if(o[a]===n||o[a].listener===n){u=o[a].listener,s=a;break}if(s<0)return this;s===0?o.shift():spliceOne(o,s),o.length===1&&(r[t]=o[0]),r.removeListener!==void 0&&this.emit("removeListener",t,u||n)}return this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.removeAllListeners=function(t){var n,o,r;if(o=this._events,o===void 0)return this;if(o.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):o[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete o[t]),this;if(arguments.length===0){var s=Object.keys(o),a;for(r=0;r<s.length;++r)a=s[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=o[t],typeof n=="function")this.removeListener(t,n);else if(n!==void 0)for(r=n.length-1;r>=0;r--)this.removeListener(t,n[r]);return this};function _listeners(e,t,n){var o=e._events;if(o===void 0)return[];var r=o[t];return r===void 0?[]:typeof r=="function"?n?[r.listener||r]:[r]:n?unwrapListeners(r):arrayClone(r,r.length)}EventEmitter.prototype.listeners=function(t){return _listeners(this,t,!0)},EventEmitter.prototype.rawListeners=function(t){return _listeners(this,t,!1)},EventEmitter.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):listenerCount.call(e,t)},EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}EventEmitter.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(e,t){for(var n=new Array(t),o=0;o<t;++o)n[o]=e[o];return n}function spliceOne(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function unwrapListeners(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function once(e,t){return new Promise(function(n,o){function r(a){e.removeListener(t,s),o(a)}function s(){typeof e.removeListener=="function"&&e.removeListener("error",r),n([].slice.call(arguments))}eventTargetAgnosticAddListener(e,t,s,{once:!0}),t!=="error"&&addErrorHandlerIfEventEmitter(e,r,{once:!0})})}function addErrorHandlerIfEventEmitter(e,t,n){typeof e.on=="function"&&eventTargetAgnosticAddListener(e,"error",t,n)}function eventTargetAgnosticAddListener(e,t,n,o){if(typeof e.on=="function")o.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener=="function")e.addEventListener(t,function r(s){o.once&&e.removeEventListener(t,r),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}function NodeRegister(e){this._constructors={},this.context=e}NodeRegister.prototype.register=function(e){var t=e.metadata.name;this._constructors[t]=e},NodeRegister.prototype.createNode=function(e,t,n){if(this._constructors.hasOwnProperty(e)===!1)throw new Error("Unknown node type with name "+e);return this._constructors[e](this.context,t,n)},NodeRegister.prototype.getNodeMetadata=function(e){if(this._constructors.hasOwnProperty(e)===!1)throw new Error("Unknown node type with name "+e);return this._constructors[e].metadata},NodeRegister.prototype.hasNode=function(e){return this._constructors.hasOwnProperty(e)},NodeRegister.prototype.getInputType=function(e,t){const n=this.getNodeMetadata(e);return n.inputs[t]&&n.inputs[t].type};function Timer(e,t){this.duration=t.duration||0,this._isRunning=!1,this._hasCalledOnStart=!1,this.scheduler=e,this.repeatCount=1,this.delay=0;for(var n in t)this[n]=t[n]}Timer.prototype.start=function(){return this._isRunning&&this.stop(),this.scheduler.scheduleTimer(this),this},Timer.prototype.stop=function(){this.scheduler.stopTimer(this),this._hasCalledOnStart=!1,this._isRunning=!1,this._wasStopped=!0},Timer.prototype.isRunning=function(){return this._isRunning},Timer.prototype.durationLeft=function(){return this._durationLeft};function TimerScheduler(e){this.requestFrame=e,this.runningTimers=[],this.newTimers=[]}TimerScheduler.prototype.createTimer=function(e){return new Timer(this,e)},TimerScheduler.prototype.scheduleTimer=function(e){this.newTimers.indexOf(e)===-1&&(e.repeatCount===0&&(e.repeatCount=1e5),this.newTimers.push(e),this.requestFrame())},TimerScheduler.prototype.stopTimer=function(e){var t;e._isRunning?(t=this.runningTimers.indexOf(e),t!==-1&&this.runningTimers.splice(t,1),e.onStop&&!e._wasStopped&&e.onStop()):(t=this.newTimers.indexOf(e),t!==-1&&this.newTimers.splice(t,1))},TimerScheduler.prototype.runTimers=function(e){var t=[],n=[],o=[],r,s=this.runningTimers.length,a;for(r=0;r<s;++r)o[r]=this.runningTimers[r];for(r=0;r<s;++r)if(a=o[r],a&&e>=a._start){a._hasCalledOnStart===!1&&a.onStart&&(a.onStart(),a._hasCalledOnStart=!0);var u;a.duration>0?u=(e-a._start)/(a.duration*a.repeatCount):u=1,a._durationLeft=a.duration*(1-u);var l=u*a.repeatCount-Math.floor(u*a.repeatCount);u>=1&&(l=1),a.onRunning&&a.onRunning(l),u<1&&a._isRunning?t.push(a):a._wasStopped||n.push(a)}else t.push(a);for(this.runningTimers=t,r=0;r<n.length;++r)n[r]._isRunning=!1,n[r]._hasCalledOnStart=!1,n[r].onFinish&&n[r].onFinish();if(this.newTimers.length>0){for(r=0;r<this.newTimers.length;++r)a=this.newTimers[r],a._start=e+a.delay,a._isRunning=!0,a._wasStopped=!1,this.runningTimers.push(a),a.delay===0&&(a.onStart&&(a.onStart(),a._hasCalledOnStart=!0),a.onRunning&&a.onRunning(0));this.newTimers.length=0}},TimerScheduler.prototype.hasPendingTimers=function(){return this.runningTimers.length>0||this.newTimers.length>0};class Variants{constructor({graphModel:t,getNodeScope:n}){this.getNodeScope=n,t&&(this.graphModel=t,t.on("variantUpdated",o=>this.onVariantUpdated(o)))}getVariant(t,n){if(this.graphModel)return this.graphModel.getVariant(t,n)}onVariantUpdated(t){const n=this.getNodeScope();if(!n)return;const r=n.getNodesWithTypeRecursive(t.typename).filter(s=>s.variant?s.variant.name===t.name:s.model&&s.model.variant===t.name);for(const s of r)s.setVariant(t)}}function OutputProperty(e){if(!e.owner)throw new Error("Owner must be set");this.getter=e.getter,this.connections=[],this.owner=e.owner,this.name=e.name,this.onFirstConnectionAdded=e.onFirstConnectionAdded,this.onLastConnectionRemoved=e.onLastConnectionRemoved,this._id=void 0}Object.defineProperties(OutputProperty.prototype,{value:{get(){return this.getter.call(this.owner)}},id:{get(){return this._id||(this._id=this.owner.id+this.name),this._id}},registerConnection:{value(e,t){this.connections.push({node:e,inputPortName:t}),this.connections.length===1&&this.onFirstConnectionAdded&&this.onFirstConnectionAdded.call(this.owner)}},deregisterConnection:{value(e,t){for(var n=0;n<this.connections.length;n++){var o=this.connections[n];if(o.node===e&&o.inputPortName===t){this.connections.splice(n,1);break}}this.connections.length===0&&this.onLastConnectionRemoved&&this.onLastConnectionRemoved.call(this.owner)}},flagDependeesDirty:{value(e){for(var t=0,n=this.connections.length;t<n;t++)this.connections[t].node.flagDirty()}},sendValue:{value(e){this._lastUpdateIteration!==this.owner._updatedAtIteration?(this._lastUpdateIteration=this.owner._updatedAtIteration,this.valuesSendThisIteration=0):this.valuesSendThisIteration++,this.valuesSendThisIteration>500&&(this.owner._cyclicLoop=!0);for(var t=0,n=this.connections.length;t<n;t++){var o=this.connections[t];o.node._setValueFromConnection(o.inputPortName,e)}}},hasConnections:{value(){return this.connections.length>0}}});function Node(e,t){this.id=t,this.context=e,this._dirty=!1,this._inputs={},this._inputValues={},this._outputs={},this._inputConnections={},this._outputList=[],this._isUpdating=!1,this._inputValuesQueue={},this._afterInputsHaveUpdatedCallbacks=[],this._internal={},this._signalsSentThisUpdate={},this._deleted=!1,this._deleteListeners=[],this._isFirstUpdate=!0,this._valuesFromConnections={},this.updateOnDirtyFlagging=!0}Node.prototype.getInputValue=function(e){return this._inputValues[e]},Node.prototype.registerInput=function(e,t){if(this.hasInput(e))throw new Error("Input property "+e+" already registered");if(this._inputs[e]=t,t.type&&t.type.units){const n=t.type.defaultUnit||t.type.units[0];this._inputValues[e]={value:t.default,type:n}}else t.hasOwnProperty("default")&&(this._inputValues[e]=t.default)},Node.prototype.deregisterInput=function(e){if(this.hasInput(e)===!1)throw new Error("Input property "+e+" doesn't exist");delete this._inputs[e],delete this._inputValues[e]},Node.prototype.registerInputs=function(e){for(const t in e)this.registerInput(t,e[t])},Node.prototype.getInput=function(e){if(this.hasInput(e)===!1){console.log("Node "+this.name+": Invalid input property "+e);return}return this._inputs[e]},Node.prototype.hasInput=function(e){return e in this._inputs},Node.prototype.registerInputIfNeeded=function(){},Node.prototype.setInputValue=function(name,value){const input=this.getInput(name);if(!input){console.log("node doesn't have input",name);return}const currentInputValue=this._inputValues[name];if(isNaN(value)===!1&¤tInputValue&¤tInputValue.unit){const e=Object.assign({},currentInputValue);e.value=value,value=e}if(this._inputValues[name]=value,input.type==="color"&&this.context&&this.context.styles)value=this.context.styles.resolveColor(value);else if(input.type==="array"&&typeof value=="string")try{value=eval(value),this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+name)}catch(e){value=[],console.log(e),this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+name,{showGlobally:!0,message:"Invalid array<br>"+e.toString()})}input.set.call(this,value)},Node.prototype.hasOutput=function(e){return e in this._outputs},Node.prototype.registerOutput=function(e,t){if(this.hasOutput(e))throw new Error("Output property "+e+" already registered");const n=new OutputProperty({owner:this,getter:t.get||t.getter,name:e,onFirstConnectionAdded:t.onFirstConnectionAdded,onLastConnectionRemoved:t.onLastConnectionRemoved});this._outputs[e]=n,this._outputList.push(n)},Node.prototype.deregisterOutput=function(e){if(this.hasOutput(e)===!1)throw new Error("Output property "+e+" isn't registered");const t=this._outputs[e];if(t.hasConnections())throw new Error("Output property "+e+" has connections and can't be removed");delete this._outputs[e];var n=this._outputList.indexOf(t);this._outputList.splice(n,1)},Node.prototype.registerOutputs=function(e){for(var t in e)this.registerOutput(t,e[t])},Node.prototype.registerOutputIfNeeded=function(){},Node.prototype.getOutput=function(e){if(this.hasOutput(e)===!1)throw new Error("Node "+this.name+" doesn't have a port named "+e);return this._outputs[e]},Node.prototype.connectInput=function(e,t,n){if(this.hasInput(e)===!1)throw new Error("Invalid connection, input doesn't exist. Trying to connect from "+t.name+" output "+n+" to "+this.name+" input "+e);var o=t.getOutput(n);if(o.registerConnection(this,e),this._inputConnections[e]||(this._inputConnections[e]=[]),this._inputConnections[e].push(o),t._signalsSentThisUpdate[n])this._setValueFromConnection(e,!0),this._setValueFromConnection(e,!1);else{var r=o.value;r!==void 0&&(this._setValueFromConnection(e,r),this.context&&this.context.connectionSentValue(o,o.value))}this.flagDirty()},Node.prototype.removeInputConnection=function(e,t,n){if(!this._inputConnections[e])throw new Error("Node removeInputConnection: Input doesn't exist");const o=this._inputConnections[e];for(let r=0;r<o.length;r++){const s=o[r];if(s.owner.id===t&&s.name===n){o.splice(r,1),s.owner.getOutput(n).deregisterConnection(this,e);break}}o.length===0&&delete this._valuesFromConnections[e]},Node.prototype.isInputConnected=function(e){return this._inputConnections.hasOwnProperty(e)?this._inputConnections[e].some(t=>t.owner.name!=="Component Inputs"?!0:t.owner.nodeScope.componentOwner.isInputConnected(t.name)):!1},Node.prototype.update=function(){if(this._isUpdating||this._dirty===!1)return;this._updatedAtIteration!==this.context.updateIteration&&(this._updatedAtIteration=this.context.updateIteration,this._updateIteration=0,this._cyclicLoop&&(this._cyclicLoop=!1)),this._isUpdating=!0;const e=100;try{for(;this._dirty&&!this._cyclicLoop;){this._updateDependencies(),this._dirty=!1;const t=Object.keys(this._inputValuesQueue);let n=!0;for(;n&&!this._cyclicLoop;){n=!1;for(let r=0;r<t.length;r++){const s=t[r],a=this._inputValuesQueue[s];a.length>0&&(this.setInputValue(s,a.shift()),a.length>0&&(n=!0))}const o=this._afterInputsHaveUpdatedCallbacks;this._afterInputsHaveUpdatedCallbacks=[];for(let r=0;r<o.length;r++)o[r].call(this)}this._updateIteration++,this._updateIteration>=e&&(this._cyclicLoop=!0)}}catch(t){throw this._isUpdating=!1,t}this._cyclicLoop&&(this.context.scheduleNextFrame(()=>{this.context.nodeIsDirty(this)}),this.context.editorConnection&&!this._cyclicWarningSent&&this.context.isWarningTypeEnabled("cyclicLoops")&&(this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"cyclic-loop",{showGlobally:!0,message:"Cyclic loop detected"}),this._cyclicWarningSent=!0,console.log("cycle detected",{id:this.id,name:this.name,component:this.nodeScope.componentOwner.name}))),this._isFirstUpdate=!1,this._isUpdating=!1},Node.prototype._updateDependencies=function(){for(var e in this._inputConnections)for(var t=this._inputConnections[e],n=0;n<t.length;++n)t[n].owner.update()},Node.prototype.flagDirty=function(){this._dirty||(this._dirty=!0,this.updateOnDirtyFlagging&&this._performDirtyUpdate())},Node.prototype._performDirtyUpdate=function(){this.context&&this.context.nodeIsDirty(this);for(var e=0;e<this._outputList.length;++e)this._outputList[e].flagDependeesDirty()},Node.prototype.sendValue=function(e,t){if(this.hasOutput(e)===!1){console.log("Error: Node",this.name,"doesn't have a output named",e);return}if(t===void 0)return;const n=this.getOutput(e);n.sendValue(t),this.context&&this.context.connectionSentValue(n,t)},Node.prototype.flagOutputDirty=function(e){const t=this.getOutput(e);this.sendValue(e,t.value)},Node.prototype.flagAllOutputsDirty=function(){for(const e of this._outputList)this.sendValue(e.name,e.value)},Node.prototype.sendSignalOnOutput=function(e){if(this.hasOutput(e)===!1){console.log("Error: Node",this.name,"doesn't have a output named",e);return}const t=this.getOutput(e);t.sendValue(!0),t.sendValue(!1),this._signalsSentThisUpdate[e]=!0,this.scheduleAfterInputsHaveUpdated(function(){this._signalsSentThisUpdate[e]=!1}),this.context&&this.context.connectionSentSignal(t)},Node.prototype._setValueFromConnection=function(e,t){this._valuesFromConnections[e]=t,this.queueInput(e,t)},Node.prototype._hasInputBeenSetFromAConnection=function(e){return this._valuesFromConnections.hasOwnProperty(e)},Node.prototype.queueInput=function(e,t){if(this._inputValuesQueue[e]||(this._inputValuesQueue[e]=[]),this._isFirstUpdate){const n=this._inputValuesQueue[e][0];n===!0||(n instanceof Object&&n.unit&&!(t instanceof Object)&&(t={value:t,unit:n.unit}),this._inputValuesQueue[e].length=0)}this._inputValuesQueue[e].push(t),this.flagDirty()},Node.prototype.scheduleAfterInputsHaveUpdated=function(e){this._afterInputsHaveUpdatedCallbacks.push(e),this.flagDirty()},Node.prototype.setNodeModel=function(e){this.model=e,e.on("parameterUpdated",this._onNodeModelParameterUpdated,this),e.on("variantUpdated",this._onNodeModelVariantUpdated,this),e.on("inputPortRemoved",t=>{this.hasInput(t.name)&&this.deregisterInput(t.name)},this),e.on("outputPortRemoved",t=>{this.hasOutput(t.name)&&this.deregisterOutput(t.name)},this)},Node.prototype.addDeleteListener=function(e){this._deleteListeners.push(e)},Node.prototype._onNodeDeleted=function(){this.model&&(this.model.removeListenersWithRef(this),this.model=void 0),this._deleted=!0;for(const e of this._deleteListeners)e.call(this)},Node.prototype._onNodeModelParameterUpdated=function(e){if(this.registerInputIfNeeded(e.name),e.value!==void 0)if(e.state){if(!this._getVisualStates){console.log("Node has nos visual states, but got a parameter for state",e.state);return}this._getVisualStates().indexOf(e.state)!==-1&&this.queueInput(e.name,e.value)}else this.queueInput(e.name,e.value);else{let t;const n=this.variant;e.state?n&&n.stateParameters.hasOwnProperty(e.state)&&n.stateParameters[e.state].hasOwnProperty(e.name)?t=n.stateParameters[e.state][e.name]:this.model.parameters.hasOwnProperty(e.name)?t=this.model.parameters[e.name]:n&&n.parameters.hasOwnProperty(e.name)&&(t=n.parameters[e.name]):n&&n.parameters.hasOwnProperty(e.name)&&(t=n.parameters[e.name]),t===void 0&&(t=this.context.getDefaultValueForInput(this.model.type,e.name),this._resetReactVirtualDOM&&this._resetReactVirtualDOM()),this.queueInput(e.name,t)}},Node.prototype._onNodeModelVariantUpdated=function(e){this.setVariant(e)};function guid(){function e(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function NodeScope(e,t){this.context=e,this.nodes={},this.componentOwner=t,this.componentInstanceChildren={}}function verifyData(e,t){t.forEach(function(n){if(!e[n])throw new Error("Missing "+n)})}NodeScope.prototype.addConnection=function(e){try{verifyData(e,["sourceId","sourcePort","targetId","targetPort"])}catch(o){throw new Error("Error in connection: "+o.message)}try{var t=this.getNodeWithId(e.sourceId),n=this.getNodeWithId(e.targetId);n.registerInputIfNeeded(e.targetPort),t.registerOutputIfNeeded(e.sourcePort),n.connectInput(e.targetPort,t,e.sourcePort)}catch(o){console.error(o.message)}},NodeScope.prototype.setNodeParameters=function(e,t){const n=this.context.variants.getVariant(t.type,t.variant);if(n)e.setVariant(n);else{const s=t.parameters;var o=Object.keys(s);if(this.context.nodeRegister.hasNode(e.name)){var r=this.context.nodeRegister.getNodeMetadata(e.name);o.sort(function(a,u){var l=r.inputs[a],d=r.inputs[u];return(d?d.inputPriority:0)-(l?l.inputPriority:0)})}o.forEach(a=>{e.registerInputIfNeeded(a),e.hasInput(a)!==!1&&e.queueInput(a,s[a])})}},NodeScope.prototype.createNodeFromModel=async function(e,t){if(e.type==="Component Children"){if(e.parent){var n=this.getNodeWithId(e.parent.id);this.componentOwner.setChildRoot(n)}return}var o;try{o=await this.createNode(e.type,e.id),o.updateOnDirtyFlagging=t!==!1,o.setNodeModel(e)}catch(r){console.error(r.message),this.context.editorConnection&&this.context.isWarningTypeEnabled("nodescope")&&this.context.editorConnection.sendWarning(this.componentOwner.name,e.id,"nodelibrary-unknown-node",{message:r.message,showGlobally:!0});return}return e.variant&&o.setVariant&&o.setVariant(e.variant),this.setNodeParameters(o,e),e.parent&&this.insertNodeInTree(o,e),o},NodeScope.prototype.insertNodeInTree=function(e,t){var n=this.getNodeWithId(t.parent.id),o=t.parent.children.indexOf(t);if(!n.addChild)throw new Error("Node "+n.id+" of type "+n.constructor.name+" can't have children");n.addChild(e,o)},NodeScope.prototype.getNodeWithId=function(e){if(this.nodes.hasOwnProperty(e)===!1)throw new Error("Unknown node id "+e);return this.nodes[e]},NodeScope.prototype.hasNodeWithId=function(e){return this.nodes.hasOwnProperty(e)},NodeScope.prototype.createPrimitiveNode=function(e,t,n){if(t||(t=guid()),this.nodes.hasOwnProperty(t))throw Error("duplicate id "+t);const o=this.context.nodeRegister.createNode(e,t,this);if(n)for(const r in n)o[r]=n[r];return this.nodes[t]=o,o},NodeScope.prototype.createNode=async function(e,t,n){if(t||(t=guid()),this.nodes.hasOwnProperty(t))throw Error("duplicate id "+t);let o;if(this.context.nodeRegister.hasNode(e)){if(o=this.context.nodeRegister.createNode(e,t,this),n)for(const r in n)o[r]=n[r]}else o=await this.context.createComponentInstanceNode(e,t,this,n),this.componentInstanceChildren[t]=o;return this.nodes[t]=o,o},NodeScope.prototype.getNodesWithIdRecursive=function(e){function t(o,r,s){o.nodes.hasOwnProperty(r)&&s.push(o.nodes[r]);var a=Object.keys(o.nodes).filter(function(u){return o.nodes[u]instanceof ComponentInstanceNode});a.forEach(function(u){t(o.nodes[u].nodeScope,r,s)})}var n=[];return t(this,e,n),n},NodeScope.prototype.getNodesWithType=function(e){var t=this,n=Object.keys(this.nodes).filter(function(o){return t.nodes[o].name===e});return n.map(function(o){return t.nodes[o]})},NodeScope.prototype.getNodesWithTypeRecursive=function(e){var t=this;function n(){o=o.concat(t.getNodesWithType(e));var r=Object.keys(t.nodes).filter(function(s){return t.nodes[s]instanceof ComponentInstanceNode});r.forEach(function(s){var a=t.nodes[s].nodeScope.getNodesWithTypeRecursive(e);o=o.concat(a)})}var o=[];return n(),o},NodeScope.prototype.getAllNodesRecursive=function(){let e=[];return(()=>{e=e.concat(Object.values(this.nodes));var n=Object.keys(this.nodes).filter(o=>this.nodes[o]instanceof ComponentInstanceNode);n.forEach(o=>{var r=this.nodes[o].nodeScope.getAllNodesRecursive();e=e.concat(r)})})(),e},NodeScope.prototype.getAllNodesWithVariantRecursive=function(e){return this.getAllNodesRecursive().filter(n=>n.variant===e)},NodeScope.prototype.onNodeModelRemoved=function(e){var t=this.getNodeWithId(e.id);if(e.parent){var n=this.getNodeWithId(e.parent.id);n.removeChild(t)}t._onNodeDeleted(),delete this.nodes[t.id],delete this.componentInstanceChildren[t.id]},NodeScope.prototype.removeConnection=function(e){var t=this.getNodeWithId(e.targetId);t.removeInputConnection(e.targetPort,e.sourceId,e.sourcePort)},NodeScope.prototype.setComponentModel=async function(e){this.componentModel=e;const t=[];for(const o of e.getAllNodes()){const r=await this.createNodeFromModel(o,!1);r&&t.push(r)}e.getAllConnections().forEach(o=>this.addConnection(o)),t.forEach(o=>o.updateOnDirtyFlagging=!0),t.forEach(o=>{o._dirty&&o._performDirtyUpdate()}),e.on("connectionAdded",o=>this.addConnection(o),this),e.on("connectionRemoved",this.removeConnection,this),e.on("nodeAdded",this.createNodeFromModel,this);var n=this;e.on("nodeParentWillBeRemoved",function(o){if(o.type==="Component Children"){o.parent&&this.componentOwner.setChildRoot(null);return}const r=n.getNodeWithId(o.id);r.parent&&r.parent.removeChild(r)},this),e.on("nodeParentUpdated",function(o){if(o.type==="Component Children"){var r=this.getNodeWithId(o.parent.id);this.componentOwner.setChildRoot(r)}else{var s=n.getNodeWithId(o.id);n.insertNodeInTree(s,o)}},this),e.on("nodeRemoved",function(o){o.type!=="Component Children"&&n.onNodeModelRemoved(o)},this);for(const o in this.nodes){const r=this.nodes[o];r.nodeScopeDidInitialize&&r.nodeScopeDidInitialize()}},NodeScope.prototype.reset=function(){this.componentModel&&(this.componentModel.removeListenersWithRef(this),this.componentModel=void 0),Object.keys(this.nodes).forEach(e=>{this.nodes.hasOwnProperty(e)&&this.deleteNode(this.nodes[e])})},NodeScope.prototype.deleteNode=function(e){if(this.nodes.hasOwnProperty(e.id)===!1){console.error("Node doesn't belong to this scope",e.id,e.name);return}if(e.parent&&e.parent.removeChild(e),e.getChildren&&e.getChildren().forEach(t=>{e.removeChild(t),(t.parentNodeScope||t.nodeScope).deleteNode(t)}),this.componentModel){const t=this.componentModel.getConnectionsFrom(e.id),n=this.componentModel.getConnectionsTo(e.id);t.concat(n).forEach(o=>{this.nodes.hasOwnProperty(o.targetId)&&this.nodes.hasOwnProperty(o.sourceId)&&this.removeConnection(o)})}e._onNodeDeleted(),delete this.nodes[e.id],delete this.componentInstanceChildren[e.id]},NodeScope.prototype.sendEventFromThisScope=function(e,t,n,o,r){if(o)for(var s=this.getNodesWithType("Event Receiver").filter(function(m){return m.getChannelName()===e}),a=0;a<s.length;a++){var u=s[a].handleEvent(t);if(u)return!0}if(n==="parent"&&this.componentOwner.parentNodeScope){const m=this.componentOwner.parent?this.componentOwner.parent.nodeScope:this.componentOwner.parentNodeScope;if(!m)return;m.sendEventFromThisScope(e,t,n,!0)}else if(n==="children"){var l=this.nodes;for(var d in l){var p=l[d].children;p&&p.forEach(m=>{if(m.name&&this.context.hasComponentModelWithName(m.name)){var y=m.nodeScope.sendEventFromThisScope(e,t,n,!0);if(y)return!0}})}}else if(n==="siblings"){let m;if(this.componentOwner.parent?m=this.componentOwner.parent.nodeScope:m=this.componentOwner.parentNodeScope,!m)return;var l=m.nodes;for(var d in l){var p=l[d].children;if(p){var f=p.filter(S=>S.name&&this.context.hasComponentModelWithName(S.name)&&S.nodeScope!==this);f.forEach(S=>{var C=S.nodeScope.sendEventFromThisScope(e,t,null,!0);if(C)return!0})}}}return!1};let componentIdCounter=0;function ComponentInstanceNode(e,t,n){Node.call(this,e,t),this.nodeScope=new NodeScope(e,this),this.parentNodeScope=n,this._internal.childRoot=null,this._internal.componentOutputValues={},this._internal.componentOutputs=[],this._internal.componentInputs=[],this._internal.inputValues={},this._internal.roots=[],this._internal.instanceId="__$ndl_componentInstaceId"+componentIdCounter,this.nodeScope.modelScope=n?n.modelScope:void 0,componentIdCounter++}ComponentInstanceNode.prototype=Object.create(Node.prototype,{setComponentModel:{value:async function(e){this.componentModel=e;var t=this;await this.nodeScope.setComponentModel(e),this._internal.componentInputs=this.nodeScope.getNodesWithType("Component Inputs"),this._internal.componentOutputs=this.nodeScope.getNodesWithType("Component Outputs"),Object.values(e.getInputPorts()).forEach(this.registerComponentInputPort.bind(this)),Object.values(e.getOutputPorts()).forEach(this.registerComponentOutputPort.bind(this));const n=e.roots||[];this._internal.roots=n.map(o=>this.nodeScope.getNodeWithId(o)),e.on("rootAdded",o=>{this._internal.roots.push(this.nodeScope.getNodeWithId(o)),this.forceUpdate()},this),e.on("rootRemoved",function(o){const r=this._internal.roots.findIndex(s=>s.id===o);r!==-1&&this._internal.roots.splice(r,1),this.forceUpdate()},this),e.on("inputPortAdded",this.registerComponentInputPort.bind(this),this),e.on("outputPortAdded",this.registerComponentOutputPort.bind(this),this),e.on("inputPortRemoved",function(o){t.hasInput(o.name)&&t.deregisterInput(o.name)},this),e.on("outputPortRemoved",function(o){this.hasOutput(o.name)&&t.deregisterOutput(o.name)},this),e.on("nodeAdded",function(o){o.type==="Component Inputs"?t._internal.componentInputs.push(t.nodeScope.getNodeWithId(o.id)):o.type==="Component Outputs"&&t._internal.componentOutputs.push(t.nodeScope.getNodeWithId(o.id))},this),e.on("nodeRemoved",function(o){function r(s,a){return s.filter(u=>u.id!==a)}o.type==="Component Inputs"?t._internal.componentInputs=r(t._internal.componentInputs,o.id):o.type==="Component Outputs"&&(t._internal.componentOutputs=r(t._internal.componentOutputs,o.id))},this),e.on("renamed",function(o){t.name=o.newName},this)}},_onNodeDeleted:{value(){this.componentModel&&(this.componentModel.removeListenersWithRef(this),this.componentModel=void 0),this.nodeScope.reset(),Node.prototype._onNodeDeleted.call(this)}},registerComponentInputPort:{value(e){this.registerInput(e.name,{set(t){this._internal.inputValues[e.name]=t,this._internal.componentInputs.forEach(function(n){n.registerOutputIfNeeded(e.name),n.flagOutputDirty(e.name)})}})}},registerComponentOutputPort:{value(e){this.registerOutput(e.name,{getter(){return this._internal.componentOutputValues[e.name]}})}},setOutputFromComponentOutput:{value(e,t){this.hasOutput(e)!==!1&&(this._internal.creatorCallbacks&&this._internal.creatorCallbacks.onOutputChanged&&this._internal.creatorCallbacks.onOutputChanged(e,t,this._internal.componentOutputValues[e]),this._internal.componentOutputValues[e]=t,this.flagOutputDirty(e))}},setChildRoot:{value(e){const t=this._internal.childRoot,n=e;if(this._internal.childRoot=n,this.model&&this.model.children){const o=this.parentNodeScope,r=this.model.children.filter(s=>s.type!=="Component Children").map(s=>o.getNodeWithId(s.id));if(t)for(let s=0;s<r.length;s++)t.isChild(r[s])&&t.removeChild(r[s]);if(n)for(let s=0;s<r.length;s++){const a=r[s],u=a.model.parent.children.indexOf(a.model);this.addChild(a,u)}}}},getChildRootIndex:{value(){if(!this._internal.childRoot||!this._internal.childRoot.model||!this._internal.childRoot.model.children)return 0;for(var e=this._internal.childRoot.model.children,t=0;t<e.length;t++)if(e[t].type==="Component Children")return t;return 0}},getChildRoot:{value(){return this._internal.childRoot?this._internal.childRoot:null}},getRoots:{value(){return this._internal.roots}},triggerDidMount:{value(){this._internal.roots.forEach(e=>{e.triggerDidMount&&e.triggerDidMount()})}},render:{value(){return this._internal.roots.length===0?null:this._internal.roots[0].render()}},setChildIndex:{value(e){this.getRoots().forEach(t=>t.setChildIndex&&t.setChildIndex(e))}},addChild:{value(e,t){this.getChildRoot().addChild(e,t+this.getChildRootIndex())}},removeChild:{value(e){this.getChildRoot().removeChild(e)}},getChildren:{value(e){const t=this.getChildRoot();return t?t.getChildren():[]}},isChild:{value(e){return this.getChildRoot()?this.getChildRoot().isChild(e):!1}},contains:{value(e){return this.getRoots().some(t=>t.contains&&t.contains(e))}},_performDirtyUpdate:{value(){Node.prototype._performDirtyUpdate.call(this);for(var e=this._internal.componentInputs,t=0,n=e.length;t<n;t++)e[t].flagDirty();this._internal.componentOutputs.forEach(function(o){o.flagDirty()})}},getRef:{value(){const e=this._internal.roots[0];return e?e.getRef():void 0}},update:{value(){Node.prototype.update.call(this),this._internal.componentOutputs.forEach(function(e){e.update()})}},forceUpdate:{value(){this.parent&&(this.parent.cachedChildren=void 0,this.parent.forceUpdate())}},getInstanceId:{value(){return this._internal.instanceId}}}),ComponentInstanceNode.prototype.constructor=ComponentInstanceNode;function NodeContext(e){e=e||{},e.runningInEditor=e.hasOwnProperty("runningInEditor")?e.runningInEditor:!1,this._dirtyNodes=[],this.callbacksAfterUpdate=[],this.graphModel=e.graphModel,this.platform=e.platform,this.eventEmitter=new EventEmitter,this.eventEmitter.setMaxListeners(1e6),this.eventSenderEmitter=new EventEmitter,this.eventSenderEmitter.setMaxListeners(1e6),this.globalValues={},this.globalsEventEmitter=new EventEmitter,this.globalsEventEmitter.setMaxListeners(1e6),this.runningInEditor=e.runningInEditor,this.currentFrameTime=0,this.frameNumber=0,this.updateIteration=0,this.nodeRegister=new NodeRegister(this),this.timerScheduler=new TimerScheduler(this.scheduleUpdate.bind(this)),this.componentModels={},this.debugInspectorsEnabled=!1,this.connectionsToPulse={},this.connectionsToPulseChanged=!1,this.debugInspectors={},this.connectionPulsingCallbackScheduled=!1,this.editorConnection=e.editorConnection,this.rootComponent=void 0,this._outputHistory={},this._signalHistory={},this.warningTypes={},this.bundleFetchesInFlight=new Map,this.variants=new Variants({graphModel:this.graphModel,getNodeScope:()=>this.rootComponent?this.rootComponent.nodeScope:null}),this.editorConnection&&(this.editorConnection.on("debugInspectorsUpdated",t=>{this.onDebugInspectorsUpdated(t)}),this.editorConnection.on("getConnectionValue",({clientId:t,connectionId:n})=>{if(this.editorConnection.clientId!==t)return;const o=this._outputHistory[n];this.editorConnection.sendConnectionValue(n,o?o.value:void 0)}))}NodeContext.prototype.setRootComponent=function(e){this.rootComponent=e},NodeContext.prototype.getCurrentTime=function(){return this.platform.getCurrentTime()},NodeContext.prototype.onDebugInspectorsUpdated=function(e){this.debugInspectorsEnabled&&(e=e.map(t=>{if(t.type==="connection"){const n=t.connection;t.id=n.fromId+n.fromProperty}else t.type==="node"&&(t.id=t.nodeId);return t}),this.debugInspectors={},e.forEach(t=>this.debugInspectors[t.id]=t),this.sendDebugInspectorValues())},NodeContext.prototype.updateDirtyNodes=function(){var e,t,n=!0,o=0;for(this.updateIteration++,this.isUpdating=!0;n&&o<10;){var r=this._dirtyNodes;for(this._dirtyNodes=[],e=0,t=r.length;e<t;++e)try{r[e]._deleted||r[e].update()}catch(a){console.error(a,a.stack)}var s=this.callbacksAfterUpdate;for(this.callbacksAfterUpdate=[],e=0,t=s.length;e<t;e++)try{s[e]()}catch(a){console.error(a)}n=this.callbacksAfterUpdate.length>0||this._dirtyNodes.length>0,o++}this.isUpdating=!1},NodeContext.prototype.update=function(){this.frameNumber++,this.updateDirtyNodes(),this.timerScheduler.hasPendingTimers()&&(this.scheduleUpdate(),this.timerScheduler.runTimers(this.currentFrameTime)),this.debugInspectorsEnabled&&this.sendDebugInspectorValues()},NodeContext.prototype.reset=function(){this.eventEmitter.emit("applicationDataReloaded");var e=this.eventEmitter;["frameStart","frameEnd"].forEach(function(t){e.removeAllListeners(t)}),this.globalValues={},this._dirtyNodes.length=0,this.callbacksAfterUpdate.length=0,this.timerScheduler.runningTimers=[],this.timerScheduler.newTimers=[],this.rootComponent=void 0,this.clearDebugInspectors()},NodeContext.prototype.nodeIsDirty=function(e){this._dirtyNodes.push(e),this.scheduleUpdate()},NodeContext.prototype.scheduleUpdate=function(){this.eventEmitter.emit("scheduleUpdate")},NodeContext.prototype.scheduleAfterUpdate=function(e){this.callbacksAfterUpdate.push(e),this.scheduleUpdate()},NodeContext.prototype.scheduleNextFrame=function(e){this.eventEmitter.once("frameStart",e),this.scheduleUpdate()},NodeContext.prototype.setGlobalValue=function(e,t){this.globalValues[e]=t,this.globalsEventEmitter.emit(e)},NodeContext.prototype.getGlobalValue=function(e){return this.globalValues[e]},NodeContext.prototype.registerComponentModel=function(e){if(this.componentModels.hasOwnProperty(e.name))throw new Error("Duplicate component name "+e.name);this.componentModels[e.name]=e;var t=this;e.on("renamed",function(n){delete t.componentModels[n.oldName],t.componentModels[n.newName]=e},this)},NodeContext.prototype.deregisterComponentModel=function(e){this.componentModels.hasOwnProperty(e.name)&&(this.componentModels[e.name].removeListenersWithRef(this),delete this.componentModels[e.name])},NodeContext.prototype.fetchComponentBundle=async function(e){const t=async n=>{let r=`${Noodl.Env.BaseUrl||"/"}noodl_bundles/${n}.json`;const s=await fetch(r);if(s.status===404)throw new Error("Component not found "+n);const a=await s.json();for(const u of a)this.graphModel.hasComponentWithName(u.name)===!1&&await this.graphModel.importComponentFromEditorData(u)};if(this.bundleFetchesInFlight.has(e))await this.bundleFetchesInFlight.get(e);else{const n=t(e);this.bundleFetchesInFlight.set(e,n),await n}},NodeContext.prototype.getComponentModel=async function(e){if(!e)throw new Error("Component instance must have a name");if(this.componentModels.hasOwnProperty(e)===!1){const t=this.graphModel.getBundleContainingComponent(e);if(!t)throw new Error("Can't find component model for "+e);for(const n of this.graphModel.getBundleDependencies(t))this.fetchComponentBundle(n);await this.fetchComponentBundle(t)}return this.componentModels[e]},NodeContext.prototype.hasComponentModelWithName=function(e){return this.componentModels.hasOwnProperty(e)},NodeContext.prototype.createComponentInstanceNode=async function(e,t,n,o){var r=new ComponentInstanceNode(this,t,n);r.name=e;for(const a in o)r[a]=o[a];const s=await this.getComponentModel(e);return await r.setComponentModel(s),r},NodeContext.prototype._formatConnectionValue=function(e){if(typeof e=="object"&&e&&e.constructor&&e.constructor.name==="Node")e="<Node> "+e.name;else if(typeof e=="object"&&typeof window<"u"&&e instanceof HTMLElement)e=`DOM Node <${e.tagName}>`;else{if(typeof e=="string"&&!e.startsWith("[Signal]"))return'"'+e+'"';if(Number.isNaN(e))return"NaN"}return e},NodeContext.prototype.connectionSentValue=function(e,t){if(!this.editorConnection||!this.editorConnection.isConnected()||!this.debugInspectorsEnabled)return;const n=this.getCurrentTime();if(this._outputHistory[e.id]={value:t,timestamp:n},this.connectionsToPulse.hasOwnProperty(e.id)){this.connectionsToPulse[e.id].timestamp=n;return}const o=[];e.connections.forEach(r=>{o.push(e.owner.id+e.name+r.node.id+r.inputPortName)}),this.connectionsToPulse[e.id]={timestamp:n,connections:o},this.connectionsToPulseChanged=!0,this.connectionPulsingCallbackScheduled===!1&&(this.connectionPulsingCallbackScheduled=!0,setTimeout(this.clearOldConnectionPulsing.bind(this),100))},NodeContext.prototype.connectionSentSignal=function(e){const t=e.id;this._signalHistory.hasOwnProperty(t)||(this._signalHistory[t]={count:0}),this._signalHistory[t].count++,this.connectionSentValue(e,"[Signal] Trigger count "+this._signalHistory[t].count)},NodeContext.prototype.clearDebugInspectors=function(){this.debugInspectors={},this.connectionsToPulse={},this.editorConnection.sendPulsingConnections(this.connectionsToPulse)},NodeContext.prototype.clearOldConnectionPulsing=function(){this.connectionPulsingCallbackScheduled=!1;var e=this.getCurrentTime(),t=this,n=Object.keys(this.connectionsToPulse);n.forEach(function(o){var r=t.connectionsToPulse[o];e-r.timestamp>100&&(t.connectionsToPulseChanged=!0,delete t.connectionsToPulse[o])}),this.connectionsToPulseChanged&&(this.connectionsToPulseChanged=!1,this.editorConnection.sendPulsingConnections(this.connectionsToPulse)),Object.keys(this.connectionsToPulse).length>0&&(this.connectionPulsingCallbackScheduled=!0,setTimeout(this.clearOldConnectionPulsing.bind(this),500))},NodeContext.prototype._getDebugInspectorValueForNode=function(e){if(!this.rootComponent)return;const t=this.rootComponent.nodeScope.getNodesWithIdRecursive(e),n=t[t.length-1];if(n&&n.getInspectInfo){const o=n.getInspectInfo();if(o!==void 0)return{type:"node",id:e,value:o}}},NodeContext.prototype.sendDebugInspectorValues=function(){const e=[];for(const t in this.debugInspectors){const n=this.debugInspectors[t];if(n.type==="connection"&&this._outputHistory.hasOwnProperty(t)){const o=this._outputHistory[t].value;e.push({type:"connection",id:t,value:this._formatConnectionValue(o)})}else if(n.type==="node"){const o=this._getDebugInspectorValueForNode(t);o&&e.push(o)}}e.length>0&&this.editorConnection.sendDebugInspectorValues(e),this.connectionsToPulseChanged&&(this.connectionsToPulseChanged=!1,this.editorConnection.sendPulsingConnections(this.connectionsToPulse))},NodeContext.prototype.setDebugInspectorsEnabled=function(e){this.debugInspectorsEnabled=e,this.editorConnection.debugInspectorsEnabled=e,e&&this.sendDebugInspectorValues()},NodeContext.prototype.sendGlobalEventFromEventSender=function(e,t){this.eventSenderEmitter.emit(e,t)},NodeContext.prototype.setPopupCallbacks=function({onShow:e,onClose:t}){this.onShowPopup=e,this.onClosePopup=t},NodeContext.prototype.showPopup=async function(e,t,n){if(!this.onShowPopup)return;const o=this.rootComponent.nodeScope,r=await o.createNode(e);for(const d in t)r.setInputValue(d,t[d]);r.popupParent=n?.senderNode||null;const s=o.createPrimitiveNode("Group");s.setInputValue("flexDirection","node"),s.setInputValue("cssClassName","noodl-popup");const a=this.graphModel.getSettings().bodyScroll;s.setInputValue("position",a?"fixed":"absolute");var u=r.nodeScope.getNodesWithType("NavigationClosePopup");if(u&&u.length>0)for(var l=0;l<u.length;l++)u[l]._setCloseCallback((d,p)=>{this.scheduleNextFrame(()=>{o.hasNodeWithId(s.id)&&(this.onClosePopup(s),o.deleteNode(s),n&&n.onClosePopup&&n.onClosePopup(d,p))})});this.onShowPopup(s),requestAnimationFrame(()=>{s.addChild(r)})},NodeContext.prototype.setWarningTypes=function(e){Object.assign(this.warningTypes,e)},NodeContext.prototype.isWarningTypeEnabled=function(e){return this.warningTypes.hasOwnProperty(e)?!!this.warningTypes[e]:!0},NodeContext.prototype.getDefaultValueForInput=function(e,t){if(this.nodeRegister.hasNode(e)===!1)return;const o=this.nodeRegister.getNodeMetadata(e).inputs[t];if(o)return o.type.defaultUnit?{value:o.default,unit:o.type.defaultUnit}:o.default};function EventSender(){this.listeners={},this.listenersWithRefs={}}EventSender.prototype.on=function(e,t,n){n?(this.listenersWithRefs.hasOwnProperty(e)||(this.listenersWithRefs[e]=new Map),this.listenersWithRefs[e].get(n)||this.listenersWithRefs[e].set(n,[]),this.listenersWithRefs[e].get(n).push(t)):(this.listeners.hasOwnProperty(e)||(this.listeners[e]=[]),this.listeners[e].push(t))},EventSender.prototype.removeListenersWithRef=function(e){Object.keys(this.listenersWithRefs).forEach(t=>{const n=this.listenersWithRefs[t];n.has(e)&&n.delete(e)})},EventSender.prototype.removeAllListeners=function(e){e?(delete this.listeners[e],delete this.listenersWithRefs[e]):(this.listeners={},this.listenersWithRefs={})},EventSender.prototype.emit=async function(e,t){const n=this.listeners[e];if(n)for(let r=0;r<n.length;r++){const s=n[r];await Promise.resolve(s.call(null,t))}const o=this.listenersWithRefs[e];if(o)for(const[r,s]of o)for(const a of s)await Promise.resolve(a.call(r,t))};function Services(){}Services.events=new EventEmitter;class ActiveWarnings{constructor(){this.currentWarnings=new Map}setWarning(t,n,o){if(this.currentWarnings.has(t)){const r=this.currentWarnings.get(t);return r[n]===o?!1:(r[n]=o,!0)}else return this.currentWarnings.set(t,{[n]:o}),!0}clearWarning(t,n){const o=this.currentWarnings.get(t);return!o||!o[n]?!1:(delete o[n],Object.keys(o).length===0&&delete this.currentWarnings.delete(t),!0)}clearWarnings(t){return this.currentWarnings.has(t)===!1?!1:(this.currentWarnings.delete(t),!0)}}function EditorConnection(e){var t=e||{};EventSender.call(this),this.runtimeType=t.runtimeType,this.platform=t.platform,this.ws=t.platform&&t.platform.webSocketClass||(typeof WebSocket<"u"?WebSocket:void 0),this.wsOptions=t.platform&&t.platform.webSocketOptions||void 0,this.reconnectOnClose=!0,this.enableDebugger=!1,this.lastSendTimestamp=0,this.sendQueue=[],this.sendTimer=void 0,this.activeWarnings=new ActiveWarnings}EditorConnection.prototype=Object.create(EventSender.prototype),EditorConnection.prototype.constructor=EditorConnection,EditorConnection.prototype.isRunningLocally=function(){var e=this.platform.isRunningLocally&&this.platform.isRunningLocally()||typeof document<"u"&&(document.location.hostname==="localhost"||document.location.hostname==="127.0.0.1");return e},EditorConnection.prototype.connect=function(e){this.socket=this.wsOptions?new this.ws(e,this.wsOptions):new this.ws(e);var t=this;this.socket.addEventListener("open",function(){t.clientId=guid(),t.socket.send(JSON.stringify({cmd:"register",type:"viewer",clientId:t.clientId})),t.emit("connected")}),this.socket.addEventListener("close",function(n){t.reconnectOnClose&&t.reconnect(e),console.log("Editor connection closed",n.code,n.reason),t.emit("connectionClosed")}),this.socket.addEventListener("error",function(n){console.log("Editor connection error, trying to reconnect")}),this.socket.addEventListener("message",async n=>{const o=typeof n.data=="string"?n.data:await n.data.text(),r=JSON.parse(o);let s;r.cmd==="registered"||(r.cmd==="export"?(s=JSON.parse(r.content),r.type==="full"&&r.target===this.clientId&&t.emit("exportDataFull",s)):r.cmd==="hoverStart"?t.emit("hoverStart",r.content.id):r.cmd==="hoverEnd"?t.emit("hoverEnd",r.content.id):r.cmd==="refresh"?t.emit("reload"):r.cmd==="debugInspectors"?this.debugInspectorsEnabled&&(s=JSON.parse(r.content),t.emit("debugInspectorsUpdated",s.inspectors)):r.cmd==="debuggingEnabled"?t.isRunningLocally()&&(s=JSON.parse(r.content),t.emit("debuggingEnabledChanged",s.enabled)):r.cmd==="getConnectionValue"?t.isRunningLocally()&&(s=JSON.parse(r.content),await t.emit("getConnectionValue",{clientId:s.clientId,connectionId:s.connectionId})):r.cmd==="modelUpdate"?await t.emit("modelUpdate",r.content):r.cmd==="publish"?Services.pubsub.routeMessage(r):r.cmd==="noodlModules"?t.emit("noodlModules",JSON.parse(r.content)):r.cmd==="mqttUpdate"?t.emit("mqttUpdate",r.content):r.cmd==="activeComponentChanged"?t.emit("activeComponentChanged",r.component):console.log("Command not implemented",r))})},EditorConnection.prototype.reconnect=function(e){var t=this;setTimeout(function(){t.connect(e)},2e3)},EditorConnection.prototype.isConnected=function(){return this.socket!==void 0&&this.socket.readyState===this.ws.OPEN};const getCircularReplacer=()=>{const e=new WeakSet;return(t,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n}};EditorConnection.prototype.send=function(e){const t=this.platform.getCurrentTime(),n=t-this.lastSendTimestamp,o=r=>{try{this.socket.send(JSON.stringify(r))}catch(s){if(s.message&&s.message.startsWith("Converting circular"))try{this.socket.send(JSON.stringify(r,getCircularReplacer()))}catch(a){console.log("failed to send message to editor",r,a)}else console.log("failed to send message to editor",r,s)}};n<200||this.sendTimer||!this.isConnected()?(this.sendQueue.push(e),this.sendTimer||(this.sendTimer=setTimeout(()=>{if(this.isConnected()===!1)return;const r=50;for(let s=0;s<this.sendQueue.length;s+=r){const a=this.sendQueue.slice(s,s+r);o(a)}this.sendQueue=[],this.sendTimer=void 0,this.lastSendTimestamp=this.platform.getCurrentTime()},100))):(this.lastSendTimestamp=t,o(e))},EditorConnection.prototype.sendInspectId=function(e){this.send({cmd:"select",type:"viewer",content:JSON.stringify({id:e})})},EditorConnection.prototype.sendSelectComponent=function(e){this.send({cmd:"select",type:"viewer",content:JSON.stringify({componentName:e})})},EditorConnection.prototype.sendPulsingConnections=function(e){var t=[];Object.keys(e).forEach(function(n){var o=e[n];t=t.concat(o.connections)}),this.send({cmd:"connectiondebugpulse",type:"viewer",content:JSON.stringify({connectionsToPulse:t})})},EditorConnection.prototype.sendDebugInspectorValues=function(e){this.send({cmd:"debuginspectorvalues",type:"viewer",content:{inspectors:e}})},EditorConnection.prototype.sendConnectionValue=function(e,t){this.send({cmd:"connectionValue",type:"viewer",content:{connectionId:e,value:t}})};const dynamicPortsHash={};function _detectRename(e,t){if(!(!e||!t)&&e.length===t.length){for(var n={},o=0;o<e.length;o++){if(t.indexOf(e[o])===-1){if(n.before)return;n.before=e[o]}if(e.indexOf(t[o])===-1){if(n.after)return;n.after=t[o]}}return n.before&&n.after?n:void 0}}EditorConnection.prototype.sendDynamicPorts=function(e,t,n){var o=JSON.stringify(t);if(dynamicPortsHash[e]!==o){if(dynamicPortsHash[e]&&t&&n&&n.detectRenamed){var r=Array.isArray(n.detectRenamed)?n.detectRenamed:[n.detectRenamed],s=[];r.forEach(a=>{var u=JSON.parse(dynamicPortsHash[e]),l=[].concat(t);a.prefix&&(u=u.filter(p=>p.name.startsWith(a.prefix)),l=l.filter(p=>p.name.startsWith(a.prefix))),a.plug&&(u=u.filter(p=>p.plug===a.plug),l=l.filter(p=>p.plug===a.plug)),l=l.map(p=>p.name.substring((a.prefix||"").length)),u=u.map(p=>p.name.substring((a.prefix||"").length));var d=_detectRename(u,l);d&&s.push({plug:a.plug,patterns:[(a.prefix||"")+"{{*}}"],before:d.before,after:d.after})}),s.length>0&&(n.renamed=s),delete n.detectRenamed}dynamicPortsHash[e]=o,this.send({cmd:"instanceports",type:"viewer",content:JSON.stringify({nodeid:e,ports:t,options:n})})}},EditorConnection.prototype.sendWarning=function(e,t,n,o){this.activeWarnings.setWarning(t,n,o)&&this.send({cmd:"showwarning",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t,key:n,warning:o})})},EditorConnection.prototype.clearWarning=function(e,t,n){this.activeWarnings.clearWarning(t,n)&&this.send({cmd:"showwarning",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t,key:n,warning:void 0})})},EditorConnection.prototype.clearWarnings=function(e,t){this.activeWarnings.clearWarnings(t)&&this.send({cmd:"clearwarnings",type:"viewer",content:JSON.stringify({componentName:e,nodeId:t})})},EditorConnection.prototype.sendPatches=function(e){this.send({cmd:"patchproject",type:"viewer",content:JSON.stringify(e)})},EditorConnection.prototype.requestFullExport=function(){this.send({cmd:"register",type:"viewer"})},EditorConnection.prototype.requestNoodlModules=function(){this.send({cmd:"getNoodlModules",type:"viewer"})};var serviceRequests={};EditorConnection.prototype.sendServiceRequest=function(e,t){e.token=guid(),e.clientId=this.clientId,serviceRequests[e.token]=t,this.send(e)},EditorConnection.prototype.close=function(){this.reconnectOnClose=!1,this.isConnected()!==!1&&this.socket.close()},EditorConnection.prototype.sendNodeLibrary=function(e){this.send({cmd:"nodelibrary",type:"viewer",runtimeType:this.runtimeType,content:e,clientId:this.clientId})},EditorConnection.prototype.sendComponentMetadata=function(e,t,n){this.send({cmd:"componentMetadata",type:"viewer",content:JSON.stringify({componentName:e,key:t,data:n})})},EditorConnection.prototype.sendProjectMetadata=function(e,t){this.send({cmd:"projectMetadata",type:"viewer",content:JSON.stringify({key:e,data:t})})};function formatDynamicPorts(e){const t=[];for(const n of e.dynamicports)if(n.ports||n.template||n.port||n.channelPort)t.push(n);else if(n.inputs||n.outputs){const o=[];if(n.inputs)for(const s of n.inputs)o.push(formatPort(s,e.inputs[s],"input"));if(n.outputs)for(const s of n.outputs)o.push(formatPort(s,e.outputs[s],"output"));const r={name:n.name||"conditionalports/basic",condition:n.condition,ports:o};t.push(r)}return t}function formatPort(e,t,n){var o={name:e,type:t.type,plug:n};return t.group&&(o.group=t.group),t.displayName&&(o.displayName=t.displayName),t.description&&(o.description=t.description),t.editorName&&(o.editorName=t.editorName),t.default!==void 0&&(o.default=t.default),t.hasOwnProperty("index")&&(o.index=t.index),t.tooltip&&(o.tooltip=t.tooltip),t.tab&&(o.tab=t.tab),t.popout&&(o.popout=t.popout),t.allowVisualStates&&(o.allowVisualStates=t.allowVisualStates),o}function generateNodeLibrary(e){var t={typecasts:[{from:"string",to:["number","boolean","image","color","enum","textStyle","dimension","array","object"]},{from:"boolean",to:["number","string","signal"]},{from:"number",to:["boolean","string","dimension"]},{from:"date",to:["string"]},{from:"signal",to:["boolean","number"]},{from:"image",to:[]},{from:"cloudfile",to:["string","image"]},{from:"color",to:[]},{from:"enum",to:[]},{from:"object",to:[]},{from:"domelement",to:[]},{from:"reference",to:[]},{from:"font",to:[]},{from:"textStyle",to:["string"]},{from:"collection",to:["array"]},{from:"array",to:["collection"]}],dynamicports:[{type:"conditionalports",name:"basic"},{type:"expand",name:"basic"}],colors:{nodes:{component:{base:"#643D8B",baseHighlighted:"#79559b",header:"#4E2877",headerHighlighted:"#643d8b",outline:"#4E2877",outlineHighlighted:"#b58900",text:"#dbd0e4"},visual:{base:"#315272",baseHighlighted:"#4d6784",header:"#173E5D",headerHighlighted:"#315272",outline:"#173E5D",outlineHighlighted:"#b58900",text:"#cfd5de"},data:{base:"#465524",baseHighlighted:"#5b6a37",header:"#314110",headerHighlighted:"#465524",outline:"#314110",outlineHighlighted:"#b58900",text:"#d2d6c5"},javascript:{base:"#7E3660",baseHighlighted:"#944e74",header:"#67214B",headerHighlighted:"#7e3660",outline:"#67214B",outlineHighlighted:"#d57bab",text:"#e4cfd9"},default:{base:"#4C4F59",baseHighlighted:"#62656e",header:"#373B45",headerHighlighted:"#4c4f59",outline:"#373B45",outlineHighlighted:"#b58900",text:"#d3d4d6"}},connections:{signal:{normal:"#006f82",highlighted:"#7ec2cf",pulsing:"#ffffff"},default:{normal:"#875d00",highlighted:"#e5ae32",pulsing:"#ffffff"}}},nodetypes:[{name:"Component Children",shortDesc:"This node is a placeholder for where children of this component will be inserted.",docs:"https://docs.noodl.net/nodes/component-utilities/component-children",color:"component",allowAsChild:!0,category:"Visual",haveComponentChildren:["Visual"]}]},n=Object.keys(e._constructors);n.forEach(function(s){var a=e._constructors[s].metadata,u={name:s,searchTags:a.searchTags};t.nodetypes.push(u),a.version&&(u.version=a.version),a.displayNodeName&&(u.displayNodeName=a.displayNodeName),a.nodeDoubleClickAction&&(u.nodeDoubleClickAction=a.nodeDoubleClickAction),a.shortDesc&&(u.shortDesc=a.shortDesc),a.module&&(u.module=a.module),a.deprecated&&(u.deprecated=!0),a.haveComponentPorts&&(u.haveComponentPorts=!0),a.category==="Visual"&&(u.allowAsChild=!0,u.allowAsExportRoot=!0,u.color="visual"),a.allowAsExportRoot!==void 0&&(u.allowAsExportRoot=a.allowAsExportRoot),a.allowChildren&&(u.allowChildrenWithCategory=["Visual"],u.color="visual"),a.allowChildrenWithCategory&&(u.allowChildrenWithCategory=a.allowChildrenWithCategory),a.singleton&&(u.singleton=!0),a.allowAsChild&&(u.allowAsChild=!0),a.docs&&(u.docs=a.docs),a.shortDocs?u.shortDocs=a.shortDocs:a.docs&&a.docs.indexOf("https://docs.noodl.net")===0&&(u.shortDocs=a.docs.replace("/#","")+"-short.md"),u.category=a.category,a.panels&&(u.panels=a.panels),a.usePortAsLabel&&(u.usePortAsLabel=a.usePortAsLabel,u.portLabelTruncationMode=a.portLabelTruncationMode),a.color&&(u.color=a.color),a.dynamicports&&(u.dynamicports=formatDynamicPorts(a)),a.exportDynamicPorts&&(u.exportDynamicPorts=a.exportDynamicPorts),a.visualStates&&(u.visualStates=a.visualStates),a.useVariants&&(u.useVariants=a.useVariants),a.connectionPanel&&(u.connectionPanel=a.connectionPanel),u.ports=[];var l=u.dynamicports||[],d={},p={};l.filter(m=>m.channelPort!==void 0).forEach(m=>{p[m.channelPort.plug+"/"+m.channelPort.name]=!0}),l.length&&(u.dynamicports=l),Object.keys(a.inputs).forEach(function(m){if(!(d.hasOwnProperty("input/"+m)||p.hasOwnProperty("input/"+m))){var y=a.inputs[m];y.exportToEditor!==!1&&u.ports.push(formatPort(m,y,"input"))}});function f(m,y){var v={name:m,type:y.type,plug:"output"};y.group&&(v.group=y.group),y.displayName&&(v.displayName=y.displayName),y.editorName&&(v.editorName=y.editorName),y.hasOwnProperty("index")&&(v.index=y.index),u.ports.push(v)}Object.keys(a.outputs).forEach(function(m){if(!(d.hasOwnProperty("output/"+m)||p.hasOwnProperty("output/"+m))){var y=a.outputs[m];f(m,y)}})});const o=[{name:"UI Elements",description:"Buttons, inputs, containers, media",type:"visual",subCategories:[{name:"Basic Elements",items:["Group","net.noodl.visual.columns","Text","Image","Video","Circle","net.noodl.visual.icon"]},{name:"UI Controls",items:["net.noodl.controls.button","net.noodl.controls.checkbox","net.noodl.controls.options","net.noodl.controls.radiobutton","Radio Button Group","net.noodl.controls.range","net.noodl.controls.textinput"]}]},{name:"Navigation & Popups",description:"Page routing, navigation, popups",type:"logic",subCategories:[{name:"Navigation",items:["Router","RouterNavigate","PageInputs","net.noodl.externallink","PageStackNavigateToPath"]},{name:"Component Stack",items:["Page Stack","PageStackNavigate","PageStackNavigateBack"]},{name:"Popups",items:["NavigationShowPopup","NavigationClosePopup"]}]},{name:"Logic & Utilities",description:"Logic, events, string manipulation",type:"logic",subCategories:[{name:"General Utils",items:["States","Value Changed","Timer","Color Blend","Number Remapper","Counter","Drag","net.noodl.animatetovalue"]},{name:"Logic",items:["Boolean To String","Switch","And","Or","Condition","Inverter"]},{name:"Events",items:["Event Sender","Event Receiver"]},{name:"String Manipulation",items:["Substring","String Mapper","String Format","Date To String","Unique Id"]},{name:"System",items:["Screen Resolution","Open File Picker"]},{name:"Variables",items:["String","Boolean","Color","Number"]}]},{name:"Component Utilities",description:"Component inputs, outputs & object",type:"component",subCategories:[{name:"",items:["Component Inputs","Component Outputs","Component Children","net.noodl.ComponentObject","net.noodl.ParentComponentObject","net.noodl.SetComponentObjectProperties","net.noodl.SetParentComponentObjectProperties"]}]},{name:"Read & Write Data",description:"Arrays, objects, cloud data",type:"data",subCategories:[{name:"",items:["RunTasks","For Each","For Each Actions","Model2","SetModelProperties","NewModel","Set Variable","Variable2"]},{name:"Array",items:["Collection2","CollectionNew","CollectionRemove","CollectionClear","CollectionInsert","Filter Collection","Map Collection","Static Data"]},{name:"Cloud Data",items:["DbModel2","NewDbModelProperties","FilterDBModels","SetDbModelProperties","DbCollection2","DeleteDbModelProperties","AddDbModelRelation","RemoveDbModelRelation","Cloud File","Upload File","CloudFunction2","DbConfig"]},{name:"User",items:["net.noodl.user.LogIn","net.noodl.user.LogOut","net.noodl.user.SignUp","net.noodl.user.User","net.noodl.user.SetUserProperties","net.noodl.user.VerifyEmail","net.noodl.user.SendEmailVerification","net.noodl.user.ResetPassword","net.noodl.user.RequestPasswordReset"]},{name:"External Data",items:["REST2"]}]},{name:"Custom Code",description:"Custom JavaScript and CSS",type:"javascript",subCategories:[{name:"",items:["Expression","JavaScriptFunction","Javascript2","CSS Definition"]}]},{name:"Cloud Functions",description:"Nodes to be used in cloud functions",type:"data",subCategories:[{name:"",items:["noodl.cloud.request","noodl.cloud.response"]},{name:"Cloud Data",items:["noodl.cloud.aggregate"]}]}];t.nodeIndex={coreNodes:o};const r=[];return n.forEach(s=>{e._constructors[s].metadata.module&&r.push(s)}),r.length&&(t.nodeIndex.moduleNodes=[{name:"",items:r}]),t}function addModuleSettings(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.settings&&o.settings.forEach(function(r){e.ports.push(r)})}}function generateProjectSettings(e,t){const n={dynamicports:[],ports:[]};return addModuleSettings(n,t),n}function NodeModel(e,t){EventSender.call(this),this.id=e,this.type=t,this.inputs=[],this.outputs=[],this.children=[],this.parameters={},this.inputPorts={},this.outputPorts={}}NodeModel.prototype=Object.create(EventSender.prototype),NodeModel.prototype.setParameter=function(e,t,n){n?(this.stateParameters||(this.stateParameters={}),this.stateParameters[n]||(this.stateParameters[n]={}),t===void 0?delete this.stateParameters[n][e]:this.stateParameters[n][e]=t):t===void 0?delete this.parameters[e]:this.parameters[e]=t,this.emit("parameterUpdated",{name:e,value:t,state:n})},NodeModel.prototype.setParameters=function(e){Object.keys(e).forEach(t=>{this.setParameter(t,e[t])})},NodeModel.prototype.setStateParameters=function(e){this.stateParameters=e},NodeModel.prototype.setStateTransitions=function(e){this.stateTransitions=e},NodeModel.prototype.setStateTransitionParamter=function(e,t,n){this.stateTransitions||(this.stateTransitions={}),t?this.stateTransitions[n][e]=t:delete this.stateTransitions[n][e]},NodeModel.prototype.setDefaultStateTransition=function(e,t){this.defaultStateTransitions||(this.defaultStateTransitions={}),this.defaultStateTransitions[t]=e},NodeModel.prototype.addInputPort=function(e){this.inputPorts[e.name]=e,this.emit("inputPortAdded",e)},NodeModel.prototype.getInputPort=function(e){return this.inputPorts[e]},NodeModel.prototype.getInputPorts=function(){return this.inputPorts},NodeModel.prototype.removeInputPortWithName=function(e){if(this.inputPorts.hasOwnProperty(e)){var t=this.inputPorts[e];delete this.inputPorts[e],this.emit("inputPortRemoved",t)}},NodeModel.prototype.updateInputPortTypes=function(e){var t=!1;for(var n in e)this.inputPorts[n]!==void 0&&(this.inputPorts[n].type=e[n].type,t=!0);t&&this.emit("inputPortTypesUpdated")},NodeModel.prototype.addOutputPort=function(e){this.outputPorts[e.name]=e,this.emit("outputPortAdded",e)},NodeModel.prototype.getOutputPort=function(e){return this.outputPorts[e]},NodeModel.prototype.getOutputPorts=function(){return this.outputPorts},NodeModel.prototype.removeOutputPortWithName=function(e){if(this.outputPorts.hasOwnProperty(e)){var t=this.outputPorts[e];delete this.outputPorts[e],this.emit("outputPortRemoved",t)}},NodeModel.prototype.updateOutputPortTypes=function(e){var t=!1;for(var n in e)this.outputPorts[n]!==void 0&&(this.outputPorts[n].type=e[n].type,t=!0);t&&this.emit("outputPortTypesUpdated")},NodeModel.prototype.addChild=function(e,t){e.parent=this,t===void 0?this.children.push(e):this.children.splice(t,0,e),this.emit("childAdded",e)},NodeModel.prototype.removeChild=function(e){e.parent=void 0;var t=this.children.indexOf(e);this.children.splice(t,1),this.emit("childRemoved",e)},NodeModel.prototype.reset=function(){this.removeAllListeners()},NodeModel.prototype.setVariant=function(e){this.variant=e,this.emit("variantUpdated",e)},NodeModel.createFromExportData=function(e){var t=new NodeModel(e.id,e.type);if(e.parameters&&t.setParameters(e.parameters),e.stateParameters&&t.setStateParameters(e.stateParameters),e.stateTransitions&&t.setStateTransitions(e.stateTransitions),e.defaultStateTransitions)for(const n in e.defaultStateTransitions)t.setDefaultStateTransition(e.defaultStateTransitions[n],n);return e.ports&&e.ports.forEach(function(n){n.plug==="outputs"&&(n.plug="output"),(n.plug==="input"||n.plug==="input/output")&&t.addInputPort(n),(n.plug==="output"||n.plug==="input/output")&&t.addOutputPort(n)}),e.variant&&t.setVariant(e.variant),t};function ComponentModel(e){EventSender.call(this),this.name=e,this.nodes=[],this.connections=[],this.roots=[],this.inputPorts={},this.outputPorts={},this.metadata={}}ComponentModel.prototype=Object.create(EventSender.prototype),ComponentModel.prototype.addNode=async function(e){e.component=this,this.nodes[e.id]=e,await this.emit("nodeAdded",e)},ComponentModel.prototype.hasNodeWithId=function(e){return this.getNodeWithId(e)!==void 0},ComponentModel.prototype.getNodeWithId=function(e){return this.nodes[e]},ComponentModel.prototype.getAllNodes=function(){return Object.values(this.nodes)},ComponentModel.prototype.getNodesWithType=function(e){var t=[],n=this;return Object.keys(this.nodes).forEach(function(o){var r=n.nodes[o];r.type===e&&t.push(r)}),t},ComponentModel.prototype.addConnection=function(e){if(this.connections.push(e),this.emit("connectionAdded",e),e.targetId){const t=this.getNodeWithId(e.targetId);t&&t.emit("inputConnectionAdded",e)}},ComponentModel.prototype.removeConnection=function(e){const t=this.connections.findIndex(n=>n.sourceId===e.sourceId&&n.sourcePort===e.sourcePort&&n.targetId===e.targetId&&n.targetPort===e.targetPort);if(t===-1){console.log("Connection doesn't exist",e);return}if(this.connections.splice(t,1),this.emit("connectionRemoved",e),e.targetId){const n=this.getNodeWithId(e.targetId);n&&n.emit("inputConnectionRemoved",e)}},ComponentModel.prototype.getConnectionsFromPort=function(e,t){return this.connections.filter(function(n){return n.sourceId===e&&n.sourcePort===t})},ComponentModel.prototype.getConnectionsToPort=function(e,t){return this.connections.filter(function(n){return n.targetId===e&&n.targetPort===t})},ComponentModel.prototype.getConnectionsFrom=function(e){return this.connections.filter(function(t){return t.sourceId===e})},ComponentModel.prototype.getConnectionsTo=function(e){return this.connections.filter(function(t){return t.targetId===e})},ComponentModel.prototype.addRootId=function(e){this.roots.indexOf(e)===-1&&(this.roots.push(e),this.emit("rootAdded",e))},ComponentModel.prototype.removeRootId=function(e){const t=this.roots.indexOf(e);t!==-1&&(this.roots.splice(t,1),this.emit("rootRemoved",e))},ComponentModel.prototype.getRoots=function(){return this.roots},ComponentModel.prototype.removeNodeWithId=async function(e){const t=this.getNodeWithId(e);if(!t)return console.warn("ERROR: Attempted to remove non-existing node with ID:",e),!1;for(;t.children.length>0;){const o=t.children[0];await this.removeNodeWithId(o.id)||t.children.shift()}const n=this.getConnectionsTo(e).concat(this.getConnectionsFrom(e));for(let o=0;o<n.length;o++)this.removeConnection(n[o]);return this.setNodeParent(t,null),this.roots.indexOf(t.id)!==-1&&this.removeRootId(t.id),await this.emit("nodeRemoved",t),t.removeAllListeners(),delete this.nodes[e],await this.emit("nodeWasRemoved",t),!0},ComponentModel.prototype.getAllConnections=function(){return this.connections},ComponentModel.prototype.getInputPorts=function(){return this.inputPorts},ComponentModel.prototype.getOutputPorts=function(){return this.outputPorts},ComponentModel.prototype.addInputPort=function(e){this.inputPorts[e.name]=e,this.emit("inputPortAdded",e)},ComponentModel.prototype.addOutputPort=function(e){this.outputPorts[e.name]=e,this.emit("outputPortAdded",e)},ComponentModel.prototype.removeOutputPortWithName=function(e){if(this.outputPorts.hasOwnProperty(e)){var t=this.outputPorts[e];delete this.outputPorts[e],this.emit("outputPortRemoved",t)}},ComponentModel.prototype.removeInputPortWithName=function(e){if(this.inputPorts.hasOwnProperty(e)){var t=this.inputPorts[e];delete this.inputPorts[e],this.emit("inputPortRemoved",t)}},ComponentModel.prototype.updateInputPortTypes=function(e){var t=!1;for(var n in e)this.inputPorts[n]!==void 0&&(this.inputPorts[n].type=e[n].type,t=!0);t&&this.emit("inputPortTypesUpdated")},ComponentModel.prototype.updateOutputPortTypes=function(e){var t=!1;for(var n in e)this.outputPorts[n]!==void 0&&(this.outputPorts[n].type=e[n].type,t=!0);t&&this.emit("outputPortTypesUpdated")},ComponentModel.prototype.renameInputPortOnNodeWithId=function(e,t,n){var o=this.getConnectionsToPort(e,t);o.forEach(this.removeConnection.bind(this));var r=this.getNodeWithId(e),s={...r.getInputPort(t)};s&&(r.removeInputPortWithName(t),s.name=n,r.addInputPort(s)),o.forEach(function(a){a.targetPort=n}),o.forEach(this.addConnection.bind(this))},ComponentModel.prototype.renameOutputPortOnNodeWithId=function(e,t,n){var o=this.getConnectionsFromPort(e,t);o.forEach(this.removeConnection.bind(this));var r=this.getNodeWithId(e),s={...r.getOutputPort(t)};r.removeOutputPortWithName(t),s.name=n,r.addOutputPort(s),o.forEach(function(a){a.sourcePort=n}),o.forEach(this.addConnection.bind(this))},ComponentModel.prototype.setNodeParent=function(e,t,n){this.roots.indexOf(e.id)!==-1&&this.removeRootId(e.id),e.parent&&(this.emit("nodeParentWillBeRemoved",e),e.parent.removeChild(e)),e.emit("parentUpdated",t),t&&(t.addChild(e,n),this.emit("nodeParentUpdated",e))},ComponentModel.prototype.importEditorNodeData=async function(e,t,n){var o=NodeModel.createFromExportData(e);if(await this.addNode(o),t&&this.setNodeParent(o,this.getNodeWithId(t),n),e.children)for(let r=0;r<e.children.length;r++){const s=e.children[r];await this.importEditorNodeData(s,o.id,r)}},ComponentModel.prototype.reset=async function(){for(;this.roots.length;)await this.removeNodeWithId(this.roots[0]);for(const e of this.nodes)this.hasNodeWithId(e)&&await this.removeNodeWithId(e);if(this.nodes.length>0)throw new Error("Not all nodes were removed during a reset");if(this.connections.length>0)throw new Error("Not all connections were removed during a reset")},ComponentModel.prototype.rename=function(e){var t=this.name;this.name=e,this.emit("renamed",{oldName:t,newName:e})},ComponentModel.prototype.setMetadata=function(e,t){this.metadata[e]=t},ComponentModel.prototype.getMetadata=function(e){return e?this.metadata[e]:this.metadata},ComponentModel.createFromExportData=async function(e){var t=new ComponentModel(e.name);if(e.metadata)for(const n in e.metadata)t.setMetadata(n,e.metadata[n]);if(e.ports&&e.ports.forEach(function(n){(n.plug==="input"||n.plug==="input/output")&&t.addInputPort(n),(n.plug==="output"||n.plug==="input/output")&&t.addOutputPort(n)}),e.nodes)for(const n of e.nodes)await t.importEditorNodeData(n);return e.connections&&e.connections.forEach(n=>t.addConnection(n)),e.roots&&e.roots.forEach(n=>t.addRootId(n)),t};function GraphModel(){EventSender.call(this),this.components={},this.settings={},this.metadata={}}GraphModel.prototype=Object.create(EventSender.prototype),GraphModel.prototype.importComponentFromEditorData=async function(e){var t=await ComponentModel.createFromExportData(e);this.addComponent(t)},GraphModel.prototype.getBundleContainingComponent=function(e){return this.componentToBundleMap.get(e)},GraphModel.prototype.getBundlesContainingSheet=function(e){const t=new Set;for(const n of this.componentToBundleMap.keys()){const o=n.indexOf("/#")!==0;(o&&e==="Default"||!o&&n.indexOf("/#"+e)===0)&&t.add(this.componentToBundleMap.get(n))}return Array.from(t)},GraphModel.prototype.getBundleDependencies=function(e){const t=new Set,n=o=>{const r=this.componentIndex[o];for(const s of r.dependencies)t.has(s)||(t.add(s),n(s))};return n(e),Array.from(t)},GraphModel.prototype.importEditorData=async function(e){this.componentIndex=e.componentIndex,this.routerIndex=e.routerIndex,this.componentToBundleMap=new Map;for(const t in e.componentIndex){const n=e.componentIndex[t];for(const o of n.components)this.componentToBundleMap.set(o,t)}this.variants=e.variants||[],e.settings&&this.setSettings(e.settings),e.metadata&&this.setAllMetaData(e.metadata);for(const t of e.components)await this.importComponentFromEditorData(t);this.setRootComponentName(e.rootComponent)},GraphModel.prototype.setRootComponentName=function(e){this.rootComponent=e,this.emit("rootComponentNameUpdated",e)},GraphModel.prototype.getNodesWithType=function(e){for(var t=[],n=Object.keys(this.components),o=0;o<n.length;o++){var r=this.components[n[o]];t=t.concat(r.getNodesWithType(e))}return t},GraphModel.prototype.getComponentWithName=function(e){return this.components[e]},GraphModel.prototype.hasComponentWithName=function(e){return!!this.components[e]},GraphModel.prototype.getAllComponents=function(){return Object.keys(this.components).map(e=>this.components[e])},GraphModel.prototype.getAllNodes=function(){for(var e=[],t=Object.keys(this.components),n=0;n<t.length;n++){var o=this.components[t[n]];e=e.concat(o.getAllNodes())}return e},GraphModel.prototype.addComponent=function(e){this.components[e.name]=e,this.getNodesWithType(e.name).forEach(this._addComponentPorts.bind(this)),e.getAllNodes().forEach(this._onNodeAdded.bind(this)),e.on("nodeAdded",this._onNodeAdded.bind(this),this),e.on("nodeRemoved",this._onNodeRemoved.bind(this),this),e.on("nodeWasRemoved",this._onNodeWasRemoved.bind(this),this),this.emit("componentAdded",e)},GraphModel.prototype.removeComponentWithName=async function(e){if(this.components.hasOwnProperty(e)===!1){console.error("GraphModel: Component with name "+e+" not in graph");return}var t=this.components[e];await t.reset(),t.removeAllListeners(),delete this.components[t.name],this.emit("componentRemoved",t)},GraphModel.prototype.renameComponent=function(e,t){if(this.components.hasOwnProperty(e)===!1){console.error("GraphModel: Component with name "+e+" not in graph");return}this.getNodesWithType(e).forEach(function(o){o.type=t});var n=this.components[e];n.rename(t),delete this.components[e],this.components[t]=n,this.emit("componentRenamed",n)},GraphModel.prototype._addComponentPorts=function(e){if(this.components.hasOwnProperty(e.type)){var t=this.components[e.type];const n=t.getInputPorts(),o=t.getOutputPorts();Object.keys(n).forEach(r=>{e.addInputPort(n[r])}),Object.keys(o).forEach(r=>{e.addOutputPort(o[r])})}},GraphModel.prototype._onNodeAdded=function(e){this._addComponentPorts(e),this.emit("nodeAdded",e),this.emit("nodeAdded."+e.type,e)},GraphModel.prototype._onNodeRemoved=function(e){this.emit("nodeRemoved",e),this.emit("nodeRemoved."+e.type,e)},GraphModel.prototype._onNodeWasRemoved=function(e){this.emit("nodeWasRemoved",e),this.emit("nodeWasRemoved."+e.type,e)},GraphModel.prototype.reset=async function(){for(const e of Object.keys(this.components))await this.removeComponentWithName(e);this.setSettings({})},GraphModel.prototype.isEmpty=function(){return Object.keys(this.components).length===0},GraphModel.prototype.setSettings=function(e){this.settings=e,this.emit("projectSettingsChanged",e)},GraphModel.prototype.getSettings=function(){return this.settings},GraphModel.prototype.setAllMetaData=function(e){for(const t in e)this.setMetaData(t,e[t])},GraphModel.prototype.setMetaData=function(e,t){this.metadata[e]&&JSON.stringify(this.metadata[e])===JSON.stringify(t)||(this.metadata[e]=t,this.emit("metadataChanged",{key:e,data:t}),this.emit("metadataChanged."+e,t))},GraphModel.prototype.getMetaData=function(e){return e?this.metadata[e]:this.metadata},GraphModel.prototype.getVariants=function(){return this.variants||[]},GraphModel.prototype.getVariant=function(e,t){return this.variants.find(n=>n.name===t&&n.typename===e)},GraphModel.prototype.updateVariant=function(e){const t=this.variants.findIndex(n=>n.name===e.name&&n.typename===e.typename);t!==-1&&this.variants.splice(t,1),this.variants.push(e),this.emit("variantUpdated",e)},GraphModel.prototype.updateVariantParameter=function(e,t,n,o,r){const s=this.getVariant(t,e);if(!s){console.log("updateVariantParameter: can't find variant",e,t);return}r?(s.stateParameters.hasOwnProperty(r)||(s.stateParameters[r]={}),o===void 0?delete s.stateParameters[r][n]:s.stateParameters[r][n]=o):o===void 0?delete s.parameters[n]:s.parameters[n]=o,this.emit("variantUpdated",s)},GraphModel.prototype.updateVariantDefaultStateTransition=function(e,t,n,o){const r=this.getVariant(t,e);r&&(r.defaultStateTransitions[o]=n,this.emit("variantUpdated",r))},GraphModel.prototype.updateVariantStateTransition=function(e){const{variantTypeName:t,variantName:n,state:o,parameterName:r,curve:s}=e,a=this.getVariant(t,n);a&&(a.stateTransitions[o]||(a.stateTransitions[o]={}),a.stateTransitions[o][r]=s)},GraphModel.prototype.deleteVariant=function(e,t){const n=this.variants.findIndex(o=>o.name===t&&o.typename===e);n!==-1&&this.variants.splice(n,1)};function createSetter(e){var t=!1;return function(n){n=!!n,n&&t===!1&&e.valueChangedToTrue.call(this),t=n}}const EdgeTriggeredInput=Object.freeze(Object.defineProperty({__proto__:null,createSetter},Symbol.toStringTag,{value:"Module"}));function createNodeConstructor(e){const t=class extends Node{constructor(n,o){super(n,o)}getInspectInfo(){return e.getInspectInfo?.()??void 0}nodeScopeDidInitialize(){return e.nodeScopeDidInitialize?.()??void 0}};return e.prototypeExtensions&&Object.defineProperties(t.prototype,e.prototypeExtensions),Object.defineProperty(t.prototype,"name",{value:e.name}),t}function registerInput(e,t,n,o){if(e.hasOwnProperty(n))throw new Error("Input property "+n+" already registered");!o.set&&!o.valueChangedToTrue&&(o.set=()=>{}),o.set&&(e[n]={set:o.set},["color","textStyle","array"].forEach(s=>{o.type&&(o.type===s||o.type.name===s)&&(e[n].type=s)})),o.setUnitType&&(e[n].setUnitType=o.setUnitType),t.inputs[n]={displayName:o.displayName,editorName:o.editorName,group:o.group,type:o.type,default:o.default,index:o.index,exportToEditor:o.hasOwnProperty("exportToEditor")?o.exportToEditor:!0,inputPriority:o.inputPriority||0,tooltip:o.tooltip,tab:o.tab,popout:o.popout,allowVisualStates:o.allowVisualStates,nodeDoubleClickAction:o.nodeDoubleClickAction},o.valueChangedToTrue&&(t.inputs[n].type={name:"signal",allowConnectionsOnly:!0})}function registerInputs(e,t,n){Object.keys(n).forEach(function(o){registerInput(e,t,o,n[o])})}function registerNumberedInputs(e,t){for(const n of Object.keys(t))registerNumberedInput(e,n,t[n])}function registerNumberedInput(e,t,n){const o=e.registerInputIfNeeded;e.registerInputIfNeeded=function(r){if(o&&o.call(e,r),e.hasInput(r)||!r.startsWith(t))return;const s=Number(r.slice(t.length+1));e.registerInput(r,{type:n.type,set:n.createSetter.call(e,s)})}}function registerOutputsMetadata(e,t){Object.keys(t).forEach(function(n){var o=t[n];e.outputs[n]={displayName:o.displayName,editorName:o.editorName,group:o.group,type:o.type,index:o.index,exportToEditor:o.hasOwnProperty("exportToEditor")?o.exportToEditor:!0}})}function initializeDefaultValues(e,t){Object.keys(t).forEach(n=>{const o=t[n].default;o!==void 0&&(t[n].type.defaultUnit?e[n]={unit:t[n].type.defaultUnit,value:o}:e[n]=o)})}function defineNode(e){if(!e.category)throw new Error("Node must have a category");if(!e.name)throw new Error("Node must have a name");const t={inputs:{},outputs:{},category:e.category,dynamicports:e.dynamicports,exportDynamicPorts:e.exportDynamicPorts,useVariants:e.useVariants,allowChildren:e.allowChildren,allowChildrenWithCategory:e.allowChildrenWithCategory,singleton:e.singleton,connectionPanel:e.connectionPanel,allowAsChild:e.allowAsChild,visualStates:e.visualStates,panels:e.panels,color:e.color,usePortAsLabel:e.usePortAsLabel,portLabelTruncationMode:e.portLabelTruncationMode,name:e.name,displayNodeName:e.displayNodeName||e.displayName,deprecated:e.deprecated,haveComponentPorts:e.haveComponentPorts,version:e.version,module:e.module,docs:e.docs,allowAsExportRoot:e.allowAsExportRoot,nodeDoubleClickAction:e.nodeDoubleClickAction,searchTags:e.searchTags};e._internal=e._internal||{},e.prototypeExtensions=e.methods||e.prototypeExtensions||{},e.inputs=e.inputs||{},e.outputs=e.outputs||{},e.initialize=e.initialize||function(){};let n={};registerInputs(n,t,e.inputs),registerOutputsMetadata(t,e.outputs),Object.keys(e.prototypeExtensions).forEach(function(s){e.prototypeExtensions[s].value||(e.prototypeExtensions[s]={value:e.prototypeExtensions[s]})});const o=createNodeConstructor({name:e.name,getInspectInfo:e.getInspectInfo,nodeScopeDidInitialize:e.nodeScopeDidInitialize,prototypeExtensions:e.prototypeExtensions}),r=function(s,a,u){const l=new o(s,a);return l._inputs=Object.create(n),Object.keys(e.inputs).forEach(function(d){var p=e.inputs[d];p.valueChangedToTrue&&(l._inputs[d]={set:createSetter({valueChangedToTrue:p.valueChangedToTrue})})}),Object.keys(e.outputs).forEach(function(d){var p=e.outputs[d];p.type==="signal"?l.registerOutput(d,{getter(){}}):l.registerOutput(d,p)}),e.numberedInputs&®isterNumberedInputs(l,e.numberedInputs),l.nodeScope=u,initializeDefaultValues(l._inputValues,t.inputs),e.initialize.call(l),l};return r.metadata=t,e.numberedInputs&®isterSetupFunctionForNumberedInputs(r,e.name,e.numberedInputs),r}function registerSetupFunctionForNumberedInputs(e,t,n){const o=Object.keys(n);o.length&&(e.setupNumberedInputDynamicPorts=function(r,s){const a=r.editorConnection;if(!a||!a.isRunningLocally())return;function u(d,p,f){const m=d.component.getConnectionsTo(d.id).map(N=>N.targetPort),v=Object.keys(d.parameters).concat(m).filter(N=>N.startsWith(p+" ")),S=(v.length?1+Math.max(...v.map(N=>Number(N.slice(p.length+1)))):0)+1,C=[];for(let N=0;N<S;N++){const T={name:p+" "+N,displayName:(f.displayPrefix||p)+" "+N,type:f.type,plug:"input",group:f.group};f.hasOwnProperty("index")&&(T.index=f.index+N),C.push(T)}return C}function l(d){const p=o.map(f=>u(d,f,n[f])).flat();a.sendDynamicPorts(d.id,p)}s.on("nodeAdded."+t,d=>{l(d),d.on("parameterUpdated",()=>{l(d)}),d.on("inputConnectionAdded",()=>{l(d)}),d.on("inputConnectionRemoved",()=>{l(d)})})})}function extend(e,t){for(var n in t)if(n==="initialize"&&e.initialize){var o=e.initialize;e.initialize=function(){o.call(this),t.initialize.call(this)}}else t[n]&&t[n].constructor===Object?e[n]=extend(e[n]||{},t[n]):t[n]&&t[n].constructor===Array&&e[n]&&e[n].constructor==Array?e[n]=e[n].concat(t[n]):e[n]=t[n];return e}function difference$1(e,t){const n=new Set(t);return e.filter(o=>!n.has(o))}async function handleEvent(e,t,n){function o(u,l){var d={},p={};l.forEach(function(C){C&&C.plug==="outputs"&&(C.plug="output"),(C.plug==="input"||C.plug==="input/output")&&(d[C.name]=C),(C.plug==="output"||C.plug==="input/output")&&(p[C.name]=C)});var f=Object.keys(u.getInputPorts()),m=difference$1(f,Object.keys(d)),y=difference$1(Object.keys(d),f);u.updateInputPortTypes(d),m.forEach(u.removeInputPortWithName.bind(u)),y.forEach(function(C){u.addInputPort(d[C]),u.parameters&&u.parameters.hasOwnProperty(C)&&r(e.rootComponent.nodeScope,u,C,u.parameters[C])}),u.updateOutputPortTypes(p);var v=Object.keys(u.getOutputPorts()),P=difference$1(v,Object.keys(p)),S=difference$1(Object.keys(p),v);P.forEach(u.removeOutputPortWithName.bind(u)),S.forEach(function(C){u.addOutputPort(p[C])})}function r(u,l,d,p){var f=u.getNodesWithIdRecursive(l.id);f.forEach(function(m){m.queueInput(d,p)})}var s;if(!(n.componentName&&(s=t.getComponentWithName(n.componentName),!s))){n.port&&n.port.plug==="outputs"&&(n.port.plug="output");var a={nodeAdded(u){s.importEditorNodeData(u.model,u.parentId,u.childIndex)},nodeRemoved:async function(u){s.hasNodeWithId(u.model.id)&&await s.removeNodeWithId(u.model.id)},connectionAdded(u){s.addConnection(u.model)},connectionRemoved(u){s.removeConnection(u.model);var l=s.getNodeWithId(u.model.targetId);if(s.getConnectionsToPort(l.id,u.model.targetId).length===0){var d=l.parameters[u.model.targetPort];d===void 0&&(d=e.getDefaultValueForInput(l.type,u.model.targetPort)),r(e.rootComponent.nodeScope,l,u.model.targetPort,d)}},parameterChanged(u){const l=s.getNodeWithId(u.nodeId);if(l===void 0){console.log("parameterChanged: Unknown node id",u);return}if(u.parameters){const d=new Set(Object.keys(u.parameters).concat(Object.keys(u.oldParameters)));for(const p of d)l.setParameter(p,u.parameters[p])}u.parameterName&&l.setParameter(u.parameterName,u.parameterValue,u.state)},nodeAttached(u){s.setNodeParent(s.getNodeWithId(u.nodeId),s.getNodeWithId(u.parentId),u.childIndex)},nodeDetached(u){s.setNodeParent(s.getNodeWithId(u.nodeId),null),s.addRootId(u.nodeId)},componentAdded(u){t.importComponentFromEditorData(u.model)},componentRemoved:async function(u){await t.removeComponentWithName(u.componentName)},rootAdded(u){s.addRootId(u.nodeId)},portAdded(u){var l=s.getNodeWithId(u.nodeId);(u.port.plug==="input"||u.port.plug==="input/output")&&(l.addInputPort(u.port),l.parameters.hasOwnProperty(u.port)&&r(e.rootComponent.nodeScope,l,u.port,l.parameters[u.port])),(u.port.plug==="output"||u.port.plug==="input/output")&&l.addOutputPort(u.port)},portRemoved(u){var l=s.getNodeWithId(u.nodeId);(u.port.plug==="input"||u.port.plug==="input/output")&&l.removeInputPortWithName(u.port.name),(u.port.plug==="output"||u.port.plug==="input/output")&&l.removeOutputPortWithName(u.port.name)},nodePortRenamed(u){(u.port.plug==="input"||u.port.plug==="input/output")&&s.renameInputPortOnNodeWithId(u.nodeId,u.oldName,u.port.name),(u.port.plug==="output"||u.port.plug==="input/output")&&s.renameOutputPortOnNodeWithId(u.nodeId,u.oldName,u.port.name);var l=s.getNodeWithId(u.nodeId);l.type==="Component Inputs"?(s.addInputPort(u.port),t.getNodesWithType(s.name).forEach(function(d){d.component.renameInputPortOnNodeWithId(d.id,u.oldName,u.port.name)}),s.removeInputPortWithName(u.oldName)):l.type==="Component Outputs"&&(s.addOutputPort(u.port),t.getNodesWithType(s.name).forEach(function(d){d.component.renameOutputPortOnNodeWithId(d.id,u.oldName,u.port.name)}),s.removeOutputPortWithName(u.oldName))},componentPortsUpdated(u){o(s,u.ports)},instancePortsChanged(u){if(s.hasNodeWithId(u.nodeId)){var l=s.getNodeWithId(u.nodeId);o(l,u.ports)}},componentRenamed(u){t.renameComponent(u.oldName,u.newName)},settingsChanged(u){t.setSettings(u.settings)},metadataChanged(u){t.setMetaData(u.key,u.data)},componentMetadataChanged(u){const l=t.getComponentWithName(u.componentName);l&&l.setMetadata(u.key,u.data)},variantParametersChanged(u){if(u.variant)t.updateVariant(u.variant);else if(t.updateVariantParameter(u.variantName,u.variantTypeName,u.parameterName,u.parameterValue,u.state),u.parameterValue===void 0){const l=t.getVariant(u.variantTypeName,u.variantName);e.rootComponent.nodeScope.getAllNodesWithVariantRecursive(l).forEach(p=>{p.queueInput(u.parameterName,p.getParameter(u.parameterName))})}},variantDeleted(u){t.deleteVariant(u.variantTypeName,u.variantName)},variantChanged(u){const l=s.getNodeWithId(u.nodeId),d=t.getVariant(l.type,u.variantName);l.setVariant(d)},variantRenamed(u){const l=t.getVariant(u.variantTypeName,u.oldVariantName);l&&(l.name=l.variantName)},defaultStateTransitionChanged(u){s.getNodeWithId(u.nodeId).setDefaultStateTransition(u.curve,u.state)},stateTransitionsChanged(u){const l=s.getNodeWithId(u.nodeId);u.parameterName&&l.setStateTransitionParamter(u.parameterName,u.curve,u.state)},variantDefaultStateTransitionChanged(u){t.updateVariantDefaultStateTransition(u.variantName,u.variantTypeName,u.curve,u.state)},variantStateTransitionsChanged(u){t.updateVariantStateTransition(u)},routerIndexChanged(u){t.routerIndex=u.data}};a.hasOwnProperty(n.type)?(await a[n.type](n),e.scheduleUpdate()):console.log("Unknown event",n)}}async function asyncPool(e,t,n){const o=[],r=[];for(const s of t){const a=Promise.resolve().then(()=>n(s,t));if(o.push(a),e<=t.length){const u=a.then(()=>r.splice(r.indexOf(u),1));r.push(u),r.length>=e&&await Promise.race(r)}}return Promise.all(o)}const ComponentInputs={node:{name:"Component Inputs",shortDesc:"This node is used to define the inputs of a component.",docs:"https://docs.noodl.net/nodes/component-utilities/component-inputs",panels:[{name:"PortEditor",context:["select","connectFrom"],title:"Inputs",plug:"output",type:{name:"*"},canArrangeInGroups:!0},{name:"PropertyEditor",hidden:!0}],getInspectInfo(){return{type:"value",value:this.nodeScope.componentOwner._internal.inputValues}},color:"component",haveComponentPorts:!0,category:"Component Utilities",methods:{registerOutputIfNeeded(e){this.hasOutput(e)||this.registerOutput(e,{getter(){return this.nodeScope.componentOwner._internal.inputValues[e]}})},_updateDependencies(){this.nodeScope.componentOwner.update()}}}},ComponentOutputs={node:{category:"Component Utilities",name:"Component Outputs",shortDesc:"This node is used to define the outputs of a component.",docs:"https://docs.noodl.net/nodes/component-utilities/component-outputs",panels:[{name:"PortEditor",context:["select","connectTo"],title:"Outputs",plug:"input",type:{name:"*"},canArrangeInGroups:!0},{name:"PropertyEditor",hidden:!0}],color:"component",haveComponentPorts:!0,prototypeExtensions:{registerInputIfNeeded(e){this.hasInput(e)||this.registerInput(e,{set(t){this.nodeScope.componentOwner.setOutputFromComponentOutput(e,t)}})}}}};function Model(e,t){this.id=e,this.data=t}const models=Model._models={},proxies={},_modelProxyHandler={get(e,t,n){return typeof e[t]=="function"?e[t].bind(e):t in e?Reflect.get(e,t,n):e.get(t)},set(e,t,n){if(t==="_class")e._class=n;else{if(t==="id")return console.log(`Noodl.Object warning: id is readonly (Id is ${e.id}, trying to set to ${n})`),!0;e.set(t,n)}return!0},ownKeys(e){return Reflect.ownKeys(e.data)},getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e.data,t)}};Model.get=function(e){return e===void 0&&(e=Model.guid()),models[e]||(models[e]=new Model(e,{}),proxies[e]=new Proxy(models[e],_modelProxyHandler)),proxies[e]},Model.create=function(e){var t=e||{},n=Model.get(t.id);for(var o in t)o!=="id"&&n.set(o,t[o]);return n},Model.exists=function(e){return models[e]!==void 0},Model.instanceOf=function(e){return e instanceof Model||e.target instanceof Model};function _randomString(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";for(let o=0;o<e;++o)n+=t[Math.floor((1+Math.random())*65536)%t.length];return n}Model.guid=function e(){return _randomString(10)},Model.prototype.on=function(e,t){this.listeners||(this.listeners={}),this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t)},Model.prototype.off=function(e,t){if(this.listeners&&this.listeners[e]){var n=this.listeners[e].indexOf(t);n!==-1&&this.listeners[e].splice(n,1)}},Model.prototype.notify=function(e,t){if(this.listeners&&this.listeners[e])for(var n=this.listeners[e].slice(),o=0;o<n.length;o++)n[o](t)},Model.prototype.setAll=function(e){for(var t in e)if(t!=="id"&&this.data[t]!==e[t]){var n=this.data[t];this.data[t]=e[t],this.notify("change",{name:t,value:e[t],old:n})}},Model.prototype.fill=function(e=null){for(const t in this.data){if(t==="id")continue;const n=this.data[t];this.data[t]=e,this.notify("change",{name:t,value:this.data[t],old:n})}},Model.prototype.set=function(e,t,n){if(n&&n.resolve&&e.indexOf(".")!==-1){const s=e.split(".");let a=this;for(let u=0;u<s.length-1;u++){const l=a.get(s[u]);if(Model.instanceOf(l))a=l;else return}a.set(s[s.length-1],t);return}const o=n&&n.forceChange,r=this.data[e];this.data[e]=t,(o||r!==t)&&(!n||!n.silent)&&this.notify("change",{name:e,value:t,old:r})},Model.prototype.getId=function(){return this.id},Model.prototype.get=function(e,t){if(t&&t.resolve&&e.indexOf(".")!==-1){const n=e.split(".");let o=this;for(let r=0;r<n.length-1;r++){const s=o.get(n[r]);if(Model.instanceOf(s))o=s;else return}return o.get(n[n.length-1])}return this.data[e]},Model.prototype.toJSON=function(){return Object.assign({},this.data,{id:this.id})},Model.Scope=function(){this.models={},this.proxies={}},Model.Scope.prototype.get=function(e){return e===void 0&&(e=Model.guid()),this.models[e]||(this.models[e]=new Model(e,{}),this.proxies[e]=new Proxy(this.models[e],_modelProxyHandler)),this.proxies[e]},Model.Scope.prototype.create=function(e){var t=e||{},n=this.get(t.id);for(var o in t)o!=="id"&&n.set(o,t[o]);return n},Model.Scope.prototype.exists=function(e){return this.models[e]!==void 0},Model.Scope.prototype.instanceOf=function(e){return e instanceof Model||e.target instanceof Model},Model.Scope.prototype.guid=function e(){return _randomString(10)},Model.Scope.prototype.reset=function(){this.models={},this.proxies={},delete this._cloudStore};function sendSignalOnInput(e,t){e.queueInput(t,!0),e.queueInput(t,!1)}const RunTasksDefinition={name:"RunTasks",displayNodeName:"Run Tasks",docs:"https://docs.noodl.net/nodes/data/run-tasks",color:"data",category:"Data",initialize(){this._internal.queuedOperations=[],this._internal.state="idle",this._internal.maxRunningTasks=10,this._internal.activeTasks=new Map},inputs:{items:{group:"Data",displayName:"Items",type:"array",set(e){e&&e!==this._internal.items&&(this._internal.items=e)}},stopOnFailure:{group:"General",displayName:"Stop On Failure",type:"boolean",default:!1,set(e){this._internal.stopOnFailure=e}},maxRunningTasks:{group:"General",displayName:"Max Running Tasks",type:"number",default:10,set(e){this._internal.maxRunningTasks=e}},taskTemplate:{type:"component",displayName:"Template",group:"General",set(e){this._internal.template=e}},run:{group:"General",displayName:"Do",type:"signal",valueChangedToTrue(){this.scheduleRun()}},abort:{group:"General",displayName:"Abort",type:"signal",valueChangedToTrue(){this.scheduleAbort()}}},outputs:{success:{type:"signal",group:"Events",displayName:"Success"},failure:{type:"signal",group:"Events",displayName:"Failure"},done:{type:"signal",group:"Events",displayName:"Done"},aborted:{type:"signal",group:"Events",displayName:"Aborted"}},methods:{scheduleRun(){var e=this._internal;e.hasScheduledRun||(e.hasScheduledRun=!0,this.scheduleAfterInputsHaveUpdated(()=>{this._queueOperation(()=>{e.hasScheduledRun=!1,this.run()})}))},scheduleAbort(){var e=this._internal;e.hasScheduledAbort||(e.hasScheduledAbort=!0,this.scheduleAfterInputsHaveUpdated(()=>{this._queueOperation(()=>{e.hasScheduledAbort=!1,this.abort()})}))},async createTaskComponent(e){const t=this._internal,o=(this.nodeScope.modelScope||Model).create(e);var r=await this.nodeScope.createNode(t.template,guid(),{_forEachModel:o,_forEachNode:this});const s=r.isInputConnected.bind(r);r.isInputConnected=u=>u==="Do"?!0:s(u),r.hasInput("Id")&&r.setInputValue("Id",o.getId()),r.hasInput("id")&&r.setInputValue("id",o.getId());for(var a in r._inputs)o.data[a]!==void 0&&r.setInputValue(a,o.data[a]);return r._internal.creatorCallbacks={onOutputChanged:(u,l,d)=>{(d===!1||d===void 0)&&l===!0&&this.itemOutputSignalTriggered(u,o,r)}},r},async startTask(e){const t=this._internal;try{const n=await this.createTaskComponent(e);t.runningTasks++,sendSignalOnInput(n,"Do"),t.activeTasks.set(n.id,n)}catch(n){console.log(n)}},async run(){const e=this._internal;if(this.context.editorConnection&&(e.state!=="idle"?this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"Cannot start when not in idle mode"}):e.template?e.items?this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks"):this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"No items array provided."}):this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"run-tasks",{message:"No task template specified."})),e.state==="idle"&&e.template&&e.items){e.state="running",e.numTasks=e.items.length,e.failedTasks=0,e.completedTasks=0,e.queuedTasks=[].concat(e.items),e.runningTasks=0,e.items.length===0&&(this.sendSignalOnOutput("success"),e.state="idle");for(let t=0;t<Math.min(e.maxRunningTasks,e.queuedTasks.length);t++){const n=e.queuedTasks.shift();if(!n)break;this.startTask(n)}}},abort(){const e=this._internal;e.state="aborted"},itemOutputSignalTriggered(e,t,n){const o=this._internal;if(o.state==="idle")return;const r=()=>{if(o.state==="aborted"){this.sendSignalOnOutput("aborted"),o.state="idle";return}if(o.completedTasks===o.numTasks)o.failedTasks===0?this.sendSignalOnOutput("success"):this.sendSignalOnOutput("failure"),this.sendSignalOnOutput("done"),o.state="idle";else if(o.stopOnFailure)if(o.failedTasks===0){o.runningTasks++;const s=o.queuedTasks.shift();s&&this.startTask(s)}else this.sendSignalOnOutput("failure"),this.sendSignalOnOutput("aborted");else{o.runningTasks++;const s=o.queuedTasks.shift();s&&this.startTask(s)}};e==="Success"?(o.completedTasks++,o.runningTasks--,r()):e==="Failure"&&(o.completedTasks++,o.failedTasks++,o.runningTasks--,r()),o.activeTasks.delete(n.id),this.nodeScope.deleteNode(n)},_queueOperation(e){this._internal.queuedOperations.push(e),this._runQueueOperations()},async _runQueueOperations(){if(!this.runningOperations){for(this.runningOperations=!0;this._internal.queuedOperations.length;)await this._internal.queuedOperations.shift()();this.runningOperations=!1}}},_deleteAllTasks(){for(const e of this._internal.activeTasks)this.nodeScope.deleteNode(e);this._internal.activeTasks.clear()},_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this._deleteAllTasks()}},RunTasks={node:RunTasksDefinition},defaultRequestScript=`//Add custom code to setup the request object before the request
|
|
2
|
+
//is made.
|
|
3
|
+
//
|
|
4
|
+
//*Request.resource contains the resource path of the request.
|
|
5
|
+
//*Request.method contains the method, GET, POST, PUT or DELETE.
|
|
6
|
+
//*Request.headers is a map where you can add additional headers.
|
|
7
|
+
//*Request.parameters is a map the parameters that will be appended
|
|
8
|
+
// to the url.
|
|
9
|
+
//*Request.content contains the content of the request as a javascript
|
|
10
|
+
// object.
|
|
11
|
+
//
|
|
12
|
+
`,defaultResponseScript=`// Add custom code to convert the response content to outputs
|
|
13
|
+
//
|
|
14
|
+
//*Response.status The status code of the response
|
|
15
|
+
//*Response.content The content of the response as a javascript
|
|
16
|
+
// object.
|
|
17
|
+
//*Response.request The request object that resulted in the response.
|
|
18
|
+
//
|
|
19
|
+
//*Inputs and *Outputs contain the inputs and outputs of the node.
|
|
20
|
+
`,RestNode={name:"REST2",displayNodeName:"REST",docs:"https://docs.noodl.net/nodes/data/rest",category:"Data",color:"data",searchTags:["http","request","fetch"],initialize(){this._internal.inputValues={},this._internal.outputValues={},this._internal.outputValuesProxy=new Proxy(this._internal.outputValues,{set:(e,t,n)=>(n!==this._internal.outputValues[t]&&(this.registerOutputIfNeeded("out-"+t),this._internal.outputValues[t]=n,this.flagOutputDirty("out-"+t)),!0)}),this._internal.self={}},getInspectInfo(){return this._internal.inspectData?{type:"value",value:this._internal.inspectData}:{type:"text",value:"[Not executed yet]"}},inputs:{resource:{type:"string",displayName:"Resource",group:"Request",default:"/",set(e){this._internal.resource=e}},method:{type:{name:"enum",enums:[{label:"GET",value:"GET"},{label:"POST",value:"POST"},{label:"PUT",value:"PUT"},{label:"PATCH",value:"PATCH"},{label:"DELETE",value:"DELETE"}]},displayName:"Method",group:"Request",default:"GET",set(e){this._internal.method=e}},requestScript:{type:{name:"string",allowEditOnly:!0,codeeditor:"javascript"},displayName:"Request",default:defaultRequestScript,group:"Scripts",set(e){try{this._internal.requestFunc=new Function("Inputs","Outputs","Request",e)}catch(t){console.log(t)}}},responseScript:{type:{name:"string",allowEditOnly:!0,codeeditor:"javascript"},displayName:"Response",default:defaultResponseScript,group:"Scripts",set(e){try{this._internal.responseFunc=new Function("Inputs","Outputs","Response",e)}catch(t){console.log(t)}}},fetch:{type:"signal",displayName:"Fetch",group:"Actions",valueChangedToTrue(){this.scheduleFetch()}},cancel:{type:"signal",displayName:"Cancel",group:"Actions",valueChangedToTrue(){this.cancelFetch()}}},outputs:{failure:{type:"signal",displayName:"Failure",group:"Events"},success:{type:"signal",displayName:"Success",group:"Events"},canceled:{type:"signal",displayName:"Canceled",group:"Events"}},prototypeExtensions:{getScriptOutputValue(e){return this._internal.outputValues[e]},setScriptInputValue(e,t){return this._internal.inputValues[e]=t},registerOutputIfNeeded(e){if(!this.hasOutput(e)&&e.startsWith("out-"))return this.registerOutput(e,{getter:this.getScriptOutputValue.bind(this,e.substring(4))})},registerInputIfNeeded(e){if(!this.hasInput(e)&&e.startsWith("in-"))return this.registerInput(e,{set:this.setScriptInputValue.bind(this,e.substring(3))})},scheduleFetch(){var e=this._internal;e.hasScheduledFetch||(e.hasScheduledFetch=!0,this.scheduleAfterInputsHaveUpdated(this.doFetch.bind(this)))},doResponse(e,t,n){this._internal.responseFunc&&this._internal.responseFunc.apply(this._internal.self,[this._internal.inputValues,this._internal.outputValuesProxy,{status:e,content:t,request:n}]),this._internal.inspectData={status:e,content:t},e>=200&&e<300?this.sendSignalOnOutput("success"):this.sendSignalOnOutput("failure")},doExternalFetch(e){var t=e.resource;if(Object.keys(e.parameters).length>0){var n=Object.keys(e.parameters).map(function(a){return a+"="+encodeURIComponent(e.parameters[a])});t+="?"+n.join("&")}if(typeof _noodl_cloud_runtime_version>"u"){var o=this,r=new window.XMLHttpRequest;this._xhr=r,r.open(e.method,t,!0);for(var s in e.headers)r.setRequestHeader(s,e.headers[s]);r.onreadystatechange=function(){var a=!1;if(this.readyState===4||this.readyState===XMLHttpRequest.DONE){var u=this.status,l=this.getResponseHeader("content-type"),d=this.response;if(delete this._xhr,l){l=l.toLowerCase();const p=l.indexOf("json")!==-1?JSON.parse(d):d;o.doResponse(u,p,e),a=!0}a===!1&&o.doResponse(u,d,e)}},r.onerror=function(a){delete this._xhr,o.sendSignalOnOutput("failure")},r.onabort=function(){delete this._xhr,o.sendSignalOnOutput("canceled")},e.content?(r.setRequestHeader("Content-Type","application/json"),r.send(JSON.stringify(e.content))):r.send()}else{const a=Object.assign({},e.headers,e.content?{"Content-Type":"application/json"}:{});fetch(t,{method:e.method,headers:a,body:e.content?JSON.stringify(e.content):void 0}).then(u=>{const l=u.headers.get("content-type");l?l.indexOf("/json")!==-1?u.json().then(d=>{this.doResponse(u.status,d,e)}):this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"rest-run-waring-",{message:"REST only supports json content type in response."}):u.text().then(d=>{this.doResponse(u.status,d,e)})}).catch(u=>{console.log("REST: Failed to request",t),console.log(u),this.sendSignalOnOutput("failure")})}},doFetch(){this._internal.hasScheduledFetch=!1;var e=this._internal.resource;if(e)for(var t in this._internal.inputValues)e=e.replace("{"+t+"}",this._internal.inputValues[t]);var n={resource:e,headers:{},method:this._internal.method!==void 0?this._internal.method:"GET",parameters:{}};this._internal.requestFunc&&this._internal.requestFunc.apply(this._internal.self,[this._internal.inputValues,this._internal.outputValuesProxy,n]),this.doExternalFetch(n)},cancelFetch(){typeof _noodl_cloud_runtime_version>"u"?this._xhr&&this._xhr.abort():this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"rest-run-waring-",{message:"REST doesn't support cancel in cloud functions."})}}};function _parseScriptForErrors(e,t,n,o,r,s){if(r.editorConnection.clearWarning(o.component.name,o.id,"rest-run-waring-"+n),e===void 0){r.editorConnection.clearWarning(o.component.name,o.id,"rest-parse-waring-"+n);return}try{new Function(...t,e),r.editorConnection.clearWarning(o.component.name,o.id,"rest-parse-waring-"+n)}catch(p){r.editorConnection.sendWarning(o.component.name,o.id,"rest-parse-waring-"+n,{message:"<strong>"+n+"</strong>: "+p.message,showGlobally:!0})}function a(p){return s.find(f=>f.name===p)!==void 0}const u=e.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,""),l=u.match(/Inputs\.[A-Za-z0-9]+/g);if(l){const p={};l.forEach(f=>{p[f.substring(7)]=!0}),Object.keys(p).forEach(f=>{a("in-"+f)||s.push({name:"in-"+f,displayName:f,plug:"input",type:"*",group:"Inputs"})})}const d=u.match(/Outputs\.[A-Za-z0-9]+/g);if(d){const p={};d.forEach(f=>{p[f.substring(8)]=!0}),Object.keys(p).forEach(f=>{a("out-"+f)||s.push({name:"out-"+f,displayName:f,plug:"output",type:"*",group:"Outputs"})})}}const RestNode$1={node:RestNode,setup(e,t){if(!e.editorConnection)return;function n(o){function r(){if(!o.parameters)return;var s=[];function a(f){for(var m=0;m<s.length;m++)if(s[m].name===f&&s[m].plug==="input")return!0;return!1}if(o.parameters.resource){var u=o.parameters.resource.match(/\{[A-Za-z0-9_]*\}/g);for(var l in u){var d=u[l],p=d.replace("{","").replace("}","");a("in-"+p)||s.push({name:"in-"+p,displayName:p,type:"string",plug:"input",group:"Inputs"})}}o.parameters.requestScript&&_parseScriptForErrors(o.parameters.requestScript,["Inputs","Outputs","Request"],"Request script",o,e,s),o.parameters.responseScript&&_parseScriptForErrors(o.parameters.responseScript,["Inputs","Outputs","Response"],"Response script",o,e,s),e.editorConnection.sendDynamicPorts(o.id,s)}r(),o.on("parameterUpdated",function(){r()})}t.on("editorImportComplete",()=>{t.on("nodeAdded.REST2",function(o){n(o)});for(const o of t.getNodesWithType("REST2"))n(o)})}};var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var lodash_difference,hasRequiredLodash_difference;function requireLodash_difference(){if(hasRequiredLodash_difference)return lodash_difference;hasRequiredLodash_difference=1;var e=200,t="__lodash_hash_undefined__",n=9007199254740991,o="[object Arguments]",r="[object Function]",s="[object GeneratorFunction]",a=/[\\^$.*+?()[\]{}|]/g,u=/^\[object .+?Constructor\]$/,l=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,d=typeof self=="object"&&self&&self.Object===Object&&self,p=l||d||Function("return this")();function f(c,h,g){switch(g.length){case 0:return c.call(h);case 1:return c.call(h,g[0]);case 2:return c.call(h,g[0],g[1]);case 3:return c.call(h,g[0],g[1],g[2])}return c.apply(h,g)}function m(c,h){var g=c?c.length:0;return!!g&&P(c,h,0)>-1}function y(c,h){for(var g=-1,_=h.length,I=c.length;++g<_;)c[I+g]=h[g];return c}function v(c,h,g,_){for(var I=c.length,b=g+-1;++b<I;)if(h(c[b],b,c))return b;return-1}function P(c,h,g){if(h!==h)return v(c,S,g);for(var _=g-1,I=c.length;++_<I;)if(c[_]===h)return _;return-1}function S(c){return c!==c}function C(c,h){return c.has(h)}function N(c,h){return c?.[h]}function T(c){var h=!1;if(c!=null&&typeof c.toString!="function")try{h=!!(c+"")}catch{}return h}var O=Array.prototype,ne=Function.prototype,G=Object.prototype,J=p["__core-js_shared__"],z=function(){var c=/[^.]+$/.exec(J&&J.keys&&J.keys.IE_PROTO||"");return c?"Symbol(src)_1."+c:""}(),q=ne.toString,V=G.hasOwnProperty,B=G.toString,ie=RegExp("^"+q.call(V).replace(a,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),K=p.Symbol,oe=G.propertyIsEnumerable,re=O.splice,Q=K?K.isConcatSpreadable:void 0,X=Math.max,se=Z(p,"Map"),F=Z(Object,"create");function w(c){var h=-1,g=c?c.length:0;for(this.clear();++h<g;){var _=c[h];this.set(_[0],_[1])}}function ae(){this.__data__=F?F(null):{}}function ue(c){return this.has(c)&&delete this.__data__[c]}function le(c){var h=this.__data__;if(F){var g=h[c];return g===t?void 0:g}return V.call(h,c)?h[c]:void 0}function de(c){var h=this.__data__;return F?h[c]!==void 0:V.call(h,c)}function ce(c,h){var g=this.__data__;return g[c]=F&&h===void 0?t:h,this}w.prototype.clear=ae,w.prototype.delete=ue,w.prototype.get=le,w.prototype.has=de,w.prototype.set=ce;function x(c){var h=-1,g=c?c.length:0;for(this.clear();++h<g;){var _=c[h];this.set(_[0],_[1])}}function pe(){this.__data__=[]}function he(c){var h=this.__data__,g=L(h,c);if(g<0)return!1;var _=h.length-1;return g==_?h.pop():re.call(h,g,1),!0}function fe(c){var h=this.__data__,g=L(h,c);return g<0?void 0:h[g][1]}function me(c){return L(this.__data__,c)>-1}function ge(c,h){var g=this.__data__,_=L(g,c);return _<0?g.push([c,h]):g[_][1]=h,this}x.prototype.clear=pe,x.prototype.delete=he,x.prototype.get=fe,x.prototype.has=me,x.prototype.set=ge;function M(c){var h=-1,g=c?c.length:0;for(this.clear();++h<g;){var _=c[h];this.set(_[0],_[1])}}function ye(){this.__data__={hash:new w,map:new(se||x),string:new w}}function ve(c){return U(this,c).delete(c)}function _e(c){return U(this,c).get(c)}function Ce(c){return U(this,c).has(c)}function Ne(c,h){return U(this,c).set(c,h),this}M.prototype.clear=ye,M.prototype.delete=ve,M.prototype.get=_e,M.prototype.has=Ce,M.prototype.set=Ne;function W(c){var h=-1,g=c?c.length:0;for(this.__data__=new M;++h<g;)this.add(c[h])}function Se(c){return this.__data__.set(c,t),this}function Ie(c){return this.__data__.has(c)}W.prototype.add=W.prototype.push=Se,W.prototype.has=Ie;function L(c,h){for(var g=c.length;g--;)if(De(c[g][0],h))return g;return-1}function be(c,h,g,_){var I=-1,b=m,E=!0,A=c.length,k=[],Le=h.length;if(!A)return k;h.length>=e&&(b=C,E=!1,h=new W(h));e:for(;++I<A;){var D=c[I],$=D;if(D=D!==0?D:0,E&&$===$){for(var te=Le;te--;)if(h[te]===$)continue e;k.push(D)}else b(h,$,_)||k.push(D)}return k}function Oe(c,h,g,_,I){var b=-1,E=c.length;for(g||(g=we),I||(I=[]);++b<E;){var A=c[b];g(A)&&y(I,A)}return I}function Pe(c){if(!ee(c)||Re(c))return!1;var h=Y(c)||T(c)?ie:u;return h.test(xe(c))}function Ee(c,h){return h=X(h===void 0?c.length-1:h,0),function(){for(var g=arguments,_=-1,I=X(g.length-h,0),b=Array(I);++_<I;)b[_]=g[h+_];_=-1;for(var E=Array(h+1);++_<h;)E[_]=g[_];return E[h]=b,f(c,this,E)}}function U(c,h){var g=c.__data__;return Te(h)?g[typeof h=="string"?"string":"hash"]:g.map}function Z(c,h){var g=N(c,h);return Pe(g)?g:void 0}function we(c){return Ae(c)||Fe(c)||!!(Q&&c&&c[Q])}function Te(c){var h=typeof c;return h=="string"||h=="number"||h=="symbol"||h=="boolean"?c!=="__proto__":c===null}function Re(c){return!!z&&z in c}function xe(c){if(c!=null){try{return q.call(c)}catch{}try{return c+""}catch{}}return""}var Me=Ee(function(c,h){return H(c)?be(c,Oe(h,1,H)):[]});function De(c,h){return c===h||c!==c&&h!==h}function Fe(c){return H(c)&&V.call(c,"callee")&&(!oe.call(c,"callee")||B.call(c)==o)}var Ae=Array.isArray;function je(c){return c!=null&&Ve(c.length)&&!Y(c)}function H(c){return We(c)&&je(c)}function Y(c){var h=ee(c)?B.call(c):"";return h==r||h==s}function Ve(c){return typeof c=="number"&&c>-1&&c%1==0&&c<=n}function ee(c){var h=typeof c;return!!c&&(h=="object"||h=="function")}function We(c){return!!c&&typeof c=="object"}return lodash_difference=Me,lodash_difference}var lodash_differenceExports=requireLodash_difference();const difference=getDefaultExportFromCjs(lodash_differenceExports),ExpressionNode={name:"Expression",docs:"https://docs.noodl.net/nodes/math/expression",usePortAsLabel:"expression",category:"CustomCode",color:"javascript",nodeDoubleClickAction:{focusPort:"Expression"},searchTags:["javascript"],initialize(){var e=this._internal;e.scope={},e.hasScheduledEvaluation=!1,e.code=void 0,e.cachedValue=0,e.currentExpression="",e.compiledFunction=void 0,e.inputNames=[],e.inputValues=[]},getInspectInfo(){return this._internal.cachedValue},inputs:{expression:{group:"General",inputPriority:1,type:{name:"string",allowEditOnly:!0,codeeditor:"javascript"},displayName:"Expression",set(e){var t=this._internal;t.currentExpression=functionPreamble+"return ("+e+");",t.compiledFunction=void 0;var n=parsePorts(e),o=difference(n,t.inputNames),r=difference(t.inputNames,n),s=this;r.forEach(function(a){s.deregisterInput(a),delete t.scope[a]}),o.forEach(function(a){s.hasInput(a)||(s.registerInput(a,{set(u){t.scope[a]=u,this.isInputConnected("run")||this._scheduleEvaluateExpression()}}),t.scope[a]=0,s._inputValues[a]=0)}),t.inputNames=Object.keys(t.scope),this.isInputConnected("run")||this._scheduleEvaluateExpression()}},run:{group:"Actions",displayName:"Run",type:"signal",valueChangedToTrue(){this._scheduleEvaluateExpression()}}},outputs:{result:{group:"Result",type:"*",displayName:"Result",getter(){return this._internal.currentExpression?this._internal.cachedValue:0}},isTrue:{group:"Result",type:"boolean",displayName:"Is True",getter(){return this._internal.currentExpression?!!this._internal.cachedValue:!1}},isFalse:{group:"Result",type:"boolean",displayName:"Is False",getter(){return this._internal.currentExpression?!this._internal.cachedValue:!0}},isTrueEv:{group:"Events",type:"signal",displayName:"On True"},isFalseEv:{group:"Events",type:"signal",displayName:"On False"}},prototypeExtensions:{registerInputIfNeeded:{value(e){this.hasInput(e)||(this._internal.scope[e]=0,this._inputValues[e]=0,this.registerInput(e,{set(t){this._internal.scope[e]=t,this.isInputConnected("run")||this._scheduleEvaluateExpression()}}))}},_scheduleEvaluateExpression:{value(){var e=this._internal;e.hasScheduledEvaluation===!1&&(e.hasScheduledEvaluation=!0,this.flagDirty(),this.scheduleAfterInputsHaveUpdated(function(){var t=e.cachedValue;e.cachedValue=this._calculateExpression(),t!==e.cachedValue&&(this.flagOutputDirty("result"),this.flagOutputDirty("isTrue"),this.flagOutputDirty("isFalse")),e.cachedValue?this.sendSignalOnOutput("isTrueEv"):this.sendSignalOnOutput("isFalseEv"),e.hasScheduledEvaluation=!1}))}},_calculateExpression:{value(){var e=this._internal;e.compiledFunction||(e.compiledFunction=this._compileFunction());for(var t=0;t<e.inputNames.length;++t){var n=e.scope[e.inputNames[t]];e.inputValues[t]=n}try{return e.compiledFunction.apply(null,e.inputValues)}catch(o){console.error("Error in expression:",o.message)}return 0}},_compileFunction:{value(){var e=this._internal.currentExpression,t=Object.keys(this._internal.scope),n=e+t.join(" ");if(compiledFunctionsCache.hasOwnProperty(n)===!1){t.push(e);try{compiledFunctionsCache[n]=construct(Function,t)}catch(o){console.error("Failed to compile JS function",o.message)}}return compiledFunctionsCache[n]}}}};var functionPreamble=["var min = Math.min, max = Math.max, cos = Math.cos, sin = Math.sin, tan = Math.tan, sqrt = Math.sqrt, pi = Math.PI, round = Math.round, floor = Math.floor, ceil = Math.ceil, abs = Math.abs, random = Math.random;"].join("");function construct(e,t){function n(){return e.apply(this,t)}return n.prototype=e.prototype,new n}var compiledFunctionsCache={},portsToIgnore=["min","max","cos","sin","tan","sqrt","pi","round","floor","ceil","abs","random","Math","window","document","undefined","Vars","true","false","null","Boolean"];function parsePorts(e){var t=[];function n(s){portsToIgnore.indexOf(s)===-1&&(t.some(function(a){return a===s})||t.push(s))}e=e.replace(/\"([^\"]*)\"/g,"").replace(/\'([^\']*)\'/g,"");var o=e.matchAll(/[a-zA-Z\_\$][a-zA-Z0-9\.\_\$]*/g);for(const s of o){var r=s[0];r.indexOf(".")!==-1&&(r=r.split(".")[0]),n(r)}return t}function updatePorts$7(e,t,n){var o=parsePorts(t),r=o.map(function(s){return{group:"Parameters",name:s,type:{name:"*",editAsType:"string"},plug:"input"}});n.sendDynamicPorts(e,r)}function evalCompileWarnings(e,t){try{new Function(t.parameters.expression),e.clearWarning(t.component.name,t.id,"expression-compile-error")}catch(n){e.sendWarning(t.component.name,t.id,"expression-compile-error",{message:n.message})}}const Expression={node:ExpressionNode,setup(e,t){!e.editorConnection||!e.editorConnection.isRunningLocally()||t.on("nodeAdded.Expression",function(n){n.parameters.expression&&(updatePorts$7(n.id,n.parameters.expression,e.editorConnection),evalCompileWarnings(e.editorConnection,n)),n.on("parameterUpdated",function(o){o.name==="expression"&&(updatePorts$7(n.id,n.parameters.expression,e.editorConnection),evalCompileWarnings(e.editorConnection,n))})})}};function getAbsoluteUrl(e){const t=String(e);return!t||t[0]==="/"||t.includes("://")||t.startsWith("data:")?t:(Noodl.baseUrl||"/")+t}function logJavaScriptNodeError(e){typeof e=="string"?console.log("Error in JS node run code.",e):console.log("Error in JS node run code.",Object.getPrototypeOf(e).constructor.name+": "+e.message,e.stack)}var userFunctionsCache={};function JavascriptNodeParser(e,t){this.inputs={},this.outputs={},this.error=void 0,this.code=e;const n=t?t.node:void 0;this._initializeAPIs();var o=userFunctionsCache[e];if(!o)try{o=new Function(["define","script","Node","Component"],JavascriptNodeParser.getCodePrefix()+e),userFunctionsCache[e]=o}catch(r){this.error=r.message,console.error(r)}if(o)try{o(this.define.bind(this),this.script.bind(this),this.apis.Node,n?JavascriptNodeParser.getComponentScopeForNode(n):{}),this._afterSourced()}catch(r){this.error=r.message,console.error(r)}}JavascriptNodeParser.prototype.define=function(e){this.inputs=e.inputs||{},this.outputs=e.outputs||{},this.setup=e.setup,this.change=e.run||e.change,this.destroy=e.destroy,this.definedObject=e};function _scriptExtend(e){var t={inputs:e.inputs||{},outputs:e.outputs||{},setup(o,r){if(this.inputs=o,this.outputs=r,this.setOutputs=function(a){for(var u in a)this.outputs[u]=a[u],this.flagOutputDirty(u)},e.methods)for(var s in e.methods)this[s]=e.methods[s];e.setup&&e.setup.apply(this)},destroy(o,r){this.inputs=o,this.outputs=r,e.destroy&&e.destroy.apply(this)},change(o,r){this.inputs=o,this.outputs=r;var s=this._oldInputs||{};if(e.changed){for(var a in o)if(o[a]!==s[a]){var u=e.changed[a];typeof u=="function"&&u.apply(this,[o[a],s[a]])}}this._oldInputs=Object.assign({},o)}};if(e.signals)for(var n in e.signals)t[n]=e.signals[n],t.inputs[n]="signal";return t}JavascriptNodeParser.prototype.script=function(e){var t=_scriptExtend(e);this.inputs=t.inputs||{},this.outputs=t.outputs||{},this.setup=t.setup,this.change=t.run||t.change,this.destroy=t.destroy,this.definedObject=t},JavascriptNodeParser.prototype._initializeAPIs=function(){this.apis={},this.apis.Node={Inputs:{},Outputs:{},Signals:{},Setters:{}}},JavascriptNodeParser.prototype._afterSourced=function(){if(this.definedObject===void 0){var e=this.apis.Node;if(this.inputs=Object.assign({},e.Inputs||{}),this.outputs=Object.assign({},e.Outputs||{}),this.setup=function(n,o){const r=this;e.setOutputs=function(s){for(var a in s)o[a]=s[a],r.flagOutputDirty(a)},e.OnInit&&e.OnInit.apply(this)},this.destroy=e.OnDestroy||this.destory,this.change=(n,o,r)=>{for(var s in r)typeof e.Setters[s]=="function"&&e.Setters[s](n[s]);typeof e.OnInputsChanged=="function"&&e.OnInputsChanged()},this.definedObject={inputs:this.inputs,outputs:this.outputs,setup:this.setup,destroy:this.destroy,change:this.change},e.Signals!==void 0)for(var t in e.Signals)typeof e.Signals[t]=="function"&&(this.inputs[t]="signal",this.definedObject[t]=e.Signals[t])}},JavascriptNodeParser.createFromCode=function(e,t){return new JavascriptNodeParser(e,t)},JavascriptNodeParser.createFromURL=function(e,t,n){e=getAbsoluteUrl(e);var o=new window.XMLHttpRequest;o.open("GET",e,!0),o.onreadystatechange=function(){(this.readyState===4||this.readyState===XMLHttpRequest.DONE)&&t(new JavascriptNodeParser(this.response))},o.onerror=function(){console.log("Failed to request",e)},o.send()},JavascriptNodeParser.parseAndAddPortsFromScript=function(e,t,n){function o(s){return typeof s=="string"?t.find(a=>a.name===s)!==void 0:t.find(a=>a.name===s.name&&a.plug===s.plug)!==void 0}function r(s,a){if(s==null)return;const u={};for(const l of s){let d=l[1];d!==void 0&&(u[d]=!0)}Object.keys(u).forEach(l=>{o({name:a.prefix+l,plug:a.plug})||t.push({name:a.prefix+l,displayName:l,plug:a.plug,type:a.type,group:a.group})})}n.skipInputs||(r(e.matchAll(/Inputs\.([A-Za-z0-9_]+)/g),{type:n.inputType||"*",plug:"input",group:n.inputGroup||"Inputs",prefix:n.inputPrefix||""}),r(e.matchAll(/Inputs\s*\[\s*(?:'|")(.*)(?:'|")\s*\]/g),{type:n.inputType||"*",plug:"inputs",group:n.inputGroup||"Inputs",prefix:n.inputPrefix||""})),n.skipOutputs||(n.skipOutputSignals||(r(e.matchAll(/Outputs\.([A-Za-z0-9]+)\s*\(\s*\)/g),{type:"signal",plug:"output",group:"Outputs",prefix:n.outputPrefix||""}),r(e.matchAll(/Outputs\s*\[\s*(?:'|")(.*)(?:'|")\s*\]\(\s*\)/g),{type:"signal",plug:"output",group:"Outputs",prefix:n.outputPrefix||""})),n.skipRegularOutputs||(r(e.matchAll(/Outputs\.([A-Za-z0-9_]+)/g),{type:"*",plug:"output",group:"Outputs",prefix:n.outputPrefix||""}),r(e.matchAll(/Outputs\s*\[\s*\"([^\"]*)\"\s*\]/g),{type:"*",plug:"output",group:"Outputs",prefix:n.outputPrefix||""})))},JavascriptNodeParser.prototype.getPorts=function(){var e=[],t=this;return Object.keys(this.inputs).forEach(function(n){var o=t.inputs[n],r={name:n,plug:"input"};if(typeof o=="string")r.type={name:o},r.group="Inputs";else for(var s in o)r[s]=o[s];e.push(r)}),Object.keys(this.outputs).forEach(function(n){e.push({name:n,type:{name:t.outputs[n]},plug:"output",group:"Outputs"})}),JavascriptNodeParser.parseAndAddPortsFromScript(this.code,e,{}),e};const _componentScopes={};function _findParentComponentStateModelId(e){function t(o){let r;if(o.getRoots().length>0){const s=o.getRoots()[0];s.getVisualParentNode?s.getVisualParentNode()&&(r=s.getVisualParentNode().nodeScope.componentOwner):s.parentNodeScope&&(r=o.parentNodeScope.componentOwner)}else o.parentNodeScope&&(r=o.parentNodeScope.componentOwner);if(r&&r.nodeScope&&r.nodeScope.componentOwner!==o)return r.nodeScope.getNodesWithType("net.noodl.ComponentObject").length>0||r.nodeScope.getNodesWithType("Component State").length>0?r:t(r)}const n=t(e.nodeScope.componentOwner);if(n)return"componentState"+n.getInstanceId()}function _findForEachModel(e){for(var t=e.nodeScope.componentOwner;t!==void 0&&t._forEachModel===void 0&&t.parentNodeScope;)t=t.parentNodeScope.componentOwner;return t!==void 0?t._forEachModel:void 0}JavascriptNodeParser.getComponentScopeForNode=function(e){const t=e.nodeScope.componentOwner.getInstanceId();if(_componentScopes[t]===void 0){_componentScopes[t]={};const r=(e.nodeScope.modelScope||Model).get("componentState"+t);_componentScopes[t].Object=r}const n=_findParentComponentStateModelId(e),o=n!==void 0?(e.nodeScope.modelScope||Model).get(n):void 0;return _componentScopes[t].ParentObject=o,_componentScopes[t].RepeaterObject=_findForEachModel(e),_componentScopes[t]},JavascriptNodeParser.getCodePrefix=function(){return`const Script = (typeof Node !== 'undefined')?Node:undefined;
|
|
21
|
+
`},JavascriptNodeParser.createNoodlAPI=function(){return typeof window<"u"&&window.Noodl!==void 0?window.Noodl:{}};const SimpleJavascriptNode={name:"JavaScriptFunction",displayNodeName:"Function",docs:"https://docs.noodl.net/nodes/javascript/function",category:"CustomCode",color:"javascript",nodeDoubleClickAction:{focusPort:"Script"},searchTags:["javascript"],exportDynamicPorts:!0,initialize(){this._internal.inputValues={},this._internal.outputValues={},this._internal.outputValuesProxy=new Proxy(this._internal.outputValues,{set:(e,t,n)=>{if(!this._deleted)return n!==this._internal.outputValues[t]&&(this.registerOutputIfNeeded("out-"+t),this._internal.outputValues[t]=n,this.flagOutputDirty("out-"+t)),!0}}),this._internal._this={}},getInspectInfo(){return[{type:"value",value:{inputs:this._internal.inputValues,outputs:this._internal.outputValues}}]},inputs:{scriptInputs:{type:{name:"proplist",allowEditOnly:!0},group:"Script Inputs",set(e){}},scriptOutputs:{type:{name:"proplist",allowEditOnly:!0},group:"Script Outputs",set(e){}},functionScript:{displayName:"Script",plug:"input",type:{name:"string",allowEditOnly:!0,codeeditor:"javascript"},group:"General",set(e){if(e===void 0){this._internal.func=void 0;return}this._internal.func=this.parseScript(e),this.isInputConnected("run")||this.scheduleRun()}},run:{type:"signal",displayName:"Run",group:"Actions",valueChangedToTrue(){this.scheduleRun()}}},outputs:{},methods:{scheduleRun(){this.runScheduled||(this.runScheduled=!0,this.scheduleAfterInputsHaveUpdated(()=>{this.runScheduled=!1,this._deleted||this.runScript()}))},runScript:async function(){const e=this._internal.func;if(e===void 0)return;const t=this._internal.inputValues,n=this._internal.outputValuesProxy;for(const o in this.model.outputPorts)if(this._isSignalType(o)){const r=()=>{this.hasOutput(o)&&this.sendSignalOnOutput(o)};this._internal.outputValues[o.substring(4)]=r,this._internal.outputValues[o.substring(4)].send=r}try{await e.apply(this._internal._this,[t,n,JavascriptNodeParser.createNoodlAPI(this.nodeScope.modelScope),JavascriptNodeParser.getComponentScopeForNode(this)])}catch(o){logJavaScriptNodeError(o),this.context.editorConnection&&this.context.isWarningTypeEnabled("javascriptExecution")&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"js-function-run-waring",{showGlobally:!0,message:o.message,stack:o.stack})}},setScriptInputValue(e,t){this._internal.inputValues[e]=t,this.isInputConnected("run")||this.scheduleRun()},getScriptOutputValue(e){if(!this._isSignalType(e))return this._internal.outputValues[e]},setScriptInputType(e,t){this._internal.inputTypes[e]=t},setScriptOutputType(e,t){this._internal.outputTypes[e]=t},parseScript(e){var t;try{const n=Object.getPrototypeOf(async function(){}).constructor;t=new n("Inputs","Outputs","Noodl","Component",JavascriptNodeParser.getCodePrefix()+e)}catch(n){console.log("Error while parsing action script: "+n)}return t},_isSignalType(e){return this.model.outputPorts[e]&&this.model.outputPorts[e].type==="signal"},registerInputIfNeeded(e){if(!this.hasInput(e)){if(e.startsWith("in-")){const t=e.substring(3),n={set:this.setScriptInputValue.bind(this,t)};this.model&&this.model.parameters["intype-"+t]&&(n.type=this.model.parameters["intype-"+t]),this.registerInput(e,n)}if(e.startsWith("intype-")){const t=e.substring(7);this.registerInput(e,{set(n){this.hasInput("in"+t)&&(this.getInput("in"+t).type=n)}})}e.startsWith("outtype-")&&this.registerInput(e,{set(){}})}},registerOutputIfNeeded(e){if(!this.hasOutput(e)&&e.startsWith("out-"))return this.registerOutput(e,{getter:this.getScriptOutputValue.bind(this,e.substring(4))})}}};function _parseScriptForErrorsAndPorts(e,t,n,o,r){if(o.editorConnection.clearWarning(n.component.name,n.id,"js-function-run-waring"),e===void 0){o.editorConnection.clearWarning(n.component.name,n.id,"js-function-parse-waring");return}try{const s=Object.getPrototypeOf(async function(){}).constructor;new s("Inputs","Outputs","Noodl","Component",e),o.editorConnection.clearWarning(n.component.name,n.id,"js-function-parse-waring")}catch(s){o.editorConnection.sendWarning(n.component.name,n.id,"js-function-parse-waring",{showGlobally:!0,message:s.message})}JavascriptNodeParser.parseAndAddPortsFromScript(e,r,{inputPrefix:"in-",outputPrefix:"out-"})}const inputTypeEnums=[{value:"string",label:"String"},{value:"boolean",label:"Boolean"},{value:"number",label:"Number"},{value:"object",label:"Object"},{value:"date",label:"Date"},{value:"array",label:"Array"},{value:"color",label:"Color"}],SimpleJavaScript={node:SimpleJavascriptNode,setup(e,t){if(!e.editorConnection||!e.editorConnection.isRunningLocally())return;function n(o){function r(){var s=[];const a=inputTypeEnums.concat([{value:"signal",label:"Signal"}]);o.parameters.scriptOutputs!==void 0&&o.parameters.scriptOutputs.length>0&&o.parameters.scriptOutputs.forEach(u=>{s.push({name:"outtype-"+u.label,displayName:"Type",editorName:u.label+" | Type",plug:"input",type:{name:"enum",enums:a,allowEditOnly:!0},default:"string",parent:"scriptOutputs",parentItemId:u.id}),s.push({name:"out-"+u.label,displayName:u.label,plug:"output",type:o.parameters["outtype-"+u.label]||"*",group:"Outputs"})}),o.parameters.scriptInputs!==void 0&&o.parameters.scriptInputs.length>0&&o.parameters.scriptInputs.forEach(u=>{s.push({name:"intype-"+u.label,displayName:"Type",editorName:u.label+" | Type",plug:"input",type:{name:"enum",enums:inputTypeEnums,allowEditOnly:!0},default:"string",parent:"scriptInputs",parentItemId:u.id}),s.push({name:"in-"+u.label,displayName:u.label,plug:"input",type:o.parameters["intype-"+u.label]||"string",group:"Inputs"})}),_parseScriptForErrorsAndPorts(o.parameters.functionScript,"Script ",o,e,s),s.forEach(u=>{u.type==="signal"&&u.plug==="output"&&(o.outputPorts[u.name]=u)}),e.editorConnection.sendDynamicPorts(o.id,s)}r(),o.on("parameterUpdated",function(s){r()})}t.on("editorImportComplete",()=>{t.on("nodeAdded.JavaScriptFunction",function(o){n(o)});for(const o of t.getNodesWithType("JavaScriptFunction"))n(o)})}};Object.defineProperty(Array.prototype,"items",{enumerable:!1,get(){return this},set(e){this.set(e)}}),Object.defineProperty(Array.prototype,"each",{enumerable:!1,writable:!1,value:Array.prototype.forEach}),Object.defineProperty(Array.prototype,"size",{enumerable:!1,writable:!1,value(){return this.length}}),Object.defineProperty(Array.prototype,"get",{enumerable:!1,writable:!1,value(e){return this[e]}}),Object.defineProperty(Array.prototype,"getId",{enumerable:!1,writable:!1,value(){return this._id}}),Object.defineProperty(Array.prototype,"id",{enumerable:!1,get(){return this.getId()}}),Object.defineProperty(Array.prototype,"set",{enumerable:!1,writable:!1,value(e){var t,n;if(e===this)return;e=e||[];function o(d){for(var p={},f=d.length,m=0;m<f;m++){var y=d[m];p[y.getId()]=y}return p}var r=[];for(t=e.length,n=0;n<t;n++){var s=e[n];Model.instanceOf(s)?r.push(s):r.push(Model.create(s))}var a=this.items,u=o(a),l=o(r);for(t=a.length,n=0;n<t;n++)l.hasOwnProperty(a[n].getId())||(this.removeAtIndex(n),n--,t--);for(n=0;n<Math.min(a.length,r.length);n++)a[n]!==r[n]&&(u.hasOwnProperty(r[n].getId())&&this.remove(r[n]),this.addAtIndex(r[n],n));for(n=a.length;n<r.length;n++)this.add(r[n])}}),Object.defineProperty(Array.prototype,"notify",{enumerable:!1,writable:!1,value:async function(e,t){if(this._listeners&&this._listeners[e])for(var n=this._listeners[e].slice(),o=0;o<n.length;o++)await n[o](t)}}),Object.defineProperty(Array.prototype,"contains",{enumerable:!1,writable:!1,value(e){return this.indexOf(e)!==-1}}),Object.defineProperty(Array.prototype,"add",{enumerable:!1,writable:!1,value:async function(e){this.contains(e)||(this.items.push(e),await this.notify("add",{item:e,index:this.items.length-1}),await this.notify("change"),await e.notify("add",{collection:this}))}}),Object.defineProperty(Array.prototype,"remove",{enumerable:!1,writable:!1,value(e){var t=this.items.indexOf(e);t!==-1&&this.removeAtIndex(t)}}),Object.defineProperty(Array.prototype,"addAtIndex",{enumerable:!1,writable:!1,value:async function(e,t){this.contains(e)||(this.items.splice(t,0,e),await this.notify("add",{item:e,index:t}),await this.notify("change"),await e.notify("add",{collection:this,index:t}))}}),Object.defineProperty(Array.prototype,"removeAtIndex",{enumerable:!1,writable:!1,value:async function(e){var t=this.items[e];this.items.splice(e,1),await this.notify("remove",{item:t,index:e}),await this.notify("change"),await t.notify("remove",{collection:this})}}),Object.defineProperty(Array.prototype,"on",{enumerable:!1,writable:!1,value(e,t){this._listeners||Object.defineProperty(this,"_listeners",{enumerable:!1,writable:!1,value:{}}),this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t)}}),Object.defineProperty(Array.prototype,"off",{enumerable:!1,writable:!1,value(e,t){if(this._listeners&&this._listeners[e]){var n=this._listeners[e].indexOf(t);n!==-1&&this._listeners[e].splice(n,1)}}});class Collection extends Array{}const collections=Collection._collections={};Collection.create=function(e){const t=Model.guid();return collections[t]=new Collection,Object.defineProperty(collections[t],"_id",{enumerable:!1,writable:!1,value:t}),e&&collections[t].set(e),collections[t]},Collection.get=function(e){return e===void 0&&(e=Model.guid()),collections[e]||(collections[e]=new Collection,Object.defineProperty(collections[e],"_id",{enumerable:!1,writable:!1,value:e})),collections[e]},Collection.instanceOf=function(e){return e instanceof Collection},Collection.exists=function(e){return collections[e]!==void 0};function convertVisualFilter(e,t){var n=t.queryParameters;if(e.combinator!==void 0&&e.rules!==void 0){if(e.rules.length===0)return;if(e.rules.length===1)return convertVisualFilter(e.rules[0],t);{const l={},d="$"+e.combinator;return l[d]=[],e.rules.forEach(p=>{var f=convertVisualFilter(p,t);f!==void 0&&l[d].push(f)}),l}}else if(e.operator==="related to"){var o=e.input!==void 0?n[e.input]:void 0;return o===void 0?void 0:{$relatedTo:{object:{__type:"Pointer",objectId:o,className:e.relatedTo},key:e.relationProperty}}}else{const l={};var r,o=e.input!==void 0?n[e.input]:e.value;if(e.operator==="exist")return l[e.property]={$exists:!0},l;if(e.operator==="not exist")return l[e.property]={$exists:!1},l;if(o===void 0)return;if(CloudStore._collections[t.collectionName])var s=CloudStore._collections[t.collectionName].schema;var a=s&&s.properties&&s.properties[e.property]?s.properties[e.property].type:void 0;if(a==="Date"&&(o instanceof Date||(o=new Date(o.toString())),o={__type:"Date",iso:o.toISOString()}),e.operator==="greater than")r={$gt:o};else if(e.operator==="greater than or equal to")r={$gte:o};else if(e.operator==="less than")r={$lt:o};else if(e.operator==="less than or equal to")r={$lte:o};else if(e.operator==="equal to")r={$eq:o};else if(e.operator==="not equal to")r={$ne:o};else if(e.operator==="points to"){var u=s&&s.properties&&s.properties[e.property]?s.properties[e.property].targetClass:void 0;r={$eq:{__type:"Pointer",objectId:o,className:u}}}else e.operator==="contain"&&(r={$regex:o,$options:"i"});return l[e.property]=r,l}}function matchesQuery(e,t){var n=!0;if(t===void 0)return!0;if(t.$and!==void 0)t.$and.forEach(r=>{n&=matchesQuery(e,r)});else if(t.$or!==void 0)n=!1,t.$or.forEach(r=>{n|=matchesQuery(e,r)});else{var o=Object.keys(t);o.forEach(r=>{if(r==="objectId")t[r].$eq!==void 0?n&=e.getId()===t[r].$eq:t[r].$in!==void 0&&(n&=t[r].$in.indexOf(e.getId())!==-1);else if(r==="$relatedTo")n=!1;else{var s=e.get(r);t[r].$eq!==void 0&&t[r].$eq.__type==="Pointer"?n&=s===t[r].$eq.objectId:t[r].$eq!==void 0?n&=s==t[r].$eq:t[r].$ne!==void 0?n&=s!=t[r].$ne:t[r].$lt!==void 0?n&=s<t[r].$lt:t[r].$lte!==void 0?n&=s<=t[r].$lt:t[r].$gt!==void 0?n&=s>t[r].$gt:t[r].$gte!==void 0?n&=s>=t[r].$gte:t[r].$exists!==void 0?n&=s!==void 0:t[r].$in!==void 0?n&=t[r].$in.indexOf(s)!==-1:t[r].$nin!==void 0?n&=t[r].$in.indexOf(s)===-1:t[r].$regex!==void 0&&(n&=new RegExp(t[r].$regex,t[r].$options).test(s))}})}return n}function compareObjects(e,t,n){for(var o=0;o<e.length;o++){let r=e[o];if(r[0]==="-"){let s=r.substring(1);if(t.get(s)>n.get(s))return-1;if(t.get(s)<n.get(s))return 1}else{if(t.get(r)>n.get(r))return 1;if(t.get(r)<n.get(r))return-1}}return 0}function convertVisualSorting(e){return e.map(t=>(t.order==="descending"?"-":"")+t.property)}function _value(e){return e instanceof Date&&typeof e.toISOString=="function"?{__type:"Date",iso:e.toISOString()}:e}function convertFilterOp(e,t){const n=Object.keys(e);if(n.length===0)return{};if(n.length!==1)return t.error("Filter must only have one key found "+n.join(","));const o={},r=n[0];if(e.and!==void 0&&Array.isArray(e.and))o.$and=e.and.map(a=>convertFilterOp(a,t));else if(e.or!==void 0&&Array.isArray(e.or))o.$or=e.or.map(a=>convertFilterOp(a,t));else if(e.idEqualTo!==void 0)o.objectId={$eq:e.idEqualTo};else if(e.idContainedIn!==void 0)o.objectId={$in:e.idContainedIn};else if(e.relatedTo!==void 0){const a=e.relatedTo.id;if(a===void 0)return t.error("Must provide id in relatedTo filter");const u=e.relatedTo.key;if(u===void 0)return t.error("Must provide key in relatedTo filter");const l=e.relatedTo.className||(t.modelScope||Model).get(a)?._class;if(typeof l>"u")return t.error("Must preload the Pointer or include className");o.$relatedTo={object:{__type:"Pointer",objectId:a,className:l},key:u}}else if(typeof e[r]=="object"){const a=e[r];if(a.equalTo!==void 0)o[r]={$eq:_value(a.equalTo)};else if(a.notEqualTo!==void 0)o[r]={$ne:_value(a.notEqualTo)};else if(a.lessThan!==void 0)o[r]={$lt:_value(a.lessThan)};else if(a.greaterThan!==void 0)o[r]={$gt:_value(a.greaterThan)};else if(a.lessThanOrEqualTo!==void 0)o[r]={$lte:_value(a.lessThanOrEqualTo)};else if(a.greaterThanOrEqualTo!==void 0)o[r]={$gte:_value(a.greaterThanOrEqualTo)};else if(a.exists!==void 0)o[r]={$exists:a.exists};else if(a.containedIn!==void 0)o[r]={$in:a.containedIn};else if(a.notContainedIn!==void 0)o[r]={$nin:a.notContainedIn};else if(a.pointsTo!==void 0){let u=null;CloudStore._collections[t.collectionName]&&(u=CloudStore._collections[t.collectionName].schema);const l=u&&u.properties&&u.properties[r]?u.properties[r].targetClass:void 0;(u&&u.properties&&u.properties[r]?u.properties[r].type:void 0)==="Relation"?o[r]={__type:"Pointer",objectId:a.pointsTo,className:l}:Array.isArray(a.pointsTo)?o[r]={$in:a.pointsTo.map(p=>({__type:"Pointer",objectId:p,className:l}))}:o[r]={$eq:{__type:"Pointer",objectId:a.pointsTo,className:l}}}else if(a.matchesRegex!==void 0)o[r]={$regex:a.matchesRegex,$options:a.options};else if(a.text!==void 0&&a.text.search!==void 0){var s=a.text.search;typeof s=="string"?o[r]={$text:{$search:{$term:s,$caseSensitive:!1}}}:o[r]={$text:{$search:{$term:s.term,$language:s.language,$caseSensitive:s.caseSensitive,$diacriticSensitive:s.diacriticSensitive}}}}else if(a.nearSphere!==void 0){var s=a.nearSphere;o[r]={$nearSphere:{__type:"GeoPoint",latitude:s.latitude,longitude:s.longitude},$maxDistanceInMiles:s.$maxDistanceInMiles,$maxDistanceInKilometers:s.maxDistanceInKilometers,$maxDistanceInRadians:s.maxDistanceInRadians}}else if(a.withinBox!==void 0){var s=a.withinBox;o[r]={$within:{$box:s.map(l=>({__type:"GeoPoint",latitude:l.latitude,longitude:l.longitude}))}}}else if(a.withinPolygon!==void 0){var s=a.withinPolygon;o[r]={$geoWithin:{$polygon:s.map(l=>({__type:"GeoPoint",latitude:l.latitude,longitude:l.longitude}))}}}}else t.error("Unrecognized filter keys "+n.join(","));return o}var DbCollectionNode={name:"DbCollection2",docs:"https://docs.noodl.net/nodes/data/cloud-data/query-records",displayName:"Query Records",category:"Cloud Services",usePortAsLabel:"collectionName",color:"data",initialize(){var e=this;this._internal.queryParameters={};var t=!1;this._internal.collectionChangedCallback=function(){t||(t=!0,e.scheduleAfterInputsHaveUpdated(function(){e.flagOutputDirty("count"),e.flagOutputDirty("firstItemId"),e.flagOutputDirty("isEmpty"),t=!1}))},this._internal.cloudStoreEvents=function(o){if(e.isInputConnected("storageFetch")===!0||e._internal.collection===void 0||o.collection!==e._internal.name)return;function r(s){if(e._internal.currentQuery.sort!==void 0){for(var a=0;a<e._internal.collection.size()&&!(compareObjects(e._internal.currentQuery.sort,e._internal.collection.get(a),s)>0);a++);e._internal.collection.addAtIndex(s,a)}else e._internal.collection.add(s);let u=e._internal.collection.size();e._internal.currentQuery.limit!==void 0&&u>e._internal.currentQuery.limit&&e._internal.collection.remove(e._internal.collection.get(e._internal.currentQuery.sort!==void 0&&e._internal.currentQuery.sort[0][0]==="-"?u-1:0)),e.flagOutputDirty("items"),e.flagOutputDirty("count"),e.flagOutputDirty("firstItemId"),e.flagOutputDirty("isEmpty")}if(o.type==="create"){const s=Model.get(o.object.objectId);s!==void 0&&matchesQuery(s,e._internal.currentQuery.where)&&r(s)}else if(o.type==="save"){const s=Model.get(o.objectId);if(s!==void 0){const a=matchesQuery(s,e._internal.currentQuery.where);!a&&e._internal.collection.contains(s)?(e._internal.collection.remove(s),e.flagOutputDirty("items"),e.flagOutputDirty("count"),e.flagOutputDirty("firstItemId"),e.flagOutputDirty("isEmpty")):a&&!e._internal.collection.contains(s)&&r(s)}}else if(o.type==="delete"){const s=Model.get(o.objectId);s!==void 0&&(e._internal.collection.remove(s),e.flagOutputDirty("items"),e.flagOutputDirty("count"),e.flagOutputDirty("firstItemId"),e.flagOutputDirty("isEmpty"))}};const n=CloudStore.forScope(this.nodeScope.modelScope);n.on("save",this._internal.cloudStoreEvents),n.on("create",this._internal.cloudStoreEvents),n.on("delete",this._internal.cloudStoreEvents),this._internal.storageSettings={}},getInspectInfo(){const e=this._internal.collection;return e?[{type:"value",value:e.items}]:{type:"text",value:"[Not executed yet]"}},inputs:{},outputs:{items:{type:"array",displayName:"Items",group:"General",getter(){return this._internal.collection}},firstItemId:{type:"string",displayName:"First Record Id",group:"General",getter(){if(this._internal.collection){var e=this._internal.collection.get(0);if(e!==void 0)return e.getId()}}},isEmpty:{type:"boolean",displayName:"Is Empty",group:"General",getter(){return this._internal.collection?this._internal.collection.size()===0:!0}},count:{type:"number",displayName:"Count",group:"General",getter(){return this._internal.collection?this._internal.collection.size():0}},fetched:{group:"Events",type:"signal",displayName:"Success"},failure:{group:"Events",type:"signal",displayName:"Failure"},error:{type:"string",displayName:"Error",group:"Error",getter(){return this._internal.error}}},prototypeExtensions:{setCollectionName(e){this._internal.name=e,this.isInputConnected("storageFetch")===!1&&this.scheduleFetch()},setCollection(e){this.bindCollection(e),this.flagOutputDirty("firstItemId"),this.flagOutputDirty("isEmpty"),this.flagOutputDirty("items"),this.flagOutputDirty("count")},unbindCurrentCollection(){var e=this._internal.collection;e&&(e.off("change",this._internal.collectionChangedCallback),this._internal.collection=void 0)},bindCollection(e){this.unbindCurrentCollection(),this._internal.collection=e,e&&e.on("change",this._internal.collectionChangedCallback)},_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this.unbindCurrentCollection();const e=CloudStore.forScope(this.nodeScope.modelScope);e.off("insert",this._internal.cloudStoreEvents),e.off("delete",this._internal.cloudStoreEvents),e.off("save",this._internal.cloudStoreEvents)},setError(e){this._internal.err=e,this.flagOutputDirty("error"),this.sendSignalOnOutput("failure")},scheduleFetch(){var e=this._internal;e.fetchScheduled||(e.fetchScheduled=!0,this.scheduleAfterInputsHaveUpdated(()=>{e.fetchScheduled=!1,this.fetch()}))},fetch(){this.context.editorConnection&&(this._internal.name===void 0?this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"query-collection",{message:"No collection specified for query"}):this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"query-collection"));const e=Collection.get(),t=this.getStorageFilter(),n=this.getStorageLimit(),o=this.getStorageSkip(),r=this.getStorageFetchTotalCount();this._internal.currentQuery={where:t.where,sort:t.sort,limit:n,skip:o},CloudStore.forScope(this.nodeScope.modelScope).query({collection:this._internal.name,where:t.where,sort:t.sort,limit:n,skip:o,count:r,success:(s,a)=>{s!==void 0&&e.set(s.map(u=>{var l=CloudStore._fromJSON(u,this._internal.name,this.nodeScope.modelScope);return l})),a!==void 0&&(this._internal.storageSettings.storageTotalCount=a,this.hasOutput("storageTotalCount")&&this.flagOutputDirty("storageTotalCount")),this.setCollection(e),this.sendSignalOnOutput("fetched")},error:s=>{this.setCollection(e),this.setError(s||"Failed to fetch.")}})},getStorageFilter(){const e=this._internal.storageSettings;if(e.storageFilterType===void 0||e.storageFilterType==="simple"){const d=this._internal.visualFilter!==void 0?convertVisualFilter(this._internal.visualFilter,{queryParameters:this._internal.queryParameters,collectionName:this._internal.name}):void 0,p=this._internal.visualSorting!==void 0?convertVisualSorting(this._internal.visualSorting):void 0;return{where:d,sort:p}}else if(e.storageFilterType==="json"){if(!this._internal.filterFunc)try{var t=e.storageJSONFilter;t=t.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,""),this._internal.filterVariables=t.match(/\$[A-Za-z0-9]+/g)||[];var n=["filter","where","sort","Inputs"].concat(this._internal.filterVariables).concat([t]);this._internal.filterFunc=Function.apply(null,n)}catch(p){this._internal.filterFunc=void 0,console.log("Error while parsing filter script: "+p)}if(!this._internal.filterFunc)return;var o={},r=[],s=this,a=function(p){o=convertFilterOp(p,{collectionName:s._internal.name,error(f){s.context.editorConnection.sendWarning(s.nodeScope.componentOwner.name,s.id,"query-collection-filter",{message:f})}})},u=function(p){r=p};const d={};for(let p in e)p.startsWith("storageFilterValue-")&&(d[p.substring(19)]=e[p]);var l=[a,a,u,d];this._internal.filterVariables.forEach(p=>{l.push(e["storageFilterValue-"+p.substring(1)])});try{this._internal.filterFunc.apply(this,l)}catch(p){console.log("Error while running filter script: "+p)}return{where:o,sort:r}}},getStorageLimit(){const e=this._internal.storageSettings;if(e.storageEnableLimit)return e.storageLimit||10},getStorageSkip(){const e=this._internal.storageSettings;if(e.storageEnableLimit)return e.storageSkip||0},getStorageFetchTotalCount(){return!!this._internal.storageSettings.storageEnableCount},registerOutputIfNeeded(e){this.hasOutput(e)||this.registerOutput(e,{getter:userOutputGetter$2.bind(this,e)})},setVisualFilter(e){this._internal.visualFilter=e,this.isInputConnected("storageFetch")===!1&&this.scheduleFetch()},setVisualSorting(e){this._internal.visualSorting=e,this.isInputConnected("storageFetch")===!1&&this.scheduleFetch()},setQueryParameter(e,t){this._internal.queryParameters[e]=t,this.isInputConnected("storageFetch")===!1&&this.scheduleFetch()},registerInputIfNeeded(e){if(this.hasInput(e))return;if(e.startsWith("qp-"))return this.registerInput(e,{set:this.setQueryParameter.bind(this,e.substring(3))});const t={storageFetch:this.scheduleFetch.bind(this)};if(t[e])return this.registerInput(e,{set:createSetter({valueChangedToTrue:t[e]})});const n={collectionName:this.setCollectionName.bind(this),visualFilter:this.setVisualFilter.bind(this),visualSort:this.setVisualSorting.bind(this)};if(n[e])return this.registerInput(e,{set:n[e]});this.registerInput(e,{set:userInputSetter$4.bind(this,e)})}}};function userOutputGetter$2(e){return this._internal.storageSettings[e]}function userInputSetter$4(e,t){this._internal.storageSettings[e]=t,this.isInputConnected("storageFetch")===!1&&this.scheduleFetch()}const _defaultJSONQuery=`// Write your query script here, check out the reference documentation for examples
|
|
22
|
+
where({ })
|
|
23
|
+
`;function updatePorts$6(e,t,n,o){var r=[];const s=o.getMetaData("dbCollections"),a=o.getMetaData("systemCollections"),u=[{label:"User",value:"_User"},{label:"Role",value:"_Role"}];if(r.push({name:"collectionName",type:{name:"enum",enums:u.concat(s!==void 0?s.map(f=>({value:f.name,label:f.name})):[]),allowEditOnly:!0},displayName:"Class",plug:"input",group:"General"}),r.push({name:"storageFilterType",type:{name:"enum",allowEditOnly:!0,enums:[{value:"simple",label:"Visual"},{value:"json",label:"Javascript"}]},displayName:"Filter",default:"simple",plug:"input",group:"General"}),r.push({type:"boolean",plug:"input",group:"Limit",name:"storageEnableLimit",displayName:"Use limit"}),t.storageEnableLimit&&(r.push({type:"number",default:10,plug:"input",group:"Limit",name:"storageLimit",displayName:"Limit"}),r.push({type:"number",default:0,plug:"input",group:"Limit",name:"storageSkip",displayName:"Skip"})),r.push({type:"signal",plug:"input",group:"Actions",name:"storageFetch",displayName:"Do"}),r.push({type:"boolean",plug:"input",group:"Total Count",name:"storageEnableCount",displayName:"Fetch total count"}),t.storageEnableCount&&r.push({type:"number",plug:"output",group:"General",name:"storageTotalCount",displayName:"Total Count"}),t.storageFilterType===void 0||t.storageFilterType==="simple"){if(t.collectionName!==void 0){var l=s&&s.find(f=>f.name===t.collectionName);if(l===void 0&&a&&(l=a.find(f=>f.name===t.collectionName)),l&&l.schema&&l.schema.properties){let m=function(y){if(y.schema!==void 0&&y.schema.properties!==void 0)for(var v in y.schema.properties){var P=y.schema.properties[v];P.type==="Relation"&&P.targetClass===t.collectionName&&(f.relations===void 0&&(f.relations={}),f.relations[y.name]===void 0&&(f.relations[y.name]=[]),f.relations[y.name].push({property:v}))}};const f=JSON.parse(JSON.stringify(l.schema));s&&s.forEach(m),a&&a.forEach(m),r.push({name:"visualFilter",plug:"input",type:{name:"query-filter",schema:f,allowEditOnly:!0},displayName:"Filter",group:"Filter"}),r.push({name:"visualSort",plug:"input",type:{name:"query-sorting",schema:f,allowEditOnly:!0},displayName:"Sort",group:"Sorting"})}if(t.visualFilter!==void 0){let m=function(y){y!==void 0&&(y.rules!==void 0?y.rules.forEach(v=>m(v)):y.input!==void 0&&(f[y.input]=!0))};const f={};m(t.visualFilter),Object.keys(f).forEach(y=>{r.push({name:"qp-"+y,plug:"input",type:"*",displayName:y,group:"Query Parameters"})})}}}else if(t.storageFilterType==="json"){r.push({type:{name:"string",allowEditOnly:!0,codeeditor:"javascript"},plug:"input",group:"Filter",name:"storageJSONFilter",default:_defaultJSONQuery,displayName:"Filter"});var d=t.storageJSONFilter;if(d){d=d.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");var p=d.match(/\$[A-Za-z0-9]+/g);if(p){const f={};p.forEach(m=>{f[m]=!0}),Object.keys(f).forEach(m=>{r.push({name:"storageFilterValue-"+m.substring(1),displayName:m.substring(1),group:"Filter Values",plug:"input",type:{name:"*",allowConnectionsOnly:!0}})})}JavascriptNodeParser.parseAndAddPortsFromScript(d,r,{inputPrefix:"storageFilterValue-",inputGroup:"Filter Values",inputType:{name:"*",allowConnectionsOnly:!0},skipOutputs:!0})}}n.sendDynamicPorts(e,r)}const DbCollectionNode2={node:DbCollectionNode,setup(e,t){if(!e.editorConnection||!e.editorConnection.isRunningLocally())return;function n(o){updatePorts$6(o.id,o.parameters,e.editorConnection,t),o.on("parameterUpdated",function(r){(r.name.startsWith("storage")||r.name==="visualFilter"||r.name==="collectionName")&&updatePorts$6(o.id,o.parameters,e.editorConnection,t)}),t.on("metadataChanged.dbCollections",function(r){CloudStore.invalidateCollections(),updatePorts$6(o.id,o.parameters,e.editorConnection,t)}),t.on("metadataChanged.systemCollections",function(r){CloudStore.invalidateCollections(),updatePorts$6(o.id,o.parameters,e.editorConnection,t)}),t.on("metadataChanged.cloudservices",function(r){CloudStore.instance._initCloudServices()})}t.on("editorImportComplete",()=>{t.on("nodeAdded.DbCollection2",function(o){n(o)});for(const o of t.getNodesWithType("DbCollection2"))n(o)})}},ModelNodeDefinition$1={name:"DbModel2",docs:"https://docs.noodl.net/nodes/data/cloud-data/record",displayNodeName:"Record",shortDesc:"Database model",category:"Cloud Services",usePortAsLabel:"collectionName",color:"data",dynamicports:[{name:"conditionalports/extended",condition:"idSource = explicit OR idSource NOT SET",inputs:["modelId"]}],initialize(){const e=this._internal;e.inputValues={},e.relationModelIds={};const t=this;this._internal.onModelChangedCallback=function(n){t.isInputConnected("fetch")||(t.hasOutput("prop-"+n.name)&&t.flagOutputDirty("prop-"+n.name),t.hasOutput("changed-"+n.name)&&t.sendSignalOnOutput("changed-"+n.name),t.sendSignalOnOutput("changed"))}},getInspectInfo(){const e=this._internal.model;return e?[{type:"text",value:"Id: "+e.getId()},{type:"value",value:e.data}]:"[No Record]"},outputs:{id:{type:"string",displayName:"Id",group:"General",getter(){return this._internal.model?this._internal.model.getId():this._internal.modelId}},fetched:{type:"signal",displayName:"Fetched",group:"Events"},changed:{type:"signal",displayName:"Changed",group:"Events"},failure:{type:"signal",displayName:"Failure",group:"Events"},error:{type:"string",displayName:"Error",group:"Error",getter(){return this._internal.error}}},inputs:{idSource:{type:{name:"enum",enums:[{label:"Specify explicitly",value:"explicit"},{label:"From repeater",value:"foreach"}],allowEditOnly:!0},default:"explicit",displayName:"Id Source",group:"General",set(e){e==="foreach"&&this.scheduleAfterInputsHaveUpdated(()=>{for(var t=this.nodeScope.componentOwner;t!==void 0&&t._forEachModel===void 0&&t.parentNodeScope;)t=t.parentNodeScope.componentOwner;this.setModel(t!==void 0?t._forEachModel:void 0)})}},modelId:{type:{name:"string",allowConnectionsOnly:!0},displayName:"Id",group:"General",set(e){e instanceof Model?e=e.getId():typeof e=="object"&&(e=Model.create(e).getId()),this._internal.modelId=e,this.isInputConnected("fetch")===!1?this.setModelID(e):this.flagOutputDirty("id")}},fetch:{displayName:"Fetch",group:"Actions",valueChangedToTrue(){this.scheduleFetch()}}},methods:{setCollectionID(e){this._internal.collectionId=e},setModelID(e){var t=(this.nodeScope.modelScope||Model).get(e);this.setModel(t)},setModel(e){this._internal.model&&this._internal.model.off("change",this._internal.onModelChangedCallback),this._internal.model=e,this.flagOutputDirty("id"),e.on("change",this._internal.onModelChangedCallback);for(var t in e.data)this.hasOutput("prop-"+t)&&this.flagOutputDirty("prop-"+t);this.sendSignalOnOutput("fetched")},_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this._internal.model&&this._internal.model.off("change",this._internal.onModelChangedCallback)},scheduleOnce(e,t){const n=this,o="hasScheduled"+e;this._internal[o]||(this._internal[o]=!0,this.scheduleAfterInputsHaveUpdated(function(){n._internal[o]=!1,t()}))},setError(e){this._internal.error=e,this.flagOutputDirty("error"),this.sendSignalOnOutput("failure"),this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"storage-op-warning",{message:e,showGlobally:!0})},clearWarnings(){this.context.editorConnection&&this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"storage-op-warning")},scheduleFetch(){const e=this,t=this._internal;this.scheduleOnce("Fetch",function(){if(t.modelId===void 0||t.modelId===""){e.setError("Missing Id.");return}const n=CloudStore.forScope(e.nodeScope.modelScope);n.fetch({collection:t.collectionId,objectId:t.modelId,success(o){const r=n._fromJSON(o,t.collectionId);t.model!==r&&(t.model&&t.model.off("change",t.onModelChangedCallback),t.model=r,r.on("change",t.onModelChangedCallback)),e.flagOutputDirty("id"),delete o.objectId;for(const s in o)e.hasOutput("prop-"+s)&&e.flagOutputDirty("prop-"+s);e.sendSignalOnOutput("fetched")},error(o){e.setError(o||"Failed to fetch.")}})})},scheduleStore(){var e=this._internal;e.model&&this.scheduleOnce("Store",function(){for(var t in e.inputValues)e.model.set(t,e.inputValues[t],{resolve:!0})})},registerOutputIfNeeded(e){this.hasOutput(e)||e.startsWith("prop-")&&this.registerOutput(e,{getter:userOutputGetter$1.bind(this,e.substring(5))})},registerInputIfNeeded(e){if(this.hasInput(e))return;const t={};if(t[e])return this.registerInput(e,{set:createSetter({valueChangedToTrue:t[e]})});const n={collectionName:this.setCollectionID.bind(this)};if(n[e])return this.registerInput(e,{set:n[e]});e.startsWith("prop-")&&this.registerInput(e,{set:userInputSetter$3.bind(this,e.substring(5))})}}};function userOutputGetter$1(e){return this._internal.model?this._internal.model.get(e,{resolve:!0}):void 0}function userInputSetter$3(e,t){this._internal.inputValues[e]=t}function updatePorts$5(e,t,n,o){var r=[];const s=o.getMetaData("dbCollections"),a=o.getMetaData("systemCollections"),u=[{label:"User",value:"_User"},{label:"Role",value:"_Role"}];if(r.push({name:"collectionName",displayName:"Class",group:"General",type:{name:"enum",enums:u.concat(s!==void 0?s.map(m=>({value:m.name,label:m.name})):[]),allowEditOnly:!0},plug:"input"}),t.collectionName&&s){var l=s.find(m=>m.name===t.collectionName);if(l===void 0&&a&&(l=a.find(m=>m.name===t.collectionName)),l&&l.schema&&l.schema.properties){var d=l.schema.properties;for(var p in d){var f=d[p];if(!r.find(m=>m.name===p)&&f.type!=="Relation"){const m={String:"string",Boolean:"boolean",Number:"number",Date:"date"};r.push({type:{name:m[f.type]?m[f.type]:"*"},plug:"output",group:"Properties",name:"prop-"+p,displayName:p}),r.push({type:"signal",plug:"output",group:"Changed Events",displayName:p+" Changed",name:"changed-"+p})}}}}n.sendDynamicPorts(e,r)}const DbModelNode2={node:ModelNodeDefinition$1,setup(e,t){if(!e.editorConnection||!e.editorConnection.isRunningLocally())return;function n(o){updatePorts$5(o.id,o.parameters,e.editorConnection,t),o.on("parameterUpdated",function(){updatePorts$5(o.id,o.parameters,e.editorConnection,t)}),t.on("metadataChanged.dbCollections",function(){CloudStore.invalidateCollections(),updatePorts$5(o.id,o.parameters,e.editorConnection,t)}),t.on("metadataChanged.systemCollections",function(){CloudStore.invalidateCollections(),updatePorts$5(o.id,o.parameters,e.editorConnection,t)})}t.on("editorImportComplete",()=>{t.on("nodeAdded.DbModel2",function(o){n(o)});for(const o of t.getNodesWithType("DbModel2"))n(o)})}};function addBaseInfo$1(e,t){const n=t===void 0||t.includeInputProperties,o=t!==void 0&&t.includeRelations;Object.assign(e.node,{category:"Data",color:"data",inputs:e.node.inputs||{},outputs:e.node.outputs||{},methods:e.node.methods||{}}),Object.assign(e.node.outputs,{failure:{type:"signal",displayName:"Failure",group:"Events"},error:{type:"string",displayName:"Error",group:"Error",getter(){return this._internal.error}}}),Object.assign(e.node.methods,{scheduleOnce(r,s){const a=this,u="hasScheduled"+r;this._internal[u]||(this._internal[u]=!0,this.scheduleAfterInputsHaveUpdated(function(){a._internal[u]=!1,s()}))},checkWarningsBeforeCloudOp(){return this.clearWarnings(),this._internal.collectionId?!0:(this.setError("No class name specified"),!1)},setError(r){this._internal.error=r,this.flagOutputDirty("error"),this.sendSignalOnOutput("failure"),this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"storage-op-warning",{message:r,showGlobally:!0})},clearWarnings(){this.context.editorConnection&&this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"storage-op-warning")}}),Object.assign(e,{setup(r,s){if(!r.editorConnection||!r.editorConnection.isRunningLocally())return;function a(u){function l(){var d=[];const p=s.getMetaData("dbCollections"),f=s.getMetaData("systemCollections"),m=[{label:"User",value:"_User"},{label:"Role",value:"_Role"}],y=u.parameters;if(d.push({name:"collectionName",displayName:"Class",group:"General",type:{name:"enum",enums:m.concat(p!==void 0?p.map(N=>({value:N.name,label:N.name})):[]),allowEditOnly:!0},plug:"input"}),o&&y.collectionName&&p){var v=p.find(N=>N.name===y.collectionName);if(v===void 0&&f&&(v=f.find(N=>N.name===y.collectionName)),v&&v.schema&&v.schema.properties){const N=v.schema.properties,T=Object.keys(N).filter(O=>N[O].type==="Relation").map(O=>({label:O,value:O}));d.push({name:"relationProperty",displayName:"Relation",group:"General",type:{name:"enum",enums:T,allowEditOnly:!0},plug:"input"})}}if(n&&y.collectionName&&p){const N={String:"string",Boolean:"boolean",Number:"number",Date:"date"};var v=p.find(O=>O.name===y.collectionName);if(v===void 0&&f&&(v=f.find(O=>O.name===y.collectionName)),v&&v.schema&&v.schema.properties){var P=v.schema.properties;for(var S in P){var C=P[S];d.find(O=>O.name===S)||d.push({type:{name:N[C.type]?N[C.type]:"*"},plug:"input",group:"Properties",name:"prop-"+S,displayName:S})}}}e._additionalDynamicPorts&&e._additionalDynamicPorts(u,d,s),r.editorConnection.sendDynamicPorts(u.id,d)}l(),u.on("parameterUpdated",function(d){l()}),s.on("metadataChanged.dbCollections",function(d){CloudStore.invalidateCollections(),l()}),s.on("metadataChanged.systemCollections",function(d){CloudStore.invalidateCollections(),l()})}s.on("editorImportComplete",()=>{s.on("nodeAdded."+e.node.name,function(u){a(u)});for(const u of s.getNodesWithType(e.node.name))a(u)})}})}function addModelId$1(e,t){Object.assign({},e.node),e.setup;var n=Object.assign({},e.node.methods);const o=t===void 0||t.includeInputs,r=t===void 0||t.includeOutputs;Object.assign(e.node,{inputs:e.node.inputs||{},outputs:e.node.outputs||{},methods:e.node.methods||{}}),o&&(Object.assign(e.node,{usePortAsLabel:"collectionName"}),e.node.dynamicports=(e.node.dynamicports||[]).concat([{name:"conditionalports/extended",condition:"idSource = explicit OR idSource NOT SET",inputs:["modelId"]}]),Object.assign(e.node.inputs,{idSource:{type:{name:"enum",enums:[{label:"Specify explicitly",value:"explicit"},{label:"From repeater",value:"foreach"}],allowEditOnly:!0},default:"explicit",displayName:"Id Source",group:"General",tooltip:`Choose if you want to specify the Id explicitly,
|
|
24
|
+
or if you want it to be that of the current record in a repeater.`,set(s){s==="foreach"&&this.scheduleAfterInputsHaveUpdated(()=>{for(var a=this.nodeScope.componentOwner;a!==void 0&&a._forEachModel===void 0&&a.parentNodeScope;)a=a.parentNodeScope.componentOwner;this.setModel(a!==void 0?a._forEachModel:void 0)})}},modelId:{type:{name:"string",identifierOf:"ModelName",identifierDisplayName:"Object Ids"},displayName:"Id",group:"General",set(s){s instanceof Model&&(s=s.getId()),this._internal.modelId=s,this.setModelID(s)}}})),r&&Object.assign(e.node.outputs,{id:{type:"string",displayName:"Id",group:"General",getter(){return this._internal.model?this._internal.model.getId():this._internal.modelId}}}),Object.assign(e.node.methods,{setCollectionID(s){this._internal.collectionId=s,this.clearWarnings()},setModelID(s){var a=(this.nodeScope.modelScope||Model).get(s);this.setModel(a)},setModel(s){this._internal.model=s,this.flagOutputDirty("id")},registerInputIfNeeded(s){this.hasInput(s)||(s==="collectionName"&&this.registerInput(s,{set:this.setCollectionID.bind(this)}),n&&n.registerInputIfNeeded&&n.registerInputIfNeeded.call(this,s))}})}function addInputProperties$1(e){var t={node:Object.assign({},e.node),setup:e.setup},n=Object.assign({},e.node.methods);Object.assign(e.node,{inputs:e.node.inputs||{},outputs:e.node.outputs||{},methods:e.node.methods||{}}),Object.assign(e.node,{initialize(){var o=this._internal;o.inputValues={},t.node.initialize&&t.node.initialize.call(this)}}),Object.assign(e.node.outputs,{}),Object.assign(e.node.inputs,{}),Object.assign(e.node.methods,{registerInputIfNeeded(o){this.hasInput(o)||(o.startsWith("prop-")&&this.registerInput(o,{set:this._setInputValue.bind(this,o.substring(5))}),n&&n.registerInputIfNeeded&&n.registerInputIfNeeded.call(this,o))},_setInputValue(o,r){this._internal.inputValues[o]=r}})}function addRelationProperty(e){Object.assign({},e.node),e.setup;var t=Object.assign({},e.node.methods);Object.assign(e.node,{inputs:e.node.inputs||{},outputs:e.node.outputs||{},methods:e.node.methods||{}}),Object.assign(e.node.inputs,{targetId:{type:{name:"string",allowConnectionsOnly:!0},displayName:"Target Record Id",group:"General",set(n){this._internal.targetModelId=n}}}),Object.assign(e.node.methods,{registerInputIfNeeded(n){this.hasInput(n)||(n==="relationProperty"&&this.registerInput(n,{set:this.setRelationProperty.bind(this)}),t&&t.registerInputIfNeeded&&t.registerInputIfNeeded.call(this,n))},setRelationProperty(n){this._internal.relationProperty=n}})}function _getCurrentUser(e){if(typeof _noodl_cloud_runtime_version>"u"){var t=localStorage["Parse/"+CloudStore.instance.appId+"/currentUser"];if(t!==void 0){let n;try{n=JSON.parse(t)}catch{}return n!==void 0?n.objectId:void 0}}else return e.get("Request").UserId}function addAccessControl(e){var t={node:Object.assign({},e.node),setup:e.setup},n=Object.assign({},e.node.methods);Object.assign(e.node,{inputs:e.node.inputs||{},outputs:e.node.outputs||{},methods:e.node.methods||{}}),Object.assign(e.node,{initialize(){var r=this._internal;r.accessControl={},t.node.initialize&&t.node.initialize.call(this)}}),Object.assign(e.node.inputs,{accessControl:{type:{name:"proplist",autoName:"Rule",allowEditOnly:!0},index:1e3,displayName:"Access Control Rules",group:"Access Control Rules",set(r){this._internal.accessControlRules=r}}});const o=e._additionalDynamicPorts;e._additionalDynamicPorts=function(r,s,a){r.parameters.accessControl!==void 0&&r.parameters.accessControl.length>0&&r.parameters.accessControl.forEach(u=>{const l="acl-"+u.id;s.push({name:l+"-target",displayName:"Target",editorName:u.label+" | Target",plug:"input",type:{name:"enum",enums:[{value:"user",label:"User"},{value:"everyone",label:"Everyone"},{value:"role",label:"Role"}],allowEditOnly:!0},group:u.label+" Access Rule",default:"user",parent:"accessControl",parentItemId:u.id}),r.parameters[l+"-target"]==="role"?s.push({name:l+"-role",displayName:"Role",editorName:u.label+" | Role",group:u.label+" Access Rule",plug:"input",type:"string",parent:"accessControl",parentItemId:u.id}):(r.parameters[l+"-target"]===void 0||r.parameters[l+"-target"]==="user")&&s.push({name:l+"-userid",displayName:"User Id",group:u.label+" Access Rule",editorName:u.label+" | User Id",plug:"input",type:{name:"string",allowConnectionsOnly:!0},parent:"accessControl",parentItemId:u.id}),s.push({name:l+"-read",displayName:"Read",editorName:u.label+" | Read",group:u.label+" Access Rule",plug:"input",type:{name:"boolean"},default:!0,parent:"accessControl",parentItemId:u.id}),s.push({name:l+"-write",displayName:"Write",editorName:u.label+" | Write",group:u.label+" Access Rule",plug:"input",type:{name:"boolean"},default:!0,parent:"accessControl",parentItemId:u.id})}),o&&o(r,s,a)},Object.assign(e.node.methods,{registerInputIfNeeded(r){this.hasInput(r)||(r.startsWith("acl-")&&this.registerInput(r,{set:this.setAccessControl.bind(this,r)}),n&&n.registerInputIfNeeded&&n.registerInputIfNeeded.call(this,r))},_getACL(){let r={};function s(u){return{read:u.read===void 0?!0:u.read,write:u.write===void 0?!0:u.write}}const a=_getCurrentUser(this.nodeScope.modelScope);return this._internal.accessControlRules!==void 0&&this._internal.accessControlRules.forEach(u=>{const l=this._internal.accessControl[u.id];if(l===void 0){const d=a;d!==void 0&&(r[d]={write:!0,read:!0})}else if(l.target==="everyone")r["*"]=s(l);else if(l.target==="user"){const d=l.userid||a;r[d]=s(l)}else l.target==="role"&&(r["role:"+l.role]=s(l))}),Object.keys(r).length>0?r:void 0},setAccessControl(r,s){const a=r.split("-");this._internal.accessControl[a[1]]===void 0&&(this._internal.accessControl[a[1]]={}),this._internal.accessControl[a[1]][a[2]]=s}})}const SetDbModelPropertiedNodeDefinition={node:{name:"SetDbModelProperties",docs:"https://docs.noodl.net/nodes/data/cloud-data/set-record-properties",displayNodeName:"Set Record Properties",usePortAsLabel:"collectionName",dynamicports:[{name:"conditionalports/extended",condition:"storeType = cloud OR storeType NOT SET",inputs:["storeProperties"]}],inputs:{store:{displayName:"Do",group:"Actions",valueChangedToTrue(){this._internal.storeType===void 0||this._internal.storeType==="cloud"?this.scheduleSave():this.scheduleStore()}},storeProperties:{displayName:"Properties to store",group:"General",type:{name:"enum",enums:[{label:"Only specified",value:"specified"},{label:"All",value:"all"}]},default:"specified",set(e){this._internal.storeProperties=e}},storeType:{displayName:"Store to",group:"General",type:{name:"enum",enums:[{label:"Cloud and local",value:"cloud"},{label:"Local only",value:"local"}]},default:"cloud",set(e){this._internal.storeType=e}}},outputs:{stored:{type:"signal",displayName:"Success",group:"Events"}},methods:{scheduleSave(){const e=this,t=this._internal;this.checkWarningsBeforeCloudOp()&&this.scheduleOnce("StorageSave",function(){if(!t.model){e.setError("Missing Record Id");return}const n=t.model;for(const o in t.inputValues)n.set(o,t.inputValues[o],{resolve:!0});CloudStore.forScope(e.nodeScope.modelScope).save({collection:t.collectionId,objectId:n.getId(),data:t.storeProperties==="all"?n.data:t.inputValues,acl:e._getACL(),success(o){for(var r in o)n.set(r,o[r]);e.sendSignalOnOutput("stored")},error(o){e.setError(o||"Failed to save.")}})})},scheduleStore(){if(!this.hasScheduledStore){this.hasScheduledStore=!0;var e=this._internal;this.scheduleAfterInputsHaveUpdated(()=>{if(this.hasScheduledStore=!1,!!e.model){for(var t in e.inputValues)e.model.set(t,e.inputValues[t],{resolve:!0});this.sendSignalOnOutput("stored")}})}}}}};addBaseInfo$1(SetDbModelPropertiedNodeDefinition),addModelId$1(SetDbModelPropertiedNodeDefinition),addInputProperties$1(SetDbModelPropertiedNodeDefinition),addAccessControl(SetDbModelPropertiedNodeDefinition);var DeleteDbModelPropertiedNodeDefinition={node:{name:"DeleteDbModelProperties",docs:"https://docs.noodl.net/nodes/data/cloud-data/delete-record",displayNodeName:"Delete Record",shortDesc:"Stores any amount of properties and can be used standalone or together with Collections and For Each nodes.",inputs:{store:{displayName:"Do",group:"Actions",valueChangedToTrue(){this.storageDelete()}}},outputs:{deleted:{type:"signal",displayName:"Success",group:"Events"}},methods:{storageDelete(){const e=this,t=this._internal;this.checkWarningsBeforeCloudOp()&&this.scheduleOnce("StorageDelete",function(){if(!t.model){e.setError("Missing Record Id");return}CloudStore.forScope(e.nodeScope.ModelScope).delete({collection:t.collectionId,objectId:t.model.getId(),success(){t.model.notify("delete"),e.sendSignalOnOutput("deleted")},error(n){e.setError(n||"Failed to delete.")}})})}}}};addBaseInfo$1(DeleteDbModelPropertiedNodeDefinition,{includeInputProperties:!1}),addModelId$1(DeleteDbModelPropertiedNodeDefinition);var NewDbModelPropertiedNodeDefinition={node:{name:"NewDbModelProperties",docs:"https://docs.noodl.net/nodes/data/cloud-data/create-new-record",displayName:"Create New Record",usePortAsLabel:"collectionName",inputs:{store:{displayName:"Do",group:"Actions",valueChangedToTrue(){this.storageInsert()}},sourceObjectId:{type:{name:"string",allowConnectionsOnly:!0},displayName:"Source Object Id",group:"General",set(e){e instanceof Model&&(e=e.getId()),this._internal.sourceObjectId=e}}},outputs:{created:{type:"signal",displayName:"Success",group:"Events"}},methods:{storageInsert(){const e=this._internal;this.checkWarningsBeforeCloudOp()&&this.scheduleOnce("StorageInsert",()=>{const t=Object.assign({},e.sourceObjectId?(this.nodeScope.modelScope||Model).get(e.sourceObjectId).data:{},e.inputValues),n=CloudStore.forScope(this.nodeScope.modelScope);n.create({collection:e.collectionId,data:t,acl:this._getACL(),success:o=>{const r=n._fromJSON(o,e.collectionId);this.setModel(r),this.sendSignalOnOutput("created")},error:o=>{this.setError(o||"Failed to insert.")}})})}}}};addBaseInfo$1(NewDbModelPropertiedNodeDefinition),addModelId$1(NewDbModelPropertiedNodeDefinition,{includeOutputs:!0}),addInputProperties$1(NewDbModelPropertiedNodeDefinition),addAccessControl(NewDbModelPropertiedNodeDefinition);var AddDbModelRelationNodeDefinition$1={node:{name:"AddDbModelRelation",docs:"https://docs.noodl.net/nodes/data/cloud-data/add-record-relation",displayNodeName:"Add Record Relation",usePortAsLabel:"collectionName",inputs:{store:{displayName:"Do",group:"Actions",valueChangedToTrue(){this.scheduleAddRelation()}}},outputs:{relationAdded:{type:"signal",displayName:"Success",group:"Events"}},methods:{validateInputs(){if(!this.context.editorConnection)return;const e=t=>{this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"add-relation",{message:t})};this._internal.collectionId===void 0?e("No class specified"):this._internal.relationProperty===void 0?e("No relation property specified"):this._internal.targetModelId===void 0?e("No target record Id (the record to add a relation to) specified"):this._internal.model===void 0?e("No record Id specified (the record that should get the relation)"):this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"add-relation")},scheduleAddRelation(e){const t=this,n=this._internal;this.scheduleOnce("StorageAddRelation",function(){if(t.validateInputs(),!!n.model){var o=n.model,r=n.targetModelId;r!==void 0&&CloudStore.forScope(t.nodeScope.modelScope).addRelation({collection:n.collectionId,objectId:o.getId(),key:n.relationProperty,targetObjectId:r,targetClass:(t.nodeScope.modelScope||Model).get(r)._class,success(s){for(var a in s)o.set(a,s[a]);t.sendSignalOnOutput("relationAdded")},error(s){t.setError(s||"Failed to add relation.")}})}})}}}};addBaseInfo$1(AddDbModelRelationNodeDefinition$1,{includeRelations:!0}),addModelId$1(AddDbModelRelationNodeDefinition$1),addRelationProperty(AddDbModelRelationNodeDefinition$1);var AddDbModelRelationNodeDefinition={node:{name:"RemoveDbModelRelation",docs:"https://docs.noodl.net/nodes/data/cloud-data/remove-record-relation",displayName:"Remove Record Relation",usePortAsLabel:"collectionName",inputs:{store:{displayName:"Do",group:"Actions",valueChangedToTrue(){this.scheduleRemoveRelation()}}},outputs:{relationRemoved:{type:"signal",displayName:"Success",group:"Events"}},methods:{validateInputs(){if(!this.context.editorConnection)return;const e=t=>{this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"add-relation",{message:t})};this._internal.collectionId===void 0?e("No class specified"):this._internal.relationProperty===void 0?e("No relation property specified"):this._internal.targetModelId===void 0?e("No target record Id (the record to add a relation to) specified"):this._internal.model===void 0?e("No record Id specified (the record that should get the relation)"):this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"add-relation")},scheduleRemoveRelation(e){const t=this,n=this._internal;this.scheduleOnce("StorageRemoveRelation",function(){if(t.validateInputs(),!!n.model){var o=n.model,r=n.targetModelId;r!==void 0&&CloudStore.forScope(t.nodeScope.modelScope).removeRelation({collection:n.collectionId,objectId:o.getId(),key:n.relationProperty,targetObjectId:r,targetClass:(t.nodeScope.modelScope||Model).get(r)._class,success(s){for(var a in s)o.set(a,s[a]);t.sendSignalOnOutput("relationRemoved")},error(s){t.setError(s||"Failed to remove relation.")}})}})}}}};addBaseInfo$1(AddDbModelRelationNodeDefinition,{includeRelations:!0}),addModelId$1(AddDbModelRelationNodeDefinition),addRelationProperty(AddDbModelRelationNodeDefinition);var FilterDBModelsNode={name:"FilterDBModels",docs:"https://docs.noodl.net/nodes/data/cloud-data/filter-records",displayNodeName:"Filter Records",shortDesc:"Filter, sort and limit array",category:"Data",color:"data",initialize(){var e=this;this._internal.collectionChangedCallback=function(){e.isInputConnected("filter")!==!0&&e.scheduleFilter()},this._internal.cloudStoreEvents=function(t){e.isInputConnected("filter")!==!0&&e._internal.visualFilter!==void 0&&e._internal.collection!==void 0&&t.collection===e._internal.collectionName&&t.objectId!==void 0&&e._internal.collection.contains(Model.get(t.objectId))&&e.scheduleFilter()},CloudStore.instance.on("save",this._internal.cloudStoreEvents),this._internal.enabled=!0,this._internal.filterSettings={},this._internal.filterParameters={}},getInspectInfo(){const e=this._internal.filteredCollection;return e?[{type:"text",value:"Id: "+e.getId()},{type:"value",value:e.items}]:{type:"text",value:"[Not executed yet]"}},inputs:{items:{type:"array",displayName:"Items",group:"General",set(e){this.bindCollection(e),this.isInputConnected("filter")===!1&&this.scheduleFilter()}},enabled:{type:"boolean",group:"General",displayName:"Enabled",default:!0,set(e){this._internal.enabled=e,this.isInputConnected("filter")===!1&&this.scheduleFilter()}},filter:{type:"signal",group:"Actions",displayName:"Filter",valueChangedToTrue(){this.scheduleFilter()}}},outputs:{items:{type:"array",displayName:"Items",group:"General",getter(){return this._internal.filteredCollection}},firstItemId:{type:"string",displayName:"First Record Id",group:"General",getter(){if(this._internal.filteredCollection!==void 0){const e=this._internal.filteredCollection.get(0);if(e!==void 0)return e.getId()}}},count:{type:"number",displayName:"Count",group:"General",getter(){return this._internal.filteredCollection?this._internal.filteredCollection.size():0}},modified:{group:"Events",type:"signal",displayName:"Filtered"}},prototypeExtensions:{unbindCurrentCollection(){var e=this._internal.collection;e&&(e.off("change",this._internal.collectionChangedCallback),this._internal.collection=void 0)},bindCollection(e){this.unbindCurrentCollection(),this._internal.collection=e,e&&e.on("change",this._internal.collectionChangedCallback)},_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this.unbindCurrentCollection(),CloudStore.instance.off("save",this._internal.cloudStoreEvents)},getLimit(){const e=this._internal.filterSettings;if(e.filterEnableLimit)return e.filterLimit||10},getSkip(){const e=this._internal.filterSettings;if(e.filterEnableLimit)return e.filterSkip||0},scheduleFilter(){this.collectionChangedScheduled||(this.collectionChangedScheduled=!0,this.scheduleAfterInputsHaveUpdated(()=>{if(this.collectionChangedScheduled=!1,!!this._internal.collection){var e=[].concat(this._internal.collection.items);if(this._internal.enabled){const a=this._internal.visualFilter;if(a!==void 0){var t=convertVisualFilter(a,{queryParameters:this._internal.filterParameters,collectionName:this._internal.collectionName});t&&(e=e.filter(u=>matchesQuery(u,t)))}var n=this._internal.visualSorting;if(n!==void 0&&n.length>0)var o=convertVisualSorting(n);o&&e.sort(compareObjects.bind(this,o));var r=this.getSkip();r&&(e=e.slice(r,e.length));var s=this.getLimit();s&&(e=e.slice(0,s))}this._internal.filteredCollection=Collection.create(e),this.sendSignalOnOutput("modified"),this.flagOutputDirty("firstItemId"),this.flagOutputDirty("items"),this.flagOutputDirty("count")}}))},setCollectionName(e){this._internal.collectionName=e},setVisualFilter(e){this._internal.visualFilter=e,this.isInputConnected("filter")===!1&&this.scheduleFilter()},setVisualSorting(e){this._internal.visualSorting=e,this.isInputConnected("filter")===!1&&this.scheduleFilter()},setFilterParameter(e,t){this._internal.filterParameters[e]=t,this.isInputConnected("filter")===!1&&this.scheduleFilter()},registerInputIfNeeded(e){if(!this.hasInput(e)){if(e==="collectionName")return this.registerInput(e,{set:this.setCollectionName.bind(this)});if(e==="visualFilter")return this.registerInput(e,{set:this.setVisualFilter.bind(this)});if(e==="visualSorting")return this.registerInput(e,{set:this.setVisualSorting.bind(this)});if(e.startsWith("fp-"))return this.registerInput(e,{set:this.setFilterParameter.bind(this,e.substring(3))});this.registerInput(e,{set:userInputSetter$2.bind(this,e)})}}}};function userInputSetter$2(e,t){this._internal.filterSettings[e]=t,this.isInputConnected("filter")===!1&&this.scheduleFilter()}function updatePorts$4(e,t,n,o){var r=[];if(r.push({name:"collectionName",type:{name:"enum",enums:o!==void 0?o.map(u=>({value:u.name,label:u.name})):[],allowEditOnly:!0},displayName:"Class",plug:"input",group:"General"}),r.push({type:"boolean",plug:"input",group:"Limit",name:"filterEnableLimit",displayName:"Use limit"}),t.filterEnableLimit&&(r.push({type:"number",default:10,plug:"input",group:"Limit",name:"filterLimit",displayName:"Limit"}),r.push({type:"number",default:0,plug:"input",group:"Limit",name:"filterSkip",displayName:"Skip"})),t.collectionName!==void 0){var s=o.find(u=>u.name===t.collectionName);if(s&&s.schema&&s.schema.properties){const u=JSON.parse(JSON.stringify(s.schema)),l={Boolean:!0,String:!0,Date:!0,Number:!0,Pointer:!0};for(var a in u.properties)l[u.properties[a].type]||delete u.properties[a];r.push({name:"visualFilter",plug:"input",type:{name:"query-filter",schema:u,allowEditOnly:!0},displayName:"Filter",group:"Filter"}),r.push({name:"visualSorting",plug:"input",type:{name:"query-sorting",schema:u,allowEditOnly:!0},displayName:"Sorting",group:"Sorting"})}if(t.visualFilter!==void 0){let l=function(d){d!==void 0&&(d.rules!==void 0?d.rules.forEach(p=>l(p)):d.input!==void 0&&(u[d.input]=!0))};const u={};l(t.visualFilter),Object.keys(u).forEach(d=>{r.push({name:"fp-"+d,plug:"input",type:"*",displayName:d,group:"Filter Parameters"})})}}n.sendDynamicPorts(e,r)}const FilterDbModelsNode={node:FilterDBModelsNode,setup(e,t){!e.editorConnection||!e.editorConnection.isRunningLocally()||t.on("nodeAdded.FilterDBModels",function(n){updatePorts$4(n.id,n.parameters,e.editorConnection,t.getMetaData("dbCollections")),n.on("parameterUpdated",function(o){updatePorts$4(n.id,n.parameters,e.editorConnection,t.getMetaData("dbCollections"))}),t.on("metadataChanged.dbCollections",function(o){CloudStore.invalidateCollections(),updatePorts$4(n.id,n.parameters,e.editorConnection,o)}),t.on("metadataChanged.systemCollections",function(o){CloudStore.invalidateCollections(),updatePorts$4(n.id,n.parameters,e.editorConnection,o)})})}};var ModelNodeDefinition={name:"Model2",docs:"https://docs.noodl.net/nodes/data/object/object-node",displayNodeName:"Object",shortDesc:"Stores any amount of properties and can be used standalone or together with Collections and For Each nodes.",category:"Data",usePortAsLabel:"modelId",color:"data",dynamicports:[{name:"conditionalports/extended",condition:"idSource = explicit OR idSource NOT SET",inputs:["modelId"]}],initialize(){var e=this._internal;e.inputValues={},e.dirtyValues={};var t=this;this._internal.onModelChangedCallback=function(n){t.isInputConnected("fetch")!==!0&&(t.hasOutput("prop-"+n.name)&&t.flagOutputDirty("prop-"+n.name),t.hasOutput("changed-"+n.name)&&t.sendSignalOnOutput("changed-"+n.name),t.sendSignalOnOutput("changed"))}},getInspectInfo(){const e=this._internal.model;return e?[{type:"text",value:"Id: "+e.getId()},{type:"value",value:e.data}]:"[No Object]"},outputs:{id:{type:"string",displayName:"Id",group:"General",getter(){return this._internal.model?this._internal.model.getId():this._internal.modelId}},changed:{type:"signal",displayName:"Changed",group:"Events"},fetched:{type:"signal",displayName:"Fetched",group:"Events"}},inputs:{idSource:{type:{name:"enum",enums:[{label:"Specify explicitly",value:"explicit"},{label:"From repeater",value:"foreach"}],allowEditOnly:!0},default:"explicit",displayName:"Get Id from",group:"General",set(e){e==="foreach"&&this.scheduleAfterInputsHaveUpdated(()=>{for(var t=this.nodeScope.componentOwner;t!==void 0&&t._forEachModel===void 0&&t.parentNodeScope;)t=t.parentNodeScope.componentOwner;this.setModel(t!==void 0?t._forEachModel:void 0)})}},modelId:{type:{name:"string",identifierOf:"ModelName",identifierDisplayName:"Object Ids"},displayName:"Id",group:"General",set(e){e instanceof Model?e=e.getId():typeof e=="object"&&(e=Model.create(e).getId()),this._internal.modelId=e,this.isInputConnected("fetch")===!1?this.setModelID(e):this.flagOutputDirty("id")}},properties:{type:{name:"stringlist",allowEditOnly:!0},displayName:"Properties",group:"Properties",set(e){}},fetch:{displayName:"Fetch",group:"Actions",valueChangedToTrue(){this.scheduleSetModel()}}},prototypeExtensions:{scheduleStore(){if(!this.hasScheduledStore){this.hasScheduledStore=!0;var e=this._internal;this.scheduleAfterInputsHaveUpdated(()=>{if(this.hasScheduledStore=!1,!!e.model){for(var t in e.dirtyValues)e.model.set(t,e.inputValues[t],{resolve:!0});e.dirtyValues={}}})}},scheduleSetModel(){this.hasScheduledSetModel||(this.hasScheduledSetModel=!0,this._internal,this.scheduleAfterInputsHaveUpdated(()=>{this.hasScheduledSetModel=!1,this.setModelID(this._internal.modelId)}))},setModelID(e){var t=(this.nodeScope.modelScope||Model).get(e);this.setModel(t),this.sendSignalOnOutput("fetched")},setModel(e){if(this._internal.model&&this._internal.model.off("change",this._internal.onModelChangedCallback),this._internal.model=e,this.flagOutputDirty("id"),e){e.on("change",this._internal.onModelChangedCallback);for(var t in e.data)this.hasOutput("prop-"+t)&&this.flagOutputDirty("prop-"+t)}},_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this._internal.model&&this._internal.model.off("change",this._internal.onModelChangedCallback)},registerOutputIfNeeded(e){this.hasOutput(e)||e.startsWith("prop-")&&this.registerOutput(e,{getter:userOutputGetter.bind(this,e.substring(5))})},registerInputIfNeeded(e){this.hasInput(e)||e.startsWith("prop-")&&this.registerInput(e,{set:userInputSetter$1.bind(this,e.substring(5))})}}};function userOutputGetter(e){return this._internal.model?this._internal.model.get(e,{resolve:!0}):void 0}function userInputSetter$1(e,t){this._internal.inputValues[e]=t;const n=this._internal.model;(n?n.get(e)!==t:!0)&&(this._internal.dirtyValues[e]=!0,this.scheduleStore())}function updatePorts$3(e,t,n){var o=[],r=t.properties;if(r){r=r?r.split(","):void 0;for(var s in r){var a=r[s];o.push({type:{name:"*",allowConnectionsOnly:!0},plug:"input/output",group:"Properties",name:"prop-"+a,displayName:a}),o.push({type:"signal",plug:"output",group:"Changed Events",displayName:a+" Changed",name:"changed-"+a})}}n.sendDynamicPorts(e,o,{detectRenamed:{plug:"input/output"}})}const ModelNode2={node:ModelNodeDefinition,setup(e,t){!e.editorConnection||!e.editorConnection.isRunningLocally()||t.on("nodeAdded.Model2",function(n){updatePorts$3(n.id,n.parameters,e.editorConnection),n.on("parameterUpdated",function(o){updatePorts$3(n.id,n.parameters,e.editorConnection)})})}};function addBaseInfo(e){Object.assign(e.node,{category:"Data",color:"data"})}function addModelId(e,t){const n=t===void 0||t.includeInputs,o=t===void 0||t.includeOutputs;Object.assign(e.node,{inputs:e.node.inputs||{},outputs:e.node.outputs||{},methods:e.node.methods||{}}),n&&(Object.assign(e.node,{usePortAsLabel:"modelId"}),e.node.dynamicports=(e.node.dynamicports||[]).concat([{name:"conditionalports/extended",condition:"idSource = explicit OR idSource NOT SET",inputs:["modelId"]}]),Object.assign(e.node.inputs,{idSource:{type:{name:"enum",enums:[{label:"Specify explicitly",value:"explicit"},{label:"From repeater",value:"foreach"}],allowEditOnly:!0},default:"explicit",displayName:"Id Source",group:"General",set(r){r==="foreach"&&this.scheduleAfterInputsHaveUpdated(()=>{for(var s=this.nodeScope.componentOwner;s!==void 0&&s._forEachModel===void 0&&s.parentNodeScope;)s=s.parentNodeScope.componentOwner;this.setModel(s!==void 0?s._forEachModel:void 0)})}},modelId:{type:{name:"string",identifierOf:"ModelName",identifierDisplayName:"Object Ids"},displayName:"Id",group:"General",set(r){r instanceof Model&&(r=r.getId()),this._internal.modelId=r,this.setModelID(r)}}})),o&&Object.assign(e.node.outputs,{id:{type:"string",displayName:"Id",group:"General",getter(){return this._internal.model?this._internal.model.getId():this._internal.modelId}}}),Object.assign(e.node.methods,{setModelID(r){var s=(this.nodeScope.modelScope||Model).get(r);this.setModel(s)},setModel(r){this._internal.model=r,this.flagOutputDirty("id")}}),e.node.getInspectInfo||(e.node.getInspectInfo=function(){const r=this._internal.model;return r?[{type:"text",value:"Id: "+r.getId()},{type:"value",value:r.data}]:"[No Object]"})}function addInputProperties(def){var _def={node:Object.assign({},def.node),setup:def.setup},_methods=Object.assign({},def.node.methods);Object.assign(def.node,{inputs:def.node.inputs||{},outputs:def.node.outputs||{},methods:def.node.methods||{}}),Object.assign(def,{setup(e,t){!e.editorConnection||!e.editorConnection.isRunningLocally()||(t.on("nodeAdded."+def.node.name,function(n){function o(){var r=[];const s=[{label:"String",value:"string"},{label:"Boolean",value:"boolean"},{label:"Number",value:"number"},{label:"Date",value:"date"},{label:"Array",value:"array"},{label:"Object",value:"object"},{label:"Any",value:"*"}];var a=n.parameters.properties;if(a){a=a?a.split(","):void 0;for(var u in a){var l=a[u];r.push({type:{name:n.parameters["type-"+l]===void 0?"*":n.parameters["type-"+l]},plug:"input",group:"Property Values",displayName:l,name:"prop-"+l}),r.push({type:{name:"enum",enums:s,allowEditOnly:!0},plug:"input",group:"Property Types",displayName:l,default:"*",name:"type-"+l})}}e.editorConnection.sendDynamicPorts(n.id,r,{detectRenamed:{plug:"input"}})}o(),n.on("parameterUpdated",function(r){o()})}),_def.setup&&_def.setup(e,t))}}),Object.assign(def.node,{initialize(){var e=this._internal;e.inputValues={},e.inputTypes={},_def.node.initialize&&_def.node.initialize.call(this)}}),Object.assign(def.node.outputs,{}),Object.assign(def.node.inputs,{properties:{type:{name:"stringlist",allowEditOnly:!0},displayName:"Properties",group:"Properties to set",set(e){}}}),Object.assign(def.node.methods,{_pushInputValues(model){var internal=this._internal;const _defaultValueForType={boolean:!1,string:"",number:0,date:new Date},_allKeys={};for(const e in internal.inputTypes)_allKeys[e]=!0;for(const e in internal.inputValues)_allKeys[e]=!0;const properties=this.model.parameters.properties||"",validProperties=properties.split(","),keysToSet=Object.keys(_allKeys).filter(e=>validProperties.indexOf(e)!==-1);for(const i of keysToSet){var value=internal.inputValues[i];if(value!==void 0){if(internal.inputTypes[i]!==void 0&&internal.inputTypes[i]==="array"&&typeof value=="string"){this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+i);try{value=eval(value)}catch(e){value.indexOf("[")!==-1||value.indexOf("{")!==-1?(this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"invalid-array-"+i,{showGlobally:!0,message:"Invalid array<br>"+e.toString()}),value=[]):value=Collection.get(value)}}internal.inputTypes[i]!==void 0&&internal.inputTypes[i]==="object"&&typeof value=="string"&&(value=(this.nodeScope.modelScope||Model).get(value)),model.set(i,value,{resolve:!0})}else model.set(i,_defaultValueForType[internal.inputTypes[i]],{resolve:!0})}},scheduleStore(){if(!this.hasScheduledStore){this.hasScheduledStore=!0;var e=this._internal;this.scheduleAfterInputsHaveUpdated(()=>{this.hasScheduledStore=!1,e.model&&(this._pushInputValues(e.model),this.sendSignalOnOutput("stored"))})}},registerInputIfNeeded(e){this.hasInput(e)||(e.startsWith("prop-")&&this.registerInput(e,{set:this._setInputValue.bind(this,e.substring(5))}),e.startsWith("type-")&&this.registerInput(e,{set:this._setInputType.bind(this,e.substring(5))}),_methods&&_methods.registerInputIfNeeded&&_def.node.methods.registerInputIfNeeded.call(this,e))},_setInputValue(e,t){this._internal.inputValues[e]=t},_setInputType(e,t){this._internal.inputTypes[e]=t}})}var SetModelPropertiedNodeDefinition={node:{name:"SetModelProperties",docs:"https://docs.noodl.net/nodes/data/object/set-object-properties",displayNodeName:"Set Object Properties",inputs:{store:{displayName:"Do",group:"Actions",valueChangedToTrue(){this.scheduleStore()}}},outputs:{stored:{type:"signal",displayName:"Done",group:"Events"}}}};addBaseInfo(SetModelPropertiedNodeDefinition),addModelId(SetModelPropertiedNodeDefinition),addInputProperties(SetModelPropertiedNodeDefinition);var NewModelNodeDefinition={node:{name:"NewModel",docs:"https://docs.noodl.net/nodes/data/object/create-new-object",displayNodeName:"Create New Object",inputs:{new:{displayName:"Do",group:"Actions",valueChangedToTrue(){this.scheduleNew()}}},outputs:{created:{type:"signal",displayName:"Done",group:"Events"}},methods:{scheduleNew(){this.hasScheduledNew||(this.hasScheduledNew=!0,this.scheduleAfterInputsHaveUpdated(()=>{this.hasScheduledNew=!1;const e=(this.nodeScope.modelScope||Model).get();this._pushInputValues(e),this.setModel(e),this.sendSignalOnOutput("created")}))}}}};addBaseInfo(NewModelNodeDefinition),addModelId(NewModelNodeDefinition,{includeOutputs:!0}),addInputProperties(NewModelNodeDefinition);const CloudFileNode={name:"Cloud File",docs:"https://docs.noodl.net/nodes/data/cloud-data/cloud-file",category:"Cloud Services",color:"data",getInspectInfo(){return this._internal.cloudFile&&this._internal.cloudFile.getUrl()},outputs:{url:{type:"string",displayName:"URL",group:"General",get(){return this._internal.cloudFile&&this._internal.cloudFile.getUrl()}},name:{type:"string",displayName:"Name",group:"General",get(){if(!this._internal.cloudFile)return;const e=this._internal.cloudFile.getName().split("_");return e.length===1?e[0]:e.slice(1).join("_")}}},inputs:{file:{type:"cloudfile",displayName:"Cloud File",group:"General",set(e){e instanceof CloudFile&&(this._internal.cloudFile=e,this.flagOutputDirty("name"),this.flagOutputDirty("url"))}}}},CloudFileNode$1={node:CloudFileNode},j=class j{constructor(){this.cacheDuration=9e5}_makeRequest(t,n){if(typeof _noodl_cloud_runtime_version>"u"){var o=new XMLHttpRequest;o.onreadystatechange=function(){if(o.readyState===4){var u;try{u=JSON.parse(o.response)}catch{}o.status===200||o.status===201?n.success(u):n.error(u||{error:o.responseText,status:o.status})}};const r=Runtime.instance.getMetaData("cloudservices"),s=r.appId,a=r.endpoint;o.open("GET",a+t,!0),o.setRequestHeader("X-Parse-Application-Id",s),o.send()}else{const r=typeof _noodl_cloudservices<"u"?_noodl_cloudservices.endpoint:this.endpoint,s=typeof _noodl_cloudservices<"u"?_noodl_cloudservices.appId:this.appId,a=typeof _noodl_cloudservices<"u"?_noodl_cloudservices.masterKey:void 0;fetch(r+t,{method:"GET",headers:{"X-Parse-Application-Id":s,"X-Parse-Master-Key":a}}).then(u=>{u.status===200||u.status===201?u.json().then(l=>n.success(l)).catch(l=>n.error({error:"Config: Failed to get json result."})):u.json().then(l=>n.error(l)).catch(l=>n.error({error:"Failed to fetch."}))}).catch(u=>{n.error({error:u.message})})}}_getConfig(){return new Promise((t,n)=>{this._makeRequest("/config",{success:o=>{t(o.params||{})},error:o=>{n(o)}})})}async getConfig(){return this.configCachePending?this.configCachePending:this.configCache?(Date.now()>this.ttl&&this._getConfig().then(t=>{this.configCache=t,this.ttl=Date.now()+this.cacheDuration}),this.configCache):(this.configCachePending=this._getConfig(),this.configCache=await this.configCachePending,delete this.configCachePending,this.ttl=Date.now()+this.cacheDuration,this.configCache)}clearCache(){delete this.configCache}};j.instance=new j;let ConfigService=j;var ConfigNodeDefinition={name:"DbConfig",docs:"https://docs.noodl.net/nodes/data/cloud-data/config",displayNodeName:"Config",category:"Cloud Services",usePortAsLabel:"configKey",color:"data",initialize(){var e=this._internal;ConfigService.instance.getConfig().then(t=>{e.config=t,this.hasOutput("value")&&this.flagOutputDirty("value")})},getInspectInfo(){const e=this.getValue();return e===void 0?"[No Value]":[{type:"value",value:e}]},inputs:{},outputs:{},methods:{getValue(){const e=this._internal;if(e.useDevValue&&this.context.editorConnection&&this.context.editorConnection.isRunningLocally())return e.devValue;if(e.config!==void 0&&e.configKey!==void 0)return e.config[e.configKey]},setInternal(e,t){this._internal[e]=t,this.hasOutput("value")&&this.flagOutputDirty("value")},registerOutputIfNeeded(e){if(!this.hasOutput(e)&&e==="value")return this.registerOutput(e,{getter:this.getValue.bind(this)})},registerInputIfNeeded(e){if(!this.hasInput(e)&&(e==="configKey"||e==="useDevValue"||e==="devValue"))return this.registerInput(e,{set:this.setInternal.bind(this,e)})}}};const DbConfig={node:ConfigNodeDefinition,setup(e,t){if(!e.editorConnection||!e.editorConnection.isRunningLocally())return;function n(r){var s=[];e.editorConnection.clearWarning(r.component.name,r.id,"dbconfig-warning");const a=t.getMetaData("dbConfigSchema");let u;if(a){const l=typeof _noodl_cloud_runtime_version<"u";s.push({name:"configKey",displayName:"Parameter",group:"General",type:{name:"enum",enums:Object.keys(a).filter(d=>l||!a[d].masterKeyOnly).map(d=>({value:d,label:d})),allowEditOnly:!0},plug:"input"}),r.parameters.configKey!==void 0&&a&&a[r.parameters.configKey]?(u=a[r.parameters.configKey].type,(u==="string"||u==="boolean"||u==="number"||u==="object"||u==="array")&&(s.push({name:"useDevValue",displayName:"Enable",group:"Local Override",type:"boolean",default:!1,plug:"input"}),r.parameters.useDevValue===!0&&s.push({name:"devValue",displayName:"Value",group:"Local Override",type:u,plug:"input"}))):r.parameters.configKey!==void 0&&e.editorConnection.sendWarning(r.component.name,r.id,"dbconfig-warning",{showGlobally:!0,message:r.parameters.configKey+" config parameter is missing, add it to your cloud service."})}else e.editorConnection.sendWarning(r.component.name,r.id,"dbconfig-warning",{showGlobally:!0,message:"You need an active cloud service."});s.push({name:"value",displayName:"Value",group:"General",type:u||"*",plug:"output"}),e.editorConnection.sendDynamicPorts(r.id,s)}function o(r){n(r),r.on("parameterUpdated",function(s){n(r)}),t.on("metadataChanged.dbConfigSchema",function(s){ConfigService.instance.clearCache(),n(r)})}t.on("editorImportComplete",()=>{t.on("nodeAdded.DbConfig",function(r){o(r)});for(const r of t.getNodesWithType("DbConfig"))o(r)})}};function createDefinition(e){return{name:e.name,docs:e.docs,shortDesc:e.shortDesc,nodeDoubleClickAction:e.nodeDoubleClickAction,category:"Variables",initialize(){this._internal.currentValue=e.startValue,this._internal.latestValue=0},getInspectInfo(){return[{type:e.type.name==="color"?"color":"text",value:this._internal.currentValue}]},inputs:{value:{type:e.type,displayName:"Value",default:e.startValue,set(t){this.isInputConnected("saveValue")===!1?this.setValueTo(t):this._internal.latestValue=t}},saveValue:{displayName:"Set",valueChangedToTrue(){this.scheduleAfterInputsHaveUpdated(function(){this.setValueTo(this._internal.latestValue),this.sendSignalOnOutput("stored")})}}},outputs:{savedValue:{type:e.type.name,displayName:"Value",getter(){return this._internal.currentValue}},changed:{type:"signal",displayName:"Changed"},stored:{type:"signal",displayName:"Stored"}},prototypeExtensions:{setValueTo(t){t=e.cast(t);const n=this._internal.currentValue!==t;this._internal.currentValue=t,n&&(this.flagOutputDirty("savedValue"),this.sendSignalOnOutput("changed"),e.onChanged&&e.onChanged.call(this))}}}}const NumberNode=createDefinition({name:"Number",docs:"https://docs.noodl.net/nodes/data/number",startValue:0,nodeDoubleClickAction:{focusPort:"value"},type:{name:"number"},cast(e){return Number(e)}}),NumberVar={node:NumberNode},StringNode=createDefinition({name:"String",docs:"https://docs.noodl.net/nodes/data/string",shortDesc:"Contains a string (text).",startValue:"",nodeDoubleClickAction:{focusPort:"value"},type:{name:"string"},cast(e){return String(e)},onChanged(){this.flagOutputDirty("length")}});extend(StringNode,{usePortAsLabel:"value",portLabelTruncationMode:"length",outputs:{length:{type:"number",displayName:"Length",getter(){return this._internal.currentValue.length}}}});const StringVar={node:StringNode},BooleanNode=createDefinition({name:"Boolean",docs:"https://docs.noodl.net/nodes/data/boolean",startValue:!1,type:{name:"boolean"},cast(e){return!!e}}),BooleanVar={node:BooleanNode},ConditionNode={name:"Condition",docs:"https://docs.noodl.net/nodes/utilities/logic/condition",category:"Logic",initialize(){},getInspectInfo(){const e=this.getInputValue("condition");let t;return e===void 0&&(t="[No input]"),t=e,[{type:"value",value:t}]},inputs:{condition:{type:"boolean",displayName:"Condition",group:"General",set(e){this.isInputConnected("eval")||this.scheduleEvaluate()}},eval:{type:"signal",displayName:"Evaluate",group:"Actions",valueChangedToTrue(){this.scheduleEvaluate()}}},outputs:{ontrue:{type:"signal",displayName:"On True",group:"Events"},onfalse:{type:"signal",displayName:"On False",group:"Events"},result:{type:"boolean",displayName:"Is True",group:"Booleans",get(){return!!this.getInputValue("condition")}},isfalse:{type:"boolean",displayName:"Is False",group:"Booleans",get(){return!this.getInputValue("condition")}}},methods:{scheduleEvaluate(){this.scheduleAfterInputsHaveUpdated(()=>{this.flagOutputDirty("result"),this.flagOutputDirty("isfalse");const e=this.getInputValue("condition");this.sendSignalOnOutput(e?"ontrue":"onfalse")})}}},Condition={node:ConditionNode},AndNode={name:"And",docs:"https://docs.noodl.net/nodes/logic/and",category:"Logic",initialize(){this._internal.inputs=[]},getInspectInfo(){return and(this._internal.inputs)},numberedInputs:{input:{displayPrefix:"Input",type:"boolean",createSetter(e){return function(t){if(t=!!t,this._internal.inputs[e]===t)return;this._internal.inputs[e]=t;const n=and(this._internal.inputs);this._internal.result!==n&&(this._internal.result=n,this.flagOutputDirty("result"))}}}},outputs:{result:{type:"boolean",displayName:"Result",get(){return this._internal.result}}}},And={node:AndNode};function and(e){return e.length>0&&e.some(t=>!t)===!1}const OrNode={name:"Or",docs:"https://docs.noodl.net/nodes/logic/or",category:"Logic",initialize(){this._internal.inputs=[]},getInspectInfo(){return this._internal.inputs.some(isTrue)},numberedInputs:{input:{type:"boolean",displayPrefix:"Input",createSetter(e){return function(t){this._internal.inputs[e]!==t&&(this._internal.inputs[e]=t,this.flagOutputDirty("result"))}}}},outputs:{result:{type:"boolean",displayName:"Result",getter(){return this._internal.inputs.some(isTrue)}}}},Or={node:OrNode};function isTrue(e){return!!e}const BooleanToStringNode={name:"Boolean To String",docs:"https://docs.noodl.net/nodes/utilities/boolean-to-string",category:"Utilities",initialize(){this._internal.inputs=[],this._internal.currentSelectedIndex=0,this._internal.indexChanged=!1,this._internal.trueString="",this._internal.falseString=""},inputs:{trueString:{displayName:"String for true",type:"string",set(e){this._internal.trueString!==e&&(this._internal.trueString=e,this._internal.currentInput&&this.flagOutputDirty("currentValue"))}},falseString:{displayName:"String for false",type:"string",set(e){this._internal.falseString!==e&&(this._internal.falseString=e,this._internal.currentInput||this.flagOutputDirty("currentValue"))}},input:{type:{name:"boolean"},displayName:"Selector",set(e){this._internal.currentInput!==e&&(this._internal.currentInput=e,this.flagOutputDirty("currentValue"),this.sendSignalOnOutput("inputChanged"))}}},outputs:{currentValue:{type:"string",displayName:"Current Value",group:"Value",getter(){return this._internal.currentInput?this._internal.trueString:this._internal.falseString}},inputChanged:{type:"signal",displayName:"Selector Changed",group:"Signals"}}},BooleanToString={node:BooleanToStringNode},DateToStringNode={name:"Date To String",docs:"https://docs.noodl.net/nodes/utilities/date-to-string",category:"Utilities",initialize(){this._internal.formatString="{year}-{month}-{date}"},inputs:{formatString:{displayName:"Format",type:"string",default:"{year}-{month}-{date}",set(e){this._internal.formatString!==e&&(this._internal.formatString=e,this._internal.currentInput!==void 0&&(this._format(),this.flagOutputDirty("currentValue")))}},input:{type:{name:"date"},displayName:"Date",set(e){const t=typeof e=="string"?new Date(e):e;this._internal.currentInput!==t&&(this._internal.currentInput=t,this._format())}}},outputs:{currentValue:{type:"string",displayName:"Date String",group:"Value",getter(){return this._internal.dateString}},inputChanged:{type:"signal",displayName:"Date Changed",group:"Signals"},onError:{type:"signal",displayName:"Invalid Date",group:"Signals"}},methods:{_format(){try{const e=this._internal.currentInput,t=this._internal.formatString,n=("0"+e.getDate()).slice(-2),o=("0"+(e.getMonth()+1)).slice(-2),r=new Intl.DateTimeFormat("en-US",{month:"short"}).format(e),s=e.getFullYear(),a=s.toString().substring(2),u=("0"+e.getHours()).slice(-2),l=("0"+e.getMinutes()).slice(-2),d=("0"+e.getSeconds()).slice(-2);this._internal.dateString=t.replace(/\{date\}/g,n).replace(/\{month\}/g,o).replace(/\{monthShort\}/g,r).replace(/\{year\}/g,s).replace(/\{yearShort\}/g,a).replace(/\{hours\}/g,u).replace(/\{minutes\}/g,l).replace(/\{seconds\}/g,d)}catch{this._internal.dateString="",this.flagOutputDirty("onError")}this.flagOutputDirty("currentValue"),this.sendSignalOnOutput("inputChanged")}}},DateToString={node:DateToStringNode},StringMapperNode={name:"String Mapper",docs:"https://docs.noodl.net/nodes/string-manipulation/string-mapper",category:"Utilities",initialize(){this._internal.inputs=[],this._internal.mappings=[]},getInspectInfo(){return this._internal.mappedString},numberedInputs:{input:{type:"string",displayPrefix:"Input",group:"Inputs",index:10,createSetter(e){return function(t){t=t===void 0?"":t.toString(),this._internal.inputs[e]=t,this.scheduleMapping()}}},output:{type:"string",displayPrefix:"Mapping",index:1001,group:"Mappings",createSetter(e){return function(t){t=t===void 0?"":t.toString(),this._internal.mappings[e]=t,this.scheduleMapping()}}}},inputs:{inputString:{type:{name:"string"},index:1,displayName:"Input String",set(e){this._internal.currentInputString=e!==void 0?e.toString():void 0,this.scheduleMapping()}},defaultMapping:{type:"string",displayName:"Default",index:1e3,group:"Mappings",set(e){this._internal.defaultMapping=e,this.scheduleMapping()}}},outputs:{mappedString:{type:"string",displayName:"Mapped String",group:"Value",getter(){return this._internal.mappedString}}},prototypeExtensions:{doMapping(){this._internal.hasScheduledFetch=!1;var e=this._internal.inputs.indexOf(this._internal.currentInputString);e!==-1?this._internal.mappedString=this._internal.mappings[e]:this._internal.mappedString=this._internal.defaultMapping,this.flagOutputDirty("mappedString")},scheduleMapping(){var e=this._internal;e.hasScheduledFetch||(e.hasScheduledFetch=!0,this.scheduleAfterInputsHaveUpdated(this.doMapping.bind(this)))}}},StringMapper={node:StringMapperNode};function invert(e){if(e!==void 0)return!e}const InverterNode={name:"Inverter",docs:"https://docs.noodl.net/nodes/logic/inverter",category:"Logic",initialize(){this._internal.currentValue=void 0},getInspectInfo(){return String(invert(this._internal.currentValue))},inputs:{value:{type:{name:"boolean"},displayName:"Value",set(e){this._internal.currentValue=e,this.flagOutputDirty("result")}}},outputs:{result:{type:"boolean",displayName:"Result",getter(){return invert(this._internal.currentValue)}}}},Inverter={node:InverterNode},SubStringNode={name:"Substring",docs:"https://docs.noodl.net/nodes/string-manipulation/substring",category:"String Manipulation",initialize(){var e=this._internal;e.startIndex=0,e.endIndex=-1,e.cachedResult="",e.inputString="",e.resultDirty=!1},inputs:{start:{type:"number",displayName:"Start",default:0,set(e){this._internal.startIndex=e,this._internal.resultDirty=!0,this.flagOutputDirty("result")}},end:{type:"number",displayName:"End",default:0,set(e){this._internal.endIndex=e,this._internal.resultDirty=!0,this.flagOutputDirty("result")}},string:{type:{name:"string"},displayName:"String",default:"",set(e){e=e.toString(),this._internal.inputString=e,this._internal.resultDirty=!0,this.flagOutputDirty("result")}}},outputs:{result:{type:"string",displayName:"Result",getter(){var e=this._internal;return e.resultDirty&&(e.endIndex===-1?e.cachedResult=e.inputString.substr(e.startIndex):e.cachedResult=e.inputString.substr(e.startIndex,e.endIndex-e.startIndex),e.resultDirty=!1),e.cachedResult}}}},Substring={node:SubStringNode},StringFormatDefinition={name:"String Format",docs:"https://docs.noodl.net/nodes/string-manipulation/string-format",category:"String Manipulation",usePortAsLabel:"format",portLabelTruncationMode:"length",initialize(){const e=this._internal;e.format="",e.cachedResult="",e.resultDirty=!1,e.inputValues={}},getInspectInfo(){return this.formatValue()},inputs:{format:{type:{name:"string",multiline:!0},displayName:"Format",set(e){this._internal.format!==e&&(this._internal.format=e,this._internal.resultDirty=!0,this.scheduleFormat())}}},outputs:{formatted:{type:"string",displayName:"Formatted",get(){return this.formatValue()}}},methods:{formatValue(){var e=this._internal;if(e.resultDirty){var t=e.format,n=e.format.match(/\{[A-Za-z0-9_]*\}/g),o=[];n&&(o=n.map(function(r){return r.replace("{","").replace("}","")})),o.forEach(function(r){var s=e.inputValues[r];t=t.replace("{"+r+"}",s!==void 0?s:"")}),e.cachedResult=t,e.resultDirty=!1}return e.cachedResult},registerInputIfNeeded(e){this.hasInput(e)||this.registerInput(e,{set:userInputSetter.bind(this,e)})},scheduleFormat(){this.formatScheduled||(this.formatScheduled=!0,this.scheduleAfterInputsHaveUpdated(()=>{this.formatValue(),this.flagOutputDirty("formatted"),this.formatScheduled=!1}))}}};function userInputSetter(e,t){this._internal.inputValues[e]!==t&&(this._internal.inputValues[e]=t,this._internal.resultDirty=!0,this.scheduleFormat())}function updatePorts$2(e,t,n){var o=t.match(/\{[A-Za-z0-9_]*\}/g)||[],r=o.map(function(a){return a.replace("{","").replace("}","")}),s=r.filter(function(a,u,l){return l.indexOf(a)===u}).map(function(a){return{name:a,type:"string",plug:"input"}});n.sendDynamicPorts(e,s)}const StringFormat={node:StringFormatDefinition,setup(e,t){!e.editorConnection||!e.editorConnection.isRunningLocally()||t.on("nodeAdded.String Format",function(n){n.parameters.format&&updatePorts$2(n.id,n.parameters.format,e.editorConnection),n.on("parameterUpdated",function(o){o.name==="format"&&updatePorts$2(n.id,n.parameters.format,e.editorConnection)})})}},CounterNode={name:"Counter",docs:"https://docs.noodl.net/nodes/math/counter",category:"Math",initialize(){this._internal.currentValue=0,this._internal.startValue=0,this._internal.startValueSet=!1,this._internal.limitsEnabled=!1,this._internal.limitsMin=0,this._internal.limitsMax=0},getInspectInfo(){return"Count: "+this._internal.currentValue},inputs:{increase:{group:"Actions",displayName:"Increase Count",valueChangedToTrue(){this._internal.limitsEnabled&&this._internal.currentValue>=this._internal.limitsMax||(this._internal.currentValue++,this.flagOutputDirty("currentCount"),this.sendSignalOnOutput("countChanged"))}},decrease:{group:"Actions",displayName:"Decrease Count",valueChangedToTrue(){this._internal.limitsEnabled&&this._internal.currentValue<=this._internal.limitsMin||(this._internal.currentValue--,this.flagOutputDirty("currentCount"),this.sendSignalOnOutput("countChanged"))}},reset:{group:"Actions",displayName:"Reset To Start",valueChangedToTrue(){this.currentValue!==0&&(this._internal.currentValue=this._internal.startValue,this.flagOutputDirty("currentCount"),this.sendSignalOnOutput("countChanged"))}},startValue:{type:"number",displayName:"Start Value",default:0,set(e){this._internal.startValue=Number(e),this._internal.startValueSet===!1&&(this._internal.startValueSet=!0,this._internal.currentValue=this._internal.startValue,this.flagOutputDirty("currentCount"),this.sendSignalOnOutput("countChanged"))}},limitsMin:{type:{name:"number"},displayName:"Min Value",group:"Limits",default:0,set(e){this._internal.limitsMin=Number(e)}},limitsMax:{type:{name:"number"},displayName:"Max Value",group:"Limits",default:0,set(e){this._internal.limitsMax=Number(e)}},limitsEnabled:{type:{name:"boolean"},displayName:"Limits Enabled",group:"Limits",default:!1,set(e){this._internal.limitsEnabled=!!e}}},outputs:{currentCount:{displayName:"Current Count",type:"number",getter(){return this._internal.currentValue}},countChanged:{displayName:"Count Changed",type:"signal"}}},Counter={node:CounterNode},UniqueIdNode={name:"Unique Id",docs:"https://docs.noodl.net/nodes/utilities/unique-id",category:"String Manipulation",initialize(){var e=this._internal;e.guid=Model.guid()},getInspectInfo(){return this._internal.guid},inputs:{new:{displayName:"New",valueChangedToTrue(){var e=this._internal;e.guid=Model.guid(),this.flagOutputDirty("guid")}}},outputs:{guid:{type:"string",displayName:"Id",getter(){var e=this._internal;return e.guid}}},prototypeExtensions:{}},UniqueId={node:UniqueIdNode},SetUserPropertiesNodeDefinition={name:"net.noodl.user.SetUserProperties",docs:"https://docs.noodl.net/nodes/data/user/set-user-properties",displayNodeName:"Set User Properties",category:"Cloud Services",color:"data",initialize(){var e=this._internal;e.userProperties={}},getInspectInfo(){},outputs:{success:{type:"signal",displayName:"Success",group:"Events"},failure:{type:"signal",displayName:"Failure",group:"Events"},error:{type:"string",displayName:"Error",group:"Error",getter(){return this._internal.error}}},inputs:{store:{displayName:"Do",group:"Actions",valueChangedToTrue(){this.scheduleStore()}},email:{displayName:"Email",type:"string",group:"General",set(e){this._internal.email=e}},username:{displayName:"Username",type:"string",group:"General",set(e){this._internal.username=e}}},methods:{setError(e){this._internal.error=e,this.flagOutputDirty("error"),this.sendSignalOnOutput("failure"),this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"user-set-warning",{message:e,showGlobally:!0})},clearWarnings(){this.context.editorConnection&&this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"user-set-warning")},scheduleStore(){const e=this._internal;this.storeScheduled!==!0&&(this.storeScheduled=!0,this.scheduleAfterInputsHaveUpdated(()=>{this.storeScheduled=!1,Runtime.Services.UserService.forScope(this.nodeScope.modelScope).setUserProperties({email:this._internal.email,username:this._internal.username,properties:e.userProperties,success:()=>{this.sendSignalOnOutput("success")},error:n=>{this.setError(n)}})}))},setUserProperty(e,t){this._internal.userProperties[e]=t},registerInputIfNeeded(e){if(!this.hasInput(e)&&e.startsWith("prop-"))return this.registerInput(e,{set:this.setUserProperty.bind(this,e.substring(5))})}}};function updatePorts$1(e,t,n,o){var r=[];if(o){var s=o.find(d=>d.name==="_User");if(s&&s.schema&&s.schema.properties){var a=s.schema.properties;const d=typeof _noodl_cloud_runtime_version>"u"?["authData","createdAt","updatedAt","email","username","emailVerified","password"]:["authData","createdAt","updatedAt","email","username"];for(var u in a)if(d.indexOf(u)===-1){var l=a[u];if(!r.find(p=>p.name===u)&&l.type!=="Relation"){const p={String:"string",Boolean:"boolean",Number:"number",Date:"date"};r.push({type:{name:p[l.type]?p[l.type]:"*"},plug:"input",group:"Properties",name:"prop-"+u,displayName:u})}}}}n.sendDynamicPorts(e,r)}const SetUserProperties={node:SetUserPropertiesNodeDefinition,setup(e,t){if(!e.editorConnection||!e.editorConnection.isRunningLocally())return;function n(o){updatePorts$1(o.id,o.parameters,e.editorConnection,t.getMetaData("systemCollections")),o.on("parameterUpdated",function(r){updatePorts$1(o.id,o.parameters,e.editorConnection,t.getMetaData("systemCollections"))}),t.on("metadataChanged.systemCollections",function(r){updatePorts$1(o.id,o.parameters,e.editorConnection,r)})}t.on("editorImportComplete",()=>{t.on("nodeAdded.net.noodl.user.SetUserProperties",function(o){n(o)});for(const o of t.getNodesWithType("net.noodl.user.SetUserProperties"))n(o)})}};var UserNodeDefinition={name:"net.noodl.user.User",docs:"https://docs.noodl.net/nodes/data/user/user-node",displayNodeName:"User",category:"Cloud Services",color:"data",initialize(){var e=this;this._internal.onModelChangedCallback=function(n){e.isInputConnected("fetch")||(e.hasOutput("prop-"+n.name)&&e.flagOutputDirty("prop-"+n.name),e.hasOutput("changed-"+n.name)&&e.sendSignalOnOutput("changed-"+n.name),e.sendSignalOnOutput("changed"))};const t=Runtime.Services.UserService.forScope(this.nodeScope.modelScope);this.setUserModel(t.current),t.on("loggedIn",()=>{this.setUserModel(t.current),this.hasOutput("loggedIn")&&this.sendSignalOnOutput("loggedIn")}),t.on("sessionGained",()=>{this.setUserModel(t.current)}),t.on("loggedOut",()=>{this.setUserModel(void 0),this.hasOutput("loggedOut")&&this.sendSignalOnOutput("loggedOut")}),t.on("sessionLost",()=>{this.setUserModel(void 0),this.hasOutput("sessionLost")&&this.sendSignalOnOutput("sessionLost")})},getInspectInfo(){const e=this._internal.model;return e?[{type:"text",value:"Id: "+e.getId()},{type:"value",value:this._internal.model.data}]:"[No Model]"},outputs:{id:{type:"string",displayName:"Id",group:"General",getter(){return this._internal.model!==void 0?this._internal.model.getId():void 0}},fetched:{type:"signal",displayName:"Fetched",group:"Events"},changed:{type:"signal",displayName:"Changed",group:"Events"},failure:{type:"signal",displayName:"Failure",group:"Events"},error:{type:"string",displayName:"Error",group:"Error",getter(){return this._internal.error}},username:{type:"string",displayName:"Username",group:"General",getter(){return this._internal.model!==void 0?this._internal.model.get("username"):void 0}},email:{type:"string",displayName:"Email",group:"General",getter(){return this._internal.model!==void 0?this._internal.model.get("email"):void 0}},authenticated:{type:"boolean",displayName:"Authenticated",group:"General",getter(){return this._internal.model!==void 0}}},inputs:{fetch:{displayName:"Fetch",group:"Actions",valueChangedToTrue(){this.scheduleFetch()}}},methods:{_onNodeDeleted(){Node.prototype._onNodeDeleted.call(this),this._internal.model&&this._internal.model.off("change",this._internal.onModelChangedCallback)},scheduleOnce(e,t){const n=this,o="hasScheduled"+e;this._internal[o]||(this._internal[o]=!0,this.scheduleAfterInputsHaveUpdated(function(){n._internal[o]=!1,t()}))},setError(e){this._internal.error=e,this.flagOutputDirty("error"),this.sendSignalOnOutput("failure"),this.context.editorConnection&&this.context.editorConnection.sendWarning(this.nodeScope.componentOwner.name,this.id,"user-warning",{message:e,showGlobally:!0})},clearWarnings(){this.context.editorConnection&&this.context.editorConnection.clearWarning(this.nodeScope.componentOwner.name,this.id,"user-warning")},setUserModel(e){const t=this._internal;if(t.model!==e&&(t.model&&t.model.off("change",t.onModelChangedCallback),t.model=e,e&&e.on("change",t.onModelChangedCallback)),this.flagOutputDirty("id"),this.flagOutputDirty("authenticated"),this.flagOutputDirty("email"),this.flagOutputDirty("username"),e)for(var n in e.data)this.hasOutput("prop-"+n)&&this.flagOutputDirty("prop-"+n)},scheduleFetch(){this._internal,this.scheduleOnce("Fetch",()=>{const e=Runtime.Services.UserService.forScope(this.nodeScope.modelScope);e.fetchCurrentUser({success:t=>{this.setUserModel(e.current),this.sendSignalOnOutput("fetched")},error:t=>{this.setError(t||"Failed to fetch.")}})})},registerOutputIfNeeded(e){if(!this.hasOutput(e)){if(e==="loggedOut"||e==="loggedIn"||e==="sessionLost"){this.registerOutput(e,{getter:()=>{}});return}e.startsWith("prop-")&&this.registerOutput(e,{getter:this.getUserProperty.bind(this,e.substring(5))})}},getUserProperty(e){return this._internal.model!==void 0?this._internal.model.get(e):void 0}}};function updatePorts(e,t,n,o){var r=[];if(o){var s=o.find(d=>d.name==="_User");if(s&&s.schema&&s.schema.properties){var a=s.schema.properties;const d=["authData","password","username","email"];for(var u in a)if(d.indexOf(u)===-1){var l=a[u];if(!r.find(p=>p.name===u)&&l.type!=="Relation"){const p={String:"string",Boolean:"boolean",Number:"number",Date:"date"};r.push({type:{name:p[l.type]?p[l.type]:"*"},plug:"output",group:"Properties",name:"prop-"+u,displayName:u}),r.push({type:"signal",plug:"output",group:"Changed Events",displayName:u+" Changed",name:"changed-"+u})}}}}typeof _noodl_cloud_runtime_version>"u"&&(r.push({plug:"output",name:"loggedIn",type:"signal",displayName:"Logged In",group:"Events"}),r.push({plug:"output",name:"loggedOut",type:"signal",displayName:"Logged Out",group:"Events"}),r.push({plug:"output",name:"sessionLost",type:"signal",displayName:"Session Lost",group:"Events"})),n.sendDynamicPorts(e,r)}const User={node:UserNodeDefinition,setup(e,t){if(!e.editorConnection||!e.editorConnection.isRunningLocally())return;function n(o){updatePorts(o.id,o.parameters,e.editorConnection,t.getMetaData("systemCollections")),o.on("parameterUpdated",function(r){updatePorts(o.id,o.parameters,e.editorConnection,t.getMetaData("systemCollections"))}),t.on("metadataChanged.systemCollections",function(r){updatePorts(o.id,o.parameters,e.editorConnection,r)})}t.on("editorImportComplete",()=>{t.on("nodeAdded.net.noodl.user.User",function(o){n(o)});for(const o of t.getNodesWithType("net.noodl.user.User"))n(o)})}};function registerNodes(e){[ComponentInputs,ComponentOutputs,RunTasks,RestNode$1,Expression,SimpleJavaScript,DbCollectionNode2,DbModelNode2,SetDbModelPropertiedNodeDefinition,DeleteDbModelPropertiedNodeDefinition,NewDbModelPropertiedNodeDefinition,AddDbModelRelationNodeDefinition$1,AddDbModelRelationNodeDefinition,FilterDbModelsNode,ModelNode2,SetModelPropertiedNodeDefinition,NewModelNodeDefinition,CloudFileNode$1,DbConfig,NumberVar,StringVar,BooleanVar,Condition,And,Or,BooleanToString,DateToString,StringMapper,Inverter,Substring,StringFormat,Counter,UniqueId,SetUserProperties,User].forEach(t=>e.registerNode(t))}function Runtime(e){if(e=e||{},e.platform=e.platform||{},Runtime.instance=this,this.type=e.type||"browser",this.noodlModules=[],this.eventEmitter=new EventEmitter,this.updateScheduled=!1,this.rootComponent=null,this._currentLoadedData=null,this.isWaitingForExport=!0,this.graphModel=new GraphModel,this.errorHandlers=[],this.frameNumber=0,this.dontCreateRootComponent=!!e.dontCreateRootComponent,this.componentFilter=e.componentFilter,this.runningInEditor=!e.runDeployed,this.platform={requestUpdate:e.platform.requestUpdate,getCurrentTime:e.platform.getCurrentTime,webSocketOptions:e.platform.webSocketOptions,objectToString:e.platform.objectToString},!e.platform.requestUpdate)throw new Error("platform.requestUpdate must be set");if(!e.platform.getCurrentTime)throw new Error("platform.getCurrentTime must be set");this.editorConnection=new EditorConnection({platform:e.platform,runtimeType:this.type}),this.context=new NodeContext({runningInEditor:!e.runDeployed,editorConnection:this.editorConnection,platform:this.platform,graphModel:this.graphModel}),this.context.eventEmitter.on("scheduleUpdate",this.scheduleUpdate.bind(this)),e.runDeployed||this._setupEditorCommunication(e),this.registerGraphModelListeners(),registerNodes(this)}Runtime.prototype.prefetchBundles=async function(e,t){await asyncPool(t,e,async n=>{await this.context.fetchComponentBundle(n)})},Runtime.prototype._setupEditorCommunication=function(e){function t(n,o){if(n==null||o===null||o===void 0)return n===o;if(n===o)return!0;if(Array.isArray(n)&&n.length!==o.length||!(n instanceof Object)||!(o instanceof Object))return!1;var r=Object.keys(n);return Object.keys(o).every(function(s){return r.indexOf(s)!==-1})&&r.every(function(s){return t(n[s],o[s])})}this.editorConnection.on("exportDataFull",async n=>{if(this.graphModel.isEmpty()===!1){this.reload();return}if(this.isWaitingForExport=!1,t(this._currentLoadedData,n)===!1){if(this.componentFilter&&(n.components=n.components.filter(o=>this.componentFilter(o))),await this.setData(n),n.componentIndex){const o=Object.keys(n.componentIndex);await this.prefetchBundles(o,2)}this.graphModel.emit("editorImportComplete")}}),this.editorConnection.on("reload",this.reload.bind(this)),this.editorConnection.on("modelUpdate",this.onModelUpdateReceived.bind(this)),this.editorConnection.on("metadataUpdate",this.onMetaDataUpdateReceived.bind(this)),this.editorConnection.on("connected",()=>{this.sendNodeLibrary()})},Runtime.prototype.setDebugInspectorsEnabled=function(e){this.context.setDebugInspectorsEnabled(e)},Runtime.prototype.registerModule=function(e){if(e.nodes)for(let t of e.nodes)t.node||(t={node:t}),t.node.module=e.name||"Unknown Module",this.registerNode(t);this.noodlModules.push(e)},Runtime.prototype.registerGraphModelListeners=function(){var e=this;this.graphModel.on("componentAdded",function(t){e.context.registerComponentModel(t)},this),this.graphModel.on("componentRemoved",function(t){e.context.deregisterComponentModel(t)},this)},Runtime.prototype.reload=function(){location.reload()},Runtime.prototype.registerNode=function(e){if(e.node){const t=defineNode(e.node);this.context.nodeRegister.register(t),t.setupNumberedInputDynamicPorts&&t.setupNumberedInputDynamicPorts(this.context,this.graphModel)}else this.context.nodeRegister.register(e);e.setup&&e.setup(this.context,this.graphModel)},Runtime.prototype._setRootComponent=async function(e){this.rootComponent&&this.rootComponent.name===e||(this.rootComponent&&(this.rootComponent.model&&this.rootComponent.model.removeListenersWithRef(this),this.rootComponent=void 0),e&&(this.rootComponent=await this.context.createComponentInstanceNode(e,"rootComponent"),this.rootComponent.componentModel.on("rootAdded",()=>this.eventEmitter.emit("rootComponentUpdated"),this),this.rootComponent.componentModel.on("rootRemoved",()=>this.eventEmitter.emit("rootComponentUpdated"),this),this.context.setRootComponent(this.rootComponent)),this.eventEmitter.emit("rootComponentUpdated"))},Runtime.prototype.setData=async function(e){if(!this._disableLoad){this._currentLoadedData=e,await this.graphModel.importEditorData(e);for(const t of this.noodlModules)typeof t.setup=="function"&&t.setup.apply(t);this.dontCreateRootComponent!==!0&&(await this._setRootComponent(this.graphModel.rootComponent),this.graphModel.on("rootComponentNameUpdated",t=>{this._setRootComponent(t)}),this.graphModel.on("componentRemoved",t=>{this.rootComponent&&this.rootComponent.name===t.name&&this._setRootComponent(null)}),this.graphModel.on("componentAdded",t=>{setTimeout(()=>{!this.rootComponent&&this.graphModel.rootComponent===t.name&&this._setRootComponent(t.name)},1)})),this.scheduleUpdate()}},Runtime.prototype.scheduleUpdate=function(){this.updateScheduled||(this.updateScheduled=!0,this.platform.requestUpdate(Runtime.prototype._doUpdate.bind(this)))},Runtime.prototype._doUpdate=function(){this.updateScheduled=!1,this.context.currentFrameTime=this.platform.getCurrentTime(),this.context.eventEmitter.emit("frameStart"),this.context.update(),this.context.eventEmitter.emit("frameEnd"),this.frameNumber++},Runtime.prototype.setProjectSettings=function(e){this.projectSettings=e},Runtime.prototype.getNodeLibrary=function(){var e=generateProjectSettings(this.graphModel.getSettings(),this.noodlModules);this.projectSettings&&(this.projectSettings.ports&&(e.ports=e.ports.concat(this.projectSettings.ports)),this.projectSettings.dynamicports&&(e.dynamicports=e.ports.concat(this.projectSettings.dynamicports)));var t=generateNodeLibrary(this.context.nodeRegister);return t.projectsettings=e,JSON.stringify(t,null,3)},Runtime.prototype.sendNodeLibrary=function(){const e=this.getNodeLibrary();this.lastSentNodeLibrary!==e&&(this.lastSentNodeLibrary=e,this.editorConnection.sendNodeLibrary(e))},Runtime.prototype.connectToEditor=function(e){this.editorConnection.connect(e)},Runtime.prototype.onMetaDataUpdateReceived=function(e){this.graphModel.isEmpty()||EditorMetaDataEventsHandler.handleEvent(this.context,this.graphModel,e)},Runtime.prototype.onModelUpdateReceived=async function(e){this.isWaitingForExport||(e.type==="projectInstanceChanged"?this.reload():this.graphModel.isEmpty()===!1&&await handleEvent(this.context,this.graphModel,e))},Runtime.prototype.addErrorHandler=function(e){this.errorHandlers.push(e)},Runtime.prototype.reportError=function(e){this.errorHandlers.forEach(function(t){t(e)})},Runtime.prototype.getProjectSettings=function(){return this.graphModel.getSettings()},Runtime.prototype.getMetaData=function(e){return this.graphModel.getMetaData(e)},Runtime.Services=Services,Runtime.Node=Node,Runtime.NodeDefinition={defineNode},Runtime.EdgeTriggeredInput=EdgeTriggeredInput;const _protectedFields={_common:["_createdAt","_updatedAt","objectId"],_User:["_email_verify_token"]};function _removeProtectedFields(e,t){const n=Object.assign({},e);return _protectedFields._common.forEach(o=>delete n[o]),t&&_protectedFields[t]&&_protectedFields[t].forEach(o=>delete n[o]),n}class CloudStore{constructor(t){this._initCloudServices(),this.events=new EventEmitter,this.events.setMaxListeners(1e4),this.modelScope=t,this._fromJSON=(n,o)=>CloudStore._fromJSON(n,o,t),this._deserializeJSON=(n,o)=>CloudStore._deserializeJSON(n,o,t),this._serializeObject=(n,o)=>CloudStore._serializeObject(n,o,t)}_initCloudServices(){_collections=void 0;const t=Runtime.instance.getMetaData("cloudservices");t&&(this.appId=t.appId,this.endpoint=t.endpoint);const n=Runtime.instance.getMetaData("dbVersionMajor");this.dbVersionMajor=n}on(){this.events.on.apply(this.events,arguments)}off(){this.events.off.apply(this.events,arguments)}_makeRequest(t,n){if(typeof _noodl_cloud_runtime_version>"u"){var o=new XMLHttpRequest;o.onreadystatechange=function(){if(o.readyState===4){var s;try{s=JSON.parse(o.response||o.responseText)}catch{}o.status===200||o.status===201?n.success(s):n.error(s||{error:o.responseText,status:o.status})}},o.open(n.method||"GET",this.endpoint+t,!0),o.setRequestHeader("X-Parse-Application-Id",this.appId),typeof _noodl_cloudservices<"u"&&o.setRequestHeader("X-Parse-Master-Key",_noodl_cloudservices.masterKey);var r=localStorage["Parse/"+this.appId+"/currentUser"];if(r!==void 0)try{const s=JSON.parse(r);o.setRequestHeader("X-Parse-Session-Token",s.sessionToken)}catch{}n.onUploadProgress&&(o.upload.onprogress=s=>n.onUploadProgress(s)),n.content instanceof File?o.send(n.content):(o.setRequestHeader("Content-Type","application/json"),o.send(JSON.stringify(n.content)))}else{const s=typeof _noodl_cloudservices<"u"?_noodl_cloudservices.endpoint:this.endpoint,a=typeof _noodl_cloudservices<"u"?_noodl_cloudservices.appId:this.appId,u=typeof _noodl_cloudservices<"u"?_noodl_cloudservices.masterKey:void 0;fetch(s+t,{method:n.method||"GET",headers:{"X-Parse-Application-Id":a,"X-Parse-Master-Key":u,"Content-Type":"application/json"},body:JSON.stringify(n.content)}).then(l=>{l.status===200||l.status===201?n.method==="DELETE"?n.success(void 0):l.json().then(d=>n.success(d)).catch(d=>n.error({error:"CloudStore: Failed to get json result."})):n.method==="DELETE"?n.error({error:"Failed to delete."}):l.json().then(d=>n.error(d)).catch(d=>n.error({error:"Failed to fetch."}))}).catch(l=>{n.error({error:l.message})})}}query(t){this._makeRequest("/classes/"+t.collection,{method:"POST",content:{_method:"GET",where:t.where,limit:t.limit,skip:t.skip,include:Array.isArray(t.include)?t.include.join(","):t.include,keys:Array.isArray(t.select)?t.select.join(","):t.select,order:Array.isArray(t.sort)?t.sort.join(","):t.sort,count:t.count},success(n){t.success(n.results,n.count)},error(){t.error()}})}aggregate(t){const n=[];if(!t.group){t.error("You need to provide group option.");return}t.limit&&n.push("limit="+t.limit),t.skip&&n.push("skip="+t.skip);const o={};Object.keys(t.group).forEach(r=>{const s={},a=t.group[r];a.avg!==void 0?s.$avg="$"+a.avg:a.sum!==void 0?s.$sum="$"+a.sum:a.max!==void 0?s.$max="$"+a.max:a.min!==void 0?s.$min="$"+a.min:a.distinct!==void 0&&(s.$addToSet="$"+a.distinct),o[r]=s}),this.dbVersionMajor&&this.dbVersionMajor>4?(o._id=null,t.where&&n.push("$match="+encodeURIComponent(JSON.stringify(t.where))),n.push("$group="+JSON.stringify(o))):(o.objectId=null,t.where&&n.push("match="+encodeURIComponent(JSON.stringify(t.where))),n.push("group="+JSON.stringify(o))),this._makeRequest("/aggregate/"+t.collection+(n.length>0?"?"+n.join("&"):""),{success(r){const s={};if(!r.results||r.results.length!==1){t.success({});return}Object.keys(t.group).forEach(a=>{s[a]=r.results[0][a]}),t.success(s)},error(){t.error()}})}count(t){const n=[];t.where&&n.push("where="+encodeURIComponent(JSON.stringify(t.where))),n.push("limit=0"),n.push("count=1"),this._makeRequest("/classes/"+t.collection+(n.length>0?"?"+n.join("&"):""),{success(o){t.success(o.count)},error(){t.error()}})}distinct(t){const n=[];t.where&&n.push("where="+encodeURIComponent(JSON.stringify(t.where))),n.push("distinct="+t.property),this._makeRequest("/aggregate/"+t.collection+(n.length>0?"?"+n.join("&"):""),{success(o){t.success(o.results)},error(){t.error()}})}fetch(t){const n=[];t.include&&n.push("include="+(Array.isArray(t.include)?t.include.join(","):t.include)),t.keys&&n.push("keys="+(Array.isArray(t.keys)?t.keys.join(","):t.keys)),t.excludeKeys&&n.push("excludeKeys="+(Array.isArray(t.excludeKeys)?t.excludeKeys.join(","):t.excludeKeys)),this._makeRequest("/classes/"+t.collection+"/"+t.objectId+(n.length>0?"?"+n.join("&"):""),{method:"GET",success:o=>{t.success(o),this.events.emit("fetch",{type:"fetch",objectId:t.objectId,object:o,collection:t.collection})},error(o){t.error(o.error)}})}create(t){this._makeRequest("/classes/"+t.collection,{method:"POST",content:Object.assign(_removeProtectedFields(_serializeObject(t.data,t.collection),t.collection),{ACL:t.acl}),success:n=>{const o=Object.assign({},t.data,n);t.success(o),this.events.emit("create",{type:"create",objectId:t.objectId,object:o,collection:t.collection})},error(n){t.error(n.error)}})}increment(t){const n={};for(let o in t.properties)n[o]={__op:"Increment",amount:t.properties[o]};this._makeRequest("/classes/"+t.collection+"/"+t.objectId,{method:"PUT",content:n,success:o=>{t.success(o)},error(o){t.error(o.error)}})}save(t){const n=Object.assign({},t.data);delete n.createdAt,delete n.updatedAt,this._makeRequest("/classes/"+t.collection+"/"+t.objectId,{method:"PUT",content:Object.assign(_removeProtectedFields(_serializeObject(n,t.collection),t.collection),{ACL:t.acl}),success:o=>{t.success(o),this.events.emit("save",{type:"save",objectId:t.objectId,object:Object.assign({},t.data,o),collection:t.collection})},error(o){t.error(o.error)}})}delete(t){this._makeRequest("/classes/"+t.collection+"/"+t.objectId,{method:"DELETE",success:()=>{t.success(),this.events.emit("delete",{type:"delete",objectId:t.objectId,collection:t.collection})},error(n){t.error(n.error)}})}addRelation(t){const n={};n[t.key]={__op:"AddRelation",objects:[{__type:"Pointer",objectId:t.targetObjectId,className:t.targetClass}]},this._makeRequest("/classes/"+t.collection+"/"+t.objectId,{method:"PUT",content:n,success(o){t.success(o)},error(o){t.error(o.error)}})}removeRelation(t){const n={};n[t.key]={__op:"RemoveRelation",objects:[{__type:"Pointer",objectId:t.targetObjectId,className:t.targetClass}]},this._makeRequest("/classes/"+t.collection+"/"+t.objectId,{method:"PUT",content:n,success(o){t.success(o)},error(o){t.error(o.error)}})}uploadFile(t){this._makeRequest("/files/"+t.file.name,{method:"POST",content:t.file,contentType:t.file.type,success:n=>t.success(Object.assign({},t.data,n)),error:n=>t.error(n),onUploadProgress:t.onUploadProgress})}deleteFile(t){this._makeRequest("/files/"+t.file.name,{method:"DELETE",success:n=>t.success(Object.assign({},t.data,n)),error:n=>t.error(n)})}}function _isArrayOfObjects(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(typeof e[t]!="object"||e[t]===null)return!1;return!0}function _toJSON(e){if(e instanceof Model){var t={};for(var n in e.data)t[n]=_toJSON(e.data[n]);return t}else if(e instanceof Collection){var t=[];return e.items.forEach(r=>{t.push(_toJSON(r))}),t}return e}function _serializeObject(e,t,n){if(CloudStore._collections[t])var o=CloudStore._collections[t].schema;for(var r in e){var s=o&&o.properties&&o.properties[r]?o.properties[r].type:void 0;if(!(e[r]===void 0||e[r]===null))if(s==="Pointer"&&typeof e[r]=="string")e[r]={__type:"Pointer",className:o.properties[r].targetClass,objectId:e[r]};else if(s==="Pointer"&&typeof e[r]=="object"&&(n||Model).instanceOf(e[r]))e[r]={__type:"Pointer",className:o.properties[r].targetClass,objectId:e[r].getId()};else if(s==="Date"&&(typeof e[r]=="string"||e[r]instanceof Date))e[r]={__type:"Date",iso:e[r]instanceof Date?e[r].toISOString():e[r]};else if(s==="File"&&e[r]instanceof CloudFile){const a=e[r];e[r]={__type:"File",url:a.getUrl(),name:a.getName()}}else s==="Array"&&typeof e[r]=="string"&&Collection.exists(e[r])?e[r]=_toJSON(Collection.get(e[r])):s==="Object"&&typeof e[r]=="string"&&(n||Model).exists(e[r])?e[r]=_toJSON((n||Model).get(e[r])):s==="GeoPoint"&&typeof e[r]=="object"?e[r]={__type:"GeoPoint",latitude:Number(e[r].latitude),longitude:Number(e[r].longitude)}:e[r]=_toJSON(e[r])}return e}function _deserializeJSON(e,t,n){if(e!==void 0){if(e===null)return null;if(!(t==="Relation"&&e.__type==="Relation")){if(t==="Pointer"&&e.__type==="Pointer")return e.objectId;if(t==="Date"&&e.__type==="Date")return new Date(e.iso);if(t==="Date"&&typeof e=="string")return new Date(e);if(t==="File"&&e.__type==="File")return new CloudFile(e);if(t==="GeoPoint"&&e.__type==="GeoPoint")return{latitude:e.latitude,longitude:e.longitude};if(_isArrayOfObjects(e)){const o=[];for(let s=0;s<e.length;s++)o.push(_deserializeJSON(e[s],void 0,n));const r=Collection.get();return r.set(o),r}if(Array.isArray(e))return e;if(e&&e.__type==="Object"&&e.className!==void 0&&e.objectId!==void 0){const o=Object.assign({},e);return delete o.className,delete o.__type,_fromJSON(o,e.className,n)}if(typeof e=="object"&&e!==null){const o=(n||Model).get(e.id);for(const r in e){const s=_deserializeJSON(e[r],void 0,n);o.set(r,s)}return o}return e}}}function _fromJSON(e,t,n){const r=(n||Model).get(e.objectId||e.id);r._class=t;let s;t!==void 0&&CloudStore._collections[t]!==void 0&&(s=CloudStore._collections[t].schema);for(const a in e){if(a==="objectId"||a==="ACL")continue;const u=s&&s.properties&&s.properties[a]?s.properties[a].type:void 0,l=_deserializeJSON(e[a],u,n);r.set(a,l)}return r}CloudStore._fromJSON=_fromJSON,CloudStore._deserializeJSON=_deserializeJSON,CloudStore._serializeObject=_serializeObject,CloudStore.forScope=e=>e===void 0?CloudStore.instance:(e._cloudStore||(e._cloudStore=new CloudStore(e)),e._cloudStore);var _instance;Object.defineProperty(CloudStore,"instance",{get(){return _instance===void 0&&(_instance=new CloudStore),_instance}});var _collections;Object.defineProperty(CloudStore,"_collections",{get(){return _collections===void 0&&(_collections={},(Runtime.instance.getMetaData("dbCollections")||[]).forEach(n=>{_collections[n.name]=n}),(Runtime.instance.getMetaData("systemCollections")||[]).forEach(n=>{_collections[n.name]=n})),_collections}}),CloudStore.invalidateCollections=()=>{_collections=void 0};function createRecordsAPI(e){let t;const n=()=>(t||(t=new CloudStore(e)),t);return{async query(o,r,s){if(typeof o>"u")throw new Error("'className' is undefined");return new Promise((a,u)=>{n().query({collection:o,where:convertFilterOp(r||{},{collectionName:o,error:l=>u(l),modelScope:e}),limit:s?s.limit:void 0,sort:s?s.sort:void 0,skip:s?s.skip:void 0,include:s?s.include:void 0,select:s?s.select:void 0,count:s?s.count:void 0,success:(l,d)=>{const p=l.map(f=>n()._fromJSON(f,o));a(d!==void 0?{results:p,count:d}:p)},error:l=>{u(Error(l||"Failed to query."))}})})},async count(o,r){if(typeof o>"u")throw new Error("'className' is undefined");return new Promise((s,a)=>{n().count({collection:o,where:r?convertFilterOp(r||{},{collectionName:o,error:u=>a(u),modelScope:e}):void 0,success:u=>{s(u)},error:u=>{a(Error(u||"Failed to query."))}})})},async distinct(o,r,s){if(typeof o>"u")throw new Error("'className' is undefined");return new Promise((a,u)=>{n().distinct({collection:o,property:r,where:s?convertFilterOp(s||{},{collectionName:o,error:l=>u(l),modelScope:e}):void 0,success:l=>{a(l)},error:l=>{u(Error(l||"Failed to query."))}})})},async aggregate(o,r,s){if(typeof o>"u")throw new Error("'className' is undefined");return new Promise((a,u)=>{n().aggregate({collection:o,group:r,where:s?convertFilterOp(s||{},{collectionName:o,error:l=>u(l),modelScope:e}):void 0,success:l=>{a(l)},error:l=>{u(Error(l||"Failed to aggregate."))}})})},async fetch(o,r){if(typeof o>"u")return Promise.reject(new Error("'objectOrId' is undefined."));typeof o!="string"&&(o=o.getId());const s=(r?r.className:void 0)||(e||Model).get(o)._class;return new Promise((a,u)=>{if(!s)return u("No class name specified");n().fetch({collection:s,objectId:o,keys:r?.keys,include:r?.include,excludeKeys:r?.excludeKeys,success(l){const d=n()._fromJSON(l,s);a(d)},error(l){u(Error(l||"Failed to fetch."))}})})},async increment(o,r,s){if(typeof o>"u")return Promise.reject(new Error("'objectOrId' is undefined."));typeof o!="string"&&(o=o.getId());const a=(s?s.className:void 0)||(e||Model).get(o)._class;return new Promise((u,l)=>{if(!a)return l("No class name specified");n().increment({collection:a,objectId:o,properties:r,success:d=>{n()._fromJSON(Object.assign({objectId:o},d),a),u()},error:d=>{l(Error(d||"Failed to increment."))}})})},async save(o,r,s){if(typeof o>"u")return Promise.reject(new Error("'objectOrId' is undefined."));typeof o!="string"&&(o=o.getId());const a=(s?s.className:void 0)||(e||Model).get(o)._class,u=(e||Model).get(o);return r&&Object.keys(r).forEach(l=>{u.set(l,r[l])}),new Promise((l,d)=>{if(!a)return d("No class name specified");n().save({collection:a,objectId:o,data:r||u.data,acl:s?s.acl:void 0,success:p=>{n()._fromJSON(Object.assign({objectId:o},p),a),l()},error:p=>{d(Error(p||"Failed to save."))}})})},async create(o,r,s){if(typeof o>"u")throw new Error("'className' is undefined");return new Promise((a,u)=>{n().create({collection:o,data:r,acl:s?s.acl:void 0,success:l=>{const d=n()._fromJSON(l,o);a(d)},error:l=>{u(Error(l||"Failed to insert."))}})})},async delete(o,r){if(typeof o>"u")return Promise.reject(new Error("'objectOrId' is undefined."));typeof o!="string"&&(o=o.getId());const s=(r?r.className:void 0)||(e||Model).get(o)._class;return new Promise((a,u)=>{if(!s)return u("No class name specified");n().delete({collection:s,objectId:o,success:()=>{(e||Model).get(o).notify("delete"),a()},error:l=>{u(Error(l||"Failed to delete."))}})})},async addRelation(o){const r=o.recordId||o.record.getId(),s=o.className||(e||Model).get(r)._class,a=o.targetRecordId||o.targetRecord.getId(),u=o.targetClassName||(e||Model).get(a)._class;return new Promise((l,d)=>{if(!s)return d("No class name specified");if(!u)return d("No target class name specified");n().addRelation({collection:s,objectId:r,key:o.key,targetObjectId:a,targetClass:u,success:p=>{l()},error:p=>{d(Error(p||"Failed to add relation."))}})})},async removeRelation(o){const r=o.recordId||o.record.getId(),s=o.className||(e||Model).get(r)._class,a=o.targetRecordId||o.targetRecord.getId(),u=o.targetClassName||(e||Model).get(a)._class;return new Promise((l,d)=>{if(!s)return d("No class name specified");if(!u)return d("No target class name specified");n().removeRelation({collection:s,objectId:r,key:o.key,targetObjectId:a,targetClass:u,success:p=>{l()},error:p=>{d(Error(p||"Failed to add relation."))}})})}}}return exports.ActiveWarnings=ActiveWarnings,exports.CloudFile=CloudFile,exports.CloudStore=CloudStore,exports.Collection=Collection,exports.ComponentModel=ComponentModel,exports.ConfigService=ConfigService,exports.EditorConnection=EditorConnection,exports.EventEmitter=EventEmitter,exports.EventSender=EventSender,exports.GraphModel=GraphModel,exports.JavascriptNodeParser=JavascriptNodeParser,exports.Model=Model,exports.Node=Node,exports.NodeContext=NodeContext,exports.NodeModel=NodeModel,exports.NodeRegister=NodeRegister,exports.NodeScope=NodeScope,exports.OutputProperty=OutputProperty,exports.Runtime=Runtime,exports.Services=Services,exports.TimerScheduler=TimerScheduler,exports.Variants=Variants,exports.asyncPool=asyncPool,exports.compareObjects=compareObjects,exports.convertFilterOp=convertFilterOp,exports.convertVisualFilter=convertVisualFilter,exports.convertVisualSorting=convertVisualSorting,exports.createRecordsAPI=createRecordsAPI,exports.createSetter=createSetter,exports.createVariableDefinition=createDefinition,exports.defineNode=defineNode,exports.extend=extend,exports.generateNodeLibrary=generateNodeLibrary,exports.generateProjectSettings=generateProjectSettings,exports.getAbsoluteUrl=getAbsoluteUrl,exports.guid=guid,exports.handleEvent=handleEvent,exports.logJavaScriptNodeError=logJavaScriptNodeError,exports.matchesQuery=matchesQuery,exports.once=once,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),exports}({});
|
|
25
|
+
//# sourceMappingURL=index.iife.js.map
|