@xuda.io/runtime-bundle 1.0.930 → 1.0.932

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- export class XudaModule{constructor(e){this.func=e.func;this.glb=e.glb;this.SESSION_OBJ=e.SESSION_OBJ;this.SESSION_ID=e.SESSION_ID;this.APP_OBJ=e.APP_OBJ;this.dsSession=e.dsSession;this.job_id=e.job_id;this._session=this.SESSION_OBJ[this.SESSION_ID];return this}async get_field_value(field_id){if(!field_id){console.error("xu.getFieldValue: field_id cannot be empty");return false}let ret_get_value=await this.func.datasource.get_value(this.SESSION_ID,field_id,this.dsSession);if(!ret_get_value.found){console.error(`xu.getFieldValue: ${field_id} field not found`);return false}return ret_get_value.ret.value}async set_field_value(field_id,value,avoid_refresh){if(!field_id){console.error("xu.setFieldValue: field_id cannot be empty");return false}if(typeof value==="undefined"){console.error(`xu.setFieldValue: ${field_id} - value cannot be undefined`);return false}let ret_get_value=await this.func.datasource.get_value(this.SESSION_ID,field_id,this.dsSession);if(!ret_get_value.found){console.error(`xu.setFieldValue: ${field_id} field not found`);return false}let _ds=this._session.DS_GLB[ret_get_value.dsSessionP];const datasource_changes={[_ds.dsSession]:{[ret_get_value.currentRecordId]:{[field_id]:value}}};return await this.func.datasource.update(this.SESSION_ID,datasource_changes,null,avoid_refresh)}async invoke_event(event_id){if(!event_id){console.error("xu.invokeEvent: event_id cannot be empty");return false}let ds;for await(const[key,val]of Object.entries(Object.assign([],this._session.DS_GLB).reverse())){let ds_val=val;let ds_key=ds_val.dsSession;const _view_obj=await this.func.utils.VIEWS_OBJ.get(this.SESSION_ID,ds_val.prog_id);if(_.isEmpty(_view_obj.progEvents))continue;if(ds)break;for await(const[key,val]of Object.entries(_view_obj.progEvents)){if(val?.data?.type==="user_defined"&&val.data.event_name===event_id){ds=ds_key;break}}}if(typeof ds==="undefined"){this.reject("xu.invokeEvent error",`${event_id} event_id not found`,this.job_id);return false}return this.func.events.validate(this.SESSION_ID,"user_defined",ds,event_id)}async read_drive(filename,cb){try{const response=await fetch(`https://${this._session.domain}/workspace-drive/`+filename+"&"+this._session.gtp_token);if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.readDrive error",e,this.job_id)}}async write_drive(stream,filename,make_public,cb){var data={app_id:this._session.app_id,gtp_token:this._session.gtp_token,app_token:this._session.app_token,req_from_api:"true",public:make_public?"true":""};const form=new FormData;for(const[key,val]of Object.entries(data)){form.append(key,val)}form.append("file",stream,filename);try{const response=await fetch(this.func.common.get_url(this.SESSION_ID,"rpi","runtime_upload_file"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(form)});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.writeDrive error",e,this.job_id)}}resolve(cb,job_id){if(job_id){this.func.events.delete_job(this.SESSION_ID,job_id)}if(cb){cb()}}reject(msg,details,job_id){if(job_id){this.func.events.delete_job(this.SESSION_ID,job_id)}this.log("E",msg,details)}log(type,msg,details){this.func.utils.debug_report(this.SESSION_ID,msg,details,type)}alert(type,display,msg,details){this.func.utils.alerts.execute(this.SESSION_ID,type,display,details,msg)}async call_project_api(prog_id,params,cb){const _prog_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,prog_id);if(_prog_obj?.properties?.menuType!=="api"){return this.reject("xu.callApiProgram error",`${prog_id} is not an API program`,this.job_id)}if(this._session.engine_mode==="live_preview"||typeof IS_PROCESS_SERVER!=="undefined"){const ret=await this.func.datasource.prepare(this.SESSION_ID,prog_id,null,0,null,null,null,null,null,null,"api",null,null,null,params);try{const _ds=this._session.DS_GLB[ret.dsSessionP];if(typeof _ds.api_rendered_output==="undefined"||typeof _ds.tree_obj.apiOutput==="undefined"||!_ds.tree_obj.apiOutput){throw new Error("undefined api_rendered_output/apiOutput")}if(_ds.tree_obj.apiOutput==="json"){try{return JSON5.parse(_ds.api_rendered_output)}catch(err){console.error(err);return{}}}return _ds.api_rendered_output}catch(e){this.reject("xu.call_project_api error",e.message||e,this.job_id)}}if(["cms"].includes(this._session.engine_mode)){try{const response=await fetch(`https://${this._session.domain}/api`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({...params,...{prog_id:prog_id}})});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.get_table_data error",e,this.job_id)}}try{const response=await fetch(`https://${this._session.domain}/execute_api_program`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({...params,...{prog_id:prog_id}})});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.get_table_data error",e,this.job_id)}}async call_system_api(api_method,payload={},cb){try{let body={...{app_id:this._session.app_id,app_id_query:this._session.app_id,app_token:this._session.app_token},...payload};const response=await fetch(`https://${this._session.domain}/cpi/${api_method}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(body)});const json=await response.json();if(cb){return cb(json)}return json}catch(e){console.error(e);this.reject("xu.call_system_api error",e,this.job_id)}}async call_external_api(method,url,payload={},cb){try{let json={...{app_id:this._session.app_id,app_id_query:this._session.app_id,app_token:this._session.app_token},...payload};const response=await fetch(`https://${url}`,{method:method,headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(json)});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.call_external_api error",e,this.job_id)}}async call_javascript(prog_id,params={},evaluate=false){try{const module=await this.func.common.get_module(this.SESSION_ID,"xuda-event-javascript-module.mjs");const result=await module.call_javascript(this.SESSION_ID,this.job_id,{prog:prog_id,parameters:params},this.dsSession,evaluate);return result}catch(e){console.error(e);this.reject("xu.call_javascript error",e,this.job_id)}}async dbs_create(table_id,data,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsCreate error",`${table_id} is not a table`,this.job_id)}try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_create",{table_id:table_id,table_data:data});if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_create error",e,this.job_id)}}async dbs_read(table_id,selector={},fields=[],sort,limit=999,skip,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsRead error",`${table_id} is not a table`,this.job_id)}let data={fields:fields,table_id:table_id,dataSourceFilterModelType:"query",filterModelMongo:selector,limit:limit,skip:skip,sort:sort};try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_read",data);if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_read error",e,this.job_id)}}async dbs_update(table_id,row_id,data,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsUpdate error",`${table_id} is not a table`,this.job_id)}if(!row_id){return this.reject("xu.dbsDelete error",`row_id is a mandatory field`,this.job_id)}try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_update",{table_id:table_id,row_id:row_id,table_data:data});if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_update error",e,this.job_id)}}async dbs_delete(table_id,row_id,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsDelete error",`${table_id} is not a table`,this.job_id)}if(!row_id){return this.reject("xu.dbsDelete error",`row_id is a mandatory field`,this.job_id)}try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_delete",{table_id:table_id,ids:[row_id]});if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_delete error",e,this.job_id)}}}
1
+ export class XudaModule{constructor(e){this.func=e.func;this.glb=e.glb;this.SESSION_OBJ=e.SESSION_OBJ;this.SESSION_ID=e.SESSION_ID;this.APP_OBJ=e.APP_OBJ;this.dsSession=e.dsSession;this.job_id=e.job_id;this._session=this.SESSION_OBJ[this.SESSION_ID];return this}async get_field_value(field_id){if(!field_id){console.error("xu.getFieldValue: field_id cannot be empty");return false}let ret_get_value=await this.func.datasource.get_value(this.SESSION_ID,field_id,this.dsSession);if(!ret_get_value.found){console.error(`xu.getFieldValue: ${field_id} field not found`);return false}return ret_get_value.ret.value}async set_field_value(field_id,value,avoid_refresh){if(!field_id){console.error("xu.setFieldValue: field_id cannot be empty");return false}if(typeof value==="undefined"){console.error(`xu.setFieldValue: ${field_id} - value cannot be undefined`);return false}let ret_get_value=await this.func.datasource.get_value(this.SESSION_ID,field_id,this.dsSession);if(!ret_get_value.found){console.error(`xu.setFieldValue: ${field_id} field not found`);return false}let _ds=this._session.DS_GLB[ret_get_value.dsSessionP];const datasource_changes={[_ds.dsSession]:{[ret_get_value.currentRecordId]:{[field_id]:value}}};return await this.func.datasource.update(this.SESSION_ID,datasource_changes,null,avoid_refresh)}async invoke_event(event_id){if(!event_id){console.error("xu.invokeEvent: event_id cannot be empty");return false}let ds;for await(const[key,val]of Object.entries(Object.assign([],this._session.DS_GLB).reverse())){let ds_val=val;let ds_key=ds_val.dsSession;const _view_obj=await this.func.utils.VIEWS_OBJ.get(this.SESSION_ID,ds_val.prog_id);if(_.isEmpty(_view_obj.progEvents))continue;if(ds)break;for await(const[key,val]of Object.entries(_view_obj.progEvents)){if(val?.data?.type==="user_defined"&&val.data.event_name===event_id){ds=ds_key;break}}}if(typeof ds==="undefined"){this.reject("xu.invokeEvent error",`${event_id} event_id not found`,this.job_id);return false}return this.func.events.validate(this.SESSION_ID,"user_defined",ds,event_id)}async read_drive(filename,cb){try{const response=await fetch(`https://${this._session.domain}/workspace-drive/`+filename+"&"+this._session.gtp_token);if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.readDrive error",e,this.job_id)}}async write_drive(stream,filename,make_public,cb){var data={app_id:this._session.app_id,gtp_token:this._session.gtp_token,app_token:this._session.app_token,req_from_api:"true",public:make_public?"true":""};const form=new FormData;for(const[key,val]of Object.entries(data)){form.append(key,val)}form.append("file",stream,filename);try{const response=await fetch(this.func.common.get_url(this.SESSION_ID,"rpi","runtime_upload_file"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(form)});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.writeDrive error",e,this.job_id)}}resolve(cb,job_id){if(job_id){this.func.events.delete_job(this.SESSION_ID,job_id)}if(cb){cb()}}reject(msg,details,job_id){if(job_id){this.func.events.delete_job(this.SESSION_ID,job_id)}this.log("E",msg,details)}log(type,msg,details){this.func.utils.debug_report(this.SESSION_ID,msg,details,type)}alert(type,display,msg,details){this.func.utils.alerts.execute(this.SESSION_ID,type,display,details,msg)}async call_project_api(prog_id,params,cb){const _prog_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,prog_id);if(_prog_obj?.properties?.menuType!=="api"){return this.reject("xu.callApiProgram error",`${prog_id} is not an API program`,this.job_id)}if(this._session.engine_mode==="live_preview"||typeof IS_PROCESS_SERVER!=="undefined"){const ret=await this.func.datasource.prepare(this.SESSION_ID,prog_id,null,0,null,null,null,null,null,null,"api",null,null,null,params);try{const _ds=this._session.DS_GLB[ret.dsSessionP];if(typeof _ds.api_rendered_output==="undefined"||typeof _ds.tree_obj.apiOutput==="undefined"||!_ds.tree_obj.apiOutput){throw new Error("undefined api_rendered_output/apiOutput")}if(_ds.tree_obj.apiOutput==="json"){try{return JSON5.parse(_ds.api_rendered_output)}catch(err){console.error(err);return{}}}return _ds.api_rendered_output}catch(e){this.reject("xu.call_project_api error",e.message||e,this.job_id)}}if(["miniapp"].includes(this._session.engine_mode)){try{const response=await fetch(`https://${this._session.domain}/api`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({...params,...{prog_id:prog_id}})});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.get_table_data error",e,this.job_id)}}try{const response=await fetch(`https://${this._session.domain}/execute_api_program`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({...params,...{prog_id:prog_id}})});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.get_table_data error",e,this.job_id)}}async call_system_api(api_method,payload={},cb){try{let body={...{app_id:this._session.app_id,app_id_query:this._session.app_id,app_token:this._session.app_token},...payload};const response=await fetch(`https://${this._session.domain}/cpi/${api_method}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(body)});const json=await response.json();if(cb){return cb(json)}return json}catch(e){console.error(e);this.reject("xu.call_system_api error",e,this.job_id)}}async call_external_api(method,url,payload={},cb){try{let json={...{app_id:this._session.app_id,app_id_query:this._session.app_id,app_token:this._session.app_token},...payload};const response=await fetch(`https://${url}`,{method:method,headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(json)});if(cb){return cb(await response.json())}return await response.json()}catch(e){console.error(e);this.reject("xu.call_external_api error",e,this.job_id)}}async call_javascript(prog_id,params={},evaluate=false){try{const module=await this.func.common.get_module(this.SESSION_ID,"xuda-event-javascript-module.mjs");const result=await module.call_javascript(this.SESSION_ID,this.job_id,{prog:prog_id,parameters:params},this.dsSession,evaluate);return result}catch(e){console.error(e);this.reject("xu.call_javascript error",e,this.job_id)}}async dbs_create(table_id,data,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsCreate error",`${table_id} is not a table`,this.job_id)}try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_create",{table_id:table_id,table_data:data});if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_create error",e,this.job_id)}}async dbs_read(table_id,selector={},fields=[],sort,limit=999,skip,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsRead error",`${table_id} is not a table`,this.job_id)}let data={fields:fields,table_id:table_id,dataSourceFilterModelType:"query",filterModelMongo:selector,limit:limit,skip:skip,sort:sort};try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_read",data);if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_read error",e,this.job_id)}}async dbs_update(table_id,row_id,data,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsUpdate error",`${table_id} is not a table`,this.job_id)}if(!row_id){return this.reject("xu.dbsDelete error",`row_id is a mandatory field`,this.job_id)}try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_update",{table_id:table_id,row_id:row_id,table_data:data});if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_update error",e,this.job_id)}}async dbs_delete(table_id,row_id,cb){const _table_obj=await this.func.utils.DOCS_OBJ.get(this.SESSION_ID,table_id);if(_table_obj?.properties?.menuType!=="table"){return this.reject("xu.dbsDelete error",`${table_id} is not a table`,this.job_id)}if(!row_id){return this.reject("xu.dbsDelete error",`row_id is a mandatory field`,this.job_id)}try{const ret=await this.func.common.db(this.SESSION_ID,"dbs_delete",{table_id:table_id,ids:[row_id]});if(cb){return cb(ret)}return ret}catch(e){console.error(e);this.reject("xu.dbs_delete error",e,this.job_id)}}}
@@ -195,8 +195,8 @@ export class XudaModule {
195
195
  }
196
196
  }
197
197
 
198
- // cms
199
- if (['cms'].includes(this._session.engine_mode)) {
198
+ // miniapp
199
+ if (['miniapp'].includes(this._session.engine_mode)) {
200
200
  try {
201
201
  const response = await fetch(`https://${this._session.domain}/api`, {
202
202
  method: 'POST',
@@ -1 +1 @@
1
- const _this={};export const init_module=async e=>{_this.func=e.func;_this.glb=e.glb;_this.SESSION_OBJ=e.SESSION_OBJ;_this.APP_OBJ=e.APP_OBJ;_this.IS_DOCKER=e.IS_DOCKER;_this.IS_API_SERVER=e.IS_API_SERVER;_this.IS_PROCESS_SERVER=e.IS_PROCESS_SERVER;if(!_this.xuda_dbs_plugin&&typeof _this.IS_DOCKER==="undefined"&&typeof _this.IS_PROCESS_SERVER==="undefined"&&typeof _this.IS_API_SERVER==="undefined"){await init_xuda_dbs_plugin(e.SESSION_ID)}_this.db_replication_store;_this.db_changes_store;_this.db_replication_from_stat=3;_this.db_replication_to_stat=3};export let _db={};_db.save_data=async function(SESSION_ID,dsSessionP,keyP){var db_driver=await this.get_db_driver(SESSION_ID,dsSessionP);if(db_driver==="pouchdb"&&_this.glb.IS_WORKER){var callback_id=_this.func.utils.set_callback_queue(SESSION_ID,callbackP);var obj=_this.func.utils.clean_returned_datasource(SESSION_ID,dsSessionP);return _this.func.utils.post_back_to_client(SESSION_ID,"execute_local_sava_data",_this.SESSION_OBJ[SESSION_ID].worker_id,{ds_obj:obj,dsSessionP:dsSessionP,keyP:keyP,callback_id:callback_id})}_db.save_indicator(SESSION_ID,true);var _ds=_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];let _view_obj=await _this.func.utils.VIEWS_OBJ.get(SESSION_ID,_ds.prog_id);var dataSourceTableId=_view_obj?.progDataSource?.dataSourceTableId;if(!dataSourceTableId){_db.save_indicator(SESSION_ID,false);_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0105");return}var db_driver=await _db.get_db_driver(SESSION_ID,dsSessionP);let table_ret=await _this.func.utils.FILES_OBJ.get(SESSION_ID,dataSourceTableId);if(!table_ret.tableIndexes||_.isEmpty(table_ret.tableIndexes)){_db.save_indicator(SESSION_ID,false);_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0104");return}if(!_ds.data_feed.rows){return console.error("data_feed rows is empty")}const clean_virtual_fields=async function(table_id,data){let table_obj=await func.utils.VIEWS_OBJ.get(SESSION_ID,table_id);var data_obj={};for(const[key,val]of Object.entries(data)){const _tableFieldsObj=func.common.find_item_by_key(table_obj.tableFields,"field_id",key);if(_tableFieldsObj){data_obj[key]=val}}return data_obj};let save_ret;if(_view_obj.properties.menuType==="component"){if(_view_obj?.properties?.rwMode!=="U"){return _this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0126")}let data={prog_id:_ds.prog_id};if(_ds.data_feed.rows_added?.length){if(!_view_obj?.properties?.allowCreate){_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0120")}_.forEach(_ds.data_feed.rows_added,function(val,key){data[key]=val});delete _ds.data_feed.rows_added["newRecord"];save_ret=await _this.func.common.db(SESSION_ID,"dbs_create",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data.id,table_id:dataSourceTableId});return save_ret}if(_ds.data_feed.rows_deleted?.length){data.table_id=_ds._dataSourceTableId;data.ids=[];for await(const[key,val]of Object.entries(_ds.data_feed.rows_deleted)){data.ids.push(val);try{const row_idx=func.common.find_ROWID_idx(_ds,val);delete _ds.data_feed.rows[row_idx]}catch(error){}}_ds.data_feed.rows_deleted=[];save_ret=await _this.func.common.db(SESSION_ID,"dbs_delete",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId});return save_ret}if(_ds.data_feed.rows_changed?.length){for await(const[key,row_id]of Object.entries(_ds.data_feed.rows_changed)){if(row_id==="datasource_main")continue;let data={prog_id:_ds.prog_id};try{const row_idx=func.common.find_ROWID_idx(_ds,row_id);data.table_data=await clean_virtual_fields(_ds._dataSourceTableId,_ds.data_feed.rows[row_idx])}catch(err){console.error(err)}data.table_id=_ds._dataSourceTableId;data.row_id=row_id;save_ret=await _this.func.common.db(SESSION_ID,"dbs_update",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId})}return save_ret}return}if(_view_obj.properties.menuType!=="set_data"){return _this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0126")}var mode=_ds.set_mode;if(!mode||mode==="U"){let data={prog_id:_ds.prog_id};data.table_id=_ds._dataSourceTableId;data.row_id=_ds.currentRecordId;data.table_data={};try{const row_idx=func.common.find_ROWID_idx(_ds,_ds.currentRecordId);data.table_data=await clean_virtual_fields(_ds._dataSourceTableId,_ds.data_feed.rows[row_idx])}catch(err){console.error(err)}save_ret=await _this.func.common.db(SESSION_ID,"dbs_update",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId})}if(mode==="D"){let data={prog_id:_ds.prog_id};data.table_id=_ds._dataSourceTableId;data.ids=[_ds.currentRecordId];save_ret=await _this.func.common.db(SESSION_ID,"dbs_delete",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId});return save_ret}if(mode==="C"){if(_view_obj.properties.crudMode!=="C"&&_view_obj.properties.crudMode==="U"&&!_view_obj.properties.allowCreate){return _this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0120")}let data={prog_id:_ds.prog_id};data.table_id=_ds._dataSourceTableId;try{const row_idx=func.common.find_ROWID_idx(_ds,_ds.currentRecordId);data.table_data=_ds.data_feed.rows[row_idx];save_ret=await _this.func.common.db(SESSION_ID,"dbs_create",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data.id,table_id:dataSourceTableId});return save_ret}catch(err){console.error(err)}}};_db.get_db_driver=async function(SESSION_ID,dsSessionP){var db_driver;if(dsSessionP){var _ds=_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];let _view_obj=await _this.func.utils.VIEWS_OBJ.get(SESSION_ID,_ds.prog_id);var dataSourceTableId=_view_obj?.progDataSource?.dataSourceTableId;if(!dataSourceTableId){_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0105");return}let file_ret=await _this.func.utils.FILES_OBJ.get(SESSION_ID,dataSourceTableId);db_driver=file_ret.properties.db_driver||"xuda"}if(_this.SESSION_OBJ[SESSION_ID].engine_mode==="live_preview"&&!db_driver&&_this.SESSION_OBJ[SESSION_ID].app_id==="temp"){db_driver="pouchdb"}return db_driver};_db.get_query=async function(SESSION_ID,table_id,queryP,dsSessionP,viewSourceDescP,sourceP,reduceP,skipP,limitP,countP,idsP,sortModel,sort_dir,filterModel={filterModelNative:filterModelNative,filterModelMongo:filterModelMongo,filterModelSql:filterModelSql,filterModelUserMongo:filterModelUserMongo,filterModelUserSql:filterModelUserSql},dataSourceFilterModelType="index",total_fields_info){const get_fields=async function(_ds){var fields=[];const _view_obj=await _this.func.utils.VIEWS_OBJ.get(SESSION_ID,_ds.prog_id);if(_view_obj.progFields){for(let val of _view_obj.progFields){if(val.data.type==="table"){fields.push(val.data.field_id)}}}return fields};const run_local=async function(){if(!_this.SESSION_OBJ[SESSION_ID])return;if(!_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP])return;var ds=_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];var v=ds.v;var query_string;if(queryP.indexId){if(countP&&queryP.desc){query_string=`startkey=${JSON.stringify(queryP.endkey)}&endkey=${JSON.stringify(queryP.startkey)}`}else{query_string=`startkey=${JSON.stringify(queryP.startkey)}&endkey=${JSON.stringify(queryP.endkey)}&desc=${queryP.desc}`}}else{query_string="key="+queryP.table_id}var db_driver=await _db.get_db_driver(SESSION_ID,dsSessionP);var fields_arr=await get_fields(ds);const response={success:async function(json){if(dsSessionP&&!_this.SESSION_OBJ[SESSION_ID]?.DS_GLB?.[dsSessionP]){return}if(json.code<0){response.error(json.data);return}var data=json.data;if(dsSessionP)_this.func.utils.debug.log(SESSION_ID,ds._dataSourceTableId,{module:ds.viewModule,action:"read",prop:sourceP,details:query_string,result:data.rows?data.rows.length:0,error:null,source:viewSourceDescP,json:data,fields:_.assignIn(ds.locate_from,ds.locate_to),type:"file",dsSession:dsSessionP});return data},error:async function(err){if(dsSessionP&&!ds)return;if(dsSessionP){var err_msg=err&&err.data?err.data:err;_this.func.utils.debug.log(SESSION_ID,_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP]._dataSourceTableId,{module:ds.viewModule,action:"read",prop:sourceP,details:query_string,result:null,error:err_msg,source:viewSourceDescP,json:null,fields:_.assignIn(ds.locate_from,ds.locate_to),type:"file",dsSession:dsSessionP})}_this.func.utils.debug_report(SESSION_ID,"datasource couchDB query "+sourceP,err_msg,"E");return{rows:[],error:true}}};var data={desc:queryP.desc,indexId:queryP.indexId,key:queryP.table_id,reduce:reduceP,viewSourceDesc:viewSourceDescP,limit:limitP,skip:skipP,count:countP,ids:idsP,table_id:queryP.table_id,prog_id:ds.prog_id};data.filter_from=JSON.stringify(queryP.filter_from);data.filter_to=JSON.stringify(queryP.filter_to);data.sortOrder=queryP.sortOrder;data.table_id=queryP.table_id;data.startkey=JSON.stringify(queryP.startkey);data.endkey=JSON.stringify(queryP.endkey);if(countP&&queryP.desc){data.sortOrder="asc";data.startkey=JSON.stringify(queryP.endkey);data.endkey=JSON.stringify(queryP.startkey)}data.dataSourceFilterModelType=dataSourceFilterModelType;if(sortModel){data.sortModel=JSON.stringify(sortModel);data.sort_dir=sort_dir}if(!_.isEmpty(filterModel?.filterModelNative)){data.filterModelNative=JSON.stringify(filterModel.filterModelNative)}if(!_.isEmpty(filterModel?.filterModelMongo)){data.filterModelMongo=JSON.stringify(filterModel.filterModelMongo)}if(filterModel?.filterModelSql){data.filterModelSql=JSON.stringify(filterModel.filterModelSql)}if(!_.isEmpty(filterModel?.filterModelUserMongo)){data.filterModelUserMongo=JSON.stringify(filterModel.filterModelUserMongo)}if(filterModel?.filterModelUserSql){data.filterModelUserSql=JSON.stringify(filterModel.filterModelUserSql)}if(total_fields_info){data.total_fields_info=JSON.stringify(total_fields_info)}if(!reduceP&&!countP){data.fields=fields_arr}try{const json=await _this.func.common.db(SESSION_ID,"dbs_read",data,{node:true},dsSessionP);return await response.success(json)}catch(e){return await response.error(e?.message||e?.data||e)}};var db_driver=await this.get_db_driver(SESSION_ID,dsSessionP);if(db_driver==="pouchdb"&&_this.glb.IS_WORKER&&!_this.SESSION_OBJ[SESSION_ID].engine_mode==="live_preview"){var callback_id=_this.func.utils.set_callback_queue(SESSION_ID,callbackP);var obj=_this.func.utils.clean_returned_datasource(SESSION_ID,dsSessionP);return _this.func.utils.post_back_to_client(SESSION_ID,"execute_local_db_query",_this.SESSION_OBJ[SESSION_ID].worker_id,{ds_obj:obj,dsSessionP:dsSessionP,table_id:table_id,queryP:queryP,dsSessionP:dsSessionP,viewSourceDescP:viewSourceDescP,sourceP:sourceP,reduceP:reduceP,skipP:skipP,limitP:limitP,countP:countP,idsP:idsP,callback_id:callback_id})}return await run_local()};_db.utils={};_db.save_indicator=function(SESSION_ID,stateP){if(!_this.glb.IS_WORKER){_this.func.UI.utils.save(SESSION_ID,stateP)}};const init_xuda_dbs_plugin=async function(SESSION_ID){var _session=_this.SESSION_OBJ[SESSION_ID];const plugin_name="@xuda.io/xuda-dbs-plugin-xuda";const get_path=function(plugin_name,resource){var path=`https://${_session.domain}/plugins/${plugin_name}${resource?"/"+resource:""}?app_id=${_session.app_id}`;return path};try{_this.xuda_dbs_plugin=await import(get_path(plugin_name,"studio.mjs"));const db=await func.utils.connect_pouchdb(SESSION_ID);await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"create_design",{db:db})}catch(err){return console.error(err.message)}};_db.call_pouch_xuda_dbs_plugin=async function(SESSION_ID,method,params){return new Promise(async(resolve,reject)=>{try{if(params.e){params.table_obj=await func.utils.DOCS_OBJ.get(SESSION_ID,params.e.table_id)}await _this.xuda_dbs_plugin[method](params,resolve,reject)}catch(err){reject()}})};_db.pouch={};_db.pouch.dbs_read=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"read",{db:db,e:e})};_db.pouch.dbs_create=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"create",{db:db,e:e})};_db.pouch.dbs_delete=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"del",{db:db,e:e})};_db.pouch.dbs_update=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"update",{db:db,e:e})};_db.pouch.init_db_replication=async function(SESSION_ID){const db=await func.utils.connect_pouchdb(SESSION_ID);var _session=_this.SESSION_OBJ[SESSION_ID];if(_session.url_params.avoid_local||["live_preview","cms"].includes(_session.engine_mode)&&!_session.opt.enable_offline){return}const changes=db.changes({live:true,include_docs:true}).on("change",function(change){if(!change.doc.udfData)return;func.UI.screen.refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:change.id,table_id:change.doc.udfData.udffileid})}).on("complete",function(info){console.log("complete",info)}).on("error",function(err){console.error(err)});set_replication_stat(SESSION_ID,null,3);const db_name=APP_OBJ[_session.app_id].app_db_name;const rep=db.replicate.to(`https://${_session.domain}/db/${db_name}`,{selector:{docType:"database"},live:true,retry:true,fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}}).on("change",function(info){}).on("paused",function(err){if(err){return set_replication_stat(SESSION_ID,null,2)}set_replication_stat(SESSION_ID,null,3)}).on("active",function(){}).on("denied",function(err){set_replication_stat(SESSION_ID,null,2)}).on("complete",function(info){}).on("error",function(err){set_replication_stat(SESSION_ID,null,2)});_db.pouch.set_db_replication_from_server(SESSION_ID)};_db.pouch.set_db_replication_from_server=async function(SESSION_ID){const db=await func.utils.connect_pouchdb(SESSION_ID);const rep_docs=await _db.pouch.get_replications(SESSION_ID);const _session=_this.SESSION_OBJ[SESSION_ID];const db_name=APP_OBJ[_session.app_id].app_db_name;const remote_db_url=`https://${_session.domain}/db/${db_name}`;const remote_db=new PouchDB(remote_db_url,{fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}});if(_this.db_changes_store){_this.db_changes_store.cancel()}const write_stat=async function(rep_id,stat,reason){try{let doc=await db.get(rep_id);doc.stat=stat;doc.stat_reason=reason;try{db.put(doc)}catch(err){}}catch(err){}};const download_documents=async function(rep_doc){await write_stat(rep_doc._id,2);const remote_db=new PouchDB(remote_db_url,{fetch:function(url,opts){opts.headers.set("xu-prog_id",rep_doc.prog_id);if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}});const ret=await remote_db.find({selector:rep_doc.selector,fields:["_id"],limit:9999999999});if(ret?.code<0){return func.utils.debug_report(SESSION_ID,"download_documents",ret.data,"E")}try{var doc_ids=[];for await(let doc of ret.docs){doc_ids.push(doc._id)}db.replicate.from(remote_db_url,{doc_ids:doc_ids,retry:true,style:"main_only",fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}}).on("paused",async function(err){if(err){return}const read_ret=await _db.pouch.dbs_read(SESSION_ID,rep_doc.e);await write_stat(rep_doc._id,3)})}catch(err){await write_stat(rep_doc._id,2,err.message);console.error("replication from error",err)}};let filter_tables=[];for(let doc of rep_docs){if(!filter_tables.includes(doc.table_id))filter_tables.push(doc.table_id);if(doc.stat<3)await download_documents(doc)}try{_this.db_changes_store=remote_db.changes({since:"now",live:true,timeout:3e5,style:"main_only",include_docs:false}).on("change",async function(change){if(change.id.substr(0,4)!=="dbs-")return;if(_this.db_replication_from_stat!==3){set_replication_stat(SESSION_ID,3)}try{const existing_doc=await db.get(change.id);db.replicate.from(remote_db_url,{doc_ids:[change.id],retry:true,style:"main_only",fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}})}catch(err){try{const table_id=change.id.split("_")[0].substr(4);for(let doc of rep_docs){if(doc.table_id===table_id){download_documents(doc)}}}catch(err){console.warn(err)}}}).on("complete",function(info){}).on("error",function(err){console.error(err);set_replication_stat(SESSION_ID,2);_this.db_changes_store.cancel()})}catch(err){console.error(err)}return};_db.pouch.remove_db_replication_from_server=async function(SESSION_ID,rep_id){const db=await func.utils.connect_pouchdb(SESSION_ID);try{const doc=await db.get(rep_id);db.remove(doc)}catch(error){}};_db.pouch.get_replications=async function(SESSION_ID=Object.keys(SESSION_OBJ)[0]){const db=await func.utils.connect_pouchdb(SESSION_ID);let ret=await db.find({selector:{docType:"rep_request"}});return ret.docs};_db.pouch.get_replication_stat=async function(SESSION_ID){const _session=_this.SESSION_OBJ[SESSION_ID];return _session?.DS_GLB?.[0]?.data_system?.SYS_GLOBAL_BOL_REPLICATION_STAT};const set_replication_stat=async function(SESSION_ID,from_stat,to_stat){var _session=_this.SESSION_OBJ[SESSION_ID];if(!_session?.DS_GLB?.[0]){return setTimeout(function(){set_replication_stat(SESSION_ID,from_stat,to_stat)},1e3)}if(from_stat)_this.db_replication_from_stat=from_stat;if(to_stat)_this.db_replication_to_stat=to_stat;var data={};if(_this.db_replication_from_stat===3&&_this.db_replication_to_stat===3){data.SYS_GLOBAL_BOL_REPLICATION_STAT=1;console.info("Replication On")}else{data.SYS_GLOBAL_BOL_REPLICATION_STAT=0;console.info("Replication Off")}var datasource_changes={[0]:{["data_system"]:data}};await func.datasource.update(SESSION_ID,datasource_changes)};const refresh_document_changes_for_realtime_update=function(SESSION_ID,doc_change){var _session=_this.SESSION_OBJ[SESSION_ID];if(glb.IS_WORKER){return func.utils.post_back_to_client(SESSION_ID,"refresh_document_changes_for_realtime_update",_session.worker_id,{doc_change:doc_change})}func.UI.screen.refresh_document_changes_for_realtime_update(SESSION_ID,doc_change)};
1
+ const _this={};export const init_module=async e=>{_this.func=e.func;_this.glb=e.glb;_this.SESSION_OBJ=e.SESSION_OBJ;_this.APP_OBJ=e.APP_OBJ;_this.IS_DOCKER=e.IS_DOCKER;_this.IS_API_SERVER=e.IS_API_SERVER;_this.IS_PROCESS_SERVER=e.IS_PROCESS_SERVER;if(!_this.xuda_dbs_plugin&&typeof _this.IS_DOCKER==="undefined"&&typeof _this.IS_PROCESS_SERVER==="undefined"&&typeof _this.IS_API_SERVER==="undefined"){await init_xuda_dbs_plugin(e.SESSION_ID)}_this.db_replication_store;_this.db_changes_store;_this.db_replication_from_stat=3;_this.db_replication_to_stat=3};export let _db={};_db.save_data=async function(SESSION_ID,dsSessionP,keyP){var db_driver=await this.get_db_driver(SESSION_ID,dsSessionP);if(db_driver==="pouchdb"&&_this.glb.IS_WORKER){var callback_id=_this.func.utils.set_callback_queue(SESSION_ID,callbackP);var obj=_this.func.utils.clean_returned_datasource(SESSION_ID,dsSessionP);return _this.func.utils.post_back_to_client(SESSION_ID,"execute_local_sava_data",_this.SESSION_OBJ[SESSION_ID].worker_id,{ds_obj:obj,dsSessionP:dsSessionP,keyP:keyP,callback_id:callback_id})}_db.save_indicator(SESSION_ID,true);var _ds=_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];let _view_obj=await _this.func.utils.VIEWS_OBJ.get(SESSION_ID,_ds.prog_id);var dataSourceTableId=_view_obj?.progDataSource?.dataSourceTableId;if(!dataSourceTableId){_db.save_indicator(SESSION_ID,false);_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0105");return}var db_driver=await _db.get_db_driver(SESSION_ID,dsSessionP);let table_ret=await _this.func.utils.FILES_OBJ.get(SESSION_ID,dataSourceTableId);if(!table_ret.tableIndexes||_.isEmpty(table_ret.tableIndexes)){_db.save_indicator(SESSION_ID,false);_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0104");return}if(!_ds.data_feed.rows){return console.error("data_feed rows is empty")}const clean_virtual_fields=async function(table_id,data){let table_obj=await func.utils.VIEWS_OBJ.get(SESSION_ID,table_id);var data_obj={};for(const[key,val]of Object.entries(data)){const _tableFieldsObj=func.common.find_item_by_key(table_obj.tableFields,"field_id",key);if(_tableFieldsObj){data_obj[key]=val}}return data_obj};let save_ret;if(_view_obj.properties.menuType==="component"){if(_view_obj?.properties?.rwMode!=="U"){return _this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0126")}let data={prog_id:_ds.prog_id};if(_ds.data_feed.rows_added?.length){if(!_view_obj?.properties?.allowCreate){_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0120")}_.forEach(_ds.data_feed.rows_added,function(val,key){data[key]=val});delete _ds.data_feed.rows_added["newRecord"];save_ret=await _this.func.common.db(SESSION_ID,"dbs_create",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data.id,table_id:dataSourceTableId});return save_ret}if(_ds.data_feed.rows_deleted?.length){data.table_id=_ds._dataSourceTableId;data.ids=[];for await(const[key,val]of Object.entries(_ds.data_feed.rows_deleted)){data.ids.push(val);try{const row_idx=func.common.find_ROWID_idx(_ds,val);delete _ds.data_feed.rows[row_idx]}catch(error){}}_ds.data_feed.rows_deleted=[];save_ret=await _this.func.common.db(SESSION_ID,"dbs_delete",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId});return save_ret}if(_ds.data_feed.rows_changed?.length){for await(const[key,row_id]of Object.entries(_ds.data_feed.rows_changed)){if(row_id==="datasource_main")continue;let data={prog_id:_ds.prog_id};try{const row_idx=func.common.find_ROWID_idx(_ds,row_id);data.table_data=await clean_virtual_fields(_ds._dataSourceTableId,_ds.data_feed.rows[row_idx])}catch(err){console.error(err)}data.table_id=_ds._dataSourceTableId;data.row_id=row_id;save_ret=await _this.func.common.db(SESSION_ID,"dbs_update",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId})}return save_ret}return}if(_view_obj.properties.menuType!=="set_data"){return _this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0126")}var mode=_ds.set_mode;if(!mode||mode==="U"){let data={prog_id:_ds.prog_id};data.table_id=_ds._dataSourceTableId;data.row_id=_ds.currentRecordId;data.table_data={};try{const row_idx=func.common.find_ROWID_idx(_ds,_ds.currentRecordId);data.table_data=await clean_virtual_fields(_ds._dataSourceTableId,_ds.data_feed.rows[row_idx])}catch(err){console.error(err)}save_ret=await _this.func.common.db(SESSION_ID,"dbs_update",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId})}if(mode==="D"){let data={prog_id:_ds.prog_id};data.table_id=_ds._dataSourceTableId;data.ids=[_ds.currentRecordId];save_ret=await _this.func.common.db(SESSION_ID,"dbs_delete",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data?.id?.[0],table_id:dataSourceTableId});return save_ret}if(mode==="C"){if(_view_obj.properties.crudMode!=="C"&&_view_obj.properties.crudMode==="U"&&!_view_obj.properties.allowCreate){return _this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0120")}let data={prog_id:_ds.prog_id};data.table_id=_ds._dataSourceTableId;try{const row_idx=func.common.find_ROWID_idx(_ds,_ds.currentRecordId);data.table_data=_ds.data_feed.rows[row_idx];save_ret=await _this.func.common.db(SESSION_ID,"dbs_create",data,{},dsSessionP);refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:save_ret.data.id,table_id:dataSourceTableId});return save_ret}catch(err){console.error(err)}}};_db.get_db_driver=async function(SESSION_ID,dsSessionP){var db_driver;if(dsSessionP){var _ds=_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];let _view_obj=await _this.func.utils.VIEWS_OBJ.get(SESSION_ID,_ds.prog_id);var dataSourceTableId=_view_obj?.progDataSource?.dataSourceTableId;if(!dataSourceTableId){_this.func.utils.alerts.invoke(SESSION_ID,"system_msg","SYS_MSG_0105");return}let file_ret=await _this.func.utils.FILES_OBJ.get(SESSION_ID,dataSourceTableId);db_driver=file_ret.properties.db_driver||"xuda"}if(_this.SESSION_OBJ[SESSION_ID].engine_mode==="live_preview"&&!db_driver&&_this.SESSION_OBJ[SESSION_ID].app_id==="temp"){db_driver="pouchdb"}return db_driver};_db.get_query=async function(SESSION_ID,table_id,queryP,dsSessionP,viewSourceDescP,sourceP,reduceP,skipP,limitP,countP,idsP,sortModel,sort_dir,filterModel={filterModelNative:filterModelNative,filterModelMongo:filterModelMongo,filterModelSql:filterModelSql,filterModelUserMongo:filterModelUserMongo,filterModelUserSql:filterModelUserSql},dataSourceFilterModelType="index",total_fields_info){const get_fields=async function(_ds){var fields=[];const _view_obj=await _this.func.utils.VIEWS_OBJ.get(SESSION_ID,_ds.prog_id);if(_view_obj.progFields){for(let val of _view_obj.progFields){if(val.data.type==="table"){fields.push(val.data.field_id)}}}return fields};const run_local=async function(){if(!_this.SESSION_OBJ[SESSION_ID])return;if(!_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP])return;var ds=_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP];var v=ds.v;var query_string;if(queryP.indexId){if(countP&&queryP.desc){query_string=`startkey=${JSON.stringify(queryP.endkey)}&endkey=${JSON.stringify(queryP.startkey)}`}else{query_string=`startkey=${JSON.stringify(queryP.startkey)}&endkey=${JSON.stringify(queryP.endkey)}&desc=${queryP.desc}`}}else{query_string="key="+queryP.table_id}var db_driver=await _db.get_db_driver(SESSION_ID,dsSessionP);var fields_arr=await get_fields(ds);const response={success:async function(json){if(dsSessionP&&!_this.SESSION_OBJ[SESSION_ID]?.DS_GLB?.[dsSessionP]){return}if(json.code<0){response.error(json.data);return}var data=json.data;if(dsSessionP)_this.func.utils.debug.log(SESSION_ID,ds._dataSourceTableId,{module:ds.viewModule,action:"read",prop:sourceP,details:query_string,result:data.rows?data.rows.length:0,error:null,source:viewSourceDescP,json:data,fields:_.assignIn(ds.locate_from,ds.locate_to),type:"file",dsSession:dsSessionP});return data},error:async function(err){if(dsSessionP&&!ds)return;if(dsSessionP){var err_msg=err&&err.data?err.data:err;_this.func.utils.debug.log(SESSION_ID,_this.SESSION_OBJ[SESSION_ID].DS_GLB[dsSessionP]._dataSourceTableId,{module:ds.viewModule,action:"read",prop:sourceP,details:query_string,result:null,error:err_msg,source:viewSourceDescP,json:null,fields:_.assignIn(ds.locate_from,ds.locate_to),type:"file",dsSession:dsSessionP})}_this.func.utils.debug_report(SESSION_ID,"datasource couchDB query "+sourceP,err_msg,"E");return{rows:[],error:true}}};var data={desc:queryP.desc,indexId:queryP.indexId,key:queryP.table_id,reduce:reduceP,viewSourceDesc:viewSourceDescP,limit:limitP,skip:skipP,count:countP,ids:idsP,table_id:queryP.table_id,prog_id:ds.prog_id};data.filter_from=JSON.stringify(queryP.filter_from);data.filter_to=JSON.stringify(queryP.filter_to);data.sortOrder=queryP.sortOrder;data.table_id=queryP.table_id;data.startkey=JSON.stringify(queryP.startkey);data.endkey=JSON.stringify(queryP.endkey);if(countP&&queryP.desc){data.sortOrder="asc";data.startkey=JSON.stringify(queryP.endkey);data.endkey=JSON.stringify(queryP.startkey)}data.dataSourceFilterModelType=dataSourceFilterModelType;if(sortModel){data.sortModel=JSON.stringify(sortModel);data.sort_dir=sort_dir}if(!_.isEmpty(filterModel?.filterModelNative)){data.filterModelNative=JSON.stringify(filterModel.filterModelNative)}if(!_.isEmpty(filterModel?.filterModelMongo)){data.filterModelMongo=JSON.stringify(filterModel.filterModelMongo)}if(filterModel?.filterModelSql){data.filterModelSql=JSON.stringify(filterModel.filterModelSql)}if(!_.isEmpty(filterModel?.filterModelUserMongo)){data.filterModelUserMongo=JSON.stringify(filterModel.filterModelUserMongo)}if(filterModel?.filterModelUserSql){data.filterModelUserSql=JSON.stringify(filterModel.filterModelUserSql)}if(total_fields_info){data.total_fields_info=JSON.stringify(total_fields_info)}if(!reduceP&&!countP){data.fields=fields_arr}try{const json=await _this.func.common.db(SESSION_ID,"dbs_read",data,{node:true},dsSessionP);return await response.success(json)}catch(e){return await response.error(e?.message||e?.data||e)}};var db_driver=await this.get_db_driver(SESSION_ID,dsSessionP);if(db_driver==="pouchdb"&&_this.glb.IS_WORKER&&!_this.SESSION_OBJ[SESSION_ID].engine_mode==="live_preview"){var callback_id=_this.func.utils.set_callback_queue(SESSION_ID,callbackP);var obj=_this.func.utils.clean_returned_datasource(SESSION_ID,dsSessionP);return _this.func.utils.post_back_to_client(SESSION_ID,"execute_local_db_query",_this.SESSION_OBJ[SESSION_ID].worker_id,{ds_obj:obj,dsSessionP:dsSessionP,table_id:table_id,queryP:queryP,dsSessionP:dsSessionP,viewSourceDescP:viewSourceDescP,sourceP:sourceP,reduceP:reduceP,skipP:skipP,limitP:limitP,countP:countP,idsP:idsP,callback_id:callback_id})}return await run_local()};_db.utils={};_db.save_indicator=function(SESSION_ID,stateP){if(!_this.glb.IS_WORKER){_this.func.UI.utils.save(SESSION_ID,stateP)}};const init_xuda_dbs_plugin=async function(SESSION_ID){var _session=_this.SESSION_OBJ[SESSION_ID];const plugin_name="@xuda.io/xuda-dbs-plugin-xuda";const get_path=function(plugin_name,resource){var path=`https://${_session.domain}/plugins/${plugin_name}${resource?"/"+resource:""}?app_id=${_session.app_id}`;return path};try{_this.xuda_dbs_plugin=await import(get_path(plugin_name,"studio.mjs"));const db=await func.utils.connect_pouchdb(SESSION_ID);await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"create_design",{db:db})}catch(err){return console.error(err.message)}};_db.call_pouch_xuda_dbs_plugin=async function(SESSION_ID,method,params){return new Promise(async(resolve,reject)=>{try{if(params.e){params.table_obj=await func.utils.DOCS_OBJ.get(SESSION_ID,params.e.table_id)}await _this.xuda_dbs_plugin[method](params,resolve,reject)}catch(err){reject()}})};_db.pouch={};_db.pouch.dbs_read=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"read",{db:db,e:e})};_db.pouch.dbs_create=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"create",{db:db,e:e})};_db.pouch.dbs_delete=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"del",{db:db,e:e})};_db.pouch.dbs_update=async function(SESSION_ID,e){const db=await func.utils.connect_pouchdb(SESSION_ID);return await _db.call_pouch_xuda_dbs_plugin(SESSION_ID,"update",{db:db,e:e})};_db.pouch.init_db_replication=async function(SESSION_ID){const db=await func.utils.connect_pouchdb(SESSION_ID);var _session=_this.SESSION_OBJ[SESSION_ID];if(_session.url_params.avoid_local||_session.engine_mode==="miniapp"||_session.engine_mode!=="live_preview"&&!_session.opt.enable_offline){return}const changes=db.changes({live:true,include_docs:true}).on("change",function(change){if(!change.doc.udfData)return;func.UI.screen.refresh_document_changes_for_realtime_update(SESSION_ID,{row_id:change.id,table_id:change.doc.udfData.udffileid})}).on("complete",function(info){console.log("complete",info)}).on("error",function(err){console.error(err)});set_replication_stat(SESSION_ID,null,3);const db_name=APP_OBJ[_session.app_id].app_db_name;const rep=db.replicate.to(`https://${_session.domain}/db/${db_name}`,{selector:{docType:"database"},live:true,retry:true,fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}}).on("change",function(info){}).on("paused",function(err){if(err){return set_replication_stat(SESSION_ID,null,2)}set_replication_stat(SESSION_ID,null,3)}).on("active",function(){}).on("denied",function(err){set_replication_stat(SESSION_ID,null,2)}).on("complete",function(info){}).on("error",function(err){set_replication_stat(SESSION_ID,null,2)});_db.pouch.set_db_replication_from_server(SESSION_ID)};_db.pouch.set_db_replication_from_server=async function(SESSION_ID){const db=await func.utils.connect_pouchdb(SESSION_ID);const rep_docs=await _db.pouch.get_replications(SESSION_ID);const _session=_this.SESSION_OBJ[SESSION_ID];const db_name=APP_OBJ[_session.app_id].app_db_name;const remote_db_url=`https://${_session.domain}/db/${db_name}`;const remote_db=new PouchDB(remote_db_url,{fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}});if(_this.db_changes_store){_this.db_changes_store.cancel()}const write_stat=async function(rep_id,stat,reason){try{let doc=await db.get(rep_id);doc.stat=stat;doc.stat_reason=reason;try{db.put(doc)}catch(err){}}catch(err){}};const download_documents=async function(rep_doc){await write_stat(rep_doc._id,2);const remote_db=new PouchDB(remote_db_url,{fetch:function(url,opts){opts.headers.set("xu-prog_id",rep_doc.prog_id);if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}});const ret=await remote_db.find({selector:rep_doc.selector,fields:["_id"],limit:9999999999});if(ret?.code<0){return func.utils.debug_report(SESSION_ID,"download_documents",ret.data,"E")}try{var doc_ids=[];for await(let doc of ret.docs){doc_ids.push(doc._id)}db.replicate.from(remote_db_url,{doc_ids:doc_ids,retry:true,style:"main_only",fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}}).on("paused",async function(err){if(err){return}const read_ret=await _db.pouch.dbs_read(SESSION_ID,rep_doc.e);await write_stat(rep_doc._id,3)})}catch(err){await write_stat(rep_doc._id,2,err.message);console.error("replication from error",err)}};let filter_tables=[];for(let doc of rep_docs){if(!filter_tables.includes(doc.table_id))filter_tables.push(doc.table_id);if(doc.stat<3)await download_documents(doc)}try{_this.db_changes_store=remote_db.changes({since:"now",live:true,timeout:3e5,style:"main_only",include_docs:false}).on("change",async function(change){if(change.id.substr(0,4)!=="dbs-")return;if(_this.db_replication_from_stat!==3){set_replication_stat(SESSION_ID,3)}try{const existing_doc=await db.get(change.id);db.replicate.from(remote_db_url,{doc_ids:[change.id],retry:true,style:"main_only",fetch:function(url,opts){if(_session.gtp_token){opts.headers.set("xu-gtp-token",_session.gtp_token)}if(_session.app_token)opts.headers.set("xu-app-token",_session.app_token);{opts.headers.set("xu-db",db_name)}return PouchDB.fetch(url,opts)}})}catch(err){try{const table_id=change.id.split("_")[0].substr(4);for(let doc of rep_docs){if(doc.table_id===table_id){download_documents(doc)}}}catch(err){console.warn(err)}}}).on("complete",function(info){}).on("error",function(err){console.error(err);set_replication_stat(SESSION_ID,2);_this.db_changes_store.cancel()})}catch(err){console.error(err)}return};_db.pouch.remove_db_replication_from_server=async function(SESSION_ID,rep_id){const db=await func.utils.connect_pouchdb(SESSION_ID);try{const doc=await db.get(rep_id);db.remove(doc)}catch(error){}};_db.pouch.get_replications=async function(SESSION_ID=Object.keys(SESSION_OBJ)[0]){const db=await func.utils.connect_pouchdb(SESSION_ID);let ret=await db.find({selector:{docType:"rep_request"}});return ret.docs};_db.pouch.get_replication_stat=async function(SESSION_ID){const _session=_this.SESSION_OBJ[SESSION_ID];return _session?.DS_GLB?.[0]?.data_system?.SYS_GLOBAL_BOL_REPLICATION_STAT};const set_replication_stat=async function(SESSION_ID,from_stat,to_stat){var _session=_this.SESSION_OBJ[SESSION_ID];if(!_session?.DS_GLB?.[0]){return setTimeout(function(){set_replication_stat(SESSION_ID,from_stat,to_stat)},1e3)}if(from_stat)_this.db_replication_from_stat=from_stat;if(to_stat)_this.db_replication_to_stat=to_stat;var data={};if(_this.db_replication_from_stat===3&&_this.db_replication_to_stat===3){data.SYS_GLOBAL_BOL_REPLICATION_STAT=1;console.info("Replication On")}else{data.SYS_GLOBAL_BOL_REPLICATION_STAT=0;console.info("Replication Off")}var datasource_changes={[0]:{["data_system"]:data}};await func.datasource.update(SESSION_ID,datasource_changes)};const refresh_document_changes_for_realtime_update=function(SESSION_ID,doc_change){var _session=_this.SESSION_OBJ[SESSION_ID];if(glb.IS_WORKER){return func.utils.post_back_to_client(SESSION_ID,"refresh_document_changes_for_realtime_update",_session.worker_id,{doc_change:doc_change})}func.UI.screen.refresh_document_changes_for_realtime_update(SESSION_ID,doc_change)};
@@ -580,7 +580,7 @@ _db.pouch.init_db_replication = async function (SESSION_ID) {
580
580
  const db = await func.utils.connect_pouchdb(SESSION_ID);
581
581
  var _session = _this.SESSION_OBJ[SESSION_ID];
582
582
 
583
- if (_session.url_params.avoid_local || (['live_preview', 'cms'].includes(_session.engine_mode) && !_session.opt.enable_offline)) {
583
+ if (_session.url_params.avoid_local || _session.engine_mode === 'miniapp' || (_session.engine_mode !== 'live_preview' && !_session.opt.enable_offline)) {
584
584
  return;
585
585
  }
586
586
 
@@ -1 +1 @@
1
- const _this={};export const init_module=e=>{_this.func=e.func;_this.glb=e.glb;_this.SESSION_OBJ=e.SESSION_OBJ;_this.APP_OBJ=e.APP_OBJ;_this.IS_DOCKER=e.IS_DOCKER;_this.IS_API_SERVER=e.IS_API_SERVER;_this.IS_PROCESS_SERVER=e.IS_PROCESS_SERVER};export const get_doc_from_studio=async function(SESSION_ID,app_id,idP){return new Promise(function(resolve,reject){var _session=_this.SESSION_OBJ[SESSION_ID];if(glb.IS_WORKER){func.utils.post_back_to_client(SESSION_ID,"get_doc_from_studio",_session.worker_id,{doc_id:idP});self.addEventListener("live_preview_get_obj_response_worker_"+idP,event=>{resolve(event.detail.data)})}else{STUDIO_PEER_CONN_SEND_METHOD({service:"get_doc_obj",data:{doc_id:idP},session_id:SESSION_ID,id:STUDIO_PEER.id,source:"runtime",app_id:app_id});$("body").on("live_preview_get_obj_response_"+idP,function(e,data){resolve(data.data);$("body").off("live_preview_get_obj_response_"+idP)})}})};export const get_doc_from_websocket=async function(SESSION_ID,app_id,idP){var _session=_this.SESSION_OBJ[SESSION_ID];return new Promise(function(resolve,reject){if(glb.IS_WORKER){func.utils.post_back_to_client(SESSION_ID,"get_doc_from_websocket",_session.worker_id,{doc_id:idP});self.addEventListener("get_doc_obj_from_build_worker_"+idP,event=>{resolve(event.detail.data)})}else{if(RUNTIME_SERVER_WEBSOCKET&&RUNTIME_SERVER_WEBSOCKET_CONNECTED){RUNTIME_SERVER_WEBSOCKET.emit("message",{service:"get_doc_obj_from_build",data:{doc_id:idP}});$("body").on("get_doc_obj_from_build_response_"+idP,(e,data)=>{resolve(data.data);$("body").off("get_doc_obj_from_build_response_"+idP)})}else{throw new Error("fail to fetch from ws websocket inactive")}}})};export const DOCS_OBJ_get=async function(SESSION_ID,idP){if(!idP)return;if(idP==="_empty_panel_program"){return{_id:"_empty_panel_program",properties:{menuName:"_empty_panel_program",menuTitle:"_empty_panel_program",menuType:"component",renderType:"form"},progUi:[{id:"node-empty_panel_program",tagName:"xu-single-view",children:[{id:"node-empty_panel_program-span",tagName:"span",children:[],content:"",type:"element",attributes:{}}],content:"",type:"element",attributes:{}}],progDataSource:{},progFields:[],progEvents:[]}}var _session=_this.SESSION_OBJ[SESSION_ID];const app_id=_session.app_id;var views_ret;if(_session.engine_mode==="live_preview"){return await get_doc_from_studio(SESSION_ID,app_id,idP)}if(glb.register_startup_programs){func.common.db(SESSION_ID,"register_startup_programs",{prog_id:idP,build_id:_session?.build_info?.build||0})}views_ret=await read_objects_cache(SESSION_ID,idP,"DOCS_OBJ");if(!views_ret){if(typeof _this.IS_DOCKER==="undefined"&&typeof _this.IS_PROCESS_SERVER==="undefined"){let url=_this.func.common.get_url(SESSION_ID,"rpi","");if(["master"].includes(_this.APP_OBJ[app_id].app_type)){url+="get_doc_obj_raw"}else{url+="get_doc_obj_from_build"}let app_id_reference=_this.APP_OBJ[app_id].app_id_reference;const http=async function(){const response=await fetch(url,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","xu-gtp-token":_session.gtp_token,"xu-app-token":_session.app_token},body:JSON.stringify({app_id:app_id,doc_id:idP,build:_session.build_info.instance_build||_session.build_info.build||_session.opt.app_build_id,app_id_reference:app_id_reference,engine_mode:_session.engine_mode})});const json=await response.json();if(response){if(response&&response.status===400){return _this.func.utils.request_error(SESSION_ID,"ajax",response.statusText)}views_ret=json.data}};if(_session.engine_mode==="cms"){await http()}else{views_ret=await get_doc_from_websocket(SESSION_ID,app_id,idP)}}if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"){var ret=await __.rpi.get_prog(app_id,idP);if(ret.data){views_ret=ret.data}}if(views_ret){if(views_ret.error){console.error(views_ret);views_ret="";return}await save_objects_cache(SESSION_ID,idP,"DOCS_OBJ",views_ret)}}return views_ret};export const save_objects_cache=async function(SESSION_ID,id,obj_type,data){var _session=_this.SESSION_OBJ[SESSION_ID];if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"||_session.worker_type==="Dev"){return}var build_id=_session?.build_info?.build||0;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);var doc={_id:`cache_${build_id}_${obj_type}_${id}`,id:id,docType:"cache_objects",build_id:build_id.toString(),obj_type:obj_type,data:data};setTimeout(async function(){try{await db.get(doc_id);return}catch(e){if(await read_objects_cache(SESSION_ID,id,obj_type)){return}if(!doc.data||doc.data&&typeof doc.data==="string"&&doc.data.indexOf("error")>-1){return}try{return await db.put(doc)}catch(err){return}}},1e3)};export const read_objects_cache=async function(SESSION_ID,id,obj_type){if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"){try{const data=fs.readFileSync("/var/xuda/progs/"+id+".json","utf8");return JSON.parse(data)}catch(err){console.error("read_objects_cache",err);return}}var _session=_this.SESSION_OBJ[SESSION_ID];var build_id=_session?.build_info?.build||0;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);var ret;try{ret=await db.get(`cache_${build_id}_${obj_type}_${id}`);if(ret.data&&typeof ret.data==="string"&&ret.data.indexOf("error")>-1){return""}return ret.data}catch(err){return ret}};export const delete_objects_cache=async function(SESSION_ID,id,obj_type){const app_id=_this.SESSION_OBJ[SESSION_ID].app_id;var build_id=_session?.build_info?.build||0;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);try{var doc=await db.get(`cache_${build_id}_${obj_type}_${id}`);if(!doc)return;var ret=await db.remove(doc)}catch(err){return}return ret};export const load_objects_cache=async function(SESSION_ID){var _session=_this.SESSION_OBJ[SESSION_ID];if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"){return}const app_id=_session.app_id;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);const build_id=_this.APP_OBJ[app_id].app_build_id;let ret=await db.find({selector:{docType:"cache_objects",build_id:build_id}});for(let val of ret.docs){eval(val.obj_type)[_session.app_id][val.id]=val.data}};
1
+ const _this={};export const init_module=e=>{_this.func=e.func;_this.glb=e.glb;_this.SESSION_OBJ=e.SESSION_OBJ;_this.APP_OBJ=e.APP_OBJ;_this.IS_DOCKER=e.IS_DOCKER;_this.IS_API_SERVER=e.IS_API_SERVER;_this.IS_PROCESS_SERVER=e.IS_PROCESS_SERVER};export const get_doc_from_studio=async function(SESSION_ID,app_id,idP){return new Promise(function(resolve,reject){var _session=_this.SESSION_OBJ[SESSION_ID];if(glb.IS_WORKER){func.utils.post_back_to_client(SESSION_ID,"get_doc_from_studio",_session.worker_id,{doc_id:idP});self.addEventListener("live_preview_get_obj_response_worker_"+idP,event=>{resolve(event.detail.data)})}else{STUDIO_PEER_CONN_SEND_METHOD({service:"get_doc_obj",data:{doc_id:idP},session_id:SESSION_ID,id:STUDIO_PEER.id,source:"runtime",app_id:app_id});$("body").on("live_preview_get_obj_response_"+idP,function(e,data){resolve(data.data);$("body").off("live_preview_get_obj_response_"+idP)})}})};export const get_doc_from_websocket=async function(SESSION_ID,app_id,idP){var _session=_this.SESSION_OBJ[SESSION_ID];return new Promise(function(resolve,reject){if(glb.IS_WORKER){func.utils.post_back_to_client(SESSION_ID,"get_doc_from_websocket",_session.worker_id,{doc_id:idP});self.addEventListener("get_doc_obj_from_build_worker_"+idP,event=>{resolve(event.detail.data)})}else{if(RUNTIME_SERVER_WEBSOCKET&&RUNTIME_SERVER_WEBSOCKET_CONNECTED){RUNTIME_SERVER_WEBSOCKET.emit("message",{service:"get_doc_obj_from_build",data:{doc_id:idP}});$("body").on("get_doc_obj_from_build_response_"+idP,(e,data)=>{resolve(data.data);$("body").off("get_doc_obj_from_build_response_"+idP)})}else{throw new Error("fail to fetch from ws websocket inactive")}}})};export const DOCS_OBJ_get=async function(SESSION_ID,idP){if(!idP)return;if(idP==="_empty_panel_program"){return{_id:"_empty_panel_program",properties:{menuName:"_empty_panel_program",menuTitle:"_empty_panel_program",menuType:"component",renderType:"form"},progUi:[{id:"node-empty_panel_program",tagName:"xu-single-view",children:[{id:"node-empty_panel_program-span",tagName:"span",children:[],content:"",type:"element",attributes:{}}],content:"",type:"element",attributes:{}}],progDataSource:{},progFields:[],progEvents:[]}}var _session=_this.SESSION_OBJ[SESSION_ID];const app_id=_session.app_id;var views_ret;if(_session.engine_mode==="live_preview"){return await get_doc_from_studio(SESSION_ID,app_id,idP)}if(glb.register_startup_programs){func.common.db(SESSION_ID,"register_startup_programs",{prog_id:idP,build_id:_session?.build_info?.build||0})}views_ret=await read_objects_cache(SESSION_ID,idP,"DOCS_OBJ");if(!views_ret){if(typeof _this.IS_DOCKER==="undefined"&&typeof _this.IS_PROCESS_SERVER==="undefined"){let url=_this.func.common.get_url(SESSION_ID,"rpi","");if(["master"].includes(_this.APP_OBJ[app_id].app_type)){url+="get_doc_obj_raw"}else{url+="get_doc_obj_from_build"}let app_id_reference=_this.APP_OBJ[app_id].app_id_reference;const http=async function(){const response=await fetch(url,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","xu-gtp-token":_session.gtp_token,"xu-app-token":_session.app_token},body:JSON.stringify({app_id:app_id,doc_id:idP,build:_session.build_info.instance_build||_session.build_info.build||_session.opt.app_build_id,app_id_reference:app_id_reference,engine_mode:_session.engine_mode})});const json=await response.json();if(response){if(response&&response.status===400){return _this.func.utils.request_error(SESSION_ID,"ajax",response.statusText)}views_ret=json.data}};if(_session.engine_mode==="miniapp"){await http()}else{views_ret=await get_doc_from_websocket(SESSION_ID,app_id,idP)}}if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"){var ret=await __.rpi.get_prog(app_id,idP);if(ret.data){views_ret=ret.data}}if(views_ret){if(views_ret.error){console.error(views_ret);views_ret="";return}await save_objects_cache(SESSION_ID,idP,"DOCS_OBJ",views_ret)}}return views_ret};export const save_objects_cache=async function(SESSION_ID,id,obj_type,data){var _session=_this.SESSION_OBJ[SESSION_ID];if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"||_session.worker_type==="Dev"){return}var build_id=_session?.build_info?.build||0;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);var doc={_id:`cache_${build_id}_${obj_type}_${id}`,id:id,docType:"cache_objects",build_id:build_id.toString(),obj_type:obj_type,data:data};setTimeout(async function(){try{await db.get(doc_id);return}catch(e){if(await read_objects_cache(SESSION_ID,id,obj_type)){return}if(!doc.data||doc.data&&typeof doc.data==="string"&&doc.data.indexOf("error")>-1){return}try{return await db.put(doc)}catch(err){return}}},1e3)};export const read_objects_cache=async function(SESSION_ID,id,obj_type){if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"){try{const data=fs.readFileSync("/var/xuda/progs/"+id+".json","utf8");return JSON.parse(data)}catch(err){console.error("read_objects_cache",err);return}}var _session=_this.SESSION_OBJ[SESSION_ID];var build_id=_session?.build_info?.build||0;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);var ret;try{ret=await db.get(`cache_${build_id}_${obj_type}_${id}`);if(ret.data&&typeof ret.data==="string"&&ret.data.indexOf("error")>-1){return""}return ret.data}catch(err){return ret}};export const delete_objects_cache=async function(SESSION_ID,id,obj_type){const app_id=_this.SESSION_OBJ[SESSION_ID].app_id;var build_id=_session?.build_info?.build||0;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);try{var doc=await db.get(`cache_${build_id}_${obj_type}_${id}`);if(!doc)return;var ret=await db.remove(doc)}catch(err){return}return ret};export const load_objects_cache=async function(SESSION_ID){var _session=_this.SESSION_OBJ[SESSION_ID];if(typeof _this.IS_DOCKER!=="undefined"||typeof _this.IS_PROCESS_SERVER!=="undefined"){return}const app_id=_session.app_id;const db=await _this.func.utils.connect_pouchdb(SESSION_ID);const build_id=_this.APP_OBJ[app_id].app_build_id;let ret=await db.find({selector:{docType:"cache_objects",build_id:build_id}});for(let val of ret.docs){eval(val.obj_type)[_session.app_id][val.id]=val.data}};
@@ -164,7 +164,7 @@ export const DOCS_OBJ_get = async function (SESSION_ID, idP) {
164
164
  }
165
165
  };
166
166
 
167
- if (_session.engine_mode === 'cms') {
167
+ if (_session.engine_mode === 'miniapp') {
168
168
  await http();
169
169
  } else {
170
170
  views_ret = await get_doc_from_websocket(SESSION_ID, app_id, idP);
@@ -24,7 +24,7 @@ export const project_loader = async function (SESSION_ID, app_id, prog_id) {
24
24
  if (typeof XUDA_BUILD_INFO !== 'undefined') {
25
25
  _session.build_info = XUDA_BUILD_INFO;
26
26
  } else {
27
- if (['live_preview', 'cms'].includes(_session.engine_mode)) {
27
+ if (['live_preview', 'miniapp'].includes(_session.engine_mode)) {
28
28
  ret_build_info = await get_app_build_info(SESSION_ID, app_id);
29
29
  if (ret_build_info.code < 0) {
30
30
  return console.error(ret_build_info);
@@ -248,7 +248,7 @@ const get_rt_info = async function (SESSION_ID, app_id, last_changed_ts) {
248
248
  try {
249
249
  let ret = await db.get(`cache_rt_info`);
250
250
  const rt_info_obj = ret.data;
251
- if (rt_info_obj.data.last_changed_ts !== last_changed_ts || (!['live_preview', 'cms'].includes(_session.engine_mode) && rt_info_obj.data.app_build_id !== _session.opt.app_build_id)) {
251
+ if (rt_info_obj.data.last_changed_ts !== last_changed_ts || (!['live_preview', 'miniapp'].includes(_session.engine_mode) && rt_info_obj.data.app_build_id !== _session.opt.app_build_id)) {
252
252
  _this.func.UI.utils.progressScreen.show(SESSION_ID, 'New application setup detected, refreshing data and reloading in 5 sec');
253
253
  setTimeout(async () => {
254
254
  await func.index.delete_pouch(SESSION_ID);
@@ -1 +1 @@
1
- const _this={};export const init_module=e=>{_this.func=e.func;_this.glb=e.glb;_this.SESSION_OBJ=e.SESSION_OBJ;_this.APP_OBJ=e.APP_OBJ;_this.IS_DOCKER=e.IS_DOCKER;_this.IS_API_SERVER=e.IS_API_SERVER;_this.IS_PROCESS_SERVER=e.IS_PROCESS_SERVER};export const project_loader=async function(SESSION_ID,app_id,prog_id){try{var _session=_this.SESSION_OBJ[SESSION_ID];if(_this.func.UI.utils.get_url_attribute(SESSION_ID,"clear_cache")){await func.index.delete_pouch(SESSION_ID)}let last_changed_ts=0;var ret_build_info={};if(typeof XUDA_BUILD_INFO!=="undefined"){_session.build_info=XUDA_BUILD_INFO}else{if(["live_preview","cms"].includes(_session.engine_mode)){ret_build_info=await get_app_build_info(SESSION_ID,app_id);if(ret_build_info.code<0){return console.error(ret_build_info)}last_changed_ts=ret_build_info.data.last_changed_ts}else{try{const db=await func.utils.connect_pouchdb(SESSION_ID);await db.get(`cache_rt_info`)}catch(err){const startup_module=await func.common.get_module(SESSION_ID,"xuda-deploy-startup-loader.mjs");await startup_module.loader(SESSION_ID)}last_changed_ts=_session.opt.last_changed_ts}}await get_rt_info(SESSION_ID,app_id,last_changed_ts);insert_custom_prop(SESSION_ID);if(_session?.app_admin_prop?.app_admin_direction){$(_session.root_element).attr("dir",_session.app_admin_prop.app_admin_direction)}if(_session.engine_mode==="live_preview"){const module=await _this.func.common.get_module(SESSION_ID,"xuda-live-preview-module.esm.js");module.live_preview_loader(SESSION_ID);return}if(_this.APP_OBJ[app_id]?.is_deployment){try{await init_runtime_websocket(SESSION_ID,app_id)}catch(error){throw error}}const module=await _this.func.common.get_module(SESSION_ID,`xuda-progs-loader-module.mjs`);if(app_id!=="unknown"){await module.load_objects_cache(SESSION_ID)}await _this.func.UI.main.embed_loader(SESSION_ID)}catch(error){throw error}};const get_app_build_info=async function(SESSION_ID,app_id){return new Promise(function(resolve,reject){var _session=_this.SESSION_OBJ[SESSION_ID];let app_id_reference=_this.APP_OBJ[app_id].app_id_reference;fetch(_this.func.common.get_url(SESSION_ID,"rpi","get_app_build"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","xu-gtp-token":_session.gtp_token,"xu-app-token":_session.app_token},body:JSON.stringify({app_id:app_id,app_id_reference:app_id_reference,engine_mode:_session.engine_mode})}).then(response=>{if(!response.ok){return response.text().then(text=>{throw new Error(text)})}return response.json()}).then(async json=>{_this.SESSION_OBJ[SESSION_ID].build_info=json.data;resolve(json)}).catch(err=>{try{resolve(JSON.parse(err.message))}catch(error){resolve({code:-1,data:err.message})}})})};const get_user_group_account_info=async function(SESSION_ID,uid){var _session=SESSION_OBJ[SESSION_ID];const response=await fetch(`https://${_session.domain}/cpi/get_account_info`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({uid:uid,uid_query:$.cookie("uid")})});const json=await response.json();return json.data};const get_rt_info=async function(SESSION_ID,app_id,last_changed_ts){var _session=_this.SESSION_OBJ[SESSION_ID];return new Promise(async function(resolve,reject){const response={success:async function(ret,ajaxP){if(ret.code<0){return response.error(ret.data)}const rt_info_obj=ret.data;var app_id=rt_info_obj._id;_this.APP_OBJ[app_id]=rt_info_obj;_session.app_id=app_id;if(rt_info_obj?.deploy_data?.global_variables){_session.url_params={..._session.url_params,...rt_info_obj.deploy_data.global_variables}}let account_info=_.clone(rt_info_obj?.account_info||{});if(_session.engine_mode==="user_group"){const user_group_data=await get_user_group_account_info(SESSION_ID,rt_info_obj?.account_info?.uid);account_info=user_group_data.account_info;account_info.uid=user_group_data._id}_session.USR_OBJ={_id:account_info?.uid,usr_name:account_info?.username,usr_first_name:account_info?.first_name||account_info?.email,usr_last_name:account_info?.last_name||"",usr_email:account_info?.email,usr_profile_picture:account_info?.profile_picture};_session.login_info=rt_info_obj?.login_info;_session.client_ip=rt_info_obj.client_ip;_session.rpi_http_methods=rt_info_obj.rpi_http_methods;_session.app_admin_prop=rt_info_obj.app_admin_prop;_session.is_deployment=rt_info_obj.is_deployment;resolve();$(".loader_logo").css("background-image",`url( ${rt_info_obj.app_pic})`).hide().fadeIn()},error:async function(err){if(err){return _this.func.UI.utils.progressScreen.show(SESSION_ID,err,null,true)}console.warn("** reload request")}};const db=await func.utils.connect_pouchdb(SESSION_ID);try{let ret=await db.get(`cache_rt_info`);const rt_info_obj=ret.data;if(rt_info_obj.data.last_changed_ts!==last_changed_ts||!["live_preview","cms"].includes(_session.engine_mode)&&rt_info_obj.data.app_build_id!==_session.opt.app_build_id){_this.func.UI.utils.progressScreen.show(SESSION_ID,"New application setup detected, refreshing data and reloading in 5 sec");setTimeout(async()=>{await func.index.delete_pouch(SESSION_ID);location.reload()},5e3);return}response.success(rt_info_obj)}catch(err){fetch(_this.func.common.get_url(SESSION_ID,"rpi","get_rt_info"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","xu-gtp-token":_session.gtp_token,"xu-app-token":_session.app_token},body:JSON.stringify({app_id:app_id,prog_id:_session.engine_mode==="live_preview"?"":_session.prog_id,engine_mode:_session.engine_mode,build:_session.build_info.build,session_id:SESSION_ID,is_cordova:_this.glb.is_cordova,client_info:_session.SYS_GLOBAL_OBJ_CLIENT_INFO,client_id:_session.SYS_GLOBAL_OBJ_CLIENT_INFO.fingerprint})}).then(response=>{if(!response.ok){return response.text().then(text=>{throw new Error(text)})}return response.json()}).then(json=>{if(json.code<0){throw new Error(json.data||"unknown error")}response.success(json);var doc={_id:`cache_rt_info`,data:json,docType:"cache_app"};db.put(doc)}).catch(err=>{response.error(err.message)})}})};const insert_custom_prop=function(SESSION_ID){try{var app_id=_this.SESSION_OBJ[SESSION_ID].app_id;if(_this.APP_OBJ[app_id]?.app_custom_prop?.app_custom_header){var head=document.getElementsByTagName("head")[0];const app_custom_header=_this.APP_OBJ[app_id].app_custom_prop.app_custom_header;$(head).append(func.utils.replace_studio_drive_url(SESSION_ID,app_custom_header))}if(_this.APP_OBJ[app_id]?.app_custom_prop?.app_custom_body){$(_this.SESSION_OBJ[SESSION_ID].root_element).prepend(_this.APP_OBJ[app_id].app_custom_prop.app_custom_body)}}catch(err){console.error(err)}};const init_runtime_websocket=function(SESSION_ID,app_id){return new Promise(function(resolve,reject){const set_connected=async function(stat){var datasource_changes={[0]:{["data_system"]:{SYS_GLOBAL_BOL_CONNECTED:stat}}};await func.datasource.update(SESSION_ID,datasource_changes)};var _session=_this.SESSION_OBJ[SESSION_ID];var _data_system=_session?.DS_GLB?.[0]?.data_system;const url=`https://${location.hostname}`;var error;RUNTIME_SERVER_WEBSOCKET=io(url,{secure:true,reconnection:true,rejectUnauthorized:false,path:"/ws/socket.io"});RUNTIME_SERVER_WEBSOCKET.on("connect",()=>{console.info("RUNTIME_SERVER_WEBSOCKET connected");if(_data_system){set_connected(1)}if(_session.opt.enable_offline){if($(_session.root_element).hasClass("runtime_offline")){$(_session.root_element).removeClass("runtime_offline");func.utils.alerts.toast(SESSION_ID,"Switched to on-line mode","You are now online. All data stored while you were offline will be synchronized to the server.","success")}}else{_this.func.UI.utils.progressScreen.hide(SESSION_ID)}if(error){if(!RUNTIME_SERVER_WEBSOCKET_CONNECTED){console.warn("** reload request")}}});RUNTIME_SERVER_WEBSOCKET.on("message",e=>{if(_this.APP_OBJ[app_id].is_deployment){_this.func.UI.utils.indicator.server.busy();setTimeout(function(){_this.func.UI.utils.indicator.server.normal()},e?.data?.length*100||100)}var data=e.data;if(e.source==="http_call"){if(e.service==="get_doc_obj_from_build"){return $("body").trigger("get_doc_obj_from_build_response_"+data._id,{data:data})}if(e.service==="heartbeat"){return $("body").trigger("heartbeat_response",{data:data})}return $("body").trigger("get_ws_data_response_"+e.websocket_queue_num,{data:data,e:e})}if(e.source==="deployment_server"){console.log("document_changed",e);return func.UI.screen.refresh_document_changes_for_realtime_update(SESSION_ID,e.data)}if(data!=="connected")return;RUNTIME_SERVER_WEBSOCKET_CONNECTED=true;resolve()});var callback_done=false;RUNTIME_SERVER_WEBSOCKET.on("connect_error",error=>{if(!callback_done){resolve();callback_done=true;error=true}});RUNTIME_SERVER_WEBSOCKET.on("disconnect",async()=>{RUNTIME_SERVER_WEBSOCKET_CONNECTED=false;if(_data_system){set_connected(0)}if(_session.opt.enable_offline){$(_session.root_element).addClass("runtime_offline");func.utils.alerts.toast(SESSION_ID,"Switched to off-line mode","You have lost connection to the server and are now working offline. Once the connection is restored, all data will be synchronized.","warning")}else{_this.func.UI.utils.progressScreen.show(SESSION_ID,"Your browser has temporarily disconnected from the server. Please wait while we attempt to reconnect.")}});window.addEventListener("beforeunload",function(event){var obj={service:"close_websocket",data:{session_id:SESSION_ID}};RUNTIME_SERVER_WEBSOCKET.emit("message",obj)})})};export const run_plugins_runtime_init=async function(SESSION_ID,app_id,method){var _session=_this.SESSION_OBJ[SESSION_ID];const get_path=function(plugin_name,resource){if(_session.worker_type==="Dev"){return`../../plugins/${_session.domain}/${plugin_name}/${resource}`}return`https://${_session.domain}/plugins/${plugin_name}/runtime/${resource}?gtp_token=${_session.gtp_token}&app_id=${_session.app_id}`};if(!_this.APP_OBJ[app_id].app_plugins_purchased)return;for await(const[key,val]of Object.entries(_this.APP_OBJ[app_id].app_plugins_purchased)){if(!val.installed)continue;if(val.manifest?.[method].mjs?.exist&&!val.manifest[method].mjs.is_empty){const module=await import(get_path(key,method+".mjs"));try{await module.default({SESSION_ID:SESSION_ID})}catch(error){console.error(error)}}}};
1
+ const _this={};export const init_module=e=>{_this.func=e.func;_this.glb=e.glb;_this.SESSION_OBJ=e.SESSION_OBJ;_this.APP_OBJ=e.APP_OBJ;_this.IS_DOCKER=e.IS_DOCKER;_this.IS_API_SERVER=e.IS_API_SERVER;_this.IS_PROCESS_SERVER=e.IS_PROCESS_SERVER};export const project_loader=async function(SESSION_ID,app_id,prog_id){try{var _session=_this.SESSION_OBJ[SESSION_ID];if(_this.func.UI.utils.get_url_attribute(SESSION_ID,"clear_cache")){await func.index.delete_pouch(SESSION_ID)}let last_changed_ts=0;var ret_build_info={};if(typeof XUDA_BUILD_INFO!=="undefined"){_session.build_info=XUDA_BUILD_INFO}else{if(["live_preview","miniapp"].includes(_session.engine_mode)){ret_build_info=await get_app_build_info(SESSION_ID,app_id);if(ret_build_info.code<0){return console.error(ret_build_info)}last_changed_ts=ret_build_info.data.last_changed_ts}else{try{const db=await func.utils.connect_pouchdb(SESSION_ID);await db.get(`cache_rt_info`)}catch(err){const startup_module=await func.common.get_module(SESSION_ID,"xuda-deploy-startup-loader.mjs");await startup_module.loader(SESSION_ID)}last_changed_ts=_session.opt.last_changed_ts}}await get_rt_info(SESSION_ID,app_id,last_changed_ts);insert_custom_prop(SESSION_ID);if(_session?.app_admin_prop?.app_admin_direction){$(_session.root_element).attr("dir",_session.app_admin_prop.app_admin_direction)}if(_session.engine_mode==="live_preview"){const module=await _this.func.common.get_module(SESSION_ID,"xuda-live-preview-module.esm.js");module.live_preview_loader(SESSION_ID);return}if(_this.APP_OBJ[app_id]?.is_deployment){try{await init_runtime_websocket(SESSION_ID,app_id)}catch(error){throw error}}const module=await _this.func.common.get_module(SESSION_ID,`xuda-progs-loader-module.mjs`);if(app_id!=="unknown"){await module.load_objects_cache(SESSION_ID)}await _this.func.UI.main.embed_loader(SESSION_ID)}catch(error){throw error}};const get_app_build_info=async function(SESSION_ID,app_id){return new Promise(function(resolve,reject){var _session=_this.SESSION_OBJ[SESSION_ID];let app_id_reference=_this.APP_OBJ[app_id].app_id_reference;fetch(_this.func.common.get_url(SESSION_ID,"rpi","get_app_build"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","xu-gtp-token":_session.gtp_token,"xu-app-token":_session.app_token},body:JSON.stringify({app_id:app_id,app_id_reference:app_id_reference,engine_mode:_session.engine_mode})}).then(response=>{if(!response.ok){return response.text().then(text=>{throw new Error(text)})}return response.json()}).then(async json=>{_this.SESSION_OBJ[SESSION_ID].build_info=json.data;resolve(json)}).catch(err=>{try{resolve(JSON.parse(err.message))}catch(error){resolve({code:-1,data:err.message})}})})};const get_user_group_account_info=async function(SESSION_ID,uid){var _session=SESSION_OBJ[SESSION_ID];const response=await fetch(`https://${_session.domain}/cpi/get_account_info`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({uid:uid,uid_query:$.cookie("uid")})});const json=await response.json();return json.data};const get_rt_info=async function(SESSION_ID,app_id,last_changed_ts){var _session=_this.SESSION_OBJ[SESSION_ID];return new Promise(async function(resolve,reject){const response={success:async function(ret,ajaxP){if(ret.code<0){return response.error(ret.data)}const rt_info_obj=ret.data;var app_id=rt_info_obj._id;_this.APP_OBJ[app_id]=rt_info_obj;_session.app_id=app_id;if(rt_info_obj?.deploy_data?.global_variables){_session.url_params={..._session.url_params,...rt_info_obj.deploy_data.global_variables}}let account_info=_.clone(rt_info_obj?.account_info||{});if(_session.engine_mode==="user_group"){const user_group_data=await get_user_group_account_info(SESSION_ID,rt_info_obj?.account_info?.uid);account_info=user_group_data.account_info;account_info.uid=user_group_data._id}_session.USR_OBJ={_id:account_info?.uid,usr_name:account_info?.username,usr_first_name:account_info?.first_name||account_info?.email,usr_last_name:account_info?.last_name||"",usr_email:account_info?.email,usr_profile_picture:account_info?.profile_picture};_session.login_info=rt_info_obj?.login_info;_session.client_ip=rt_info_obj.client_ip;_session.rpi_http_methods=rt_info_obj.rpi_http_methods;_session.app_admin_prop=rt_info_obj.app_admin_prop;_session.is_deployment=rt_info_obj.is_deployment;resolve();$(".loader_logo").css("background-image",`url( ${rt_info_obj.app_pic})`).hide().fadeIn()},error:async function(err){if(err){return _this.func.UI.utils.progressScreen.show(SESSION_ID,err,null,true)}console.warn("** reload request")}};const db=await func.utils.connect_pouchdb(SESSION_ID);try{let ret=await db.get(`cache_rt_info`);const rt_info_obj=ret.data;if(rt_info_obj.data.last_changed_ts!==last_changed_ts||!["live_preview","miniapp"].includes(_session.engine_mode)&&rt_info_obj.data.app_build_id!==_session.opt.app_build_id){_this.func.UI.utils.progressScreen.show(SESSION_ID,"New application setup detected, refreshing data and reloading in 5 sec");setTimeout(async()=>{await func.index.delete_pouch(SESSION_ID);location.reload()},5e3);return}response.success(rt_info_obj)}catch(err){fetch(_this.func.common.get_url(SESSION_ID,"rpi","get_rt_info"),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","xu-gtp-token":_session.gtp_token,"xu-app-token":_session.app_token},body:JSON.stringify({app_id:app_id,prog_id:_session.engine_mode==="live_preview"?"":_session.prog_id,engine_mode:_session.engine_mode,build:_session.build_info.build,session_id:SESSION_ID,is_cordova:_this.glb.is_cordova,client_info:_session.SYS_GLOBAL_OBJ_CLIENT_INFO,client_id:_session.SYS_GLOBAL_OBJ_CLIENT_INFO.fingerprint})}).then(response=>{if(!response.ok){return response.text().then(text=>{throw new Error(text)})}return response.json()}).then(json=>{if(json.code<0){throw new Error(json.data||"unknown error")}response.success(json);var doc={_id:`cache_rt_info`,data:json,docType:"cache_app"};db.put(doc)}).catch(err=>{response.error(err.message)})}})};const insert_custom_prop=function(SESSION_ID){try{var app_id=_this.SESSION_OBJ[SESSION_ID].app_id;if(_this.APP_OBJ[app_id]?.app_custom_prop?.app_custom_header){var head=document.getElementsByTagName("head")[0];const app_custom_header=_this.APP_OBJ[app_id].app_custom_prop.app_custom_header;$(head).append(func.utils.replace_studio_drive_url(SESSION_ID,app_custom_header))}if(_this.APP_OBJ[app_id]?.app_custom_prop?.app_custom_body){$(_this.SESSION_OBJ[SESSION_ID].root_element).prepend(_this.APP_OBJ[app_id].app_custom_prop.app_custom_body)}}catch(err){console.error(err)}};const init_runtime_websocket=function(SESSION_ID,app_id){return new Promise(function(resolve,reject){const set_connected=async function(stat){var datasource_changes={[0]:{["data_system"]:{SYS_GLOBAL_BOL_CONNECTED:stat}}};await func.datasource.update(SESSION_ID,datasource_changes)};var _session=_this.SESSION_OBJ[SESSION_ID];var _data_system=_session?.DS_GLB?.[0]?.data_system;const url=`https://${location.hostname}`;var error;RUNTIME_SERVER_WEBSOCKET=io(url,{secure:true,reconnection:true,rejectUnauthorized:false,path:"/ws/socket.io"});RUNTIME_SERVER_WEBSOCKET.on("connect",()=>{console.info("RUNTIME_SERVER_WEBSOCKET connected");if(_data_system){set_connected(1)}if(_session.opt.enable_offline){if($(_session.root_element).hasClass("runtime_offline")){$(_session.root_element).removeClass("runtime_offline");func.utils.alerts.toast(SESSION_ID,"Switched to on-line mode","You are now online. All data stored while you were offline will be synchronized to the server.","success")}}else{_this.func.UI.utils.progressScreen.hide(SESSION_ID)}if(error){if(!RUNTIME_SERVER_WEBSOCKET_CONNECTED){console.warn("** reload request")}}});RUNTIME_SERVER_WEBSOCKET.on("message",e=>{if(_this.APP_OBJ[app_id].is_deployment){_this.func.UI.utils.indicator.server.busy();setTimeout(function(){_this.func.UI.utils.indicator.server.normal()},e?.data?.length*100||100)}var data=e.data;if(e.source==="http_call"){if(e.service==="get_doc_obj_from_build"){return $("body").trigger("get_doc_obj_from_build_response_"+data._id,{data:data})}if(e.service==="heartbeat"){return $("body").trigger("heartbeat_response",{data:data})}return $("body").trigger("get_ws_data_response_"+e.websocket_queue_num,{data:data,e:e})}if(e.source==="deployment_server"){console.log("document_changed",e);return func.UI.screen.refresh_document_changes_for_realtime_update(SESSION_ID,e.data)}if(data!=="connected")return;RUNTIME_SERVER_WEBSOCKET_CONNECTED=true;resolve()});var callback_done=false;RUNTIME_SERVER_WEBSOCKET.on("connect_error",error=>{if(!callback_done){resolve();callback_done=true;error=true}});RUNTIME_SERVER_WEBSOCKET.on("disconnect",async()=>{RUNTIME_SERVER_WEBSOCKET_CONNECTED=false;if(_data_system){set_connected(0)}if(_session.opt.enable_offline){$(_session.root_element).addClass("runtime_offline");func.utils.alerts.toast(SESSION_ID,"Switched to off-line mode","You have lost connection to the server and are now working offline. Once the connection is restored, all data will be synchronized.","warning")}else{_this.func.UI.utils.progressScreen.show(SESSION_ID,"Your browser has temporarily disconnected from the server. Please wait while we attempt to reconnect.")}});window.addEventListener("beforeunload",function(event){var obj={service:"close_websocket",data:{session_id:SESSION_ID}};RUNTIME_SERVER_WEBSOCKET.emit("message",obj)})})};export const run_plugins_runtime_init=async function(SESSION_ID,app_id,method){var _session=_this.SESSION_OBJ[SESSION_ID];const get_path=function(plugin_name,resource){if(_session.worker_type==="Dev"){return`../../plugins/${_session.domain}/${plugin_name}/${resource}`}return`https://${_session.domain}/plugins/${plugin_name}/runtime/${resource}?gtp_token=${_session.gtp_token}&app_id=${_session.app_id}`};if(!_this.APP_OBJ[app_id].app_plugins_purchased)return;for await(const[key,val]of Object.entries(_this.APP_OBJ[app_id].app_plugins_purchased)){if(!val.installed)continue;if(val.manifest?.[method].mjs?.exist&&!val.manifest[method].mjs.is_empty){const module=await import(get_path(key,method+".mjs"));try{await module.default({SESSION_ID:SESSION_ID})}catch(error){console.error(error)}}}};