@claspo/renderer 18.7.4 → 18.7.5-ctx.10

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
- import UrlQueryParamsSource from"../sdk/source/sources/UrlQueryParamsSource";function getLastMarTechValue(t,e){for(let r=t.length-1;r>=0;r--){const a=new URLSearchParams(t[r]),c=[];for(const[t,r]of a.entries())e.includes(t)&&r&&c.push(r);if(c.length)return c[c.length-1]}return""}export default class UTMParamsExtractor{static extractTrackingParams(t){return Object.assign(Object.assign({},UTMParamsExtractor.extractUtmParams(t)),UTMParamsExtractor.extractMarTechParams(t))}static extractUtmParams(t){const e={id:"id",fallbackValue:"",exampleValue:"exampleValue",sourceId:UrlQueryParamsSource.sourceId,arguments:[{type:"string",name:"urlQueryParamName",value:""}]},r={},a=t.getRegistry().getSource(e.sourceId),c=a.getValue("utm");return["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"].forEach(t=>{const s=c.processor(a,Object.assign(Object.assign({},e),{arguments:[Object.assign(Object.assign({},e.arguments[0]),{value:t})]}));s&&(r[t]=s)}),r}static extractMarTechParams(t){const e=t.getRegistry().getSource(UrlQueryParamsSource.sourceId).getSessionHistory(),r={};return Object.entries({rdt_cid:["rdt_cid"],sccid:["sccid","ScCid"],gclid:["gclid"],fbclid:["fbclid"],ttclid:["ttclid"],li_fat_id:["li_fat_id"],ascsubtag:["ascsubtag"],msclkid:["msclkid"],twclid:["twclid"],epik:["epik"]}).forEach(([t,a])=>{const c=getLastMarTechValue(e,a);c&&(r[t]=c)}),r}}
1
+ import UrlQueryParamsSource from"../sdk/source/sources/UrlQueryParamsSource";function getLastMarTechValue(t,e){for(let r=t.length-1;r>=0;r--){const a=new URLSearchParams(t[r]),c=[];for(const[t,r]of a.entries())e.includes(t)&&r&&c.push(r);if(c.length)return c[c.length-1]}return""}export default class UTMParamsExtractor{static extractTrackingParams(t){return Object.assign(Object.assign({},UTMParamsExtractor.extractUtmParams(t)),UTMParamsExtractor.extractMarTechParams(t))}static extractUtmParams(t){const e={id:"id",fallbackValue:"",exampleValue:"exampleValue",sourceId:UrlQueryParamsSource.sourceId,arguments:[{type:"string",name:"urlQueryParamName",value:""}]},r={},a=t.getRegistry().getSource(e.sourceId),c=null==a?void 0:a.getValue("utm");return a&&c?(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"].forEach(t=>{const s=c.processor(a,Object.assign(Object.assign({},e),{arguments:[Object.assign(Object.assign({},e.arguments[0]),{value:t})]}));s&&(r[t]=s)}),r):r}static extractMarTechParams(t){var e,r;const a=t.getRegistry().getSource(UrlQueryParamsSource.sourceId),c=null==a?void 0:a.subscriptionEntry,s=null!==(r=null===(e=null==c?void 0:c.getSessionHistory)||void 0===e?void 0:e.call(c))&&void 0!==r?r:[new URL(window.location.href).search],i={};return Object.entries({rdt_cid:["rdt_cid"],sccid:["sccid","ScCid"],gclid:["gclid"],fbclid:["fbclid"],ttclid:["ttclid"],li_fat_id:["li_fat_id"],ascsubtag:["ascsubtag"],msclkid:["msclkid"],twclid:["twclid"],epik:["epik"]}).forEach(([t,e])=>{const r=getLastMarTechValue(s,e);r&&(i[t]=r)}),i}}
@@ -1 +1 @@
1
- import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import getConfiguredResultViewIds from"../../document-model/getConfiguredResultViewIds";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import isDictionary from"@claspo/common/object/isDictionary";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isResultView(t,e){return!!t&&(systemResultStateNames.includes(t.label)||e.includes(t.id))}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}async execute(t,e,s,i){var n;if(this.formEventsListener&&this.formEventsListener.off(),this.form.submitQueuedAfterPending)return;if(this.form.preventSubmit)return void(this.form.submitQueuedAfterPending=!1);if(this.form.isPending()&&(this.form.submitQueuedAfterPending=!0,await this.form.waitForPendingValidationAndCheckIfValid()),this.form.submitQueuedAfterPending=!1,this.form.preventSubmit)return;const o=new Promise(t=>{this.submit(t,s,i)});return null===(n=this.getServices().submitState)||void 0===n||n.trackSubmission(o),o}submit(t,e,s){var i;const n=this.getServices().viewRouter.getCurrentViewIndex(),o=getConfiguredResultViewIds(this.getServices().documentModel.getShared(),this.hasFormControls()),r=this.getServices().documentModel.getViews()[n+1],a=r&&!isResultView(r,o),c=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!c.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const u=this.stateService,S=u.getState().conditionalRedirectViewId,d=c.conditionalRedirectViewId||S;S&&(c.conditionalRedirectViewId=S,u.setState({conditionalRedirectViewId:null}));let m=this.getServices().documentModel.getViews()[n+1];const l=this.getServices().documentModel.getViews()[n];if(!c.skipNavigation&&d&&getComponentCountOnView(l,"SysNetPromoterScoreComponent")+getComponentCountOnView(l,"SysFeedbackComponent")===1&&(m=this.getServices().documentModel.getViews().find(t=>t.id===c.conditionalRedirectViewId),viewHasControls(m)||isResultView(m,o)))return this.goToView(m.path[0],c),void t(!0);const E=null!==(i=c.formValue)&&void 0!==i?i:this.form.getControlsMap(),h=this.getContextValue(c);if(!c.skipNavigation&&a&&(viewHasControls(m)||!Object.keys(E).length&&!Object.keys(h).length))return this.goToView(n+1,c),void t(!0);if(!Object.keys(E).length&&!Object.keys(h).length)return void t(!0);const g=UTMParamsExtractor.extractTrackingParams(this.context),R=this.constructRequestPayload({contextValue:h,formValue:E,utmParams:g});this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_STARTED,R),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",R);if(this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot"))return this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.SUCCESS,success:!0,skipped:!0}),void t();this.sendRequest(R).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{const s=this.getTrackingMessageByStatus(e.state);if(s&&this.tracking.send(s),c.skipNavigation)return e.state===RequestStatus.TOO_MANY_REQUESTS&&this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS),e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),void t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED);switch(e.state){case RequestStatus.SUCCESS:a&&m?this.goToView(m.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getSuccessViewIndex());break;case RequestStatus.ALREADY_SUBSCRIBED:d&&m?this.goToView(m.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getAlreadySubscribedViewIndex());break;case RequestStatus.ERROR:d&&m?this.goToView(m.path[0]):this.handleErrorResponse();break;case RequestStatus.TOO_MANY_REQUESTS:this.goToView(d&&m?m.path[0]:this.getErrorViewIndex()),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.ERROR,success:!1}),c.skipNavigation||this.handleErrorResponse(),t(!1)})}getContextValue(t){var e,s;if(!t.excludeFormContext)return this.context.getKVMap();const i=(null===(s=(e=this.context).getRecordsMap)||void 0===s?void 0:s.call(e))||{};return Object.values(i).reduce((t,e)=>{var s;const i=null===(s=null==e?void 0:e.getValue)||void 0===s?void 0:s.call(e);return i&&"FORM"!==i.sourceId?(t[i.id]=i.value,t):t},{})}constructDataToSent({contextValue:t,formValue:e,utmParams:s}){const i=Object.assign({},t);return i.tracking=s,Object.keys(e).forEach(t=>{if(t.startsWith("clConsentId")){if(t.endsWith("_label"))return;const s={value:e[t]};e[`${t}_label`]&&(s.text=e[`${t}_label`]),i.consents?i.consents[t]=s:i.consents={[t]:s}}else{const s=e[t];i[t]=isDictionary(s)||Array.isArray(s)?JSON.stringify(s):s}}),i}constructRequestPayload({contextValue:t,formValue:e,utmParams:s}){let i={data:this.constructDataToSent({contextValue:t,formValue:e,utmParams:s}),referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy")};return this.configService.getConfig("widgetDebugMode")&&(i.ignoreTracking=!0),i}constructRequestHeaders(){const t={},e=this.configService.getConfig("clCustomerId");return e&&Object.assign(t,{"cl-customer-id":e}),t}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,e)}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute(this.configService.getConfig("subscribeContactUrl"),"POST",t,this.constructRequestHeaders())}getSuccessViewIndex(){return this.resolveResultViewIndex("successViewId",["DOCUMENT_VIEW_TYPE_SUCCESS","DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST","REQUEST_FORM_VIEW_TYPE_SUCCESS"])}getErrorViewIndex(){return this.resolveResultViewIndex("errorViewId",["DOCUMENT_VIEW_TYPE_ERROR"])}getAlreadySubscribedViewIndex(){const t=this.getActiveSubmitActionParams();return t&&!t.alreadySubscribedViewId?this.getSuccessViewIndex():this.resolveResultViewIndex("alreadySubscribedViewId",["DOCUMENT_VIEW_TYPE_SUBSCRIBED"])}resolveResultViewIndex(t,e){var s;const i=this.getServices().documentModel.getViews(),n=null===(s=this.getActiveSubmitActionParams())||void 0===s?void 0:s[t];if(n){const t=i.findIndex(t=>t.id===n);if(-1!==t)return t}return i.findIndex(t=>e.includes(t.label))}hasFormControls(){return this.form.getControlsAsArray().length>0}getActiveSubmitActionParams(){if(this.hasFormControls())return this.getServices().documentModel.getShared().submitActionParams}runPostSubmitActionOrGoToView(t){var e;const s=null===(e=this.getActiveSubmitActionParams())||void 0===e?void 0:e.runAction;s?this.getServices().actionFactory.get(s).execute(this.stateService.getState()):this.goToView(t())}handleErrorResponse(){const t=this.getErrorViewIndex();-1!==t?this.goToView(t):this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_ERROR_WITHOUT_VIEW)}}
1
+ import SysActionTypes from"../SysActionTypes";import SysEventTypes from"../../common/SysEventTypes";import{HttpStatus}from"@claspo/common/network/HttpStatus";import ActionCategory from"./ActionCategory";import systemResultStateNames from"../../document-model/systemResultStateNames";import getConfiguredResultViewIds from"../../document-model/getConfiguredResultViewIds";import DocumentUtils from"@claspo/common/document/DocumentUtils";import getComponentCountOnView from"../../sdk/getComponentCountOnView";import UTMParamsExtractor from"../UTMParamsExtractor";import isDictionary from"@claspo/common/object/isDictionary";function componentModelHasSubmitAction(t){var e,s;try{return!!(null===(s=null===(e=t.props)||void 0===e?void 0:e.handlers)||void 0===s?void 0:s.find(t=>{var e;return null===(e=null==t?void 0:t.actions)||void 0===e?void 0:e.find(t=>[SysActionTypes.REQUEST,SysActionTypes.SUBSCRIBE_CONTACT].includes(t.type))}))}catch(t){return!1}}function viewHasControls(t){if(!t)return!1;let e=0;return DocumentUtils.iterateDepthFirst(t,t=>{(["INPUT","MULTIPLE_INPUT","PRIZE_BASED_GAMING"].includes(t.type)||componentModelHasSubmitAction(t))&&e++}),e>0}function isResultView(t,e){return!!t&&(systemResultStateNames.includes(t.label)||e.includes(t.id))}export const RequestStatus={SUCCESS:"SUCCESS",ALREADY_SUBSCRIBED:"ALREADY_SUBSCRIBED",ERROR:"ERROR",TOO_MANY_REQUESTS:"TOO_MANY_REQUESTS"};export default class BaseRequestAction{constructor(t,e,s,i,n,o,r,a,c){this.skipHttpRequest=!0,this.id=s.id,this.params=s.params,this.form=e,this.eventEmitter=t,this.httpClient=i,this.configService=n,this.formEventsListener=null,this.tracking=o,this.stateService=r,this.context=a,this.getServices=c,this.category=ActionCategory.SUBMIT}getTrackingMessageBeforeSentData(){return""}getTrackingMessageByStatus(t){return""}async execute(t,e,s,i){var n;if(this.formEventsListener&&this.formEventsListener.off(),this.form.submitQueuedAfterPending)return;if(this.form.preventSubmit)return void(this.form.submitQueuedAfterPending=!1);if(this.form.isPending()&&(this.form.submitQueuedAfterPending=!0,await this.form.waitForPendingValidationAndCheckIfValid()),this.form.submitQueuedAfterPending=!1,this.form.preventSubmit)return;const o=new Promise(t=>{this.submit(t,s,i)});return null===(n=this.getServices().submitState)||void 0===n||n.trackSubmission(o),o}submit(t,e,s){var i;const n=this.getServices().viewRouter.getCurrentViewIndex(),o=getConfiguredResultViewIds(this.getServices().documentModel.getShared(),this.hasFormControls()),r=this.getServices().documentModel.getViews()[n+1],a=r&&!isResultView(r,o),c=Object.assign(Object.assign({},this.params),s);if(this.form.markAsTouched(),this.stateService.getState().emitActionOnSubmit&&this.eventEmitter.emit(this.stateService.getState().emitActionOnSubmit.eventName),this.stateService.getState().interceptSubmitActions&&!e)return;if(!this.form.isValid()&&!c.skipValidation)return this.eventEmitter.emit("INVALID_CONTACT_DATA_SUBMIT_ATTEMPT"),void t(!1);const u=this.stateService,S=u.getState().conditionalRedirectViewId,m=c.conditionalRedirectViewId||S;S&&(c.conditionalRedirectViewId=S,u.setState({conditionalRedirectViewId:null}));let d=this.getServices().documentModel.getViews()[n+1];const l=this.getServices().documentModel.getViews()[n];if(!c.skipNavigation&&m&&getComponentCountOnView(l,"SysNetPromoterScoreComponent")+getComponentCountOnView(l,"SysFeedbackComponent")===1&&(d=this.getServices().documentModel.getViews().find(t=>t.id===c.conditionalRedirectViewId),viewHasControls(d)||isResultView(d,o)))return this.goToView(d.path[0],c),void t(!0);const E=null!==(i=c.formValue)&&void 0!==i?i:this.form.getControlsMap(),h=this.getContextValue(c);if(!c.skipNavigation&&a&&(viewHasControls(d)||!Object.keys(E).length&&!Object.keys(h).length))return this.goToView(n+1,c),void t(!0);if(!Object.keys(E).length&&!Object.keys(h).length)return void t(!0);const g=UTMParamsExtractor.extractTrackingParams(this.context),R=this.constructRequestPayload({contextValue:h,formValue:E,utmParams:g});this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_STARTED,R),this.eventEmitter.emit("CONTACT_DATA_SUBMIT",R);if(this.getTrackingMessageBeforeSentData()&&this.tracking.send("FormFinish_[Name]"),this.configService.getConfig("isBot"))return this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.SUCCESS,success:!0,skipped:!0}),void t();this.sendRequest(R).then(t=>t.json().then(e=>t.status===HttpStatus.TOO_MANY_REQUESTS?{state:RequestStatus.TOO_MANY_REQUESTS}:{contactId:e.contactId,state:e&&e.next&&e.next.type}),()=>({state:RequestStatus.ERROR})).then(e=>{const s=this.getTrackingMessageByStatus(e.state);if(s&&this.tracking.send(s),c.skipNavigation)return e.state===RequestStatus.TOO_MANY_REQUESTS&&this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS),e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),void t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED);switch(e.state){case RequestStatus.SUCCESS:a&&d?this.goToView(d.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getSuccessViewIndex());break;case RequestStatus.ALREADY_SUBSCRIBED:m&&d?this.goToView(d.path[0]):this.runPostSubmitActionOrGoToView(()=>this.getAlreadySubscribedViewIndex());break;case RequestStatus.ERROR:m&&d?this.goToView(d.path[0]):this.handleErrorResponse();break;case RequestStatus.TOO_MANY_REQUESTS:this.goToView(m&&d?d.path[0]:this.getErrorViewIndex()),this.eventEmitter.emit(SysEventTypes.TOO_MANY_REQUESTS)}e.contactId&&"0"!==e.contactId&&this.eventEmitter.emit("CONTACT_ID_WAS_RECEIVED",e.contactId),this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,Object.assign(Object.assign({},e),{success:e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED})),t(e.state===RequestStatus.SUCCESS||e.state===RequestStatus.ALREADY_SUBSCRIBED)}).catch(()=>{this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_FINISHED,{state:RequestStatus.ERROR,success:!1}),c.skipNavigation||this.handleErrorResponse(),t(!1)})}getContextValue(t){var e,s;if(!t.excludeFormContext)return this.context.getKVMap();const i=(null===(s=(e=this.context).getRecordsMap)||void 0===s?void 0:s.call(e))||{};return Object.values(i).reduce((t,e)=>{var s;const i=null===(s=null==e?void 0:e.getValue)||void 0===s?void 0:s.call(e);return i&&"FORM"!==i.sourceId?(t[i.id]=i.value,t):t},{})}constructDataToSent({contextValue:t,formValue:e,utmParams:s}){const i=Object.assign({},t);return i.tracking=s,Object.keys(e).forEach(t=>{if(t.startsWith("clConsentId")){if(t.endsWith("_label"))return;const s={value:e[t]};e[`${t}_label`]&&(s.text=e[`${t}_label`]),i.consents?i.consents[t]=s:i.consents={[t]:s}}else{const s=e[t];i[t]=isDictionary(s)||Array.isArray(s)?JSON.stringify(s):s}}),i}constructRequestPayload({contextValue:t,formValue:e,utmParams:s}){let i={data:this.constructDataToSent({contextValue:t,formValue:e,utmParams:s}),referrer:window.location.href,triggeredBy:this.configService.getConfig("triggeredBy")};return this.configService.getConfig("widgetDebugMode")&&(i.ignoreTracking=!0),i}constructRequestHeaders(){const t={},e=this.configService.getConfig("clCustomerId");return e&&Object.assign(t,{"cl-customer-id":e}),t}goToView(t,e){this.eventEmitter.emit(SysActionTypes.GO_TO_VIEW,t,e)}sendRequest(t){return this.skipHttpRequest?Promise.resolve({status:200,json:()=>Promise.resolve({next:{type:RequestStatus.SUCCESS}})}):this.httpClient.execute(this.configService.getConfig("subscribeContactUrl"),"POST",t,this.constructRequestHeaders())}getSuccessViewIndex(){return this.resolveResultViewIndex("successViewId",["DOCUMENT_VIEW_TYPE_SUCCESS","DOCUMENT_VIEW_TYPE_SUCCESSFUL_REQUEST","REQUEST_FORM_VIEW_TYPE_SUCCESS"])}getErrorViewIndex(){return this.resolveResultViewIndex("errorViewId",["DOCUMENT_VIEW_TYPE_ERROR"])}getAlreadySubscribedViewIndex(){const t=this.getActiveSubmitActionParams();return t&&!t.alreadySubscribedViewId?this.getSuccessViewIndex():this.resolveResultViewIndex("alreadySubscribedViewId",["DOCUMENT_VIEW_TYPE_SUBSCRIBED"])}resolveResultViewIndex(t,e){var s;const i=this.getServices().documentModel.getViews(),n=null===(s=this.getActiveSubmitActionParams())||void 0===s?void 0:s[t];if(n){const t=i.findIndex(t=>t.id===n);if(-1!==t)return t}return i.findIndex(t=>e.includes(t.label))}hasFormControls(){return this.form.getControlsAsArray().length>0}getActiveSubmitActionParams(){if(this.hasFormControls())return this.getServices().documentModel.getShared().submitActionParams}runPostSubmitActionOrGoToView(t){var e;const s=null===(e=this.getActiveSubmitActionParams())||void 0===e?void 0:e.runAction;s?setTimeout(()=>{this.getServices().actionFactory.get(s).execute(this.stateService.getState())},1500):this.goToView(t())}handleErrorResponse(){const t=this.getErrorViewIndex();-1!==t?this.goToView(t):this.eventEmitter.emit(SysEventTypes.SUBMIT_REQUEST_ERROR_WITHOUT_VIEW)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@claspo/renderer",
3
- "version": "18.7.4",
3
+ "version": "18.7.5-ctx.10",
4
4
  "scripts": {
5
5
  "dev": " tsc --project tsconfig.json --watch",
6
6
  "build": "rm -rf out && tsc --project tsconfig.json && npm run minify",
@@ -7,14 +7,18 @@ export interface SourceUpdateDataI {
7
7
  value: string;
8
8
  componentId?: string;
9
9
  }
10
+ export interface ContextRecordUpdatedParamsI extends SourceUpdateDataI {
11
+ sourceId: string;
12
+ }
10
13
  export default class ContextSDK extends DefaultEventEmitter {
11
14
  sourceRegistry: SourceRegistry;
12
15
  data: ContextData;
13
16
  isStaticMode: boolean;
17
+ private subscribedSourceIds;
14
18
  constructor(sourceRegistry: SourceRegistry, contextData: ContextData, isStaticMode: boolean);
15
19
  getRegistry(): SourceRegistry;
16
20
  addRecord: (key: string, params: ContextRecordValueI) => void;
17
- updateRecord: (key: string, params: Partial<ContextRecordValueI>) => void;
21
+ updateRecord: (key: string, params: Partial<ContextRecordValueI>, eventParams?: ContextRecordUpdatedParamsI | null) => void;
18
22
  deleteRecord(key: string): void;
19
23
  getRecord: (key: string) => Record | undefined;
20
24
  getRecordsMap(): {
@@ -25,4 +29,9 @@ export default class ContextSDK extends DefaultEventEmitter {
25
29
  };
26
30
  initSources(): void;
27
31
  subscribeToSource(params: ContextRecordValueI): void;
32
+ getAffectedRecordKeys(sourceId: string, changedKey: string, componentId?: string): string[];
33
+ resolveRecordValueFromSource(record: ContextRecordValueI, source: {
34
+ getValue: (key?: string) => any;
35
+ }, fallbackValue: any): any;
36
+ arePathsOverlapping(targetPath: string, changedPath: string): boolean;
28
37
  }
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{ContextEvents}from"./ContextEvents";export default class ContextSDK extends DefaultEventEmitter{constructor(t,e,s){super(),this.addRecord=(t,e)=>{const s=this.data.addRecord(t,e);this.subscribeToSource(e),this.emit(ContextEvents.RECORD_ADDED,s)},this.updateRecord=(t,e)=>{const s=this.data.getRecord(t);(null==s?void 0:s.update(e))&&this.emit(ContextEvents.RECORD_UPDATED,s.getValue())},this.getRecord=t=>this.data.getRecord(t),this.sourceRegistry=t,this.data=e,this.isStaticMode=s,this.initSources()}getRegistry(){return this.sourceRegistry}deleteRecord(t){const e=this.data.getRecord(t);e&&!this.isStaticMode&&(this.data.deleteRecord(t),this.emit(ContextEvents.RECORD_DELETED,e))}getRecordsMap(){return this.data.getRecordsMap()}getKVMap(){return this.data.getKVMap()}initSources(){this.sourceRegistry.registerInitialSources(),this.sourceRegistry.getSources().forEach(t=>{const e=t.getValue();!this.isStaticMode&&e&&Object.keys(e).length&&Object.entries(e).forEach(([t,e])=>{this.addRecord(t,e)})})}subscribeToSource(t){const e=this.sourceRegistry.getSource(t.sourceId);e&&!e.isSubscribed()&&e.subscribe(({key:t,value:e,componentId:s})=>{this.updateRecord(s,{value:e})})}}
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{ContextEvents}from"./ContextEvents";export default class ContextSDK extends DefaultEventEmitter{constructor(e,t,s){super(),this.subscribedSourceIds=new Set,this.addRecord=(e,t)=>{const s=this.data.addRecord(e,t);this.subscribeToSource(t),this.emit(ContextEvents.RECORD_ADDED,s)},this.updateRecord=(e,t,s=null)=>{const r=this.data.getRecord(e);(null==r?void 0:r.update(t))&&this.emit(ContextEvents.RECORD_UPDATED,r.getValue(),s)},this.getRecord=e=>this.data.getRecord(e),this.sourceRegistry=e,this.data=t,this.isStaticMode=s,this.initSources()}getRegistry(){return this.sourceRegistry}deleteRecord(e){const t=this.data.getRecord(e);t&&!this.isStaticMode&&(this.data.deleteRecord(e),this.emit(ContextEvents.RECORD_DELETED,t))}getRecordsMap(){return this.data.getRecordsMap()}getKVMap(){return this.data.getKVMap()}initSources(){this.sourceRegistry.registerInitialSources(),this.sourceRegistry.getSources().forEach(e=>{const t=e.getValue();!this.isStaticMode&&t&&Object.keys(t).length&&Object.entries(t).forEach(([e,t])=>{this.addRecord(e,t)})})}subscribeToSource(e){const t=this.sourceRegistry.getSource(e.sourceId);t&&!this.subscribedSourceIds.has(t.id)&&(this.subscribedSourceIds.add(t.id),t.subscribe(({key:e,value:s,componentId:r})=>{const o={sourceId:t.id,key:e,value:s,componentId:r};this.getAffectedRecordKeys(t.id,e,r).forEach(e=>{const r=this.data.getRecord(e);if(!r)return;const c=this.resolveRecordValueFromSource(r.getValue(),t,s);this.updateRecord(e,{value:c},o)})}))}getAffectedRecordKeys(e,t,s){const r=s||t,o=new Set;return this.data.getRecord(r)&&o.add(r),Object.entries(this.data.getRecordsMap()).forEach(([s,r])=>{const c=r.getValue();c.sourceId===e&&c.sourceDependencyKey&&this.arePathsOverlapping(c.sourceDependencyKey,t)&&o.add(s)}),Array.from(o)}resolveRecordValueFromSource(e,t,s){var r;if(!e.sourceModel)return s;const o=t.getValue(e.sourceDependencyKey||e.id);return o&&"function"==typeof o.processor?o.processor(t,e.sourceModel):null!==(r=null==o?void 0:o.value)&&void 0!==r?r:e.value}arePathsOverlapping(e,t){return e===t||e.startsWith(`${t}.`)||t.startsWith(`${e}.`)}}
@@ -16,8 +16,17 @@ export default class AbstractMergeTagsProcessor {
16
16
  element: HTMLElement | null;
17
17
  mergeTags: MergeTagsMapI | null;
18
18
  componentId: string | null;
19
+ contextRecordUpdatesSubscription: {
20
+ off: () => void;
21
+ } | null;
19
22
  constructor(context: ContextSDK, configService: ConfigService);
20
23
  destroy(): void;
21
24
  process(element: HTMLElement, mergeTags: MergeTagsMapI, componentId: string): void;
22
25
  processSingleMergeTag(containerElement: HTMLElement, mergeTag: MergeTagI): void;
26
+ _subscribeToDynamicMergeTagUpdates(): void;
27
+ _processDynamicMergeTags(record: {
28
+ key?: string;
29
+ id?: string;
30
+ } | null): void;
31
+ _findMergeTagElement(mergeTagId: string): HTMLElement | null;
23
32
  }
@@ -1 +1 @@
1
- export default class AbstractMergeTagsProcessor{constructor(e,t){this.context=e,this.configService=t,this.element=null,this.mergeTags=null,this.componentId=null}destroy(){}process(e,t,s){this.element=e,this.mergeTags=t,this.componentId=s,this.mergeTags&&0!==Object.keys(this.mergeTags).length&&this.element.childNodes.forEach(e=>{if(e.nodeType!==Node.TEXT_NODE&&"MERGE_TAG"===e.getAttribute("cl-type")){const t=e.getAttribute("cl-id"),s=this.mergeTags[t];if(!s)return;this.processSingleMergeTag(e,s)}})}processSingleMergeTag(e,t){throw new Error("BaseMergeTagsProcessor: processSingleMergeTag is not implemented")}}
1
+ import{ContextEvents}from"../context/ContextEvents";export default class AbstractMergeTagsProcessor{constructor(e,t){this.context=e,this.configService=t,this.element=null,this.mergeTags=null,this.componentId=null,this.contextRecordUpdatesSubscription=null}destroy(){this.contextRecordUpdatesSubscription&&(this.contextRecordUpdatesSubscription.off(),this.contextRecordUpdatesSubscription=null)}process(e,t,s){this.element=e,this.mergeTags=t,this.componentId=s,this._subscribeToDynamicMergeTagUpdates(),this.mergeTags&&0!==Object.keys(this.mergeTags).length&&this.element.childNodes.forEach(e=>{if(e.nodeType!==Node.TEXT_NODE&&"MERGE_TAG"===e.getAttribute("cl-type")){const t=e.getAttribute("cl-id"),s=this.mergeTags[t];if(!s)return;this.processSingleMergeTag(e,s)}})}processSingleMergeTag(e,t){throw new Error("BaseMergeTagsProcessor: processSingleMergeTag is not implemented")}_subscribeToDynamicMergeTagUpdates(){this.contextRecordUpdatesSubscription&&(this.contextRecordUpdatesSubscription.off(),this.contextRecordUpdatesSubscription=null),this.contextRecordUpdatesSubscription=this.context.on(ContextEvents.RECORD_UPDATED,e=>{this._processDynamicMergeTags(e)})}_processDynamicMergeTags(e){if(!this.element||!this.mergeTags)return;const t=(null==e?void 0:e.key)||(null==e?void 0:e.id);if(!t)return;const s=this.mergeTags[t];if(!s)return;const i=this._findMergeTagElement(s.id);i&&this.processSingleMergeTag(i,s)}_findMergeTagElement(e){return this.element?this.element.getAttribute("cl-id")===e?this.element:this.element.querySelector(`[cl-id="${e}"]`):null}}
@@ -1,4 +1,6 @@
1
1
  import AbstractMergeTagsProcessor, { MergeTagI } from './AbstractMergeTagsProcessor';
2
2
  export default class StaticMergeTagsProcessor extends AbstractMergeTagsProcessor {
3
+ _getRecordId(mergeTag: MergeTagI): string;
4
+ _getMergeTagDependencyPath(mergeTag: MergeTagI): string;
3
5
  processSingleMergeTag(tagContainerElement: HTMLElement, mergeTag: MergeTagI): void;
4
6
  }
@@ -1 +1 @@
1
- import AbstractMergeTagsProcessor from"./AbstractMergeTagsProcessor";import getMostNestedNode from"@claspo/common/dom/getMostNestedNode";import{PreviewMode}from"../PreviewMode";export default class StaticMergeTagsProcessor extends AbstractMergeTagsProcessor{processSingleMergeTag(e,t){const o=this.context.getRecord(t.id),s=this.context.getRegistry().getSource(t.sourceId),i=this.context.getKVMap();let r,c;if(!o&&i[t.id]&&(c=i[t.id]),s){const e=s.getValue((null==o?void 0:o.value.id)||t.id);c=(null==e?void 0:e.value)||c,e&&"function"==typeof e.processor&&(r=e.processor(s,t))}const d=this.configService.getConfig(PreviewMode.CABINET_PREVIEW)||this.configService.getConfig(PreviewMode.EDITOR_PREVIEW)||this.configService.getConfig(PreviewMode.DEMO);let g=r||c||(null==o?void 0:o.value.value)||t.fallbackValue||(d?t.exampleValue:"");o||this.context.addRecord(t.id,Object.assign(Object.assign({recordKey:t.id,id:t.id,sourceId:t.sourceId},s?s.getValue(t.id):{}),{value:g})),e.style.fontFamily="inherit",getMostNestedNode(e).textContent=g}}
1
+ import AbstractMergeTagsProcessor from"./AbstractMergeTagsProcessor";import getMostNestedNode from"@claspo/common/dom/getMostNestedNode";import{PreviewMode}from"../PreviewMode";import JSApiVariablesSource from"../source/sources/JSApiVariablesSource";import DataLayerSource from"../source/sources/DataLayerSource";import UrlQueryParamsSource from"../source/sources/UrlQueryParamsSource";import CookieSource from"../source/sources/CookieSource";import LocalStorageSource from"../source/sources/LocalStorageSource";export default class StaticMergeTagsProcessor extends AbstractMergeTagsProcessor{_getRecordId(e){return e.id}_getMergeTagDependencyPath(e){if(!e.arguments||!Array.isArray(e.arguments))return"";const r={[JSApiVariablesSource.sourceId]:"JavaScriptVariable",[DataLayerSource.sourceId]:"dataLayerPropPath",[UrlQueryParamsSource.sourceId]:"urlQueryParamName",[CookieSource.sourceId]:"cookieName",[LocalStorageSource.sourceId]:"localStorageKey"},o=e.sourceId?r[e.sourceId]:void 0;if(!o)return"";const t=e.arguments.find(e=>e.name===o);return(null==t?void 0:t.value)||""}processSingleMergeTag(e,r){const o=this._getRecordId(r),t=this.context.getRecord(o),s=this.context.getRegistry().getSource(r.sourceId),c=this.context.getKVMap();let a,u;if(!t&&c[o]&&(u=c[o]),s){const e=s.getValue((null==t?void 0:t.value.id)||o);u=(null==e?void 0:e.value)||u,e&&"function"==typeof e.processor&&(a=e.processor(s,r))}const i=this.configService.getConfig(PreviewMode.CABINET_PREVIEW)||this.configService.getConfig(PreviewMode.EDITOR_PREVIEW)||this.configService.getConfig(PreviewMode.DEMO);let d=a||u||(null==t?void 0:t.value.value)||r.fallbackValue||(i?r.exampleValue:"");t||this.context.addRecord(o,Object.assign(Object.assign({recordKey:o,id:o,sourceId:r.sourceId,sourceDependencyKey:this._getMergeTagDependencyPath(r),sourceModel:r},s?s.getValue(o):{}),{value:d})),e.style.fontFamily="inherit",getMostNestedNode(e).textContent=d}}
@@ -1 +1 @@
1
- import{ContextEvents}from"../context/ContextEvents";import AbstractMergeTagsProcessor from"./AbstractMergeTagsProcessor";import getMostNestedNode from"@claspo/common/dom/getMostNestedNode";import DataLayerSource from"../source/sources/DataLayerSource";import UrlQueryParamsSource from"../source/sources/UrlQueryParamsSource";import JSApiVariablesSource from"../source/sources/JSApiVariablesSource";import CookieSource from"../source/sources/CookieSource";import LocalStorageSource from"../source/sources/LocalStorageSource";export default class UpdatingMergeTagsProcessor extends AbstractMergeTagsProcessor{constructor(e,o){super(e,o),this.contextSubscriptions=[this.context.on(ContextEvents.RECORD_ADDED,this._handleContextEvents.bind(this)),this.context.on(ContextEvents.RECORD_UPDATED,this._handleContextEvents.bind(this)),this.context.on(ContextEvents.RECORD_DELETED,this._handleContextEvents.bind(this))]}destroy(){super.destroy(),this.contextSubscriptions&&this.contextSubscriptions.forEach(e=>e.off())}processSingleMergeTag(e,o){if(!e)return;const t=this.context.getRecord(o.id);e.style.fontFamily="inherit",getMostNestedNode(e).textContent=o.exampleValue,this._setMergeTagValidity(t,o,e)}_setMergeTagValidity(e,o,t){let r=!1;if(e||o.sourceId===DataLayerSource.sourceId||o.sourceId===UrlQueryParamsSource.sourceId||o.sourceId===JSApiVariablesSource.sourceId||o.sourceId===CookieSource.sourceId||o.sourceId===LocalStorageSource.sourceId||(r=!0),o.sourceId===DataLayerSource.sourceId){const e=o.arguments.find(e=>"dataLayerPropPath"===e.name);e&&e.value||(r=!0)}else{(!o.exampleValue||o.arguments&&!o.arguments.find(e=>e.value))&&(r=!0)}const s="tag-error";r?t.classList.add(s):t.classList.remove(s)}_handleContextEvents(e){var o;const t=null===(o=this.mergeTags)||void 0===o?void 0:o[e.key];t&&this.processSingleMergeTag(this.element.querySelector(`[cl-id="${t.id}"]`),t)}}
1
+ import{ContextEvents}from"../context/ContextEvents";import AbstractMergeTagsProcessor from"./AbstractMergeTagsProcessor";import getMostNestedNode from"@claspo/common/dom/getMostNestedNode";import DataLayerSource from"../source/sources/DataLayerSource";import UrlQueryParamsSource from"../source/sources/UrlQueryParamsSource";import JSApiVariablesSource from"../source/sources/JSApiVariablesSource";import CookieSource from"../source/sources/CookieSource";import LocalStorageSource from"../source/sources/LocalStorageSource";export default class UpdatingMergeTagsProcessor extends AbstractMergeTagsProcessor{constructor(e,o){super(e,o),this.contextSubscriptions=[this.context.on(ContextEvents.RECORD_ADDED,this._handleContextEvents.bind(this)),this.context.on(ContextEvents.RECORD_DELETED,this._handleContextEvents.bind(this))]}destroy(){super.destroy(),this.contextSubscriptions&&this.contextSubscriptions.forEach(e=>e.off())}processSingleMergeTag(e,o){if(!e)return;const r=this.context.getRecord(o.id);e.style.fontFamily="inherit",getMostNestedNode(e).textContent=o.exampleValue,this._setMergeTagValidity(r,o,e)}_setMergeTagValidity(e,o,r){let t=!1;if(e||o.sourceId===DataLayerSource.sourceId||o.sourceId===UrlQueryParamsSource.sourceId||o.sourceId===JSApiVariablesSource.sourceId||o.sourceId===CookieSource.sourceId||o.sourceId===LocalStorageSource.sourceId||(t=!0),o.sourceId===DataLayerSource.sourceId){const e=o.arguments.find(e=>"dataLayerPropPath"===e.name);e&&e.value||(t=!0)}else{(!o.exampleValue||o.arguments&&!o.arguments.find(e=>e.value))&&(t=!0)}const s="tag-error";t?r.classList.add(s):r.classList.remove(s)}_handleContextEvents(e){var o;const r=(null==e?void 0:e.key)||(null==e?void 0:e.id);if(!r)return;const t=null===(o=this.mergeTags)||void 0===o?void 0:o[r];t&&this.processSingleMergeTag(this.element.querySelector(`[cl-id="${t.id}"]`),t)}}
@@ -2,7 +2,6 @@ import { SourceUpdateDataI } from '../context/ContextSDK';
2
2
  export interface SubscriptionEntryI {
3
3
  subscribe(cb: (data: SourceUpdateDataI) => void): void;
4
4
  getValue(key?: string): any;
5
- getSessionHistory?(): string[];
6
5
  }
7
6
  export interface SourceConfigI {
8
7
  [key: string]: any;
@@ -15,6 +14,5 @@ export default class Source {
15
14
  constructor(id: string, subscriptionEntry: SubscriptionEntryI, config?: SourceConfigI);
16
15
  subscribe(cb: (data: SourceUpdateDataI) => void): void;
17
16
  getValue(key?: string): any;
18
- getSessionHistory(): string[];
19
17
  isSubscribed(): boolean;
20
18
  }
@@ -1 +1 @@
1
- export default class Source{constructor(s,i,t={}){this.id=s,this.subscriptionEntry=i,this.config=t,this.subscribed=!1}subscribe(s){this.subscribed=!0,this.subscriptionEntry.subscribe(s)}getValue(s){return this.subscriptionEntry.getValue(s)}getSessionHistory(){var s,i;return(null===(i=(s=this.subscriptionEntry).getSessionHistory)||void 0===i?void 0:i.call(s))||[new URL(window.location.href).search]}isSubscribed(){return this.subscribed}}
1
+ export default class Source{constructor(s,i,t={}){this.id=s,this.subscriptionEntry=i,this.config=t,this.subscribed=!1}subscribe(s){this.subscribed=!0,this.subscriptionEntry.subscribe(s)}getValue(s){return this.subscriptionEntry.getValue(s)}isSubscribed(){return this.subscribed}}
@@ -1,8 +1,8 @@
1
1
  import Source from "./Source";
2
2
  import { UrlQueryParamsConfigI } from "./sources/UrlQueryParamsSource";
3
- import { JSApiVariablesConfigI } from "./sources/JSApiVariablesSource";
4
3
  import FormGroup from '../../form/FormGroup';
5
- export interface SourceRegistryConfigI extends UrlQueryParamsConfigI, JSApiVariablesConfigI {
4
+ export interface SourceRegistryConfigI extends UrlQueryParamsConfigI {
5
+ jsSource?: Source;
6
6
  [key: string]: any;
7
7
  }
8
8
  export default class SourceRegistry {
@@ -10,7 +10,7 @@ export default class SourceRegistry {
10
10
  [key: string]: Source;
11
11
  };
12
12
  sources: Source[];
13
- constructor(form: FormGroup, config: SourceRegistryConfigI);
13
+ constructor(form: FormGroup, config?: SourceRegistryConfigI);
14
14
  registerSource(source: Source): Source;
15
15
  getSource(id: string): Source | undefined;
16
16
  getSources(): Source[];
@@ -1 +1 @@
1
- import Source from"./Source";import FormSource from"./sources/FormSource";import UrlQueryParamsSource from"./sources/UrlQueryParamsSource";import DataLayerSource from"./sources/DataLayerSource";import JSApiVariablesSource from"./sources/JSApiVariablesSource";import CookieSource from"./sources/CookieSource";import LocalStorageSource from"./sources/LocalStorageSource";export default class SourceRegistry{constructor(r,e){this.registeredSourcesMap={},this.sources=[new Source("FORM",new FormSource(r)),new Source("DATA_LAYER",new DataLayerSource),new Source("URL_QUERY_PARAMS",new UrlQueryParamsSource(e)),new Source("JS_API_VARIABLE",new JSApiVariablesSource(e)),new Source("COOKIE",new CookieSource),new Source("LOCAL_STORAGE",new LocalStorageSource)]}registerSource(r){if(this.registeredSourcesMap[r.id])throw new Error(`Source with id ${r.id} already registered`);return this.registeredSourcesMap[r.id]=r}getSource(r){return this.registeredSourcesMap[r]}getSources(){return Object.values(this.registeredSourcesMap)}registerInitialSources(){return this.sources.map(r=>this.registerSource(r))}}
1
+ import Source from"./Source";import FormSource from"./sources/FormSource";import UrlQueryParamsSource from"./sources/UrlQueryParamsSource";import DataLayerSource from"./sources/DataLayerSource";import CookieSource from"./sources/CookieSource";import LocalStorageSource from"./sources/LocalStorageSource";export default class SourceRegistry{constructor(r,e={}){this.registeredSourcesMap={},this.sources=[new Source("FORM",new FormSource(r)),new Source("DATA_LAYER",new DataLayerSource),new Source("URL_QUERY_PARAMS",new UrlQueryParamsSource(e)),new Source("COOKIE",new CookieSource),new Source("LOCAL_STORAGE",new LocalStorageSource)],e.jsSource&&this.sources.push(e.jsSource)}registerSource(r){if(this.registeredSourcesMap[r.id])throw new Error(`Source with id ${r.id} already registered`);return this.registeredSourcesMap[r.id]=r}getSource(r){return this.registeredSourcesMap[r]}getSources(){return Object.values(this.registeredSourcesMap)}registerInitialSources(){return this.sources.map(r=>this.registerSource(r))}}
@@ -1,5 +1,6 @@
1
1
  import DefaultEventEmitter from "@claspo/common/DefaultEventEmitter";
2
2
  import { SourceUpdateDataI } from '../../context/ContextSDK';
3
+ import { SourceType } from "@claspo/common/document/hidden-fields.interface";
3
4
  declare global {
4
5
  interface Window {
5
6
  [key: string]: any;
@@ -21,10 +22,15 @@ export interface JSApiVariablesProcessorResultI {
21
22
  processor: (ctx: any, model: JSApiVariablesModelI) => string;
22
23
  }
23
24
  export default class JSApiVariablesSource extends DefaultEventEmitter {
24
- static sourceId: string;
25
+ static sourceId: SourceType;
25
26
  instanceName: string | undefined;
26
27
  constructor(config?: JSApiVariablesConfigI);
28
+ get appInstance(): any;
29
+ get variables(): any;
27
30
  subscribe(cb: (data: SourceUpdateDataI) => void): void;
28
31
  getValue(key?: string): JSApiVariablesProcessorResultI | Record<string, never>;
32
+ addValues<T extends {
33
+ [key: string]: any;
34
+ }>(values: T): void;
29
35
  static processModel(model: JSApiVariablesModelI, instanceName?: string): string;
30
36
  }
@@ -1 +1 @@
1
- import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";class JSApiVariablesSource extends DefaultEventEmitter{constructor(e={}){super(),this.instanceName=e.instanceName}subscribe(e){}getValue(e){return e?{processor:(e,r)=>JSApiVariablesSource.processModel(r,this.instanceName)}:{}}static processModel(e,r){var a;if(!e.arguments)return"";const t=e.arguments.find(e=>"JavaScriptVariable"===e.name);if(!(null==t?void 0:t.value)||!r||!(null===(a=window[r])||void 0===a?void 0:a.variables))return"";try{return window[r].variables[t.value]||""}catch(r){return console.error("JSApiVariablesSource: error while getting variable. Model: ",e,"Error: ",r),""}}}JSApiVariablesSource.sourceId="JS_API_VARIABLE";export default JSApiVariablesSource;
1
+ import DefaultEventEmitter from"@claspo/common/DefaultEventEmitter";import{SourceType}from"@claspo/common/document/hidden-fields.interface";import resolveVariableValue from"./resolveVariableValue";class JSApiVariablesSource extends DefaultEventEmitter{constructor(e={}){super(),this.instanceName=e.instanceName}get appInstance(){return window[this.instanceName]}get variables(){var e;return(null===(e=this.appInstance)||void 0===e?void 0:e.variables)||{}}subscribe(e){this.on("CHANGE",({values:r})=>{for(let a in r)e({key:a,value:r[a]})})}getValue(e){return e?{processor:(e,r)=>JSApiVariablesSource.processModel(r,this.instanceName)}:{}}addValues(e){if(!this.appInstance)throw new Error("Instatiate first");if(!e||"object"!=typeof e)throw new Error("Values should be object");Object.keys(e).length&&(this.appInstance.variables=Object.assign(Object.assign({},this.variables),e),this.emit("CHANGE",{values:e}))}static processModel(e,r){var a;if(!e.arguments)return"";const t=e.arguments.find(e=>"JavaScriptVariable"===e.name);if(!(null==t?void 0:t.value)||!r||!(null===(a=window[r])||void 0===a?void 0:a.variables))return"";try{const e=resolveVariableValue(window[r].variables,t.value);return null==e?"":e}catch(r){return console.error("JSApiVariablesSource: error while getting variable. Model: ",e,"Error: ",r),""}}}JSApiVariablesSource.sourceId=SourceType.JS_API_VARIABLE;export default JSApiVariablesSource;
@@ -0,0 +1 @@
1
+ export default function resolveVariableValue(variables: Record<string, any> | undefined, key: string | undefined): any;
@@ -0,0 +1 @@
1
+ import{flat}from"@claspo/common/flat";export default function resolveVariableValue(r,t){if(!r||!t)return;if(Object.prototype.hasOwnProperty.call(r,t))return r[t];const e=t.split(".").filter(Boolean);if(!e.length)return;const l=(r,t)=>{if(t>=e.length)return r;if(null!=r){if(Array.isArray(r)){const e=flat(r.map(r=>l(r,t)),1/0).filter(r=>void 0!==r);return e.length?e:void 0}return l(r[e[t]],t+1)}};return l(r,0)}