@xpell/core 2.0.0-alpha.11 → 2.0.2
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/README.md +100 -61
- package/dist/XCommand.d.ts +1 -1
- package/dist/XDataModule.d.ts +41 -0
- package/dist/XEvenetManagerModule.d.ts +10 -0
- package/dist/XEventManager.d.ts +3 -6
- package/dist/XModule.d.ts +14 -1
- package/dist/XNanoCommands.d.ts +6 -34
- package/dist/XObject.d.ts +40 -5
- package/dist/XObjectManager.d.ts +2 -0
- package/dist/XParams.d.ts +1 -1
- package/dist/XRuntime.d.ts +2 -0
- package/dist/XSkills.d.ts +47 -0
- package/dist/XUtils.d.ts +35 -0
- package/dist/Xpell.d.ts +31 -8
- package/dist/xpell-core.cjs.js +2 -2
- package/dist/xpell-core.es.js +1524 -750
- package/docs/AGENTS.md +10 -0
- package/package.json +5 -5
- package/docs/Codex.md +0 -138
package/dist/xpell-core.cjs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class k{createIgnoreList(e,t){if(!e)return t;const s=e.split(",").map(i=>i.trim()).filter(Boolean);for(const i of s)t[i]="";return t}guid(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const r=new Uint8Array(16);t.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128;const c=Array.from(r,_=>_.toString(16).padStart(2,"0"));return c.slice(0,4).join("")+"-"+c.slice(4,6).join("")+"-"+c.slice(6,8).join("")+"-"+c.slice(8,10).join("")+"-"+c.slice(10,16).join("")}const s="0123456789abcdef".split(""),i=[];let n;i[8]=i[13]=i[18]=i[23]="-",i[14]="4";for(let r=0;r<36;r++)i[r]||(n=(0|Math.random()*16)>>>0,i[r]=s[r===19?n&3|8:n&15]);return i.join("")}mergeDefaultsWithData(e,t,s=!1){if(!e)return t;e._id||(e._id=e.id??this.guid());for(const i of Object.keys(t))(!(i in e)||s)&&(e[i]=t[i]);return e}encode(e){const t=globalThis;if(typeof t.btoa=="function"){const s=encodeURIComponent(String(e)).replace(/%([0-9A-F]{2})/g,(i,n)=>String.fromCharCode(parseInt(n,16)));return t.btoa(s)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"utf8").toString("base64");throw new Error("Base64 encode not supported in this environment")}decode(e){const t=globalThis;if(typeof t.atob=="function"){const s=t.atob(String(e)),i=Array.prototype.map.call(s,n=>"%"+n.charCodeAt(0).toString(16).padStart(2,"0")).join("");return decodeURIComponent(i)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"base64").toString("utf8");throw new Error("Base64 decode not supported in this environment")}getRandomInt(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}getParam(e,t,s=0){return e?._params?.[t]??s}createDefaultScheduler(e){const t=globalThis;if(typeof t.requestAnimationFrame=="function")return n=>t.requestAnimationFrame(n);const s=typeof e=="number"&&isFinite(e)&&e>0?e:60;if(typeof t.setImmediate=="function"&&(!e||e>=60))return n=>t.setImmediate(n);const i=Math.max(1,Math.round(1e3/s));return n=>t.setTimeout(n,i)}}const f=new k;class L{#e=0;#t=0;#s=0;#i;#n;constructor(e=.05,t=1){const s=Number(e);this.#i=Number.isFinite(s)?Math.min(1,Math.max(.001,s)):.05;const i=Number(t);this.#n=Number.isFinite(i)?Math.max(0,Math.floor(i)):1}now(){const e=globalThis.performance;return e&&typeof e.now=="function"?e.now():Date.now()}calc(){const e=this.now();if(this.#s===0)return this.#s=e,this.#e;const t=e-this.#s;if(this.#s=e,!Number.isFinite(t)||t<=0)return this.#e;this.#t===0?this.#t=t:this.#t=(1-this.#i)*this.#t+this.#i*t;const s=1e3/this.#t;if(!Number.isFinite(s)||s<=0)return this.#e;const i=Math.round(s);return this.#e!==0&&this.#n>0&&Math.abs(i-this.#e)<this.#n?this.#e:(this.#e=i,this.#e)}reset(){this.#e=0,this.#t=0,this.#s=0}}class F{constructor(e){this._enabled=!0,this._show_date=!1,this._show_time=!0,this._debug=!1,e&&this.configure(e)}configure(e){typeof e._enabled=="boolean"&&(this._enabled=e._enabled),typeof e._show_date=="boolean"&&(this._show_date=e._show_date),typeof e._show_time=="boolean"&&(this._show_time=e._show_time),typeof e._debug=="boolean"&&(this._debug=e._debug)}_dt(){const e=new Date,t=this._show_date?`${e.getDate()}.${e.getMonth()}.${e.getFullYear()} `:"",s=this._show_time?`${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}.${e.getMilliseconds()}|`:"";return t+s}log(e,...t){this._enabled&&console.log(this._dt(),e,...t)}warn(e,...t){this._enabled&&console.warn(this._dt(),e,...t)}error(e,...t){this._enabled&&console.error(this._dt(),e,...t)}debug(e,...t){!this._enabled||!this._debug||console.debug(this._dt(),e,...t)}}const a=new F,S=typeof process<"u"&&!!process?.env&&process.env.NODE_ENV==="production";S||console.info("[Xpell] _xlog is redirected to console in development mode. Tip: enable 'Show timestamps' in DevTools → Console for timed logs.");const w=S?a:console;class M{constructor(){this._objects={},this._listeners=new Map,this._any_listeners=new Set,this._compat_writes=!0,this._warn_legacy_writes=!0,this._verbose=!1,this._compat_legacy_keys=!0,this._o_proxy=null,this._objects={}}get _o(){return!this._compat_writes&&!this._warn_legacy_writes?this._objects:(this._o_proxy||(this._o_proxy=new Proxy(this._objects,{set:(e,t,s)=>{const i=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy write: _o["${i}"] = ... ; prefer XData.set("${i}", value).`),this._compat_writes?this.set(i,s,{source:"legacy:_o"}):e[i]=s,!0},deleteProperty:(e,t)=>{const s=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy delete: delete _o["${s}"] ; prefer XData.delete("${s}").`),this._compat_writes?this.delete(s,{source:"legacy:_o"}):delete e[s],!0}})),this._o_proxy)}get(e){return this._objects[e]}set(e,t,s){const i=this._objects[e];this._objects[e]=t,this._emit({key:e,value:t,prev:i,ts:Date.now(),op:"set",meta:s})}patch(e,t,s){const i=this._objects[e],r={...i&&typeof i=="object"?i:{},...t};this._objects[e]=r,this._emit({key:e,value:r,prev:i,ts:Date.now(),op:"patch",meta:s})}touch(e,t){const s=this._objects[e];this._emit({key:e,value:s,prev:s,ts:Date.now(),op:"touch",meta:t})}has(e){return Object.prototype.hasOwnProperty.call(this._objects,e)}delete(e,t){const s=this._objects[e];delete this._objects[e],this._emit({key:e,value:void 0,prev:s,ts:Date.now(),op:"delete",meta:t})}pick(e,t){const s=this._objects[e];return this.delete(e,t),s}clean(){this._objects={}}on(e,t){let s=this._listeners.get(e);return s||this._listeners.set(e,s=new Set),s.add(t),()=>this.off(e,t)}off(e,t){const s=this._listeners.get(e);s&&(s.delete(t),s.size===0&&this._listeners.delete(e))}onAny(e){return this._any_listeners.add(e),()=>this._any_listeners.delete(e)}_emit(e){this._verbose&&e.meta?.trace&&(e.stack=new Error().stack);const t=this._listeners.get(e.key);if(t)for(const s of t)s(e);for(const s of this._any_listeners)s(e)}}const u=new M,P=u;class X{constructor(e){e&&Object.keys(e).forEach(t=>{this[t]=e[t]}),this.d||(this.d=Date.now())}getParam(e,t,s){return this._params?.hasOwnProperty(t)?this._params[t]:this._params?.hasOwnProperty(e)?this._params[e]:s}}const v={type:"_type",children:"_children"},p=class p{static addHtml2XpellMapItem(e,t){p.html2XMap.elements[e]=t}static parse(e,t){const s=e.split(" ");let i=new X;if(t?(i._module=t,i._op=s[0]):(i._module=s[0],i._op=s[1]),i._params={},s.length>1)for(let n=2;n<s.length;++n){const r=s[n];if(r.indexOf(":")>-1){const _=r.split(":");i._params[_[0]]=_[1]}else i._params[n-1]=s[n]}return i}static replaceSpacesInQuotes(e,t="_%20_"){return e.replace(/(['"])(.*?)\1/g,(s,i,n)=>{const r=String(n).replace(/\s/g,t);return`${i}${r}${i}`})}static parseObjectCommand(e,t){e=p.replaceSpacesInQuotes(e);const s=e.trim().split(/\s+/),i=t||s.shift();if(!i)throw new Error("Missing module name");let n;if(s[0]?.startsWith("#")&&(n=s.shift().slice(1),!n))throw new Error("Invalid object selector '#'. Use '#<id>'");const r=s.shift();if(!r)throw new Error("Missing operation");const c={};let _=null,h=null;if(s.forEach(l=>{if(h){if(h+=` ${l}`,l.endsWith(h[0])){const b=h.slice(1,-1).replace(/_%20_/g," ");c[_]=b,h=null}return}if(l.startsWith('"')||l.startsWith("'")){if(h=l,l.endsWith(l[0])&&l.length>1){const b=l.slice(1,-1).replace(/_%20_/g," ");c[_]=b,h=null}return}if(l.includes(":")){const b=l.split(":"),U=b[0],C=b.slice(1).join(":").replace(/_%20_/g," ");c[U]=C,_=null;return}_=l.replace(/_%20_/g," ")}),h)throw new Error("Unclosed quoted parameter value");return{_module:i,_object:n,_op:r,_params:c}}static xmlString2Xpell(e){const s=new DOMParser().parseFromString(e,"text/xml");return s.childNodes.length>0?p.xml2Xpell(s.childNodes[0]):{}}static xml2Xpell(e,t){const s=p.html2XMap;let i={};i._children=[];const n=e.nodeName,r=e.nodeName;let c=t;if(t?(i[v.type]="xhtml",i._html_ns="http://www.w3.org/2000/svg"):i._type=s.elements[n]?s.elements[n]:n,e.attributes)for(let _=0;_<e.attributes.length;++_){const h=e.attributes[_],l=s.attributes[h.name]?s.attributes[h.name]:h.name;i[l]=h.value}if(e?.firstChild?.nodeValue&&(i.text=e?.firstChild.nodeValue.trim()),i[v.type]=="xhtml"?i._html_tag=r:i[v.type]=="svg"&&(c=!0,i._html_ns="http://www.w3.org/2000/svg"),e?.childNodes.length>0)for(let _=0;_<e.childNodes.length;++_){const h=e.childNodes[_];h.nodeName.startsWith("#")||i[v.children].push(p.xml2Xpell(h,c))}return i}};p.html2XMap={elements:{div:"view",a:"link",b:"xhtml",h1:"xhtml",h2:"xhtml",h3:"xhtml",h4:"xhtml",h5:"xhtml",p:"xhtml",small:"xhtml",aside:"xhtml",span:"xhtml",table:"xhtml",th:"xhtml",td:"xhtml",tr:"xhtml",thead:"xhtml",tbody:"xhtml",ul:"xhtml",li:"xhtml",ol:"xhtml",canvas:"xhtml",img:"image"},attributes:{id:"_id"}};let m=p;class I{constructor(){this._log_rules={register:!1,remove:!1,fire:!1},this._events={},this._listener_index={}}on(e,t,s={},i){this._events[e]||(this._events[e]=[]);const n=s?._owner??i,r=f.guid(),c={_id:r,_callback:t,_options:s,_owner:n,_tag:s?._tag};return this._events[e].push(c),this._listener_index[r]=e,this._log_rules.register&&w.log("XEM Register",e,r),r}once(e,t,s){return this.on(e,t,{_once:!0,_owner:s})}async fire(e,t){const s=this._events[e];if(!s||s.length===0)return;this._log_rules.fire&&w.log("XEM Fire",e,t);const i=s.slice(),n=[];for(const r of i){try{r&&r._callback&&r._callback(t)}catch(c){w.error(c)}r?._options?._once&&n.push(r._id)}for(const r of n)this.remove(r)}remove(e){const t=this._listener_index[e];if(!t)return;const s=this._events[t];if(s&&s.length){const i=s.findIndex(n=>n?._id===e);i>=0&&s.splice(i,1),s.length===0&&delete this._events[t]}delete this._listener_index[e],this._log_rules.remove&&w.log("XEM Remove",t,e)}removeOwner(e){if(!e)return;const t=[];for(const s of Object.values(this._events))for(const i of s)(i?._owner??i?._options?._owner)===e&&t.push(i._id);t.forEach(s=>this.remove(s))}clear(){this._events={},this._listener_index={}}}const g=new I;class A{#e;#t;#s;constructor(){this.#e={},this.#t={},this.#s={}}get _objects(){return this.#t}hasObject(e){return this.#t.hasOwnProperty(e)}registerObjects(e){Object.keys(e).forEach(s=>this.registerObject(s,e[s]))}registerObject(e,t){this.#e[e]=t}hasObjectClass(e){return this.#e.hasOwnProperty(e)}getObjectClass(e){return this.#e[e]}getAllClasses(){return this.#e}get _classes(){return this.#e}addObject(e){e&&e._id?(this.#t[e._id]=e,(!e._name||e._name.length==0)&&(e._name=e._id),this.#s[e._name]=e._id):a.log("unable to add object")}removeObject(e){const t=this.#t[e];t&&(delete this.#s[t?._name],delete this.#t[e])}getObject(e){return this.#t[e]}go(e){return this.getObject(e)}getObjectByName(e){return this.#s[e]?this.getObject(this.#s[e]):null}}const T=["_nano_commands","_cache_cmd_txt","_cache_jcmd","_xporter","_event_listeners_ids","_parent","_children"];function j(o){return T.includes(o)}function x(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}const B={info:(o,e)=>{a.log("XObject id "+e?._id)},log:(o,e)=>{o._params&&o._params[1]?a.log(o._params[1]):a.log(e)},fire:(o,e)=>{o._params&&o._params[1]?g.fire(o._params[1],o._params[2]):o._params&&o._params.event&&g.fire(o._params.event,o._params.data)},noop:()=>{},"set-field":(o,e)=>{const t=o._params?.name,s=o._params?.value;if(!(!e||typeof t!="string"||t.length===0)){if(j(t)){a.error(`set-field denied for protected field: ${t}`);return}e[t]=s}},"delete-field":(o,e)=>{const t=o._params?.name;if(!(!e||typeof t!="string"||t.length===0)){if(j(t)){a.error(`delete-field denied for protected field: ${t}`);return}delete e[t]}},"toggle-field":(o,e)=>{const t=o._params?.name;if(!e||typeof t!="string"||t.length===0)return;if(j(t)){a.error(`toggle-field denied for protected field: ${t}`);return}const s=e[t];typeof s=="boolean"?e[t]=!s:s==null?e[t]=!0:e[t]=!1},merge:(o,e)=>{const t=o._params?.name,s=o._params?.value;if(!e||typeof t!="string"||t.length===0)return;if(j(t)){a.error(`merge denied for protected field: ${t}`);return}if(!x(s)){a.error("merge expects _params.value as a plain object");return}const i=e[t];x(i)||(e[t]={}),Object.assign(e[t],s)},"run-seq":async(o,e)=>{if(!e)return;const t=o._params?.seq;if(!Array.isArray(t)){a.error("run-seq expects _params.seq as an array");return}for(const s of t){if(typeof s=="string"){await e.run(`${e._id} ${s}`);continue}if(s&&typeof s=="object"&&s._op){const i=s._object;if(!(i==null||i==="this"||i===e._id)){a.error("run-seq rejected non-self _object target");return}const r={_op:s._op,_params:s._params?{...s._params}:void 0};await e.execute(r);continue}a.error("run-seq skipped invalid step; expected string or object with _op")}}},O={_children:"child nodes"};class y{constructor(e,t,s){this._children=[],this._parent=null,this._on={},this._once={},this._process_frame=!0,this._process_data=!0,this._nano_commands={},this._event_listeners_ids={},this._event_parsed=!1,this._mounted=!1,this._xporter={_ignore_fields:["_to_xdata_ignore_fields","_xporter","_children","_on","_once","_on_create","_on_mount","_on_frame","_on_data","_process_frame","_process_data","_parent","_event_listeners_ids","_event_parsed","_mounted","_debug"],_instance_xporters:{}},t&&f.mergeDefaultsWithData(e,t),this._id=e&&e._id?e._id:"xo-"+f.guid(),this._type="object",this._children=[],this._nano_commands={},this.addNanoCommandPack(B),e&&e.hasOwnProperty("_nano_commands")&&e._nano_commands&&(this.addNanoCommandPack(e._nano_commands),delete e._nano_commands),this.addXporterDataIgnoreFields(["_nano_commands"]),this.addXporterInstanceXporter(y,i=>i.toXData()),this._xem_options={},!s&&e&&this.parse(e,O)}log(e,...t){this._debug&&e&&a.log(this._type+"->"+this._id+"]",e,...t)}init(e,t){!t&&e&&this.parse(e,O)}parseEvents(e){if(!this._event_parsed){e||(e=this._xem_options),Object.keys(this._on).forEach(s=>{this.addEventListener(s,this._on[s],e)});const t={};Object.assign(t,e),t._once=!0,Object.keys(this._once).forEach(s=>{this.addEventListener(s,this._once[s],t)}),this._event_parsed=!0}}addEventListener(e,t,s){s||(s=this._xem_options);let i;if(typeof t=="function")i=async r=>{t(this,r)};else if(typeof t=="string")i=async r=>{const c=this._id+" "+t+" event-data='"+JSON.stringify(r).replace(/'/g,"\\'")+"'";await this.run(c)};else throw new Error("event handler must be a function");const n=g.on(e,i,s,this);this._event_listeners_ids[e]||(this._event_listeners_ids[e]=[]),this._event_listeners_ids[e].push(n)}removeEventListener(e){const t=this._event_listeners_ids[e];t&&t.length&&(t.forEach(s=>{g.remove(s)}),delete this._event_listeners_ids[e])}removeAllEventListeners(){Object.keys(this._event_listeners_ids).forEach(t=>this.removeEventListener(t))}append(e){this._children?.push(e),e._parent=this}addNanoCommand(e,t){typeof t=="function"&&(this._nano_commands[e]=t)}addNanoCommandPack(e){e&&Object.keys(e).forEach(t=>{this.addNanoCommand(t,e[t])})}addXporterDataIgnoreFields(e){this._xporter._ignore_fields=this._xporter._ignore_fields.concat(e)}addXporterInstanceXporter(e,t){const s=f.guid();this._xporter._instance_xporters[s]={cls:e,handler:t}}parse(e,t=O){Object.keys(e).forEach(i=>{!t.hasOwnProperty(i)&&e.hasOwnProperty(i)&&(this[i]=e[i])})}parseFieldsFromXDataObject(e,t){Object.keys(t).forEach(i=>{e.hasOwnProperty(i)?this[i]=e[i]:this[i]=t[i]})}parseFields(e,t,s){t.forEach(i=>{if(e.hasOwnProperty(i))this[i]=e[i];else if(s&&i.startsWith("_")){const n=i.substring(1);e.hasOwnProperty(n)&&(this[i]=e[n],this[n]=e[n])}})}async onCreate(){this._on_create?this.checkAndRunInternalFunction(this._on_create):this._on&&this._on.create?this.checkAndRunInternalFunction(this._on.create):this._once&&this._once.create&&this.checkAndRunInternalFunction(this._once.create)}async runCmd(e){const t=e instanceof X?e:new X(e);await this.execute(t)}async checkAndRunInternalFunction(e,...t){if(Array.isArray(e)){for(const s of e)await this.checkAndRunInternalFunction(s,...t);return}if(typeof e=="function"){await e(this,...t);return}if(typeof e=="string"){if(t.length>0){const s=t[0],i=JSON.stringify(s).replace(/'/g,"\\'");await this.run(`${this._id} ${e} data:'${i}'`)}else await this.run(`${this._id} ${e}`);return}if(e&&typeof e=="object"&&e._op){const s=e;if((s._object===void 0||s._object===null||s._object==="this"?this._id:s._object)!==this._id){a.error("XObject JSON handler target not supported in core-only patch; expected _object omitted/'this'/"+this._id);return}const n={_op:s._op,_params:s._params?{...s._params}:void 0};t.length>0&&(n._params||(n._params={}),Object.prototype.hasOwnProperty.call(n._params,"data")||(n._params.data=t[0])),this._debug&&a.log(this._type+"->"+this._id+"]","JSON handler executed locally",n),await this.execute(n);return}}async onMount(){if(!this._mounted){this.parseEvents(this._xem_options),this._process_data&&typeof this._data_source=="string"&&this._data_source.length>0&&this.bindDataSource(this._data_source,{initial:!0}),this._on_mount?await this.checkAndRunInternalFunction(this._on_mount):this._on&&this._on.mount?await this.checkAndRunInternalFunction(this._on.mount):this._once&&this._once.mount&&await this.checkAndRunInternalFunction(this._once.mount),this._mounted=!0;for(const e of this._children)e.onMount&&typeof e.onMount=="function"&&e.onMount()}}emptyDataSource(){const e=this._data_source;if(typeof e!="string"||e.length===0)return;const t=this._type??this.constructor.name,s=this._id??"no-id";u.delete(e,{source:`${t}#${s}.emptyDataSource`})}async onData(e){this._process_data&&(this._on_data?this.checkAndRunInternalFunction(this._on_data,e):this._on&&this._on.data?this.checkAndRunInternalFunction(this._on.data,e):this._once&&this._once.data&&this.checkAndRunInternalFunction(this._once.data,e))}async onFrame(e){this._process_frame&&(this._on_frame?this.checkAndRunInternalFunction(this._on_frame,e):this._on&&this._on.frame?this.checkAndRunInternalFunction(this._on.frame,e):this._once&&this._once.frame&&this.checkAndRunInternalFunction(this._once.frame,e));for(const t of this._children)t.onFrame&&typeof t.onFrame=="function"&&t.onFrame(e)}async run(e,t=!0){let s=this._cache_cmd_txt&&this._cache_cmd_txt==e?this._cache_jcmd:m.parseObjectCommand(e);t&&(this._cache_cmd_txt=e,this._cache_jcmd=s),await this.execute(s)}async execute(e){if(e._op&&this._nano_commands[e._op])try{await this._nano_commands[e._op](e,this)}catch(t){a.error(this._id+" has error with command name "+e._op+" "+t)}else a.error(this._id+" has no command name "+e._op)}toXData(){const e={};return Object.keys(this).forEach(t=>{if(!this._xporter._ignore_fields.includes(t)&&this.hasOwnProperty(t)&&this[t]!==void 0){const s=this[t];if(typeof s=="function")return;if(typeof s=="object"){const i=Object.keys(this._xporter._instance_xporters);let n=!0;i.forEach(r=>{this._xporter._instance_xporters[r],s instanceof this._xporter._instance_xporters[r].cls&&(e[t]=this._xporter._instance_xporters[r].handler(s),n=!1)}),n&&(e[t]=s)}else e[t]=s}}),e._children=[],this._children.length>0&&this._children.forEach(t=>{typeof t.toXData=="function"&&e._children?.push(t.toXData())}),e}toString(){return JSON.stringify(this.toXData())}clearAttributes(e){e.forEach(t=>{this.hasOwnProperty(t)&&(this[t]=null,delete this[t])})}bindDataSource(e,t){const s=t?.initial??!0,i=e??this._data_source;typeof i!="string"||i.length===0||this._process_data&&(this._xd_bound_key===i&&this._xd_unsub||(this.unbindDataSource(),this._data_source=i,this._xd_bound_key=i,this._type??this.constructor.name,this._id,this._xd_unsub=u.on(i,async n=>{await this.onData(n.value)}),s&&u.has(i)&&this.onData(u.get(i))))}unbindDataSource(){this._xd_unsub?.(),this._xd_unsub=void 0,this._xd_bound_key=void 0}async dispose(){if(this.unbindDataSource(),this._parent){const e=this._parent._children.indexOf(this);e>-1&&this._parent._children.splice(e,1)}this._process_data=!1,this._process_frame=!1,this.removeAllEventListeners(),this.clearAttributes(["_cache_cmd_txt","_cache_jcmd","_nano_commands","_event_listeners_ids","_parent","_on","_once","_xem_options","_xporter"]),this._children&&this._children.forEach(e=>{typeof e.dispose=="function"&&e.dispose()}),this._children=[]}removeChild(e,t=!1){if(t)e.dispose();else{const s=this._children.indexOf(e);s>-1&&this._children.splice(s,1),e._parent=null}}addChild(e){this.append(e)}}class W{static getObjects(){return{object:y}}}const q="engine:module:num-of-objects:";class J{constructor(e){this._log_rules={createObject:!1,removeObject:!1},this.#e=new A,this._name=e._name,this._id=f.guid()}#e;load(){a.log("Module "+this._name+" loaded")}create(e){let t;if(e.hasOwnProperty("_type"))if(this.#e.hasObjectClass(e._type)){let s=this.#e.getObjectClass(e._type);s.hasOwnProperty("defaults")&&f.mergeDefaultsWithData(e,s.defaults),t=new s(e)}else throw"Xpell object '"+e._type+"' not found";else t=new y(e);return this.#e.addObject(t),e._children&&e._children.forEach(s=>{const i=this.create(s);t.append(i)}),t.onCreate(),t}remove(e){const t=this.#e.getObject(e);if(!t)return;const s=[],i=n=>{n?._id&&(s.push(n._id),(n._children??[]).forEach(r=>i(r)))};i(t),typeof t.dispose=="function"&&t.dispose(),s.reverse().forEach(n=>this.#e.removeObject(n))}_info(e){a.log("module info")}async run(e){if(e){let t=e.trim();t.startsWith(this._name)||(t=this._name+" "+t);let s=m.parse(t);return await this.execute(s)}else throw"Unable to parse Xpell Command"}async execute(e){if(!e||!e._op)throw new Error(`Invalid XCommand: missing _op (module: ${this._name})`);const t=e._object;if(t){const n=this.#e.getObject(t);if(!n)throw new Error(`Module '${this._name}' cant find object id: ${t}`);return await n.execute(e)}const s="_"+e._op.replaceAll("-","_"),i=this[s];if(typeof i=="function")return await i.call(this,e);throw new Error(`Module '${this._name}' cant find op: ${e._op}`)}async onFrame(e){const t=this.#e._objects,s=Object.keys(t);s.forEach(i=>{const n=t[i];n&&n.onFrame&&typeof n.onFrame=="function"&&n?.onFrame(e)}),P.set(q+this._id,s.length,{source:"xmodule"})}get om(){return this.#e}get _object_manager(){return this.#e}getObject(e){return this.#e.getObject(e)}get _o(){return this.#e._objects}importObjectPack(e){this.#e.registerObjects(e.getObjects())}importObjects(e){this.importObjectPack(e)}importObject(e,t){this.#e.registerObject(e,t)}async _help(e){const t=e?._params?._op??e?._params?._command??"";return this.help(t)}help(e){return{module:this._name,usage:`${this._name} help`,ops:["help"],note:"No help() implemented for this module."}}}class V{static get(e,t,s){if(!e?._params)return s;const i=e._params[t];return i!==void 0?i:s}static has(e,t){return e?._params&&e._params[t]!==void 0}static str(e,...t){for(const s of t){const i=e?._params?.[s];if(i!=null)return String(i)}}static bool(e,t,s=!1){const i=this.get(e,t,s);if(typeof i=="boolean")return i;if(typeof i=="number")return i!==0;if(typeof i=="string"){const n=i.toLowerCase();if(["1","true","yes","on"].includes(n))return!0;if(["0","false","no","off"].includes(n))return!1}return!!i}static int(e,t,s=0){const i=this.get(e,t,s),n=parseInt(String(i),10);return Number.isFinite(n)?n:s}static json(e,t,s){const i=this.get(e,t,s);if(i==null)return s;if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{return s}return s}}class E extends Error{constructor(e,t,s){super(t),this.name="XError",this._code=e,this._level=s?._level??"error",this._meta=s?._meta,this._cause=s?._cause}toXData(){return{_code:this._code,_level:this._level,_meta:this._meta,_cause:this._cause,name:this.name,message:this.message}}toJSON(){return{...this.toXData(),stack:this.stack}}}class d{constructor(e){this._ok=!1,this._ts=Date.now(),this._pt=0,e&&this.setXData(e)}static create(e){return new d(e)}static ok(e){return new d({_ok:!0,_result:e})}static error(e){if(e instanceof E)return new d({_ok:!1,_result:e.toXData()});const t=new E("E_INTERNAL",e?.message??String(e),{_cause:e});return new d({_ok:!1,_result:t.toXData()})}stopProcessTimeCounter(){this._pt=Date.now()-this._ts}toXData(){return this.stopProcessTimeCounter(),{_ok:this._ok,_ts:this._ts,_pt:this._pt,_result:this._result}}toString(){return JSON.stringify(this.toXData())}setXData(e){e&&("_ok"in e&&(this._ok=!!e._ok),"_ts"in e&&typeof e._ts=="number"&&(this._ts=e._ts),"_pt"in e&&typeof e._pt=="number"&&(this._pt=e._pt),"_result"in e&&(this._result=e._result))}}class H extends d{constructor(e){super(d.error(e).toXData())}}class K extends d{constructor(e){super({_ok:!0,_result:e})}}const $="engine:frame-number",R="engine:fps";class N{constructor(e){this._log_rules={},this._modules={},this._schedule_frame=e?._schedule_frame??f.createDefaultScheduler(e?._target_fps),this._version="0.0.1",this._engine_id=f.guid(),this._frame_number=0,this._fps_calc=new L,this.parser=m,this._modules={},g.fire("xpell-init"),a._enabled=!1}set verbose(e){a._enabled=e}set _verbose(e){a._enabled=e}log(e,...t){a.log(e,...t)}async delay(e){return new Promise(t=>setTimeout(t,e))}loadModule(e){this._modules.hasOwnProperty(e._name)?a.log("Module "+e._name+" already loaded"):(this._modules[e._name]=e,e.load())}loadModules(...e){e.forEach(t=>this.loadModule(t))}info(){a.log(`Xpell information:
|
|
1
|
+
"use strict";var V=o=>{throw TypeError(o)};var z=(o,e,t)=>e.has(o)||V("Cannot "+t);var p=(o,e,t)=>(z(o,e,"read from private field"),t?t.call(o):e.get(o)),K=(o,e,t)=>e.has(o)?V("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(o):e.set(o,t),G=(o,e,t,s)=>(z(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class Y{createIgnoreList(e,t){if(!e)return t;const s=e.split(",").map(n=>n.trim()).filter(Boolean);for(const n of s)t[n]="";return t}guid(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const i=new Uint8Array(16);t.getRandomValues(i),i[6]=i[6]&15|64,i[8]=i[8]&63|128;const c=Array.from(i,a=>a.toString(16).padStart(2,"0"));return c.slice(0,4).join("")+"-"+c.slice(4,6).join("")+"-"+c.slice(6,8).join("")+"-"+c.slice(8,10).join("")+"-"+c.slice(10,16).join("")}const s="0123456789abcdef".split(""),n=[];let r;n[8]=n[13]=n[18]=n[23]="-",n[14]="4";for(let i=0;i<36;i++)n[i]||(r=(0|Math.random()*16)>>>0,n[i]=s[i===19?r&3|8:r&15]);return n.join("")}mergeDefaultsWithData(e,t,s=!1){if(!e)return t;e._id||(e._id=e.id??this.guid());for(const n of Object.keys(t))(!(n in e)||s)&&(e[n]=t[n]);return e}encode(e){const t=globalThis;if(typeof t.btoa=="function"){const s=encodeURIComponent(String(e)).replace(/%([0-9A-F]{2})/g,(n,r)=>String.fromCharCode(parseInt(r,16)));return t.btoa(s)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"utf8").toString("base64");throw new Error("Base64 encode not supported in this environment")}decode(e){const t=globalThis;if(typeof t.atob=="function"){const s=t.atob(String(e)),n=Array.prototype.map.call(s,r=>"%"+r.charCodeAt(0).toString(16).padStart(2,"0")).join("");return decodeURIComponent(n)}if(t.Buffer&&typeof t.Buffer.from=="function")return t.Buffer.from(String(e),"base64").toString("utf8");throw new Error("Base64 decode not supported in this environment")}getRandomInt(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}getParam(e,t,s=0){return e?._params?.[t]??s}createDefaultScheduler(e){const t=globalThis;if(typeof t.requestAnimationFrame=="function")return r=>t.requestAnimationFrame(r);const s=typeof e=="number"&&isFinite(e)&&e>0?e:60;if(typeof t.setImmediate=="function"&&(!e||e>=60))return r=>t.setImmediate(r);const n=Math.max(1,Math.round(1e3/s));return r=>t.setTimeout(r,n)}to_iso_now(){return new Date().toISOString()}is_plain_object(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}ensure_string(e,t){if(typeof e!="string"||!e.trim())throw new Error(`Invalid '${t}'`);return e.trim()}ensure_params(e){return this.is_plain_object(e)?e:{}}addIfNotNull(e,t,s){if(!(!e||!t||!Array.isArray(s)))for(const n of s){const r=e[n];r!=null&&(t[n]=r)}}als(e){const t=String(e??"");return t.endsWith("/")?t:t+"/"}cls(e){const t=String(e??"");return t.endsWith("/")?t.slice(0,-1):t}afs(e){const t=String(e??"");return t.startsWith("/")?t:"/"+t}cfs(e){const t=String(e??"");return t.startsWith("/")?t.slice(1):t}calculateExpiration(e){const s=String(e??"").trim().match(/^(\d+)([hdy])$/);if(!s)throw new Error("Invalid expiration format. Use: 1h | 2d | 3y");const n=Number.parseInt(s[1],10),r=s[2],i=Date.now();let c=0;switch(r){case"h":c=n*60*60*1e3;break;case"d":c=n*24*60*60*1e3;break;case"y":c=n*365*24*60*60*1e3;break}return i+c}}const Z=new Y,u=Z;class ae{#e=0;#t=0;#s=0;#n;#r;constructor(e=.05,t=1){const s=Number(e);this.#n=Number.isFinite(s)?Math.min(1,Math.max(.001,s)):.05;const n=Number(t);this.#r=Number.isFinite(n)?Math.max(0,Math.floor(n)):1}now(){const e=globalThis.performance;return e&&typeof e.now=="function"?e.now():Date.now()}calc(){const e=this.now();if(this.#s===0)return this.#s=e,this.#e;const t=e-this.#s;if(this.#s=e,!Number.isFinite(t)||t<=0)return this.#e;this.#t===0?this.#t=t:this.#t=(1-this.#n)*this.#t+this.#n*t;const s=1e3/this.#t;if(!Number.isFinite(s)||s<=0)return this.#e;const n=Math.round(s);return this.#e!==0&&this.#r>0&&Math.abs(n-this.#e)<this.#r?this.#e:(this.#e=n,this.#e)}reset(){this.#e=0,this.#t=0,this.#s=0}}class ee{constructor(e){this._enabled=!0,this._show_date=!1,this._show_time=!0,this._debug=!1,e&&this.configure(e)}configure(e){typeof e._enabled=="boolean"&&(this._enabled=e._enabled),typeof e._show_date=="boolean"&&(this._show_date=e._show_date),typeof e._show_time=="boolean"&&(this._show_time=e._show_time),typeof e._debug=="boolean"&&(this._debug=e._debug)}_dt(){const e=new Date,t=this._show_date?`${e.getDate()}.${e.getMonth()}.${e.getFullYear()} `:"",s=this._show_time?`${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}.${e.getMilliseconds()}|`:"";return t+s}log(e,...t){this._enabled&&console.log(this._dt(),e,...t)}warn(e,...t){this._enabled&&console.warn(this._dt(),e,...t)}error(e,...t){this._enabled&&console.error(this._dt(),e,...t)}debug(e,...t){!this._enabled||!this._debug||console.debug(this._dt(),e,...t)}}const _=new ee,te=typeof process<"u"&&!!process?.env&&process.env.NODE_ENV==="production";te||console.info("[Xpell] _xlog is redirected to console in development mode. Tip: enable 'Show timestamps' in DevTools → Console for timed logs.");const v=te?_:console;class se{constructor(){this._objects={},this._listeners=new Map,this._any_listeners=new Set,this._compat_writes=!0,this._warn_legacy_writes=!0,this._verbose=!1,this._compat_legacy_keys=!0,this._o_proxy=null,this._objects={}}get _o(){return!this._compat_writes&&!this._warn_legacy_writes?this._objects:(this._o_proxy||(this._o_proxy=new Proxy(this._objects,{set:(e,t,s)=>{const n=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy write: _o["${n}"] = ... ; prefer XData.set("${n}", value).`),this._compat_writes?this.set(n,s,{source:"legacy:_o"}):e[n]=s,!0},deleteProperty:(e,t)=>{const s=String(t);return this._warn_legacy_writes&&console.warn(`[XData] Legacy delete: delete _o["${s}"] ; prefer XData.delete("${s}").`),this._compat_writes?this.delete(s,{source:"legacy:_o"}):delete e[s],!0}})),this._o_proxy)}get(e){return this._objects[e]}set(e,t,s){const n=this._objects[e];this._objects[e]=t,this._emit({key:e,value:t,prev:n,ts:Date.now(),op:"set",meta:s})}patch(e,t,s){const n=this._objects[e],i={...n&&typeof n=="object"?n:{},...t};this._objects[e]=i,this._emit({key:e,value:i,prev:n,ts:Date.now(),op:"patch",meta:s})}touch(e,t){const s=this._objects[e];this._emit({key:e,value:s,prev:s,ts:Date.now(),op:"touch",meta:t})}has(e){return Object.prototype.hasOwnProperty.call(this._objects,e)}delete(e,t){const s=this._objects[e];delete this._objects[e],this._emit({key:e,value:void 0,prev:s,ts:Date.now(),op:"delete",meta:t})}pick(e,t){const s=this._objects[e];return this.delete(e,t),s}clean(){this._objects={}}on(e,t){let s=this._listeners.get(e);return s||this._listeners.set(e,s=new Set),s.add(t),()=>this.off(e,t)}off(e,t){const s=this._listeners.get(e);s&&(s.delete(t),s.size===0&&this._listeners.delete(e))}onAny(e){return this._any_listeners.add(e),()=>this._any_listeners.delete(e)}_emit(e){this._verbose&&e.meta?.trace&&(e.stack=new Error().stack);const t=this._listeners.get(e.key);if(t)for(const s of t)s(e);for(const s of this._any_listeners)s(e)}}const k=new se,f=k;class I{constructor(e){e&&Object.keys(e).forEach(t=>{this[t]=e[t]}),this.d||(this.d=Date.now())}getParam(e,t,s){return this._params?.hasOwnProperty(t)?this._params[t]:this._params?.hasOwnProperty(e)?this._params[e]:s}}const F={type:"_type",children:"_children"},b=class b{static addHtml2XpellMapItem(e,t){b.html2XMap.elements[e]=t}static parse(e,t){const s=e.split(" ");let n=new I;if(t?(n._module=t,n._op=s[0]):(n._module=s[0],n._op=s[1]),n._params={},s.length>1)for(let r=2;r<s.length;++r){const i=s[r];if(i.indexOf(":")>-1){const a=i.split(":");n._params[a[0]]=a[1]}else n._params[r-1]=s[r]}return n}static replaceSpacesInQuotes(e,t="_%20_"){return e.replace(/(['"])(.*?)\1/g,(s,n,r)=>{const i=String(r).replace(/\s/g,t);return`${n}${i}${n}`})}static parseObjectCommand(e,t){e=b.replaceSpacesInQuotes(e);const s=e.trim().split(/\s+/),n=t||s.shift();if(!n)throw new Error("Missing module name");let r;if(s[0]?.startsWith("#")&&(r=s.shift().slice(1),!r))throw new Error("Invalid object selector '#'. Use '#<id>'");const i=s.shift();if(!i)throw new Error("Missing operation");const c={};let a=null,l=null;if(s.forEach(h=>{if(l){if(l+=` ${h}`,h.endsWith(l[0])){const m=l.slice(1,-1).replace(/_%20_/g," ");c[a]=m,l=null}return}if(h.startsWith('"')||h.startsWith("'")){if(l=h,h.endsWith(h[0])&&h.length>1){const m=h.slice(1,-1).replace(/_%20_/g," ");c[a]=m,l=null}return}if(h.includes(":")){const m=h.split(":"),S=m[0],j=m.slice(1).join(":").replace(/_%20_/g," ");c[S]=j,a=null;return}a=h.replace(/_%20_/g," ")}),l)throw new Error("Unclosed quoted parameter value");return{_module:n,_object:r,_op:i,_params:c}}static xmlString2Xpell(e){const s=new DOMParser().parseFromString(e,"text/xml");return s.childNodes.length>0?b.xml2Xpell(s.childNodes[0]):{}}static xml2Xpell(e,t){const s=b.html2XMap;let n={};n._children=[];const r=e.nodeName,i=e.nodeName;let c=t;if(t?(n[F.type]="xhtml",n._html_ns="http://www.w3.org/2000/svg"):n._type=s.elements[r]?s.elements[r]:r,e.attributes)for(let a=0;a<e.attributes.length;++a){const l=e.attributes[a],h=s.attributes[l.name]?s.attributes[l.name]:l.name;n[h]=l.value}if(e?.firstChild?.nodeValue&&(n.text=e?.firstChild.nodeValue.trim()),n[F.type]=="xhtml"?n._html_tag=i:n[F.type]=="svg"&&(c=!0,n._html_ns="http://www.w3.org/2000/svg"),e?.childNodes.length>0)for(let a=0;a<e.childNodes.length;++a){const l=e.childNodes[a];l.nodeName.startsWith("#")||n[F.children].push(b.xml2Xpell(l,c))}return n}};b.html2XMap={elements:{div:"view",a:"link",b:"xhtml",h1:"xhtml",h2:"xhtml",h3:"xhtml",h4:"xhtml",h5:"xhtml",p:"xhtml",small:"xhtml",aside:"xhtml",span:"xhtml",table:"xhtml",th:"xhtml",td:"xhtml",tr:"xhtml",thead:"xhtml",tbody:"xhtml",ul:"xhtml",li:"xhtml",ol:"xhtml",canvas:"xhtml",img:"image"},attributes:{id:"_id"}};let w=b;class ne{#e;#t;#s;constructor(){this.#e={},this.#t={},this.#s={}}get _objects(){return this.#t}hasObject(e){return this.#t.hasOwnProperty(e)}registerObjects(e){Object.keys(e).forEach(s=>this.registerObject(s,e[s]))}registerObject(e,t){this.#e[e]=t}hasObjectClass(e){return this.#e.hasOwnProperty(e)}getObjectClass(e){return this.#e[e]}getAllClasses(){return this.getObjectClasses()}getObjectClasses(){return this.#e}get _classes(){return this.#e}addObject(e){e&&e._id?(this.#t[e._id]=e,(!e._name||e._name.length==0)&&(e._name=e._id),this.#s[e._name]=e._id):_.log("unable to add object")}removeObject(e){const t=this.#t[e];t&&(delete this.#s[t?._name],delete this.#t[e])}getObject(e){return this.#t[e]}go(e){return this.getObject(e)}getObjectByName(e){return this.#s[e]?this.getObject(this.#s[e]):null}}class ce{constructor(){this._log_rules={register:!1,remove:!1,fire:!1},this._events={},this._listener_index={}}on(e,t,s={},n){this._events[e]||(this._events[e]=[]);const r=s?._owner??n,i=u.guid(),c={_id:i,_callback:t,_options:s,_owner:r,_tag:s?._tag};return this._events[e].push(c),this._listener_index[i]=e,this._log_rules.register&&v.log("XEM Register",e,i),i}once(e,t,s){return this.on(e,t,{_once:!0,_owner:s})}async fire(e,t){const s=this._events[e];if(!s||s.length===0)return;this._log_rules.fire&&v.log("XEM Fire",e,t);const n=s.slice(),r=[];for(const i of n){try{i&&i._callback&&i._callback(t)}catch(c){v.error(c)}i?._options?._once&&r.push(i._id)}for(const i of r)this.remove(i)}remove(e){const t=this._listener_index[e];if(!t)return;const s=this._events[t];if(s&&s.length){const n=s.findIndex(r=>r?._id===e);n>=0&&s.splice(n,1),s.length===0&&delete this._events[t]}delete this._listener_index[e],this._log_rules.remove&&v.log("XEM Remove",t,e)}removeOwner(e){if(!e)return;const t=[];for(const s of Object.values(this._events))for(const n of s)(n?._owner??n?._options?._owner)===e&&t.push(n._id);t.forEach(s=>this.remove(s))}clear(){this._events={},this._listener_index={}}}let U;function _e(o){U=o}function X(){if(!U)throw new Error("XEventManager not set");return U}const le=["_nano_commands","_cache_cmd_txt","_cache_jcmd","_xporter","_event_listeners_ids","_parent","_children"];function C(o){return le.includes(o)}function H(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function g(o,e){return o._skill=e,o.getSkill=()=>e,o}const Q={info:g((o,e)=>{_.log("XObject id "+e?._id)},{_name:"info",_scope:"object",_description:"Logs the current object's id."}),log:g((o,e)=>{o._params&&o._params[1]?_.log(o._params[1]):_.log(e)},{_name:"log",_scope:"object",_description:"Logs a message or the current object.",_params:{1:"Optional message to log."}}),fire:g((o,e)=>{o._params&&o._params[1]?X().fire(String(o._params[1]),o._params[2]):o._params&&o._params.event&&X().fire(String(o._params.event),o._params.data)},{_name:"fire",_scope:"object",_description:"Fires an XEventManager event.",_params:{event:"Event name.",data:"Optional event payload.",1:"Event name shorthand.",2:"Event payload shorthand."},_example:{_op:"fire",_params:{event:"user:login",data:{source:"button"}}}}),noop:g(()=>{},{_name:"noop",_scope:"object",_description:"No-op command. Useful as a placeholder in sequences."}),"set-field":g((o,e)=>{const t=o._params?.name,s=o._params?.value;if(!(!e||typeof t!="string"||t.length===0)){if(C(t)){_.error(`set-field denied for protected field: ${t}`);return}e[t]=s}},{_name:"set-field",_scope:"object",_description:"Sets a runtime field directly on the current object.",_params:{name:"Field name.",value:"Value to assign."},_example:{_op:"set-field",_params:{name:"_text",value:"Hello"}}}),"delete-field":g((o,e)=>{const t=o._params?.name;if(!(!e||typeof t!="string"||t.length===0)){if(C(t)){_.error(`delete-field denied for protected field: ${t}`);return}delete e[t]}},{_name:"delete-field",_scope:"object",_description:"Deletes a runtime field from the current object.",_params:{name:"Field name to delete."}}),"toggle-field":g((o,e)=>{const t=o._params?.name;if(!e||typeof t!="string"||t.length===0)return;if(C(t)){_.error(`toggle-field denied for protected field: ${t}`);return}const s=e[t];typeof s=="boolean"?e[t]=!s:s==null?e[t]=!0:e[t]=!1},{_name:"toggle-field",_scope:"object",_description:"Toggles a runtime field using boolean-first semantics.",_params:{name:"Field name to toggle."}}),merge:g((o,e)=>{const t=o._params?.name,s=o._params?.value;if(!e||typeof t!="string"||t.length===0)return;if(C(t)){_.error(`merge denied for protected field: ${t}`);return}if(!H(s)){_.error("merge expects _params.value as a plain object");return}const n=e[t];H(n)||(e[t]={}),Object.assign(e[t],s)},{_name:"merge",_scope:"object",_description:"Shallow-merges a plain object into a target object field.",_params:{name:"Target field name.",value:"Plain object to merge."}}),"run-seq":g(async(o,e)=>{if(!e)return;const t=o._params?.seq;if(!Array.isArray(t)){_.error("run-seq expects _params.seq as an array");return}for(const s of t){if(typeof s=="string"){await e.run(`${e._id} ${s}`);continue}if(s&&typeof s=="object"&&s._op){const n=s._object;if(!(n==null||n==="this"||n===e._id)){_.error("run-seq rejected non-self _object target");return}const i={_op:s._op,_params:s._params?{...s._params}:void 0};await e.execute(i);continue}_.error("run-seq skipped invalid step; expected string or object with _op")}},{_name:"run-seq",_scope:"object",_description:"Runs a sequence of local nano-command steps in strict order.",_params:{seq:"Array of command strings or local command objects."},_example:{_op:"run-seq",_params:{seq:[{_op:"set-field",_params:{name:"_debug",value:!0}},{_op:"log",_params:{1:"Debug enabled"}}]}}})};let T;function he(o){T=o}function ue(){if(!T)throw new Error("XRuntime not set");return T}const q={_id:"xobject",_title:"XObject Core Runtime Contract",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Base runtime object for identity, typing, composition, lifecycle hooks, events, data binding, and nano-command execution.",_fields:{_id:"Unique object id.",_type:"Registered runtime object type.",_name:"Optional object name.",_children:"Child objects/data.",_data_source:"XData key to bind this object to.",_on:"Event handlers map.",_once:"One-time event handlers map.",_on_create:"Lifecycle handler after object creation.",_on_mount:"Lifecycle handler after mount.",_on_frame:"Frame lifecycle handler.",_on_data:"Data-source lifecycle handler.",_process_frame:"Enable/disable frame processing.",_process_data:"Enable/disable data-source processing.",_debug:"Enable object debug logs."},_exports:{_xui_fields:["_id","_type","_name","_children","_data_source","_on","_once","_on_create","_on_mount","_on_frame","_on_data","_process_frame","_process_data","_debug"]},_core_rules:["All Xpell runtime objects inherit this contract.","Generated object JSON must be data-only.","Do not generate JavaScript functions.","Use _children for composition.","Use _on/_once with nano-command strings or data-only command objects."],_notes:["Runtime methods include parse, append, run, execute, bindDataSource, unbindDataSource, toXData, dispose, and removeChild.","Most prompts should use this skill as a compact dependency summary, not full context."]},L={_children:"child nodes"},E=class E{constructor(e,t,s){this._children=[],this._parent=null,this._on={},this._once={},this._process_frame=!0,this._process_data=!0,this._nano_commands={},this._event_listeners_ids={},this._event_parsed=!1,this._mounted=!1,this._xporter={_ignore_fields:["_to_xdata_ignore_fields","_xporter","_children","_on","_once","_on_create","_on_mount","_on_frame","_on_data","_process_frame","_process_data","_parent","_event_listeners_ids","_event_parsed","_mounted","_debug"],_instance_xporters:{}},t&&u.mergeDefaultsWithData(e,t),this._id=e&&e._id?e._id:"xo-"+u.guid(),this._type="object",this._children=[],this._nano_commands={},this.addNanoCommandPack(Q),e&&e.hasOwnProperty("_nano_commands")&&e._nano_commands&&(this.addNanoCommandPack(e._nano_commands),delete e._nano_commands),this.addXporterDataIgnoreFields(["_nano_commands"]),this.addXporterInstanceXporter(E,n=>n.toXData()),this._xem_options={},!s&&e&&this.parse(e,L)}static getOwnSkill(){const e=this,t=e._skill??q;return{...t,_exports:{...t._exports??{},_nano_commands:e.getNanoCommandSkills?.()??[]}}}static getSkillChain(){const e=Object.getPrototypeOf(this),t=e&&typeof e.getSkillChain=="function"?e.getSkillChain():[],s=Object.prototype.hasOwnProperty.call(this,"_skill")?this.getOwnSkill():null;return s?[...t,s]:t}static getOwnNanoCommands(){return{...Q}}static getNanoCommands(){return{...this.getOwnNanoCommands()}}static getNanoCommandSkills(){return Object.prototype.hasOwnProperty.call(this,"getOwnNanoCommands")?Object.values(this.getOwnNanoCommands()).map(t=>t.getSkill?.()??t._skill).filter(Boolean):[]}static getArtifactStrategy(){return"canonical"}static generateArtifact(e={}){const t=this.getOwnSkill?.(),s=t?._canonical_examples?.[0],n=s?this.cloneArtifact(s):{_type:this._xtype??t?._id??"object"};return this.applyArtifactIntent(n,e)}static cloneArtifact(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}static applyArtifactIntent(e,t={}){const s=e;return t._id&&(s._id=t._id),t._label&&("_label"in s?s._label=t._label:"_text"in s?s._text=t._label:"_title"in s&&(s._title=t._label)),t._text&&"_text"in s&&(s._text=t._text),t._title&&"_title"in s&&(s._title=t._title),t._description&&"_description"in s&&(s._description=t._description),t._variant&&"_variant"in s&&(s._variant=t._variant),t._tone&&"_tone"in s&&(s._tone=t._tone),t._size&&"_size"in s&&(s._size=t._size),t._density&&"_density"in s&&(s._density=t._density),t._elevation&&"_elevation"in s&&(s._elevation=t._elevation),t.class&&(s.class=t.class),t._placeholder&&("placeholder"in s?s.placeholder=t._placeholder:"_placeholder"in s&&(s._placeholder=t._placeholder)),t._data_output&&"_data_output"in s&&(s._data_output=t._data_output),Array.isArray(t._children)&&(s._children=t._children),Array.isArray(t._actions)&&(s._actions=t._actions),Array.isArray(t._items)&&(s._items=t._items),t._flow_id&&(s._flow={_id:t._flow_id,_payload:t._payload??{}}),t._flow_event&&(s._flow_event=t._flow_event),s}static validateArtifact(e){const t=[];return(!e||typeof e!="object")&&t.push("artifact must be an object"),e._type||t.push("artifact requires _type"),{_ok:t.length===0,_errors:t}}log(e,...t){this._debug&&e&&_.log(this._type+"->"+this._id+"]",e,...t)}init(e,t){!t&&e&&this.parse(e,L)}parseEvents(e){if(!this._event_parsed){e||(e=this._xem_options),Object.keys(this._on).forEach(s=>{this.addEventListener(s,this._on[s],e)});const t={};Object.assign(t,e),t._once=!0,Object.keys(this._once).forEach(s=>{this.addEventListener(s,this._once[s],t)}),this._event_parsed=!0}}addEventListener(e,t,s){s||(s=this._xem_options);const n=async i=>{await this.checkAndRunInternalFunction(t,i)},r=X().on(e,n,s,this);return this._event_listeners_ids[e]||(this._event_listeners_ids[e]=[]),this._event_listeners_ids[e].push(r),r}removeEventListener(e){const t=this._event_listeners_ids;if(!t||typeof t!="object"||Array.isArray(t)){this._event_listeners_ids={};return}(Array.isArray(t[e])?[...t[e]]:[]).forEach(n=>{try{X().remove(n)}catch{}}),delete t[e]}removeAllEventListeners(e){const t=this._event_listeners_ids;if(!t||typeof t!="object"||Array.isArray(t)){this._event_listeners_ids={};return}(e?[e]:Object.keys(t)).forEach(n=>{try{this.removeEventListener(n)}catch{}})}append(e){this._children?.push(e),e._parent=this}addNanoCommand(e,t){typeof t=="function"&&(this._nano_commands[e]=t)}addNanoCommandPack(e){e&&Object.keys(e).forEach(t=>{this.addNanoCommand(t,e[t])})}addXporterDataIgnoreFields(e){this._xporter._ignore_fields=this._xporter._ignore_fields.concat(e)}addXporterInstanceXporter(e,t){const s=u.guid();this._xporter._instance_xporters[s]={cls:e,handler:t}}parse(e,t=L){Object.keys(e).forEach(n=>{!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&(this[n]=e[n])})}parseFieldsFromXDataObject(e,t){Object.keys(t).forEach(n=>{e.hasOwnProperty(n)?this[n]=e[n]:this[n]=t[n]})}parseFields(e,t,s){t.forEach(n=>{if(e.hasOwnProperty(n))this[n]=e[n];else if(s&&n.startsWith("_")){const r=n.substring(1);e.hasOwnProperty(r)&&(this[n]=e[r],this[r]=e[r])}})}async onCreate(){this._on_create?this.checkAndRunInternalFunction(this._on_create):this._on&&this._on.create?this.checkAndRunInternalFunction(this._on.create):this._once&&this._once.create&&this.checkAndRunInternalFunction(this._once.create)}async runCmd(e){const t=e instanceof I?e:new I(e);await this.execute(t)}async checkAndRunInternalFunction(e,...t){const s=(i,c)=>{const a=c.split(".");let l=i;for(const h of a){if(l==null)return;l=l[h]}return l},n=(i,c)=>{if(typeof i=="string")return i==="$prev"?c:i.startsWith("$prev.")?s(c,i.slice(6)):i==="$event"?t[0]:i.startsWith("$event.")?s(t[0],i.slice(7)):i==="$data"?t[0]:i.startsWith("$data.")?s(t[0],i.slice(6)):i;if(Array.isArray(i))return i.map(a=>n(a,c));if(i&&typeof i=="object"){const a={};for(const l of Object.keys(i))a[l]=n(i[l],c);return a}return i},r=async(i,c)=>{if(Array.isArray(i)){let a;for(const l of i)a=await r(l,a);return a}if(typeof i=="function")return await i(this,...t);if(typeof i=="string"){const a=w.parseObjectCommand(`${this._id} ${i}`);if(t.length>0){a._params=a._params||{};const l=t[0];a._params._event=l,!a._params.data&&!l?.target&&(a._params.data=l)}return await this.execute(a)}if(i&&typeof i=="object"&&Array.isArray(i._commands)){const a=i,l=typeof a._mode=="string"?a._mode:"sequence",h=a._stop_on_error!==!1,m=a._commands;if(l==="parallel"){const j=await Promise.allSettled(m.map(N=>r(N,c))),D=j.find(N=>N.status==="rejected");if(D&&h)throw D.reason;return j}let S=c;for(const j of m)try{S=await r(j,l==="chain"?S:c)}catch(D){if(_.error(this._type+"->"+this._id+"] command sequence failed",D),h)throw D}return S}if(i&&typeof i=="object"&&i._op){const a=i;if((a._object===void 0||a._object===null||a._object==="this"?this._id:a._object)!==this._id){_.error("XObject JSON handler target not supported; expected _object omitted/'this'/"+this._id);return}const h={...a,_params:a._params?{...a._params}:{}};if(t.length>0){const m=t[0];Object.prototype.hasOwnProperty.call(h._params,"data")||(h._params.data=m),Object.prototype.hasOwnProperty.call(h._params,"_event")||(h._params._event=m)}return h._params=n(h._params,c),this._debug&&_.log(this._type+"->"+this._id+"]","JSON handler executed locally",h),await this.execute(h)}_.error(this._type+"->"+this._id+"] invalid handler in checkAndRunInternalFunction",i)};return await r(e)}async onMount(){if(!this._mounted){this.parseEvents(this._xem_options),this._process_data&&typeof this._data_source=="string"&&this._data_source.length>0&&this.bindDataSource(this._data_source,{initial:!0}),this._on_mount?await this.checkAndRunInternalFunction(this._on_mount):this._on&&this._on.mount?await this.checkAndRunInternalFunction(this._on.mount):this._once&&this._once.mount&&await this.checkAndRunInternalFunction(this._once.mount),this._mounted=!0;for(const e of this._children)e.onMount&&typeof e.onMount=="function"&&e.onMount()}}emptyDataSource(){const e=this._data_source;if(typeof e!="string"||e.length===0)return;const t=this._type??this.constructor.name,s=this._id??"no-id";k.delete(e,{source:`${t}#${s}.emptyDataSource`})}async onData(e){this._process_data&&(this._on_data?this.checkAndRunInternalFunction(this._on_data,e):this._on&&this._on.data?this.checkAndRunInternalFunction(this._on.data,e):this._once&&this._once.data&&this.checkAndRunInternalFunction(this._once.data,e))}async onFrame(e){this._process_frame&&(this._on_frame?this.checkAndRunInternalFunction(this._on_frame,e):this._on&&this._on.frame?this.checkAndRunInternalFunction(this._on.frame,e):this._once&&this._once.frame&&this.checkAndRunInternalFunction(this._once.frame,e));for(const t of this._children)t.onFrame&&typeof t.onFrame=="function"&&t.onFrame(e)}async run(e,t=!0){let s=this._cache_cmd_txt&&this._cache_cmd_txt==e?this._cache_jcmd:w.parseObjectCommand(e);t&&(this._cache_cmd_txt=e,this._cache_jcmd=s),await this.execute(s)}async execute(e){const t=e?._op,s=typeof t=="string"&&t.startsWith("_")&&t.length>1?t.slice(1):t;if(!s){_.error(this._id+" missing _op in command");return}const n=e?._module;if(n)try{return await ue().execute({...e,_module:n,_op:s})}catch(r){_.error(this._id+" module execution failed: "+n+"."+s+" "+r);return}if(this._nano_commands[s])try{const r={...e,_op:s};return await this._nano_commands[s](r,this)}catch(r){_.error(this._id+" has error with command name "+s+" "+r);return}_.error(this._id+" has no command name "+s)}toXData(){const e={};return Object.keys(this).forEach(t=>{if(!this._xporter._ignore_fields.includes(t)&&this.hasOwnProperty(t)&&this[t]!==void 0){const s=this[t];if(typeof s=="function")return;if(typeof s=="object"){const n=Object.keys(this._xporter._instance_xporters);let r=!0;n.forEach(i=>{this._xporter._instance_xporters[i],s instanceof this._xporter._instance_xporters[i].cls&&(e[t]=this._xporter._instance_xporters[i].handler(s),r=!1)}),r&&(e[t]=s)}else e[t]=s}}),e._children=[],this._children.length>0&&this._children.forEach(t=>{typeof t.toXData=="function"&&e._children?.push(t.toXData())}),e}toString(){return JSON.stringify(this.toXData())}clearAttributes(e){e.forEach(t=>{this.hasOwnProperty(t)&&(this[t]=null,delete this[t])})}bindDataSource(e,t){const s=t?.initial??!0,n=e??this._data_source;typeof n!="string"||n.length===0||this._process_data&&(this._xd_bound_key===n&&this._xd_unsub||(this.unbindDataSource(),this._data_source=n,this._xd_bound_key=n,this._type??this.constructor.name,this._id,this._xd_unsub=k.on(n,async r=>{await this.onData(r.value)}),s&&k.has(n)&&this.onData(k.get(n))))}unbindDataSource(){this._xd_unsub?.(),this._xd_unsub=void 0,this._xd_bound_key=void 0}async dispose(){if(this.unbindDataSource(),this._parent){const e=this._parent._children.indexOf(this);e>-1&&this._parent._children.splice(e,1)}this._process_data=!1,this._process_frame=!1,this.removeAllEventListeners(),this.clearAttributes(["_cache_cmd_txt","_cache_jcmd","_nano_commands","_event_listeners_ids","_parent","_on","_once","_xem_options","_xporter"]),this._children&&this._children.forEach(e=>{typeof e.dispose=="function"&&e.dispose()}),this._children=[]}removeChild(e,t=!1){if(t)e.dispose();else{const s=this._children.indexOf(e);s>-1&&this._children.splice(s,1),e._parent=null}}addChild(e){this.append(e)}};E._xtype="object",E._skill=q;let A=E;class de{static getObjects(){return{object:A}}}const pe="engine:module:num-of-objects:",W={_id:"xmodule",_title:"XModule Runtime Contract",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Base runtime module contract for object ownership, object packs, and executable underscore-prefixed commands.",_core_rules:["Every module must have a unique _name.","Modules expose commands through methods prefixed with underscore.","Command names remove the leading underscore and convert dashes to underscores internally.","Modules own and create registered XObject classes.","Do not mutate another module's objects directly."]};var d;const R=class R{constructor(e){K(this,d);this._loaded=!1,this._loading=!1,this._log_rules={createObject:!1,removeObject:!1},G(this,d,new ne),this._name=e._name,this._id=u.guid()}static getOwnSkillBase(){return{...this._skill}}getOwnSkill(){const t=this.constructor._skill??W;return{...t,_exports:{...t._exports??{},_modules:[{_name:this._name,_scope:t._type==="server-module-api"?"server":"client",_description:t._description,_ops:this.getCommandSkills()}]}}}getSkillChain(){return[this.getOwnSkill()]}getObjectSkills(){const e=[],t=new Set;for(const s of Object.values(p(this,d).getObjectClasses())){if(typeof s.getOwnSkill!="function")continue;const n=s.getOwnSkill();n?._id&&(t.has(n._id)||(t.add(n._id),e.push(n)))}return e}getCommandSkills(){const e=Object.getPrototypeOf(this),s=this.constructor._ops??{};return Object.getOwnPropertyNames(e).filter(n=>n.startsWith("_")&&!n.startsWith("__")&&typeof this[n]=="function").map(n=>{const r=n.slice(1).replaceAll("_","-");return s[r]??{_name:r,_scope:"module",_description:`Runtime module command: ${r}`}})}async load(){if(!(this._loaded||this._loading)){this._loading=!0;try{await this.onLoad(),this._loaded=!0,_.log("Module "+this._name+" loaded")}finally{this._loading=!1}}}async onLoad(){}create(e){e._debug&&_.log("Creating object with data",e);let t;if(e.hasOwnProperty("_type")){e._debug&&_.log("Object type is",e._type,this.hasObject(e._type)?"found":"not found","in module",this._name);const s=String(e._type),n=p(this,d).getObjectClass(s);if(!n)throw`Xpell object '${s}' not found in module '${this._name}'`;typeof n=="function"&&n.hasOwnProperty("defaults")&&u.mergeDefaultsWithData(e,n.defaults),t=new n(e)}else t=new A(e);return p(this,d).addObject(t),e._children&&e._children.forEach(s=>{const n=this.create(s);t.append(n)}),t.onCreate(),t}remove(e){const t=p(this,d).getObject(e);if(!t)return;const s=[],n=r=>{r?._id&&(s.push(r._id),(r._children??[]).forEach(i=>n(i)))};n(t),typeof t.dispose=="function"&&t.dispose(),s.reverse().forEach(r=>p(this,d).removeObject(r))}_info(e){_.log("module info")}async run(e){if(e){let t=e.trim();t.startsWith(this._name)||(t=this._name+" "+t);let s=w.parse(t);return await this.execute(s)}else throw"Unable to parse Xpell Command"}async execute(e){if(!e||!e._op)throw new Error(`Invalid XCommand: missing _op (module: ${this._name})`);const t=e._object;if(t){const c=p(this,d).getObject(t);if(!c)throw new Error(`Module '${this._name}' cant find object id: ${t}`);return await c.execute(e)}const s=e._op,r="_"+(s.startsWith("_")&&s.length>1?s.slice(1):s).replaceAll("-","_"),i=this[r];if(typeof i=="function")return await i.call(this,e);throw new Error(`Module '${this._name}' cant find op: ${e._op}`)}async onFrame(e){const t=p(this,d)._objects,s=Object.keys(t);s.forEach(n=>{const r=t[n];r&&r.onFrame&&typeof r.onFrame=="function"&&r?.onFrame(e)}),f.set(pe+this._id,s.length,{source:"xmodule"})}get om(){return p(this,d)}get _object_manager(){return p(this,d)}getObject(e){return p(this,d).getObject(e)}hasObject(e){return p(this,d).hasObjectClass(e)}get _o(){return p(this,d)._objects}importObjectPack(e){p(this,d).registerObjects(e.getObjects())}importObjects(e){this.importObjectPack(e)}importObject(e,t){p(this,d).registerObject(e,t)}async _help(e){const t=e?._params?._op??e?._params?._command??"";return this.help(t)}help(e){return{module:this._name,usage:`${this._name} help`,ops:["help"],note:"No help() implemented for this module."}}};d=new WeakMap,R._skill=W,R._ops={help:{_name:"help",_scope:"module",_description:"Return module help or command-specific help."},info:{_name:"info",_scope:"module",_description:"Log basic module information."}};let M=R;const fe={_id:"xdata",_title:"XData Runtime State Contract",_version:"1.0.0",_active:!0,_type:"xdata-skill",_description:"Shared runtime state store used by Xpell modules and objects for reactive data binding.",_requires:["xmodule"],_core_rules:["Use XData for shared runtime state.","Use _data_source on objects to bind to an XData key.","Use $xdata.key references in generated payloads when a flow or command needs current state.","Do not use XData as hidden local component state.","XData keys should be explicit and stable."],_fields:{_data_source:"XData key used by XObject/XUIObject for reactive data binding.","$xdata.key":"Runtime payload reference to an XData value."}},O=class O extends M{constructor(){super({_name:O._name})}async _get(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return{_ok:!0,_result:f.get(s)}}async _set(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return t._debug&&v.log("XD SET",{key:s,value:t.value}),f.set(s,t.value,{source:t.source??"xd:set"}),{_ok:!0,_result:{key:s}}}async _patch(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");if(!u.is_plain_object(t.value))throw new Error("xd patch expects value as plain object");return f.patch(s,t.value,{source:t.source??"xd:patch"}),{_ok:!0,_result:{key:s}}}async _delete(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return f.delete(s,{source:t.source??"xd:delete"}),{_ok:!0,_result:{key:s}}}async _touch(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return f.touch(s,{source:t.source??"xd:touch"}),{_ok:!0,_result:{key:s}}}async _has(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.key,"key");return{_ok:!0,_result:f.has(s)}}};O._name="xd",O._skill=fe,O._ops={get:{_name:"get",_scope:"module",_description:"Get value from XData store.",_params:{key:"XData key."}},set:{_name:"set",_scope:"module",_description:"Set value in XData store.",_params:{key:"XData key.",value:"Value to store.",source:"Optional mutation source."}},patch:{_name:"patch",_scope:"module",_description:"Patch plain object into existing XData value.",_params:{key:"XData key.",value:"Plain object patch.",source:"Optional mutation source."}},delete:{_name:"delete",_scope:"module",_description:"Delete XData key.",_params:{key:"XData key.",source:"Optional mutation source."}},touch:{_name:"touch",_scope:"module",_description:"Trigger XData subscribers without changing value.",_params:{key:"XData key.",source:"Optional mutation source."}},has:{_name:"has",_scope:"module",_description:"Check if XData key exists.",_params:{key:"XData key."}}};let P=O;const me={_id:"xem",_title:"XEventManager Runtime Event Bus",_version:"1.0.0",_active:!0,_type:"runtime-api-skill",_description:"Global runtime event bus for decoupled communication between Xpell modules, objects, flows, and UI components.",_requires:["xmodule"],_core_rules:["Use XEM for decoupled runtime events.","Use explicit event names and explicit payload objects.","Do not use XEM as state storage.","Use XData for shared state and XEM for notifications/events.","Prefer _on/_once on objects for local event handlers."],_fields:{_on:"Object event handler map.",_once:"Object one-time event handler map.",event:"Event name to fire.",data:"Optional event payload."},_notes:["XEM is process-wide and listener order should not be assumed.","Event payloads should be JSON/data-only."]},x=class x extends M{constructor(){super({_name:x._name})}async _fire(e){const t=u.ensure_params(e?._params),s=u.ensure_string(t.event,"event"),n=t.data;t._debug&&v.log("xem fire 🔥 ",s,n),await X().fire(s,n)}};x._name="xem",x._skill=me,x._ops={fire:{_name:"fire",_scope:"module",_description:"Fire a global XEM event with optional payload data.",_params:{event:"Event name.",data:"Optional event payload.",_debug:"Optional debug log flag."},_example:{_module:"xem",_op:"fire",_params:{event:"user:login",data:{source:"login-button"}}}}};let $=x;class ge{static get(e,t,s){const r=(e?._params??e)?.[t];return r!==void 0?r:s}static has(e,t){return(e?._params??e)[t]!==void 0}static str(e,...t){const s=e?._params??e;for(const n of t){const r=s?.[n];if(r!=null)return String(r)}}static bool(e,t,s=!1){const n=e?._params??e,r=this.get(n,t,s);if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){const i=r.toLowerCase();if(["1","true","yes","on"].includes(i))return!0;if(["0","false","no","off"].includes(i))return!1}return!!r}static int(e,t,s=0){const n=e?._params??e,r=this.get(n,t,s),i=parseInt(String(r),10);return Number.isFinite(i)?i:s}static json(e,t,s){const n=e?._params??e,r=this.get(n,t,s);if(r==null)return s;if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return s}return s}}class B extends Error{constructor(e,t,s){super(t),this.name="XError",this._code=e,this._level=s?._level??"error",this._meta=s?._meta,this._cause=s?._cause}toXData(){return{_code:this._code,_level:this._level,_meta:this._meta,_cause:this._cause,name:this.name,message:this.message}}toJSON(){return{...this.toXData(),stack:this.stack}}}class y{constructor(e){this._ok=!1,this._ts=Date.now(),this._pt=0,e&&this.setXData(e)}static create(e){return new y(e)}static ok(e){return new y({_ok:!0,_result:e})}static error(e){if(e instanceof B)return new y({_ok:!1,_result:e.toXData()});const t=new B("E_INTERNAL",e?.message??String(e),{_cause:e});return new y({_ok:!1,_result:t.toXData()})}stopProcessTimeCounter(){this._pt=Date.now()-this._ts}toXData(){return this.stopProcessTimeCounter(),{_ok:this._ok,_ts:this._ts,_pt:this._pt,_result:this._result}}toString(){return JSON.stringify(this.toXData())}setXData(e){e&&("_ok"in e&&(this._ok=!!e._ok),"_ts"in e&&typeof e._ts=="number"&&(this._ts=e._ts),"_pt"in e&&typeof e._pt=="number"&&(this._pt=e._pt),"_result"in e&&(this._result=e._result))}}class ye extends y{constructor(e){super(y.error(e).toXData())}}class be extends y{constructor(e){super({_ok:!0,_result:e})}}const re="engine:frame-number",ie="engine:fps";class oe{constructor(e){this._log_rules={},this._modules={},this._schedule_frame=e?._schedule_frame??u.createDefaultScheduler(e?._target_fps),this._version="0.0.1",this._engine_id=u.guid(),this._frame_number=0,this._fps_calc=new ae,this.parser=w,this._modules={},_._enabled=!1,he(this)}set verbose(e){_._enabled=e}set _verbose(e){_._enabled=e}log(e,...t){_.log(e,...t)}async delay(e){return new Promise(t=>setTimeout(t,e))}addModule(e){return this._modules.hasOwnProperty(e._name)?(_.log("Module "+e._name+" already loaded"),!1):(this._modules[e._name]=e,!0)}loadModule(e){this.addModule(e)&&e.load()}loadModules(...e){e.forEach(t=>this.loadModule(t))}async loadModuleAsync(e){this.addModule(e)&&await e.load()}async loadModulesAsync(...e){for(const t of e)await this.loadModuleAsync(t)}info(){_.log(`Xpell information:
|
|
2
2
|
- Engine Id: `+this._engine_id+`
|
|
3
|
-
- Version `+this._version)}run(e){if(e?.length>2){let t=
|
|
3
|
+
- Version `+this._version)}run(e){if(e?.length>2){let t=w.parse(e);return this.execute(t)}else throw"Unable to parse Xpell command"}execute(e){if(e&&e._module&&this._modules[e._module])return this._modules[e._module].execute(e);throw"Xpell module "+e._module+" not loaded"}onFrame(){this._frame_number++;for(const t of Object.keys(this._modules)){const s=this._modules[t];s?.onFrame&&typeof s.onFrame=="function"&&s.onFrame(this._frame_number)}const e=this._fps_calc.calc();f.set(re,this._frame_number,{source:"engine"}),f.set(ie,e,{source:"engine"}),f._compat_legacy_keys&&(f.set("frame-number",this._frame_number,{source:"engine:legacy"}),f.set("fps",e,{source:"engine:legacy"})),this._schedule_frame(()=>this.onFrame())}getModule(e){return this._modules[e]}start(){_.log("Loading Xpell core modules...[xd, xem]"),this.loadModule(new P),this.loadModule(new $),_.log("Starting Xpell"),this.onFrame()}getCoreSkills(){return[W,q]}getModuleSkills(){return Object.values(this._modules).flatMap(e=>typeof e.getSkillChain=="function"?e.getSkillChain():[])}getSkills(){return{_runtime:{_engine_id:this._engine_id,_version:this._version},_skills:this.getCoreSkills(),_modules:Object.values(this._modules).map(e=>({_name:e._name,_skills:typeof e.getSkillChain=="function"?e.getSkillChain():[],_objects:typeof e.getObjectSkills=="function"?e.getObjectSkills():[]}))}}}const J=new oe;exports.XCommand=I;exports.XD_FPS=ie;exports.XD_FRAME_NUMBER=re;exports.XData=k;exports.XDataModule=P;exports.XError=B;exports.XEventManagerModule=$;exports.XLogger=_;exports.XModule=M;exports.XObject=A;exports.XObjectManager=ne;exports.XObjectPack=de;exports.XParams=ge;exports.XParser=w;exports.XResponse=y;exports.XResponseError=ye;exports.XResponseOK=be;exports.XUtils=Z;exports.Xpell=J;exports.XpellEngine=oe;exports._XData=se;exports._XEventManager=ce;exports._XLogger=ee;exports._XUtils=Y;exports._x=J;exports._xd=f;exports._xlog=_;exports._xu=u;exports.createNanoCommandWithSkill=g;exports.default=J;exports.getXEventManager=X;exports.setXEventManager=_e;
|