/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/xcraft-core-goblin@5.58.1/lib/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";const watt=require("gigawatts"),{v4:uuidV4}=require("uuid"),cloneDeep=require("lodash/cloneDeep"),{createStore:createStore,combineReducers:combineReducers,applyMiddleware:applyMiddleware}=require("redux"),Shredder=require("xcraft-core-shredder"),SmartId=require("./smartId"),{js:js,reflect:reflect,locks:locks}=require("xcraft-core-utils"),{isAsync:isAsync,isGenerator:isGenerator,isFunction:isFunction}=js,busConfig=require("xcraft-core-etc")().load("xcraft-core-bus"),goblinConfig=require("xcraft-core-etc")().load("xcraft-core-goblin"),appBuilder=require("./appBuilder.js"),workerBuilder=require("./workerBuilder.js"),queueBuilder=require("./queueBuilder.js"),Ripley=require("./ripley.js"),Scheduler=require("./scheduler.js"),guildEnforcer=require("./guildEnforcer.js")(busConfig,goblinConfig),osInfo=require("./osInfo.js");function createAction(e,t,i={},s=void 0){const r=isFunction(e)?e:{type:e,payload:t,meta:i,error:s};return isFunction(e)||(r.get=(e,t)=>void 0!==r.payload[e]?r.payload[e]:void 0!==r.meta[e]?r.meta[e]:t),r}const emitAsyncQuest=(...e)=>Scheduler.dispatch("quest",...e),questMiddleware=e=>t=>i=>s=>{if("DOASYNCQUEST"===s.type)try{const i=s.msg.topic,r=guildEnforcer.isBlocked;if(r(e,i))throw new Goblin.ShieldedError(`Blocked by a shield: the goblin ${e.id} is not allowed to run ${i}`);const n=Goblin.identifyUser(s.msg);if(r(n,i))throw new Goblin.ShieldedError(`Blocked by a shield: the user ${n.login||"unknown"} with the rank ${n.rank||"unknown"} is not allowed to run ${i}`);return emitAsyncQuest({quest:s.quest,dispatch:t.dispatch,questName:s.questName,caller:s.caller,callerQuest:s.callerQuest,isInCreate:s.isInCreate,isRecreate:s.isRecreate,msg:s.msg,resp:s.resp,goblin:e,schedulingMode:!1})}catch(t){s.resp.events.send(`${e.goblinName}.${s.questName}.${s.msg.id}.error`,{code:t.code,message:t.message,stack:t.stack})}return i(s)},emptyMiddleWare=()=>e=>t=>e(t);function injectMessageDataGetter(e){e.get=(t,i=null)=>e.data?Shredder.isImmutable(e.data[t])?new Shredder(e.data[t]):e.data[t]:i}function verifyMessage(e){const{topic:t,data:i}=e;if((t.endsWith(".create")||t.endsWith(".delete"))&&!i._goblinLegacy)throw new Error(`command ${t} is forbidden, use quest.create or quest.release`)}const QUESTS={},QUESTSMETA={},QUESTSHANDLES={},GOBLINS=new Map,SESSIONS=new Map,CONFIGS={};let GENERATION=0;class Goblin{static#e;static#t;static#i;static#s;static#r;static#n;static#o(){return Goblin.#e||(Goblin.#e=require("./quest.js")),Goblin.#e}static#a(){return Goblin.#t||(Goblin.#t=require("xcraft-core-utils")),Goblin.#t}static#l(){return Goblin.#i||(Goblin.#i=require("xcraft-core-host")),Goblin.#i}static#c(){return Goblin.#s||(Goblin.#s=require("./cryo/manager.js")),Goblin.#s}static#d(){return this.#r||(this.#r=require("./cache/index.js")),this.#r}static#g(){return this.#n||(this.#n=require("./sync/index.js")),this.#n}static buildApplication(e,t){return appBuilder(e,t)}static buildQueue(e,t){return queueBuilder(e,t)}static buildQueueWorker(e,t){return workerBuilder(e,t)}static registerQuests(e,t,i,s=!1){let r=Goblin.registerQuest;s&&(r=Goblin.registerSafeQuest),t&&Object.keys(t).forEach((s=>{i&&i[s]?r(e,s,t[s],i[s]):r(e,s,t[s])}))}static registerSafeQuest(e,t,i,s){Goblin.registerQuest(e,t,(function*(e,t,s){const r=reflect.funcParams(i).filter((e=>!/^(quest|next)$/.test(e))).map((e=>t.get(e)));try{return yield e.sysCreate(),js.isGenerator(i)?yield*i(e,...r,s):js.isAsync(i)?yield i(e,...r):i(e,...r,s)}finally{yield e.sysKill()}}),s)}static registerQuest(e,t,i,s){QUESTSMETA[e]||(QUESTSMETA[e]={});const r=Goblin.#a();QUESTSMETA[e][t]||(QUESTSMETA[e][t]={}),QUESTSMETA[e][t].options=s||{};const n=QUESTSMETA[e][t].options,o=Symbol.for("RUN_QUEST");if(n.skills){for(const t of n.skills)if("symbol"!=typeof t)throw new Error(`Invalid skill provided for ${e}`);n.skills.push(o)}else n.skills=[o];let a;if(n.elf){const s=["quest","next"];if(a=r.reflect.funcParams(i),s.some((e=>a.includes(e))))throw new Error(`Forbidden use of a reserved parameter (${s.join(", ")}) with ${e}.${t}`)}else a=r.reflect.funcParams(i).filter((e=>!/^(quest|next)$/.test(e)));QUESTSMETA[e][t].params=a,QUESTSHANDLES[`${e}/${t}`]=i;const l=(i,s,r)=>{const n=QUESTSMETA[e][t].params.reduce(((e,t)=>{const i=s.get(t);return Array.isArray(i)&&t.startsWith("...")?e.push(...i):e.push(i),e}),[]);if(!s.get("$msg")){const i=QUESTSMETA[e][t].params.indexOf("$msg");i>-1&&(n[i]=s)}return r&&n.push(r),QUESTSHANDLES[`${e}/${t}`](i,...n)};QUESTS[e]||(QUESTS[e]={}),isGenerator(i)||isAsync(i)?isAsync(i)?QUESTS[e][t]=l:QUESTS[e][t]=watt(l):QUESTS[e][t]=async function(e,t){return l(e,t)}}static get#u(){return{mutex:locks.getMutex,mutexId:e=>`_cryoLocks_${e}_`}}static#h(e,t){return async function(i,s){let r;i.data||(i.data={_goblinCaller:"core-host",_goblinCallerQuest:"bigbang",_goblinInCreate:!1});try{injectMessageDataGetter(i),r=i.get("id")||`${e}@${uuidV4()}`,await Goblin.#u.mutex.lock(Goblin.#u.mutexId(r));const n=Goblin.nextGen();if(-1===r.indexOf("@"))throw new Error(`Bad goblin id provided during ${e}.create, id must respect this format: (meta@)name@unique-identifier`);if(!i.data._goblinCaller||!i.data._goblinCallerQuest)throw new Error("Malformed create, missing payload");let o=GOBLINS.has(e)&&GOBLINS.get(e).get(i.data.id);const a=i.data._goblinTTL>0?i.data._goblinTTL:o?o.TTL:0;o&&(i.data._goblinRecreate=!0),o=Goblin.create(e,r,n),o.TTL=a,o.feed||i.data._goblinRecreate||(o.feed=i.data&&i.data.desktopId&&i.data.desktopId);if(!await s.command.sendAsync("warehouse.attach-to-parents",{branch:r,generation:n,parents:i.data.parent,feeds:i.data&&i.data.desktopId||null,view:i.data?._goblinView||null}))throw{code:"SILENT_HILL",message:`attach impossible (parent ${i.data.parent} unavailable in the feed)`};const l={type:"DOASYNCQUEST",caller:i.data._goblinCaller,callerQuest:i.data._goblinCallerQuest,isInCreate:i.data._goblinInCreate,isRecreate:!!i.data._goblinRecreate,msg:i,resp:s,questName:t,quest:o.doQuest(t,i,s).bind(o)};o.store.dispatch(l)}catch(n){r&&(Goblin.release(e,r),s.events.send(`<${r}.deleted>`,{id:r})),s.events.send(`${e}.${t}.${i.id}.error`,{code:n.code,message:n.message,stack:n.stack})}finally{Goblin.#u.mutex.unlock(Goblin.#u.mutexId(r))}}}static#b(e,t){const i=goblinConfig.actionsSync?.enable,s=!i,r=(e,t,i,s)=>{const r="persist"===e;return"string"==typeof i?createAction(e,{},{id:t,commitId:s,action:i}):createAction(e,r?{state:i}:i,{id:t,commitId:s})},n=async(e,t,i)=>{await e.command.sendAsync("cryo.freeze",{db:t.db,action:i,rules:t,raw:"string"==typeof i.meta.action})};return async(i,o)=>{const a=i?.data?.id;let l=i?.data?.state;try{if("object"!=typeof l||Array.isArray(l)||null===l||(l={...l}),!a)throw new Error(`No id provided for ${e}.${t}`);await Goblin.#u.mutex.lock(Goblin.#u.mutexId(a));const c=GOBLINS.get(e).get(i.data.id);let d=!c;const g=Goblin.getActorRipleyRules(a,"persist"),u=Object.assign({},g,{goblin:`${e}-${a}`});if(c&&"insertOrReplace"===t){const e=new(Goblin.#o())({goblin:c},t,i,o);if(!s){const e=r(t,a,l);await n(o,u,e)}c.dispatch("persist",{state:i.data.state},s?{id:a,commitId:uuidV4()}:{id:a});const d={branch:i.data.id,data:Shredder.fromJS(l),feeds:e.getDesktop(!0),_goblinHasDispatched:!0};if(await c.upsert(e,d),s){Goblin.#c().syncBroadcast(u.db)}else{Goblin.#g()().sync(u.db)}}if(!c){const e=Goblin.#o(),c=Goblin.#c();let h=!0;const b=new e({goblin:{}},t,i,o),f=await c.isPersisted(b,g.db,a);if("insertOrCreate"===t&&f&&(h=!1,d=!1),h){let{commitId:e}=i.data;if(!(f&&"insertOrReplace"!==t||s||e)){const e=r(t,a,l);await n(o,u,e)}!e&&s&&(e=uuidV4());const d=r("persist",a,l,e);if(await n(o,u,d),s)c.syncBroadcast(u.db);else{Goblin.#g()().sync(u.db)}}}o.events.send(`${e}.${t}.${i.id}.finished`,{success:d})}catch(s){o.events.send(`${e}.${t}.${i.id}.error`,{code:s.code,message:s.message,stack:s.stack})}finally{Goblin.#u.mutex.unlock(Goblin.#u.mutexId(a))}}}static#f(e,t){return(i,s)=>{i.data||(i.data={});try{if(!GOBLINS.has(e))return void s.events.send(`${e}.${t}.${i.id}.error`,new Error(`You must call ${e}.create before calling ${t}`));if(GOBLINS.get(e).has(e)){const r=GOBLINS.get(e).get(e),n={type:"DOASYNCQUEST",questName:t,caller:i.data._goblinCaller,callerQuest:i.data._goblinCallerQuest,isInCreate:i.data._goblinInCreate,isRecreate:!1,msg:i,resp:s,quest:r.doQuest(t,i,s).bind(r)};return void r.store.dispatch(n)}if(!i.data)throw new Error(`No id provided for ${e}.${t}`);if(!i.data.id)throw new Error(`No id provided for ${e}.${t}`);const r=GOBLINS.get(e).get(i.data.id);if(!r){let r="";i.data._goblinCaller&&(r=` from ${i.data._goblinCaller}.${i.data._goblinCallerQuest}`);const n=new Error(`Error calling quest ${e}.${t}${r}: goblin with id ${i.data.id} has not been created`);if("delete"===t&&(n.code="SILENT_HILL"),!i.data._goblinNoThrow)throw n;return s.log.warn(`goblin noThrow enabled: ${n.stack||n.message||n}`),void s.events.send(`${e}.${t}.${i.id}.finished`,{_goblinNoThrow:!0,code:n.code,message:n.message,stack:n.stack})}const n={type:"DOASYNCQUEST",questName:t,caller:i.data._goblinCaller,callerQuest:i.data._goblinCallerQuest,isInCreate:i.data._goblinInCreate,isRecreate:!1,msg:i,resp:s,quest:r.doQuest(t,i,s).bind(r)};r.store.dispatch(n)}catch(r){s.events.send(`${e}.${t}.${i.id}.error`,{code:r.code,message:r.message,stack:r.stack})}}}static getQuests(e){const t={};Object.keys(QUESTS[e]).forEach((i=>{t[i]="create"!==i?"insertOrCreate"!==i&&"insertOrReplace"!==i?Goblin.#f(e,i):Goblin.#b(e,i):Goblin.#h(e,i)}));for(const[i,s]of Object.entries(t))guildEnforcer.shield(`${e}.${i}`,s,QUESTSMETA[e][i].options.skills);return t}static getActorRipleyRules(e,t){const[i]=e.split("@",1),s=CONFIGS[i];return s?.goblinConfig?.ripley?.[t]?s.goblinConfig.ripley[t]:null}static getActorRipleyDB(e){const[t]=e.split("@",1),i=CONFIGS[t];return i?.goblinConfig?.ripley?.persist?i.goblinConfig.ripley.persist.db:null}static getActorClass(e){const[t]=e.split("@",1),i=CONFIGS[t];return i?.goblinConfig?.class}static getAllRipleyDB(){const e=new Set;for(const t of Object.values(CONFIGS))if(t?.goblinConfig?.ripley?.persist){const i=t.goblinConfig.ripley.persist.db;i&&!goblinConfig.actionsSync?.excludeDB?.includes(i)&&e.add(i)}return Array.from(e).sort()}static getAllRipleyActors(e){const t=[];for(const[i,s]of Object.entries(CONFIGS))e&&s.goblinConfig.ripley.persist.db!==e||s?.goblinConfig?.ripley?.persist&&t.push(i);return t}static nextGen(){return++GENERATION}static getSystemDesktop(e){return`system@${e.split("@")[1]}`}static extractGoblinName(e){let t=e;return-1!==e.indexOf("@")&&(t=e.split("@",1)[0]),t}static getGoblinName(e){return Goblin.extractGoblinName(e)}static getGoblinsRegistry(){return GOBLINS}static getSessionsRegistry(){return SESSIONS}static getRC(e){const t={};return Object.keys(QUESTS[e]).forEach((i=>{const s={},r=i.startsWith("_")?null:`${i} for ${e}`,n=QUESTSMETA[e][i].params;s.required=n.filter((e=>"$"!==e[0])),s.optional=n.filter((e=>"$"===e[0]));const o=QUESTSMETA[e][i].options;o.rankingPredictions=guildEnforcer.getRankingPredictions(`${e}.${i}`),t[i]={parallel:!0,desc:r,options:{params:s},questOptions:o,registrar:"xcraft-core-goblin"}})),t}static getParams(e,t){return!!QUESTSMETA[e]?.[t]&&QUESTSMETA[e][t].params}static configure(e,t,i,s){s&&!s.role?s.role="system":s={role:"system"},CONFIGS[e]||(CONFIGS[e]={}),SESSIONS.has(e)||SESSIONS.set(e,new Map),CONFIGS[e]={logicState:t,logicHandlers:i,goblinConfig:s},GOBLINS.has(e)||GOBLINS.set(e,new Map);return{handlers:Goblin.getQuests(e),rc:Goblin.getRC(e)}}static#p(e){const{goblinName:t}=e;e._elfInstance=new CONFIGS[t].goblinConfig.class(null,{ripley:CONFIGS[t].goblinConfig.ripley});for(const i in QUESTS[t])"$4ellen"===i||"insertOrCreate"===i||"insertOrReplace"===i||"persist"===i&&CONFIGS[t].goblinConfig?.ripley?.persist||(QUESTSHANDLES[`${t}/${i}`]=e._elfInstance[i].bind(e._elfInstance))}static create(e,t,i){if(GOBLINS.get(e).has(e))throw new Error("A single goblin exist");if(Object.keys(QUESTSMETA[e]).filter((e=>"init"===e||"boot"===e)).length>0)throw new Error(`Cannot create goblin ${e}: singleton reserved quest names found in your goblin, please rename 'init' or 'boot' quests to something else`);const s=t||`${e}@${uuidV4()}`;if(!i)throw new Error(`missing generation for ${s}`);if(GOBLINS.get(e).has(s)){const t=GOBLINS.get(e).get(s);return t._generationId=i,t}const r=new Goblin(s,e,CONFIGS[e].logicState,CONFIGS[e].logicHandlers,CONFIGS[e].goblinConfig,i);return CONFIGS[e].goblinConfig.class&&Goblin.#p(r),guildEnforcer.enforce(r,CONFIGS[e].goblinConfig.role),GOBLINS.get(e).set(s,r),r}static createSingle(e){const t=Goblin.#l().appArgs();if(t.tribe&&t.tribe>0&&"goblin"!==e)return null;if(GOBLINS.get(e).has(e))throw new Error("A single goblin exist");const i=Goblin.nextGen(),s=new Goblin(e,e,CONFIGS[e].logicState,CONFIGS[e].logicHandlers,CONFIGS[e].goblinConfig,i);return CONFIGS[e].goblinConfig.class&&Goblin.#p(s),guildEnforcer.enforce(s,CONFIGS[e].goblinConfig.role),GOBLINS.get(e).set(e,s),s}static release(e,t){const i=GOBLINS.get(e).get(t);if(i)i.dispose(),GOBLINS.get(e).delete(t),SESSIONS.get(e).delete(t);else{require("xcraft-core-log")("goblin-core",null).warn(`goblin ${t} already disposed; released event received two times?!`)}}_do(e,t={},i={},s=void 0){if(!this._logicHasType(e))throw new Error(`Cannot do (${e}), missing logic handler`);this.dispatch(e,t,i,s)}static async questDispatch(e,t,i,s,r,n){const o=function(e,t={},i={},r=void 0){const n=createAction(e,t,i,r);s(n)};e.running(t,!0);try{return await i({dispatch:o,goblin:e})}finally{e.running(t,!1),r&&r(n)}}dispose(){this.TTL=0,this._scheduler.dispose(),this._elfInstance&&this._elfInstance.dispose()}constructor(e,t,i,s,r,n){if(!n)throw new Error(`missing generation for ${e}`);this._generationId=n;const o=e===t;this._scheduler=new Scheduler(t,Goblin.questDispatch,o),this._goblinId=e,this._goblinName=t,this._logger=require("xcraft-core-log")(t,null),this._deferrable=[],this._goblinConfig=cloneDeep(r||{}),this._runningQuests={},this._feed={},this._TTL=0,this.schedulingMode=this._goblinConfig.schedulingMode||"foreground",this._createMsgIdList=[];const a=o?this._goblinName:`${this._goblinName}-${this._goblinId}`;if(this._goblinConfig.ripley){this._goblinConfig.ripley&&goblinConfig.enableCryo&&(this._ripley=new Ripley("cryo",null,null,null));for(const e in this._goblinConfig.ripley){if(this._goblinConfig.ripley[e].goblin=a,!("mode"in this._goblinConfig.ripley[e]))throw new Error(`Bad goblin ripley config, missing for ${e}`);if(this._ripley&&!this._ripley.hasMode(this._goblinConfig.ripley[e].mode))throw new Error(`Bad goblin ripley config, unknow mode for ${e}`)}}this._logicHasType=e=>!!s[e];const l=combineReducers({ellen:this._ripley?this._ripley.ellen.bind(this._ripley):(e={})=>e,logic:(e,t)=>e?s[t.type]?s[t.type](e,t):e:{}}),c={ellen:this._ripley?this._ripley.initialState:{},logic:new Goblin.Shredder(i)};this._store=createStore(l,c,applyMiddleware(this._ripley?this._ripley.persistWith(this._goblinConfig.ripley):emptyMiddleWare,questMiddleware(this)))}get id(){return this._goblinId}get goblinName(){return this._goblinName}get store(){return this._store}get schedulerInfos(){return this._scheduler.infos}get metrics(){if(this._goblinConfig.getMetrics){let e;this._logger.verb(`Gathering metrics for ${this.id}...`);try{e=this._goblinConfig.getMetrics(this)}catch(t){this._logger.warn(`Gathering metrics for ${this.id} failed!`),this._logger.warn(t.stack||t.message||t),e={"metricsError.total":1}}return e}return null}get storeListener(){return this._storeListener}get useRipley(){return!!this._ripley&&Object.keys(this._goblinConfig.ripley).length>0}get locks(){return require("locks")}set feed(e){this.setX("desktopId",e)}get feed(){return this.getX("desktopId")}set TTL(e){const t=this._TTL>0||e>0;if(this._TTL=e,t){Goblin.#d().update(this.id,e)}}get TTL(){return this._TTL}get questEmitter(){return this._scheduler.questEmitter}get ripley(){return CONFIGS[this._goblinName].goblinConfig.ripley}deferCreateEvent(e,t,i,s){this._createMsgIdList.push({orcName:e,msgId:t,routing:i,context:s})}isCreating(){return this.goblinName!==this._goblinId&&(this._runningQuests.create&&this._runningQuests.create>0)}isCreated(){return this.goblinName===this._goblinId||!!this._isCreated}isDeleting(){return this.goblinName!==this._goblinId&&(this._runningQuests.delete&&this._runningQuests.delete>0)}isRunning(e=null){return e?this._runningQuests[e]>0:Object.values(this._runningQuests).some((e=>e>0))}running(e,t){this._runningQuests[e]||(this._runningQuests[e]=0),this._runningQuests[e]=t?this._runningQuests[e]+1:this._runningQuests[e]-1}runningCount(e){return this._runningQuests[e]}async upsert(e,t){t._upsertQuest=e.questName,t.data=t.data.delete("private"),this.lastUpsertData?this.lastUpsertData.equals(t.data)||(await e.warehouse.upsert(t),this.lastUpsertData=t.data):(this.lastUpsertData=t.data,await e.warehouse.upsert(t))}setX(e,t){if(t&&t._dontKeepRefOnMe)throw new Error(`You cannot setX with ${e} value`);SESSIONS.get(this.goblinName).has(this.id)||SESSIONS.get(this.goblinName).set(this.id,new Map),SESSIONS.get(this.goblinName).get(this.id).set(e,t)}getX(e,t){if(!SESSIONS.get(this.goblinName).has(this.id)){if(t){const i=new Map;return i.set(e,t),SESSIONS.get(this.goblinName).set(this.id,i),i.get(e)}return null}const i=SESSIONS.get(this.goblinName).get(this.id);return t&&!i.has(e)&&i.set(e,t),i.get(e)}delX(e){SESSIONS.get(this.goblinName).get(this.id).delete(e)}getEllen(){return this.store.getState().ellen}getState(){return this.store.getState().logic}dispatch(e,t={},i={},s=void 0){const r=createAction(e,t,i,s);this.store.dispatch(r)}defer(e){this._deferrable.push(e)}async defers(e,t,i){for(;i.length>0;)try{const e=i.pop();isGenerator(e)?await watt(e)():isAsync(e)?await e():e()}catch(i){e.log.err(`one defer has failed for ${this._goblinId}/${t}: ${i.stack||i.message||i}`)}}async _doQuest(e,t,i,s){const r=new(Goblin.#o())(s,e,t,i);verifyMessage(t),injectMessageDataGetter(t);const n=this.goblinName===this._goblinId;let o=null,a=null,l=!1,c=!1,d=!1;if(t.data._goblinRecreate)return this._runningQuests.create>1?void this.deferCreateEvent(t.orcName,t.id,i.events.routing,t.context):void i.events.send(`${this._goblinName}.create.${t.id}.finished`,this.id);try{let i=!1;const s=t.data?t.data.parent:null;if("create"===e||"boot"===e||"init"===e){const e={branch:this._goblinId,generation:this._generationId,data:{},feeds:r.getDesktop(!0)||"system"};if(n||(o=!0,e.isCreating=o,e.creator=t.data._goblinCaller),e.parents=s||this._goblinId,await r.warehouse.upsert(e),0===this.TTL&&this._goblinConfig&&this._goblinConfig.cacheSize>0){await r.createCache(null);const e=Goblin.#d();await e.rank(this._goblinName,this._goblinId,this._goblinConfig.cacheSize),i=!0}}if(a=await QUESTS[this._goblinName][e](r,t),t.data?._elfStart&&await t.data._elfStart(r),"create"!==e||a||(a=this._goblinId),a&&(c=!!a._QUEST_CANCELED_,d=!!a._QUEST_FIREANDFORGET_),"warehouse"!==this.goblinName&&"delete"!==e&&!c){if("create"===e&&!s&&!n)throw new Error(`Fatal error ${t.topic} missing 'parent' parameter`);let o=this.getState().state;if(0===o.size&&(o=Shredder.fromJS({id:this._goblinId})),!o.has("id")&&!n)throw new Error(`Fatal error missing property id in ${this._goblinId}`);const a={branch:this._goblinId,data:o,feeds:r.getDesktop(!0)};if(("create"===e||n)&&(a.parents=s||this._goblinId,!r.hasDispatched&&!n))throw new Error(`Your forgot to call quest.do() in create quest of ${this.goblinName}`);if(r.hasDispatched){if(!i&&0===this.TTL&&this._goblinConfig&&this._goblinConfig.cacheSize>0){await r.createCache(null);const e=Goblin.#d();await e.rank(this._goblinName,this._goblinId)}a._goblinHasDispatched=!0,await this.upsert(r,a)}}}catch(e){l=e}finally{if(await this.defers(r,e,r._deferrable),l||"delete"!==e||c||(await this.defers(r,e,this._deferrable),this._generationId===t.data.generation&&(Goblin.release(this.goblinName,this._goblinId),i.events.send(`<${this._goblinId}.deleted>`,{id:this._goblinId}))),"create"===e&&(l||c)&&await r.warehouse.deleteBranch({branch:this._goblinId}),!0===o&&await r.warehouse.delCreator({branch:this._goblinId}),"create"===e&&this._createMsgIdList.push({orcName:t.orcName,msgId:t.id,routing:i.events.routing,context:t.context}),!l&&!d)try{if("create"===e){this._isCreated=!0;for(let t=this._createMsgIdList.length-1;t>=0;--t){const{orcName:s,msgId:r,routing:n,context:o}=this._createMsgIdList[t];i.events.send(`${s}::${this.goblinName}.${e}.${r}.finished`,a,void 0,n,o)}}else i.events.send(`${this.goblinName}.${e}.${t.id}.finished`,a)}catch(e){l=e}if(l){const s=l,n=s.stack||s,o=s.id||t.id;if(!d)if("create"===e)for(let t=this._createMsgIdList.length-1;t>=0;--t){const{orcName:r,msgId:n,routing:a,context:l}=this._createMsgIdList[t];i.events.send(`${r}::${this.goblinName}.${e}.${n}.error`,{id:o,code:s.code,name:s.name,message:s.message,stack:s.stack,info:s.info},void 0,a,l)}else i.events.send(`${this.goblinName}.${e}.${t.id}.error`,{id:o,code:s.code,name:s.name,message:s.message,stack:s.stack,info:s.info});"SILENT_HILL"!==s.code?(r.logCommandError(s,t),r.fail(`Error in the quest "${e}"`,n,"See ex.",n.stack||n.message||n)):r.log.warn(`Silent Hill: ${n.stack||n.message||n}`)}"create"===e&&(this._createMsgIdList=[])}}doQuest(e,t,i){return this._doQuest.bind(this,e,t,i)}}module.exports=Goblin,module.exports.SmartId=SmartId,module.exports.Shredder=Shredder,module.exports.skills=new Proxy({},{get:(e,t)=>{const i=Symbol.for(t);return guildEnforcer.skills.add(i),i}}),module.exports.ShieldedError=guildEnforcer.ShieldedError,module.exports.buildGuestFootprint=(e,t)=>{if("system"===e){const{appId:t,appMasterId:i,variantId:s}=require("xcraft-core-host");let r=t;i&&(r=i),s&&(r=`${r}-${s}`),e=`${e}@${r}`}const{guestHost:i,guestUser:s}=osInfo;return`guest@${SmartId.encode(s)}@${SmartId.encode(i)}@${e}@${t}`},module.exports.buildRemoteGuestFootprint=e=>{const{ip:t,socketId:i,zeppelinSessionId:s}=e;return`guest@passenger@${SmartId.encode(t)}@${s}@${i}`},module.exports.enroleUser=(e,t)=>guildEnforcer.enroleUser(t),module.exports.deroleUser=(e,t)=>{guildEnforcer.deroleUser(t)},module.exports.registerUser=e=>{guildEnforcer.registerUser(e)},module.exports.identifyUser=e=>{let t=null;if(e.context&&e.context._goblinUser)try{const[i]=e.context._goblinUser.split("@",1);"guest"!==i?t=guildEnforcer.getUser(i):(guildEnforcer.users[e.context._goblinUser]||guildEnforcer.addGuestUser(e.context._goblinUser),t=guildEnforcer.users[e.context._goblinUser]),t&&(t._goblinUser=e.context._goblinUser)}catch{t=null}if(!t){const e=Goblin.buildGuestFootprint("system","0");guildEnforcer.users[e]||guildEnforcer.addGuestUser(e),t=guildEnforcer.users[e],t._goblinUser=e}return t.getContext=()=>{const[e,i,s,r,n,o]=t._goblinUser.split("@",6);return{userId:e,local:i,domain:s,sessionType:r,sessionId:n,windowId:o}},t.lastAccess=Date.now(),t},module.exports.setUser=(e,t)=>{e&&"Quest"!==e.constructor.name&&(e=e.quest);const i={_goblinUser:t};return e.resp.msgContext=i,e.user=module.exports.identifyUser({context:i}),e.user},module.exports.dispose=()=>{const e=require("xcraft-core-log")("goblin-core");guildEnforcer.dispose();for(const t of GOBLINS.values())for(const i of t.values())try{i.dispose()}catch(t){e.warn(t.stack||t.message||t)}for(const{goblinConfig:e}of Object.values(CONFIGS))e.dispose&&e.dispose()},module.exports.createAction=createAction,module.exports.waitForHordesSync=async function(e){return new Promise((t=>{const i=e.sub("*::goblin.hordesSync-initialized",(async()=>{i(),t(!0)})),s=require("./sync/hordesSync.js")();let r=!0;const n=goblinConfig.actionsSync?.enable;if(n&&(r=s.initialized),r)i(),t(!0);else{const e=require("xcraft-core-etc")().load("xcraft-core-horde");e.hordes?.length?s.boot().then((e=>{!1===e&&(i(),t(!1))})):(i(),t(!0))}}))};const Elf=require("./elf/index.js");module.exports.Elf=Elf;
//# sourceMappingURL=/sm/da171b312e61d3258482a5a8a5dc9d91f7d702c4f6cab2e7e6bb6e96327f9544.map