@viamedici-spc/configurator-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("@viamedici/fp-ts-extensions"),ie=require("ts-pattern"),_=require("fast-equals"),u=require("react"),h=require("react/jsx-runtime"),r=require("xstate"),d=require("xstate/lib/actions"),I=require("@viamedici/fp-ts-extensions/Eq"),se=require("@xstate/react");globalThis&&globalThis.__spreadArray;var oe=function(e){return e._tag==="Some"};function O(e){return{equals(t,i){return t==null&&i==null?!0:t==null||i===null||i===void 0?!1:e.equals(t,i)}}}function y(e){return{equals(t,i){const s=n.pipe(n.O.fromNullable(t),n.O.getOrElse(()=>[])),o=n.pipe(n.O.fromNullable(i),n.O.getOrElse(()=>[]));return n.RA.getEq(e).equals(s,o)}}}const N=n.Eq.struct({localId:n.Str.Eq,componentPath:y(n.Str.Eq),sharedConfigurationModel:O(n.Str.Eq)}),re=n.O.getEq(n.RA.getEq(n.Eq.struct({attributeId:N,decisions:y(N)})));n.Eq.struct({configurationModelSource:n.Eq.fromEquals((e,t)=>_.deepEqual(e,t)),decisionsToRespect:re,usageRuleParameters:n.RR.getEq(n.Str.Eq)});const ae={equals:(e,t)=>e.choiceValueId!==t.choiceValueId?!1:e.state===t.state},ue={equals(e,t){return e.value===t.value}},le={equals(e,t){return e.value===t.value}},ce={equals(e,t){return e.state===t.state}},pe={equals(e,t){return N.equals(e.attributeId,t.attributeId)?ie.match({x:e,y:t}).with({x:{type:"Choice"},y:{type:"Choice"}},(i,s)=>ae.equals(s.x,s.y)).with({x:{type:"Numeric"},y:{type:"Numeric"}},(i,s)=>ue.equals(s.x,s.y)).with({x:{type:"Boolean"},y:{type:"Boolean"}},(i,s)=>le.equals(s.x,s.y)).with({x:{type:"Component"},y:{type:"Component"}},(i,s)=>ce.equals(s.x,s.y)).otherwise(()=>!1):!1}};n.RA.getEq(pe);const j=n.Eq.struct({localId:n.Str.Eq,componentPath:y(n.Str.Eq),sharedConfigurationModelId:O(n.Str.Eq)}),de=n.Eq.struct({localId:n.Str.Eq,componentPath:y(n.Str.Eq),sharedConfigurationModelId:O(n.Str.Eq)});var D=(e=>(e.Choice="Choice",e.ChoiceValue="ChoiceValue",e))(D||{}),p=(e=>(e.Boolean="Boolean",e.Numeric="Numeric",e.Choice="Choice",e.Component="Component",e))(p||{}),x=(e=>(e.Implicit="Implicit",e.Explicit="Explicit",e))(x||{});n.Eq.struct({localId:n.Str.Eq,componentPath:y(n.Str.Eq),sharedConfigurationModelId:O(n.Str.Eq)});function ge(e,t){return n.pipe(e.values,n.RA.filterMap(i=>n.pipe(i.decision,n.O.fromNullable,n.O.filter(s=>s.kind===t))))}function fe(e){return n.pipe(e.decision,n.O.fromNullable,n.O.filter(t=>t.kind===x.Explicit),n.O.toNullable)}function me(e){return n.pipe(e.decision,n.O.fromNullable,n.O.filter(t=>t.kind===x.Explicit),n.O.toNullable)}function Ce(e){return n.pipe(e.decision,n.O.fromNullable,n.O.toNullable)}const B=e=>e.type===p.Boolean,F=e=>e.type===p.Choice,V=e=>e.type===p.Numeric,H=e=>e.type===p.Component,Se=y(n.Str.Eq);function he(e,t,i){var s;const o=((s=t.componentPath)==null?void 0:s.length)??0;return n.pipe(e,n.RA.filter(a=>{var c;const g=((c=a.id.componentPath)==null?void 0:c.length)??0;return i?o>g?!1:n.pipe(a.id.componentPath??[],n.RA.zip(t.componentPath??[]),n.RA.every(([l,f])=>l===f)):Se.equals(a.id.componentPath,t.componentPath)}))}function ye(e,t,i){return[]}function Ee(e){return n.pipe(e,n.RA.filter(t=>{const i=n.pipe(t.id.componentPath,n.O.fromNullable,n.O.map(o=>o.length===0),n.O.getOrElse(()=>!0)),s=n.pipe(t.id.sharedConfigurationModelId,n.O.fromNullable,n.O.match(()=>!0,()=>!1));return i&&s}))}function Ae(e,t){return n.pipe(K(e),n.RA.map(i=>ge(i,t)),n.RA.flatten,n.RA.filterMap(i=>n.O.fromNullable(i)))}function qe(e,t){return n.pipe(L(e),n.RA.filter(i=>{var s;return((s=i.decision)==null?void 0:s.kind)===t}),n.RA.map(i=>fe(i)),n.RA.filterMap(i=>n.O.fromNullable(i)))}function Re(e,t){return n.pipe(Q(e),n.RA.filter(i=>{var s;return((s=i.decision)==null?void 0:s.kind)===t}),n.RA.map(i=>me(i)),n.RA.filterMap(i=>n.O.fromNullable(i)))}function be(e,t){return n.pipe(G(e),n.RA.filter(i=>{var s;return((s=i.decision)==null?void 0:s.kind)===t}),n.RA.map(i=>Ce(i)),n.RA.filterMap(i=>n.O.fromNullable(i)))}function K(e){return n.pipe(e.attributes,n.RA.filter(F))}function G(e){return n.pipe(e.attributes,n.RA.filter(H))}function L(e){return n.pipe(e.attributes,n.RA.filter(V))}function Q(e){return n.pipe(e.attributes,n.RA.filter(B))}function Oe(e,t){return n.pipe(R(e,t),n.O.toUndefined)}function xe(e,t){return n.pipe(X(e,t),n.O.toUndefined)}function Me(e,t,i){return n.pipe(X(e,t),n.O.map(s=>s.values),n.O.chain(n.flow(n.RA.findFirst(s=>s.id===i))),n.O.toUndefined)}function Pe(e,t){return n.pipe(R(e,t),n.O.filter(V),n.O.toUndefined)}function ve(e,t){return n.pipe(R(e,t),n.O.filter(B),n.O.toUndefined)}function Ue(e,t){return n.pipe(R(e,t),n.O.filter(H),n.O.toUndefined)}function R(e,t){return n.pipe(e.attributes,n.RA.findFirst(i=>j.equals(i.id,t)))}function X(e,t){return n.pipe(R(e,t),n.O.filter(F))}const E=Object.freeze(Object.defineProperty({__proto__:null,filterAttributesOfComponent:he,filterAttributesOfRoot:Ee,filterAttributesOfShared:ye,getAttribute:Oe,getBooleanAttribute:ve,getBooleanAttributes:Q,getBooleanDecisions:Re,getChoiceAttribute:xe,getChoiceAttributes:K,getChoiceDecisions:Ae,getChoiceValue:Me,getComponentAttribute:Ue,getComponentAttributes:G,getComponentDecisions:be,getNumericAttribute:Pe,getNumericAttributes:L,getNumericDecisions:qe},Symbol.toStringTag,{value:"Module"})),T=j.equals;de.equals;const Y=u.createContext(null),Z=u.createContext(null),$=u.createContext(null),J=u.createContext(null),w=()=>u.useContext(Y),A=()=>u.useContext(J),W="The configuration is not initialized. Consider using the ConfigurationSuspender or unload components manually that make use of any unsafe hook while the configuration is initializing. Check the hooks documentation to see if it is safe to use while the configuration is initializing.";function k(e){if(!e)throw new Error(W)}function q(e){if(!e)throw new Error(W)}function ee(){const e=w();return k(e),u.useMemo(()=>({explainChoiceAttributeConsequence:(t,i,s)=>e.explain({type:D.ChoiceValue,attributeId:t,choiceValueId:i,question:s}),explainChoiceAttributeConsequences:(t,i)=>e.explain({type:D.Choice,attributeId:t,question:i}),applySolution:t=>e.applySolution(t)}),[e])}function b(){const e=w();return k(e),u.useMemo(()=>({makeDecision:t=>e.makeDecision(t),setManyDecision:(t,i)=>e.setMany(t,i)}),[e])}var M=function(e){return function(t){return oe(e(t))}};const Ie=M(e=>e.type===p.Choice?n.some(e):n.none),Ne=M(e=>e.type===p.Numeric?n.some(e):n.none),De=M(e=>e.type===p.Boolean?n.some(e):n.none),we=M(e=>e.type===p.Component?n.some(e):n.none);function P(e){return e.decision!=null&&e.decision.kind===x.Explicit}function ne(e){return n.pipe(e.values,n.RA.filter(P),n.RA.map(t=>({type:p.Choice,attributeId:e.id,choiceValueId:t.id,state:null})))}function ke(e){return n.pipe(e,n.O.fromPredicate(P),n.O.map(()=>({type:p.Numeric,attributeId:e.id,state:null})))}function Te(e){return n.pipe(e,n.O.fromPredicate(P),n.O.map(()=>({type:p.Boolean,attributeId:e.id,state:null})))}function ze(e){return n.pipe(e,n.O.fromPredicate(P),n.O.map(()=>({type:p.Component,attributeId:e.id,state:null})))}function _e(e,t){return n.pipe(E.filterAttributesOfComponent(t,e,!0),i=>[n.pipe(i,n.RA.filter(Ie),n.RA.chain(ne)),n.pipe(i,n.RA.filter(Ne),n.RA.map(ke),n.RA.compact),n.pipe(i,n.RA.filter(De),n.RA.map(Te),n.RA.compact),n.pipe(i,n.RA.filter(we),n.RA.map(ze),n.RA.compact)],n.RA.flatten)}function je(e,t){const i=A();return q(i),u.useMemo(()=>n.pipe(n.O.fromNullable(e),n.O.map(n.flow(n.RA.map(s=>E.getAttribute(i,s)),t??!1?n.identity:n.RA.filterMap(n.O.fromNullable))),n.O.getOrElse(()=>i.attributes)),[e,i,t])}function Be(e){const t=A(),{explainChoiceAttributeConsequence:i,explainChoiceAttributeConsequences:s,applySolution:o}=ee(),{makeDecision:a,setManyDecision:c}=b();q(t);const g=E.getChoiceAttribute(t,e),l=u.useMemo(()=>({explainConsequence:(m,C)=>i(e,m,C),explainConsequences:m=>s(e,m),makeDecision:(m,C)=>a({type:p.Choice,attributeId:e,choiceValueId:m,state:C}),clearDecisions:n.pipe(g,n.O.fromNullable,n.O.map(ne),n.O.filter(n.RA.isNonEmpty),n.O.map(m=>()=>c(m,{type:"Default"})),n.O.getOrElse(()=>()=>Promise.resolve())),applySolution:o}),[e,g,a,c,i,s,o]),f=u.useMemo(()=>({...l,attribute:g}),[g,l]);if(g)return f}function Fe(e){const t=A(),{makeDecision:i}=b();q(t);const s=E.getNumericAttribute(t,e),o=u.useMemo(()=>({makeDecision:c=>i({type:p.Numeric,attributeId:e,state:c})}),[e,i]),a=u.useMemo(()=>({...o,attribute:s}),[s,o]);if(s)return a}function Ve(e){const t=A(),{makeDecision:i}=b();q(t);const s=E.getBooleanAttribute(t,e),o=u.useMemo(()=>({makeDecision:c=>i({type:p.Boolean,attributeId:e,state:c})}),[e,i]),a=u.useMemo(()=>({...o,attribute:s}),[s,o]);if(s)return a}function He(e){const t=A(),{makeDecision:i,setManyDecision:s}=b();q(t);const o=t.attributes,a=E.getComponentAttribute(t,e),c=u.useMemo(()=>({makeDecision:l=>i({type:p.Component,attributeId:e,state:l}),clearSubtree:n.pipe(_e(e,o),n.O.fromPredicate(n.RA.isNonEmpty),n.O.map(l=>()=>s(l,{type:"Default"})),n.O.getOrElse(()=>()=>Promise.resolve()))}),[e,i,o,s]),g=u.useMemo(()=>({...c,attribute:a}),[a,c]);if(a)return g}const Ke=n.Eq.fromEquals((e,t)=>n.RR.getEq(n.Str.Eq).equals(e??{},t??{})),Ge=n.Eq.struct({attributeId:n.Eq.fromEquals(T),decisions:n.RA.getEq(n.Eq.fromEquals(T))}),Le=n.Eq.fromEquals((e,t)=>n.RA.getEq(Ge).equals(e??[],t??[])),v=n.Eq.struct({configurationModelSource:n.Eq.fromEquals((e,t)=>_.deepEqual(e,t)),attributeRelations:Le,usageRuleParameters:Ke}),Qe=n.Eq.eqStrict,U=I.eqNullable(Qe),Xe=()=>r.createMachine({predictableActionArguments:!0,preserveActionOrder:!0,schema:{context:{},events:{}},context:{desiredClient:null,desiredSessionContext:null,actualClient:null,session:null,sessionCreationError:null,sessionUpdateError:null,hasEverSuccessfullyCreatedSession:!1},initial:"ProcessChanges",on:{ChangeConfigurationClient:{actions:["saveDesiredClient"]},ChangeSessionContext:{actions:["saveDesiredSessionContext"]}},exit:[d.log("Shutting down","SessionManagement:"),"disposeOldSession"],states:{ProcessChanges:{entry:[d.log("Entering ProcessChanges","SessionManagement:"),S(2)],always:[{target:"DisposeSession",cond:"shallDisposeSession"},{target:"CreateSession",cond:"shallCreateSession"},{target:"UpdateSession",cond:"shallUpdateSession"}]},DisposeSession:{entry:[d.log("Entering DisposeSession","SessionManagement:"),S(2)],always:{actions:["disposeOldSession"],target:"ProcessChanges"}},CreateSession:{entry:[d.log("Entering CreateSession","SessionManagement:"),S(0)],invoke:{id:"getNewSession",src:"createSession",onDone:{actions:["setSessionCreationResult","setHasEverSuccessfullyCreatedSession"],target:"ProcessChanges"},onError:{actions:"setSessionCreationError",target:"SessionCreationFailed"}}},SessionCreationFailed:{entry:[d.log("Entering SessionCreationFailed","SessionManagement:"),S(2)],always:{target:"ProcessChanges",cond:"shallImmediatelyProcessChangesAfterSessionCreationError"},exit:[d.log("Exiting SessionCreationFailed","SessionManagement:"),"clearSessionCreationError"],on:{RetrySessionCreation:{target:"ProcessChanges",actions:d.log("Retrying session creation","SessionManagement:")}}},UpdateSession:{entry:[d.log("Entering UpdateSession","SessionManagement:"),S(1)],invoke:{id:"updateExistingSession",src:"updateSession",onDone:{target:"ProcessChanges"},onError:{actions:"setSessionUpdateError",target:"SessionUpdateFailed"}}},SessionUpdateFailed:{entry:[d.log("Entering SessionUpdateFailed","SessionManagement:"),S(2)],always:{target:"ProcessChanges",cond:"shallImmediatelyProcessChangesAfterSessionUpdateError"},exit:[d.log("Exiting SessionUpdateFailed","SessionManagement:"),"clearSessionUpdateError"],on:{RetrySessionUpdate:{target:"ProcessChanges",actions:d.log("Retrying session update","SessionManagement:")}}}}},{actions:{saveDesiredClient:r.assign({desiredClient:(e,t)=>t.client}),saveDesiredSessionContext:r.assign({desiredSessionContext:(e,t)=>t.sessionContext}),disposeOldSession:r.assign((e,t)=>(e.session&&e.session.close().then(n.constVoid).catch(i=>{}),{session:null,actualClient:null})),setSessionCreationResult:r.assign((e,t)=>({session:t.data.session,actualClient:t.data.client})),setSessionCreationError:r.assign((e,t)=>({sessionCreationError:t.data})),clearSessionCreationError:r.assign({sessionCreationError:()=>null}),setSessionUpdateError:r.assign((e,t)=>({sessionUpdateError:t.data})),clearSessionUpdateError:r.assign({sessionUpdateError:()=>null}),setHasEverSuccessfullyCreatedSession:r.assign({hasEverSuccessfullyCreatedSession:()=>!0})},services:{createSession:e=>e.desiredClient.createSession(e.desiredSessionContext).then(t=>({session:t,client:e.desiredClient})).catch(t=>Promise.reject({type:t.type,client:e.desiredClient,sessionContext:e.desiredSessionContext})),updateSession:e=>e.session.setSessionContext(e.desiredSessionContext).catch(t=>Promise.reject({type:t.type,sessionContext:e.desiredSessionContext}))},guards:{shallDisposeSession:e=>e.session!=null&&(e.desiredSessionContext==null||e.desiredClient==null||!U.equals(e.actualClient,e.desiredClient)),shallCreateSession:e=>e.session==null&&e.desiredClient!=null&&e.desiredSessionContext!=null,shallUpdateSession:e=>e.session!=null&&!v.equals(e.session.getSessionContext(),e.desiredSessionContext),shallImmediatelyProcessChangesAfterSessionCreationError:e=>!U.equals(e.desiredClient,e.sessionCreationError.client)||!I.eqNullable(v).equals(e.desiredSessionContext,e.sessionCreationError.sessionContext),shallImmediatelyProcessChangesAfterSessionUpdateError:e=>!U.equals(e.desiredClient,e.actualClient)||!I.eqNullable(v).equals(e.desiredSessionContext,e.sessionUpdateError.sessionContext)}});function S(e){const t=e===0,i=e===1;return d.pure((s,o)=>{const a={isInitializing:(!s.hasEverSuccessfullyCreatedSession||t)&&s.sessionCreationError==null,errorType:s.sessionCreationError&&s.sessionCreationError.type},c={isUpdating:i&&s.sessionUpdateError==null,errorType:s.sessionUpdateError&&s.sessionUpdateError.type};return r.sendParent({type:"SessionManagementStateChanged",sessionInitialization:a,sessionUpdating:c,session:s.session})})}const Ye=e=>t=>(t({type:"ConfigurationChanged",session:e,configuration:e.getConfiguration()}),e.setOnConfigurationChangedHandler(i=>{t({type:"ConfigurationChanged",session:e,configuration:i})}),()=>{e.setOnConfigurationChangedHandler(null)}),Ze=()=>r.createMachine({predictableActionArguments:!0,preserveActionOrder:!0,schema:{context:{},events:{}},context:{session:null},on:{ConfigurationChanged:{actions:[r.sendParent((e,t)=>t)]}},initial:"ProcessChanges",states:{ProcessChanges:{entry:[d.log("Entering ProcessChanges","ConfigurationSubscriptionManagement:")],on:{ChangeSession:{actions:["saveSession"]}},always:[{target:"Subscribe",cond:(e,t)=>e.session!=null}]},Subscribe:{entry:[d.log("Entering Subscribe","ConfigurationSubscriptionManagement:")],on:{ChangeSession:{target:"ProcessChanges",cond:(e,t)=>t.session==null||e.session!==t.session,actions:["saveSession"]}},invoke:{id:"configurationSubscriptionActor",src:(e,t)=>Ye(e.session)}}}},{actions:{saveSession:r.assign((e,t)=>({session:t.session}))}}),$e=()=>{let e,t;return{promise:new Promise((s,o)=>{e=s,t=o}),resolve:e,reject:t}},z=()=>{const e=$e();return{capsule:{promise:e.promise},resolve:e.resolve,reject:e.reject}},Je=()=>r.createMachine({predictableActionArguments:!0,preserveActionOrder:!0,schema:{context:{},events:{}},context:{sessionManagementActor:null,configurationSubscriptionManagementActor:null,sessionInitialization:null,sessionUpdating:null,session:null,configuration:null,isReadyPromise:z()},entry:[r.assign({sessionManagementActor:()=>r.spawn(Xe()),configurationSubscriptionManagementActor:()=>r.spawn(Ze())})],exit:[d.stop(e=>e.sessionManagementActor),d.stop(e=>e.configurationSubscriptionManagementActor)],on:{ChangeConfigurationClient:{actions:[r.forwardTo(e=>e.sessionManagementActor)]},ChangeSessionContext:{actions:[r.forwardTo(e=>e.sessionManagementActor)]},RetrySessionCreation:{actions:[r.forwardTo(e=>e.sessionManagementActor)]},RetrySessionUpdate:{actions:[r.forwardTo(e=>e.sessionManagementActor)]},SessionManagementStateChanged:{actions:[r.assign((e,t)=>({session:t.session,sessionInitialization:t.sessionInitialization,sessionUpdating:t.sessionUpdating})),r.send(e=>({type:"ChangeSession",session:e.session}),{to:e=>e.configurationSubscriptionManagementActor}),"calculateReadyState"]},ConfigurationChanged:{actions:[r.assign((e,t)=>({configuration:{session:t.session,configuration:t.configuration}})),"calculateReadyState"]}},initial:"Idle",states:{Idle:{}}},{actions:{calculateReadyState:r.assign((e,t)=>{var o;const i=!((o=e.sessionInitialization)!=null&&o.isInitializing)&&e.session!=null&&e.configuration!=null&&e.configuration.session===e.session;return e.isReadyPromise&&i&&(e.isReadyPromise.resolve(),e.isReadyPromise.capsule.promise=null),{isReadyPromise:(()=>i?null:e.isReadyPromise!=null?e.isReadyPromise:z())()}})}});function We(e){var c,g;const[t,i]=se.useMachine(Je,{logger:(...l)=>console.log("ConfigurationManagement:",...l)});u.useEffect(()=>{i({type:"ChangeConfigurationClient",client:e.configuratorClient}),e.configuratorClient||console.warn("The configurator client is null or undefined. This will dispose the session that may exist. If this was not intended, make sure you pass a valid client.")},[e.configuratorClient]),u.useEffect(()=>{const l=n.pipe(n.O.fromNullable(e.sessionContext),n.O.chainFirst(f=>n.O.fromNullable(f.configurationModelSource)),n.O.toNullable);i({type:"ChangeSessionContext",sessionContext:l}),l||console.warn("The session context is null or undefined. This will dispose the session that may exist. If this was not intended, make sure you pass valid session context data.")},[e.sessionContext]);const s=u.useMemo(()=>{var l,f,m,C;return{isInitializing:((f=(l=t.context.isReadyPromise)==null?void 0:l.capsule)==null?void 0:f.promise)!=null,isInitializingPromise:(m=t.context.isReadyPromise)==null?void 0:m.capsule,error:((C=t.context.sessionInitialization)==null?void 0:C.errorType)&&{type:t.context.sessionInitialization.errorType,retry:()=>i({type:"RetrySessionCreation"})}}},[t.context.sessionInitialization,t.context.isReadyPromise]),o=u.useMemo(()=>{var l,f;return{isUpdating:(l=t.context.sessionUpdating)==null?void 0:l.isUpdating,error:((f=t.context.sessionUpdating)==null?void 0:f.errorType)&&{type:t.context.sessionUpdating.errorType,retry:()=>i({type:"RetrySessionUpdate"})}}},[t.context.sessionUpdating]),a=((c=t.context.configuration)==null?void 0:c.session)===t.context.session?(g=t.context.configuration)==null?void 0:g.configuration:null;return{configurationInitialization:s,configurationUpdating:o,session:t.context.session,configuration:a}}function en(e){const{configurationInitialization:t,configurationUpdating:i,session:s,configuration:o}=We({configuratorClient:e.configuratorClient,sessionContext:e});return h.jsx(Z.Provider,{value:t,children:h.jsx($.Provider,{value:i,children:h.jsx(Y.Provider,{value:s,children:h.jsx(J.Provider,{value:o,children:e.children})})})})}function te(){return u.useContext(Z)}function nn(){return u.useContext($)}function tn(e){const{children:t}=e,{isInitializingPromise:i}=te();if(i!=null&&i.promise)throw i.promise;return h.jsx(h.Fragment,{children:t})}function sn(){const e=w(),t=A();return k(e),q(t),u.useMemo(()=>({configuration:t,restoreConfiguration:i=>e.restoreConfiguration(i)}),[t,e])}exports.Configuration=en;exports.ConfigurationSuspender=tn;exports.useAttributes=je;exports.useBooleanAttribute=Ve;exports.useChoiceAttribute=Be;exports.useComponentAttribute=He;exports.useConfiguration=sn;exports.useConfigurationInitialization=te;exports.useConfigurationUpdating=nn;exports.useDecision=b;exports.useExplain=ee;exports.useNumericAttribute=Fe;
@@ -0,0 +1,184 @@
1
+ import { Attribute } from '@viamedici-spc/configurator';
2
+ import { AttributeRelations } from '@viamedici-spc/configurator';
3
+ import { BooleanAttribute } from '@viamedici-spc/configurator';
4
+ import { ChoiceAttribute } from '@viamedici-spc/configurator';
5
+ import { ChoiceExplanationResult } from '@viamedici-spc/configurator';
6
+ import { ChoiceValueDecisionState } from '@viamedici-spc/configurator';
7
+ import { ChoiceValueExplanationResult } from '@viamedici-spc/configurator';
8
+ import { ChoiceValueId } from '@viamedici-spc/configurator';
9
+ import { ComponentAttribute } from '@viamedici-spc/configurator';
10
+ import { ComponentDecisionState } from '@viamedici-spc/configurator';
11
+ import { Configuration as Configuration_2 } from '@viamedici-spc/configurator';
12
+ import { ConfigurationModelSource } from '@viamedici-spc/configurator';
13
+ import { ExplainMode } from '@viamedici-spc/configurator';
14
+ import { ExplicitDecision } from '@viamedici-spc/configurator';
15
+ import { FailureType } from '@viamedici-spc/configurator';
16
+ import { GlobalAttributeId } from '@viamedici-spc/configurator';
17
+ import { IConfiguratorClient } from '@viamedici-spc/configurator';
18
+ import { NumericAttribute } from '@viamedici-spc/configurator';
19
+ import { PropsWithChildren } from 'react';
20
+ import { SetManyMode } from '@viamedici-spc/configurator';
21
+ import { Solution } from '@viamedici-spc/configurator';
22
+
23
+ export declare function Configuration(props: PropsWithChildren<ConfigurationProps>): JSX.Element;
24
+
25
+ export declare type ConfigurationError = {
26
+ type: FailureType;
27
+ retry?: () => void;
28
+ };
29
+
30
+ export declare type ConfigurationInitialization = {
31
+ /**
32
+ * Gets whether the configuration is currently initializing.
33
+ * This information is required for some hooks to be safely used.
34
+ */
35
+ isInitializing: boolean;
36
+ /**
37
+ * Houses a promise when the configuration is in the initializing state.
38
+ * The promise resolves upon completion of the configuration initialization, subsequently becoming null.
39
+ * A new promise is generated each time the configuration re-enters the initializing state.
40
+ *
41
+ * @remarks
42
+ * The promise is wrapped in an object to navigate occasional issues where React fails to propagate updates of a React Context to child elements within a React Suspense barrier.
43
+ * Such situations can lead to the initialization promise persistently remaining non-null, and thus, being continuously thrown by the ConfigurationSuspender even after it has been fulfilled.
44
+ * Upon fulfillment of the promise, the encapsulation is imperatively updated to remove the promise for all listeners inside React Suspense barriers.
45
+ */
46
+ isInitializingPromise: EncapsulatedPromise | null;
47
+ error?: ConfigurationError;
48
+ };
49
+
50
+ export declare type ConfigurationProps = {
51
+ /**
52
+ * The client that is used to create a configuration session.
53
+ * When the instance changes, the old session is disposed and a new session is created. All decisions are discarded in this case.
54
+ */
55
+ configuratorClient: IConfiguratorClient;
56
+ configurationModelSource: ConfigurationModelSource;
57
+ attributeRelations?: AttributeRelations | null;
58
+ usageRuleParameters?: Record<string, string> | null;
59
+ };
60
+
61
+ /**
62
+ * The ConfigurationSuspender avoids to manually handle the initialization state.
63
+ * Combined with the React Suspense component, it stops the component subtree from rendering while the configuration is initializing.
64
+ * So unsafe hooks like "useAttributes" can safely be used.
65
+ * See the hook documentation whether a hook is safe to use while initialization.
66
+ */
67
+ export declare function ConfigurationSuspender(props: PropsWithChildren<{}>): JSX.Element;
68
+
69
+ export declare type ConfigurationUpdating = {
70
+ isUpdating: boolean;
71
+ error?: ConfigurationError;
72
+ };
73
+
74
+ declare type EncapsulatedPromise = {
75
+ promise: Promise<void> | null;
76
+ };
77
+
78
+ /**
79
+ * Retrieves the requested attributes. Will return all existing attributes if requested attributes is null or undefined.
80
+ * @param attributes The attributes to return or null/undefined if all attributes shall be returned.
81
+ * @param ignoreMissingAttributes Whether to ignore that requested attributes are missing. If true, missing attributes will be filtered out of the result.
82
+ * Otherwise, they will appear as undefined. Only applicable if @param attributes has items. Defaults to false.
83
+ * @throws If configuration is initializing.
84
+ */
85
+ export declare function useAttributes(attributes?: GlobalAttributeId[], ignoreMissingAttributes?: boolean): readonly Attribute[];
86
+
87
+ /**
88
+ * Gets the requested boolean attribute with the command to make decisions.
89
+ * @param attributeId The id of the boolean attribute.
90
+ * @throws If configuration is initializing.
91
+ * @returns Undefined if attribute doesn't exist, or it is not a boolean attribute.
92
+ */
93
+ export declare function useBooleanAttribute(attributeId: GlobalAttributeId): UseBooleanAttributeResult | undefined;
94
+
95
+ export declare type UseBooleanAttributeResult = {
96
+ attribute: BooleanAttribute;
97
+ makeDecision: (state: boolean | null | undefined) => Promise<void>;
98
+ };
99
+
100
+ /**
101
+ * Gets the requested choice attribute with commands for making decisions or explaining consequences.
102
+ * @param attributeId The id of the choice attribute.
103
+ * @throws If configuration is initializing.
104
+ * @returns Undefined if attribute doesn't exist, or it is not a choice attribute.
105
+ */
106
+ export declare function useChoiceAttribute(attributeId: GlobalAttributeId): UseChoiceAttributeResult | undefined;
107
+
108
+ export declare type UseChoiceAttributeResult = {
109
+ attribute: ChoiceAttribute;
110
+ makeDecision: (choiceValueId: ChoiceValueId, state: ChoiceValueDecisionState | null | undefined) => Promise<void>;
111
+ clearDecisions: () => Promise<void>;
112
+ explainConsequence: (choiceValueId: ChoiceValueId, mode?: ExplainMode) => Promise<ChoiceValueExplanationResult>;
113
+ explainConsequences: (mode?: ExplainMode) => Promise<ChoiceExplanationResult>;
114
+ applySolution(solution: Solution): Promise<void>;
115
+ };
116
+
117
+ export declare function useComponentAttribute(attributeId: GlobalAttributeId): UseComponentAttributeResult | undefined;
118
+
119
+ export declare type UseComponentAttributeResult = {
120
+ attribute: ComponentAttribute;
121
+ makeDecision: (state: ComponentDecisionState | null | undefined) => Promise<void>;
122
+ clearSubtree: () => Promise<void>;
123
+ };
124
+
125
+ /**
126
+ * Gets the current configuration data and allows to restore a configuration.
127
+ * @throws If configuration is initializing.
128
+ */
129
+ export declare function useConfiguration(): UseConfigurationResult;
130
+
131
+ /**
132
+ * Gets the initialization information for the configuration.
133
+ * This is safe to use if the configuration is initializing.
134
+ */
135
+ export declare function useConfigurationInitialization(): ConfigurationInitialization;
136
+
137
+ export declare type UseConfigurationResult = {
138
+ configuration: Configuration_2;
139
+ restoreConfiguration: (configuration: Configuration_2) => Promise<void>;
140
+ };
141
+
142
+ /**
143
+ * Gets the updating information for the configuration.
144
+ * This is safe to use if the configuration is initializing.
145
+ */
146
+ export declare function useConfigurationUpdating(): ConfigurationUpdating;
147
+
148
+ /**
149
+ * Gets commands for making one or many decisions.
150
+ * @throws If configuration is initializing.
151
+ */
152
+ export declare function useDecision(): UseDecisionResult;
153
+
154
+ export declare type UseDecisionResult = {
155
+ makeDecision: (decision: ExplicitDecision) => Promise<void>;
156
+ setManyDecision: (decisions: ReadonlyArray<ExplicitDecision>, mode: SetManyMode) => Promise<void>;
157
+ };
158
+
159
+ /**
160
+ * Gets commands for explaining consequences.
161
+ * @throws If configuration is initializing.
162
+ */
163
+ export declare function useExplain(): UseExplainResult;
164
+
165
+ export declare type UseExplainResult = {
166
+ explainChoiceAttributeConsequence(attributeId: GlobalAttributeId, choiceValueId: ChoiceValueId, mode: ExplainMode): Promise<ChoiceValueExplanationResult>;
167
+ explainChoiceAttributeConsequences(attributeId: GlobalAttributeId, mode: ExplainMode): Promise<ChoiceExplanationResult>;
168
+ applySolution(solution: Solution): Promise<void>;
169
+ };
170
+
171
+ /**
172
+ * Gets the requested numeric attribute with the command to make decisions.
173
+ * @param attributeId The id of the numeric attribute.
174
+ * @throws If configuration is initializing.
175
+ * @returns Undefined if attribute doesn't exist, or it is not a numeric attribute.
176
+ */
177
+ export declare function useNumericAttribute(attributeId: GlobalAttributeId): UseNumericAttributeResult | undefined;
178
+
179
+ export declare type UseNumericAttributeResult = {
180
+ attribute: NumericAttribute;
181
+ makeDecision: (state: number | null | undefined) => Promise<void>;
182
+ };
183
+
184
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,1039 @@
1
+ import { Eq as f, Str as g, O as s, RA as o, RR as J, pipe as r, flow as W, some as U, none as I, identity as he, constVoid as Se } from "@viamedici/fp-ts-extensions";
2
+ import { match as ye } from "ts-pattern";
3
+ import { deepEqual as $ } from "fast-equals";
4
+ import { createContext as D, useContext as N, useMemo as m, useEffect as L } from "react";
5
+ import { jsx as x, Fragment as Ee } from "react/jsx-runtime";
6
+ import { createMachine as H, assign as p, sendParent as ee, spawn as Q, forwardTo as R, send as be } from "xstate";
7
+ import { log as C, pure as qe, stop as X } from "xstate/lib/actions";
8
+ import { eqNullable as F } from "@viamedici/fp-ts-extensions/Eq";
9
+ import { useMachine as Pe } from "@xstate/react";
10
+ globalThis && globalThis.__spreadArray;
11
+ var ve = function(e) {
12
+ return e._tag === "Some";
13
+ };
14
+ function w(e) {
15
+ return {
16
+ equals(n, t) {
17
+ return n == null && t == null ? !0 : n == null || t === null || t === void 0 ? !1 : e.equals(n, t);
18
+ }
19
+ };
20
+ }
21
+ function q(e) {
22
+ return {
23
+ equals(n, t) {
24
+ const i = r(s.fromNullable(n), s.getOrElse(() => [])), a = r(s.fromNullable(t), s.getOrElse(() => []));
25
+ return o.getEq(e).equals(i, a);
26
+ }
27
+ };
28
+ }
29
+ const V = f.struct({
30
+ localId: g.Eq,
31
+ componentPath: q(g.Eq),
32
+ sharedConfigurationModel: w(g.Eq)
33
+ }), Ae = s.getEq(o.getEq(f.struct({
34
+ attributeId: V,
35
+ decisions: q(V)
36
+ })));
37
+ f.struct({
38
+ configurationModelSource: f.fromEquals((e, n) => $(e, n)),
39
+ decisionsToRespect: Ae,
40
+ usageRuleParameters: J.getEq(g.Eq)
41
+ });
42
+ const xe = {
43
+ equals: (e, n) => e.choiceValueId !== n.choiceValueId ? !1 : e.state === n.state
44
+ }, Me = {
45
+ equals(e, n) {
46
+ return e.value === n.value;
47
+ }
48
+ }, Re = {
49
+ equals(e, n) {
50
+ return e.value === n.value;
51
+ }
52
+ }, Ue = {
53
+ equals(e, n) {
54
+ return e.state === n.state;
55
+ }
56
+ }, Ie = {
57
+ equals(e, n) {
58
+ return V.equals(e.attributeId, n.attributeId) ? ye({ x: e, y: n }).with({
59
+ x: {
60
+ type: "Choice"
61
+ /* Choice */
62
+ },
63
+ y: {
64
+ type: "Choice"
65
+ /* Choice */
66
+ }
67
+ }, (t, i) => xe.equals(i.x, i.y)).with({
68
+ x: {
69
+ type: "Numeric"
70
+ /* Numeric */
71
+ },
72
+ y: {
73
+ type: "Numeric"
74
+ /* Numeric */
75
+ }
76
+ }, (t, i) => Me.equals(i.x, i.y)).with({
77
+ x: {
78
+ type: "Boolean"
79
+ /* Boolean */
80
+ },
81
+ y: {
82
+ type: "Boolean"
83
+ /* Boolean */
84
+ }
85
+ }, (t, i) => Re.equals(i.x, i.y)).with({
86
+ x: {
87
+ type: "Component"
88
+ /* Component */
89
+ },
90
+ y: {
91
+ type: "Component"
92
+ /* Component */
93
+ }
94
+ }, (t, i) => Ue.equals(i.x, i.y)).otherwise(() => !1) : !1;
95
+ }
96
+ };
97
+ o.getEq(Ie);
98
+ const ne = f.struct({
99
+ localId: g.Eq,
100
+ componentPath: q(g.Eq),
101
+ sharedConfigurationModelId: w(g.Eq)
102
+ }), De = f.struct({
103
+ localId: g.Eq,
104
+ componentPath: q(g.Eq),
105
+ sharedConfigurationModelId: w(g.Eq)
106
+ });
107
+ var j = /* @__PURE__ */ ((e) => (e.Choice = "Choice", e.ChoiceValue = "ChoiceValue", e))(j || {}), d = /* @__PURE__ */ ((e) => (e.Boolean = "Boolean", e.Numeric = "Numeric", e.Choice = "Choice", e.Component = "Component", e))(d || {}), k = /* @__PURE__ */ ((e) => (e.Implicit = "Implicit", e.Explicit = "Explicit", e))(k || {});
108
+ f.struct({
109
+ localId: g.Eq,
110
+ componentPath: q(g.Eq),
111
+ sharedConfigurationModelId: w(g.Eq)
112
+ });
113
+ function Ne(e, n) {
114
+ return r(
115
+ e.values,
116
+ o.filterMap((t) => r(
117
+ t.decision,
118
+ s.fromNullable,
119
+ s.filter((i) => i.kind === n)
120
+ ))
121
+ );
122
+ }
123
+ function we(e) {
124
+ return r(
125
+ e.decision,
126
+ s.fromNullable,
127
+ s.filter((n) => n.kind === k.Explicit),
128
+ s.toNullable
129
+ );
130
+ }
131
+ function ke(e) {
132
+ return r(
133
+ e.decision,
134
+ s.fromNullable,
135
+ s.filter((n) => n.kind === k.Explicit),
136
+ s.toNullable
137
+ );
138
+ }
139
+ function Oe(e) {
140
+ return r(
141
+ e.decision,
142
+ s.fromNullable,
143
+ s.toNullable
144
+ );
145
+ }
146
+ const te = (e) => e.type === d.Boolean, ie = (e) => e.type === d.Choice, se = (e) => e.type === d.Numeric, oe = (e) => e.type === d.Component, _e = q(g.Eq);
147
+ function ze(e, n, t) {
148
+ var i;
149
+ const a = ((i = n.componentPath) == null ? void 0 : i.length) ?? 0;
150
+ return r(e, o.filter((l) => {
151
+ var c;
152
+ const h = ((c = l.id.componentPath) == null ? void 0 : c.length) ?? 0;
153
+ return t ? a > h ? !1 : r(
154
+ l.id.componentPath ?? [],
155
+ o.zip(n.componentPath ?? []),
156
+ o.every(([u, S]) => u === S)
157
+ ) : _e.equals(l.id.componentPath, n.componentPath);
158
+ }));
159
+ }
160
+ function Te(e, n, t) {
161
+ return [];
162
+ }
163
+ function Be(e) {
164
+ return r(e, o.filter((n) => {
165
+ const t = r(
166
+ n.id.componentPath,
167
+ s.fromNullable,
168
+ s.map((a) => a.length === 0),
169
+ s.getOrElse(() => !0)
170
+ ), i = r(
171
+ n.id.sharedConfigurationModelId,
172
+ s.fromNullable,
173
+ s.match(() => !0, () => !1)
174
+ );
175
+ return t && i;
176
+ }));
177
+ }
178
+ function Fe(e, n) {
179
+ return r(
180
+ re(e),
181
+ o.map((t) => Ne(t, n)),
182
+ o.flatten,
183
+ o.filterMap((t) => s.fromNullable(t))
184
+ );
185
+ }
186
+ function Ve(e, n) {
187
+ return r(
188
+ le(e),
189
+ o.filter((t) => {
190
+ var i;
191
+ return ((i = t.decision) == null ? void 0 : i.kind) === n;
192
+ }),
193
+ o.map((t) => we(t)),
194
+ o.filterMap((t) => s.fromNullable(t))
195
+ );
196
+ }
197
+ function je(e, n) {
198
+ return r(
199
+ ue(e),
200
+ o.filter((t) => {
201
+ var i;
202
+ return ((i = t.decision) == null ? void 0 : i.kind) === n;
203
+ }),
204
+ o.map((t) => ke(t)),
205
+ o.filterMap((t) => s.fromNullable(t))
206
+ );
207
+ }
208
+ function He(e, n) {
209
+ return r(
210
+ ae(e),
211
+ o.filter((t) => {
212
+ var i;
213
+ return ((i = t.decision) == null ? void 0 : i.kind) === n;
214
+ }),
215
+ o.map((t) => Oe(t)),
216
+ o.filterMap((t) => s.fromNullable(t))
217
+ );
218
+ }
219
+ function re(e) {
220
+ return r(
221
+ e.attributes,
222
+ o.filter(ie)
223
+ );
224
+ }
225
+ function ae(e) {
226
+ return r(
227
+ e.attributes,
228
+ o.filter(oe)
229
+ );
230
+ }
231
+ function le(e) {
232
+ return r(
233
+ e.attributes,
234
+ o.filter(se)
235
+ );
236
+ }
237
+ function ue(e) {
238
+ return r(
239
+ e.attributes,
240
+ o.filter(te)
241
+ );
242
+ }
243
+ function Ke(e, n) {
244
+ return r(
245
+ M(e, n),
246
+ s.toUndefined
247
+ );
248
+ }
249
+ function Ge(e, n) {
250
+ return r(
251
+ ce(e, n),
252
+ s.toUndefined
253
+ );
254
+ }
255
+ function Le(e, n, t) {
256
+ return r(
257
+ ce(e, n),
258
+ s.map((i) => i.values),
259
+ s.chain(W(o.findFirst((i) => i.id === t))),
260
+ s.toUndefined
261
+ );
262
+ }
263
+ function Qe(e, n) {
264
+ return r(
265
+ M(e, n),
266
+ s.filter(se),
267
+ s.toUndefined
268
+ );
269
+ }
270
+ function Xe(e, n) {
271
+ return r(
272
+ M(e, n),
273
+ s.filter(te),
274
+ s.toUndefined
275
+ );
276
+ }
277
+ function Ye(e, n) {
278
+ return r(
279
+ M(e, n),
280
+ s.filter(oe),
281
+ s.toUndefined
282
+ );
283
+ }
284
+ function M(e, n) {
285
+ return r(
286
+ e.attributes,
287
+ o.findFirst((t) => ne.equals(t.id, n))
288
+ );
289
+ }
290
+ function ce(e, n) {
291
+ return r(
292
+ M(e, n),
293
+ s.filter(ie)
294
+ );
295
+ }
296
+ const P = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
297
+ __proto__: null,
298
+ filterAttributesOfComponent: ze,
299
+ filterAttributesOfRoot: Be,
300
+ filterAttributesOfShared: Te,
301
+ getAttribute: Ke,
302
+ getBooleanAttribute: Xe,
303
+ getBooleanAttributes: ue,
304
+ getBooleanDecisions: je,
305
+ getChoiceAttribute: Ge,
306
+ getChoiceAttributes: re,
307
+ getChoiceDecisions: Fe,
308
+ getChoiceValue: Le,
309
+ getComponentAttribute: Ye,
310
+ getComponentAttributes: ae,
311
+ getComponentDecisions: He,
312
+ getNumericAttribute: Qe,
313
+ getNumericAttributes: le,
314
+ getNumericDecisions: Ve
315
+ }, Symbol.toStringTag, { value: "Module" })), Y = ne.equals;
316
+ De.equals;
317
+ const de = D(null), fe = D(null), ge = D(null), pe = D(null), K = () => N(de), v = () => N(pe), me = "The configuration is not initialized. Consider using the ConfigurationSuspender or unload components manually that make use of any unsafe hook while the configuration is initializing. Check the hooks documentation to see if it is safe to use while the configuration is initializing.";
318
+ function G(e) {
319
+ if (!e)
320
+ throw new Error(me);
321
+ }
322
+ function A(e) {
323
+ if (!e)
324
+ throw new Error(me);
325
+ }
326
+ function Ze() {
327
+ const e = K();
328
+ return G(e), m(() => ({
329
+ explainChoiceAttributeConsequence: (n, t, i) => e.explain({
330
+ type: j.ChoiceValue,
331
+ attributeId: n,
332
+ choiceValueId: t,
333
+ question: i
334
+ }),
335
+ explainChoiceAttributeConsequences: (n, t) => e.explain({
336
+ type: j.Choice,
337
+ attributeId: n,
338
+ question: t
339
+ }),
340
+ applySolution: (n) => e.applySolution(n)
341
+ }), [e]);
342
+ }
343
+ function O() {
344
+ const e = K();
345
+ return G(e), m(() => ({
346
+ makeDecision: (n) => e.makeDecision(n),
347
+ setManyDecision: (n, t) => e.setMany(n, t)
348
+ }), [e]);
349
+ }
350
+ var _ = function(e) {
351
+ return function(n) {
352
+ return ve(e(n));
353
+ };
354
+ };
355
+ const Je = _((e) => e.type === d.Choice ? U(e) : I), We = _((e) => e.type === d.Numeric ? U(e) : I), $e = _((e) => e.type === d.Boolean ? U(e) : I), en = _((e) => e.type === d.Component ? U(e) : I);
356
+ function z(e) {
357
+ return e.decision != null && e.decision.kind === k.Explicit;
358
+ }
359
+ function Ce(e) {
360
+ return r(
361
+ e.values,
362
+ o.filter(z),
363
+ o.map((n) => ({
364
+ type: d.Choice,
365
+ attributeId: e.id,
366
+ choiceValueId: n.id,
367
+ state: null
368
+ }))
369
+ );
370
+ }
371
+ function nn(e) {
372
+ return r(
373
+ e,
374
+ s.fromPredicate(z),
375
+ s.map(() => ({
376
+ type: d.Numeric,
377
+ attributeId: e.id,
378
+ state: null
379
+ }))
380
+ );
381
+ }
382
+ function tn(e) {
383
+ return r(
384
+ e,
385
+ s.fromPredicate(z),
386
+ s.map(() => ({
387
+ type: d.Boolean,
388
+ attributeId: e.id,
389
+ state: null
390
+ }))
391
+ );
392
+ }
393
+ function sn(e) {
394
+ return r(
395
+ e,
396
+ s.fromPredicate(z),
397
+ s.map(() => ({
398
+ type: d.Component,
399
+ attributeId: e.id,
400
+ state: null
401
+ }))
402
+ );
403
+ }
404
+ function on(e, n) {
405
+ return r(
406
+ P.filterAttributesOfComponent(n, e, !0),
407
+ (t) => [
408
+ r(
409
+ t,
410
+ o.filter(Je),
411
+ o.chain(Ce)
412
+ ),
413
+ r(
414
+ t,
415
+ o.filter(We),
416
+ o.map(nn),
417
+ o.compact
418
+ ),
419
+ r(
420
+ t,
421
+ o.filter($e),
422
+ o.map(tn),
423
+ o.compact
424
+ ),
425
+ r(
426
+ t,
427
+ o.filter(en),
428
+ o.map(sn),
429
+ o.compact
430
+ )
431
+ ],
432
+ o.flatten
433
+ );
434
+ }
435
+ function xn(e, n) {
436
+ const t = v();
437
+ return A(t), m(
438
+ () => r(
439
+ s.fromNullable(e),
440
+ s.map(W(
441
+ o.map((i) => P.getAttribute(t, i)),
442
+ n ?? !1 ? he : o.filterMap(s.fromNullable)
443
+ )),
444
+ s.getOrElse(() => t.attributes)
445
+ ),
446
+ [e, t, n]
447
+ );
448
+ }
449
+ function Mn(e) {
450
+ const n = v(), { explainChoiceAttributeConsequence: t, explainChoiceAttributeConsequences: i, applySolution: a } = Ze(), { makeDecision: l, setManyDecision: c } = O();
451
+ A(n);
452
+ const h = P.getChoiceAttribute(n, e), u = m(() => ({
453
+ explainConsequence: (y, E) => t(e, y, E),
454
+ explainConsequences: (y) => i(e, y),
455
+ makeDecision: (y, E) => l({
456
+ type: d.Choice,
457
+ attributeId: e,
458
+ choiceValueId: y,
459
+ state: E
460
+ }),
461
+ clearDecisions: r(
462
+ h,
463
+ s.fromNullable,
464
+ s.map(Ce),
465
+ // Only setMany if there are decisions to clear.
466
+ s.filter(o.isNonEmpty),
467
+ s.map((y) => () => c(y, { type: "Default" })),
468
+ s.getOrElse(() => () => Promise.resolve())
469
+ ),
470
+ applySolution: a
471
+ }), [e, h, l, c, t, i, a]), S = m(() => ({
472
+ ...u,
473
+ attribute: h
474
+ }), [h, u]);
475
+ if (h)
476
+ return S;
477
+ }
478
+ function Rn(e) {
479
+ const n = v(), { makeDecision: t } = O();
480
+ A(n);
481
+ const i = P.getNumericAttribute(n, e), a = m(() => ({
482
+ makeDecision: (c) => t({
483
+ type: d.Numeric,
484
+ attributeId: e,
485
+ state: c
486
+ })
487
+ }), [e, t]), l = m(() => ({
488
+ ...a,
489
+ attribute: i
490
+ }), [i, a]);
491
+ if (i)
492
+ return l;
493
+ }
494
+ function Un(e) {
495
+ const n = v(), { makeDecision: t } = O();
496
+ A(n);
497
+ const i = P.getBooleanAttribute(n, e), a = m(() => ({
498
+ makeDecision: (c) => t({
499
+ type: d.Boolean,
500
+ attributeId: e,
501
+ state: c
502
+ })
503
+ }), [e, t]), l = m(() => ({
504
+ ...a,
505
+ attribute: i
506
+ }), [i, a]);
507
+ if (i)
508
+ return l;
509
+ }
510
+ function In(e) {
511
+ const n = v(), { makeDecision: t, setManyDecision: i } = O();
512
+ A(n);
513
+ const a = n.attributes, l = P.getComponentAttribute(n, e), c = m(() => ({
514
+ makeDecision: (u) => t({
515
+ type: d.Component,
516
+ attributeId: e,
517
+ state: u
518
+ }),
519
+ clearSubtree: r(
520
+ on(e, a),
521
+ // Only setMany if there are decisions to clear.
522
+ s.fromPredicate(o.isNonEmpty),
523
+ s.map((u) => () => i(u, { type: "Default" })),
524
+ s.getOrElse(() => () => Promise.resolve())
525
+ )
526
+ }), [e, t, a, i]), h = m(() => ({
527
+ ...c,
528
+ attribute: l
529
+ }), [l, c]);
530
+ if (l)
531
+ return h;
532
+ }
533
+ const rn = f.fromEquals((e, n) => J.getEq(g.Eq).equals(e ?? {}, n ?? {})), an = f.struct({
534
+ attributeId: f.fromEquals(Y),
535
+ decisions: o.getEq(f.fromEquals(Y))
536
+ }), ln = f.fromEquals((e, n) => o.getEq(an).equals(e ?? [], n ?? [])), T = f.struct({
537
+ configurationModelSource: f.fromEquals((e, n) => $(e, n)),
538
+ attributeRelations: ln,
539
+ usageRuleParameters: rn
540
+ }), un = f.eqStrict, B = F(un), cn = () => H({
541
+ predictableActionArguments: !0,
542
+ preserveActionOrder: !0,
543
+ schema: {
544
+ context: {},
545
+ events: {}
546
+ },
547
+ context: {
548
+ desiredClient: null,
549
+ desiredSessionContext: null,
550
+ actualClient: null,
551
+ session: null,
552
+ sessionCreationError: null,
553
+ sessionUpdateError: null,
554
+ hasEverSuccessfullyCreatedSession: !1
555
+ },
556
+ initial: "ProcessChanges",
557
+ on: {
558
+ ChangeConfigurationClient: {
559
+ actions: ["saveDesiredClient"]
560
+ },
561
+ ChangeSessionContext: {
562
+ actions: ["saveDesiredSessionContext"]
563
+ }
564
+ },
565
+ exit: [
566
+ C("Shutting down", "SessionManagement:"),
567
+ "disposeOldSession"
568
+ ],
569
+ states: {
570
+ ProcessChanges: {
571
+ entry: [
572
+ C("Entering ProcessChanges", "SessionManagement:"),
573
+ b(
574
+ 2
575
+ /* Other */
576
+ )
577
+ ],
578
+ always: [
579
+ { target: "DisposeSession", cond: "shallDisposeSession" },
580
+ { target: "CreateSession", cond: "shallCreateSession" },
581
+ { target: "UpdateSession", cond: "shallUpdateSession" }
582
+ ]
583
+ },
584
+ DisposeSession: {
585
+ entry: [
586
+ C("Entering DisposeSession", "SessionManagement:"),
587
+ b(
588
+ 2
589
+ /* Other */
590
+ )
591
+ ],
592
+ always: {
593
+ actions: ["disposeOldSession"],
594
+ target: "ProcessChanges"
595
+ }
596
+ },
597
+ CreateSession: {
598
+ entry: [
599
+ C("Entering CreateSession", "SessionManagement:"),
600
+ b(
601
+ 0
602
+ /* CreateSession */
603
+ )
604
+ ],
605
+ invoke: {
606
+ id: "getNewSession",
607
+ src: "createSession",
608
+ onDone: {
609
+ actions: ["setSessionCreationResult", "setHasEverSuccessfullyCreatedSession"],
610
+ target: "ProcessChanges"
611
+ },
612
+ onError: {
613
+ actions: "setSessionCreationError",
614
+ target: "SessionCreationFailed"
615
+ }
616
+ }
617
+ },
618
+ SessionCreationFailed: {
619
+ entry: [
620
+ C("Entering SessionCreationFailed", "SessionManagement:"),
621
+ b(
622
+ 2
623
+ /* Other */
624
+ )
625
+ ],
626
+ always: {
627
+ // Immediately process changes if there were changes during session creation attempt
628
+ // This will also be triggered if session context or client changes
629
+ target: "ProcessChanges",
630
+ cond: "shallImmediatelyProcessChangesAfterSessionCreationError"
631
+ },
632
+ exit: [
633
+ C("Exiting SessionCreationFailed", "SessionManagement:"),
634
+ "clearSessionCreationError"
635
+ ],
636
+ on: {
637
+ RetrySessionCreation: {
638
+ target: "ProcessChanges",
639
+ actions: C("Retrying session creation", "SessionManagement:")
640
+ }
641
+ }
642
+ },
643
+ UpdateSession: {
644
+ entry: [
645
+ C("Entering UpdateSession", "SessionManagement:"),
646
+ b(
647
+ 1
648
+ /* UpdateSession */
649
+ )
650
+ ],
651
+ invoke: {
652
+ id: "updateExistingSession",
653
+ src: "updateSession",
654
+ onDone: {
655
+ target: "ProcessChanges"
656
+ },
657
+ onError: {
658
+ actions: "setSessionUpdateError",
659
+ target: "SessionUpdateFailed"
660
+ }
661
+ }
662
+ },
663
+ SessionUpdateFailed: {
664
+ entry: [
665
+ C("Entering SessionUpdateFailed", "SessionManagement:"),
666
+ b(
667
+ 2
668
+ /* Other */
669
+ )
670
+ ],
671
+ always: {
672
+ // Immediately process changes if there were changes during session update attempt
673
+ // This will also be triggered if session context or client changes
674
+ target: "ProcessChanges",
675
+ cond: "shallImmediatelyProcessChangesAfterSessionUpdateError"
676
+ },
677
+ exit: [
678
+ C("Exiting SessionUpdateFailed", "SessionManagement:"),
679
+ "clearSessionUpdateError"
680
+ ],
681
+ on: {
682
+ RetrySessionUpdate: {
683
+ target: "ProcessChanges",
684
+ actions: C("Retrying session update", "SessionManagement:")
685
+ }
686
+ }
687
+ }
688
+ }
689
+ }, {
690
+ actions: {
691
+ saveDesiredClient: p({
692
+ desiredClient: (e, n) => n.client
693
+ }),
694
+ saveDesiredSessionContext: p({
695
+ desiredSessionContext: (e, n) => n.sessionContext
696
+ }),
697
+ disposeOldSession: p((e, n) => (e.session && e.session.close().then(Se).catch((t) => {
698
+ }), {
699
+ session: null,
700
+ actualClient: null
701
+ })),
702
+ setSessionCreationResult: p((e, n) => ({
703
+ session: n.data.session,
704
+ actualClient: n.data.client
705
+ })),
706
+ setSessionCreationError: p((e, n) => ({
707
+ sessionCreationError: n.data
708
+ })),
709
+ clearSessionCreationError: p({ sessionCreationError: () => null }),
710
+ setSessionUpdateError: p((e, n) => ({
711
+ sessionUpdateError: n.data
712
+ })),
713
+ clearSessionUpdateError: p({ sessionUpdateError: () => null }),
714
+ setHasEverSuccessfullyCreatedSession: p({
715
+ hasEverSuccessfullyCreatedSession: () => !0
716
+ })
717
+ },
718
+ services: {
719
+ createSession: (e) => e.desiredClient.createSession(e.desiredSessionContext).then((n) => ({
720
+ session: n,
721
+ client: e.desiredClient
722
+ })).catch((n) => Promise.reject({
723
+ type: n.type,
724
+ client: e.desiredClient,
725
+ sessionContext: e.desiredSessionContext
726
+ })),
727
+ updateSession: (e) => e.session.setSessionContext(e.desiredSessionContext).catch((n) => Promise.reject({
728
+ type: n.type,
729
+ sessionContext: e.desiredSessionContext
730
+ }))
731
+ },
732
+ guards: {
733
+ shallDisposeSession: (e) => e.session != null && (e.desiredSessionContext == null || e.desiredClient == null || !B.equals(e.actualClient, e.desiredClient)),
734
+ shallCreateSession: (e) => e.session == null && e.desiredClient != null && e.desiredSessionContext != null,
735
+ shallUpdateSession: (e) => e.session != null && !T.equals(e.session.getSessionContext(), e.desiredSessionContext),
736
+ shallImmediatelyProcessChangesAfterSessionCreationError: (e) => (
737
+ // The desired client and the desired session context is not the same that resulted in the error.
738
+ !B.equals(e.desiredClient, e.sessionCreationError.client) || !F(T).equals(e.desiredSessionContext, e.sessionCreationError.sessionContext)
739
+ ),
740
+ shallImmediatelyProcessChangesAfterSessionUpdateError: (e) => (
741
+ // The desired client was changed
742
+ !B.equals(e.desiredClient, e.actualClient) || !F(T).equals(e.desiredSessionContext, e.sessionUpdateError.sessionContext)
743
+ )
744
+ }
745
+ });
746
+ function b(e) {
747
+ const n = e === 0, t = e === 1;
748
+ return qe((i, a) => {
749
+ const l = {
750
+ isInitializing: (!i.hasEverSuccessfullyCreatedSession || n) && i.sessionCreationError == null,
751
+ errorType: i.sessionCreationError && i.sessionCreationError.type
752
+ }, c = {
753
+ isUpdating: t && i.sessionUpdateError == null,
754
+ errorType: i.sessionUpdateError && i.sessionUpdateError.type
755
+ };
756
+ return ee({
757
+ type: "SessionManagementStateChanged",
758
+ sessionInitialization: l,
759
+ sessionUpdating: c,
760
+ session: i.session
761
+ });
762
+ });
763
+ }
764
+ const dn = (e) => (n) => (n({
765
+ type: "ConfigurationChanged",
766
+ session: e,
767
+ configuration: e.getConfiguration()
768
+ }), e.setOnConfigurationChangedHandler((t) => {
769
+ n({
770
+ type: "ConfigurationChanged",
771
+ session: e,
772
+ configuration: t
773
+ });
774
+ }), () => {
775
+ e.setOnConfigurationChangedHandler(null);
776
+ }), fn = () => H({
777
+ predictableActionArguments: !0,
778
+ preserveActionOrder: !0,
779
+ schema: {
780
+ context: {},
781
+ events: {}
782
+ },
783
+ context: {
784
+ session: null
785
+ },
786
+ on: {
787
+ // Forward the configuration data to the parent.
788
+ ConfigurationChanged: {
789
+ actions: [
790
+ ee((e, n) => n)
791
+ ]
792
+ }
793
+ },
794
+ initial: "ProcessChanges",
795
+ states: {
796
+ ProcessChanges: {
797
+ entry: [
798
+ C("Entering ProcessChanges", "ConfigurationSubscriptionManagement:")
799
+ ],
800
+ on: {
801
+ ChangeSession: {
802
+ actions: [
803
+ "saveSession"
804
+ ]
805
+ }
806
+ },
807
+ always: [
808
+ {
809
+ target: "Subscribe",
810
+ cond: (e, n) => e.session != null
811
+ }
812
+ ]
813
+ },
814
+ Subscribe: {
815
+ entry: [
816
+ C("Entering Subscribe", "ConfigurationSubscriptionManagement:")
817
+ ],
818
+ on: {
819
+ ChangeSession: {
820
+ target: "ProcessChanges",
821
+ cond: (e, n) => n.session == null || e.session !== n.session,
822
+ actions: [
823
+ "saveSession"
824
+ ]
825
+ }
826
+ },
827
+ invoke: {
828
+ id: "configurationSubscriptionActor",
829
+ src: (e, n) => dn(e.session)
830
+ }
831
+ }
832
+ }
833
+ }, {
834
+ actions: {
835
+ saveSession: p((e, n) => ({
836
+ session: n.session
837
+ }))
838
+ }
839
+ }), gn = () => {
840
+ let e, n;
841
+ return {
842
+ promise: new Promise((i, a) => {
843
+ e = i, n = a;
844
+ }),
845
+ resolve: e,
846
+ reject: n
847
+ };
848
+ }, Z = () => {
849
+ const e = gn();
850
+ return {
851
+ capsule: { promise: e.promise },
852
+ resolve: e.resolve,
853
+ reject: e.reject
854
+ };
855
+ }, pn = () => H({
856
+ predictableActionArguments: !0,
857
+ preserveActionOrder: !0,
858
+ schema: {
859
+ context: {},
860
+ events: {}
861
+ },
862
+ context: {
863
+ sessionManagementActor: null,
864
+ configurationSubscriptionManagementActor: null,
865
+ sessionInitialization: null,
866
+ sessionUpdating: null,
867
+ session: null,
868
+ configuration: null,
869
+ isReadyPromise: Z()
870
+ },
871
+ entry: [
872
+ p({
873
+ sessionManagementActor: () => Q(cn()),
874
+ configurationSubscriptionManagementActor: () => Q(fn())
875
+ })
876
+ ],
877
+ exit: [
878
+ X((e) => e.sessionManagementActor),
879
+ X((e) => e.configurationSubscriptionManagementActor)
880
+ ],
881
+ on: {
882
+ // Forward events for sessionManagement
883
+ ChangeConfigurationClient: {
884
+ actions: [
885
+ R((e) => e.sessionManagementActor)
886
+ ]
887
+ },
888
+ ChangeSessionContext: {
889
+ actions: [
890
+ R((e) => e.sessionManagementActor)
891
+ ]
892
+ },
893
+ RetrySessionCreation: {
894
+ actions: [
895
+ R((e) => e.sessionManagementActor)
896
+ ]
897
+ },
898
+ RetrySessionUpdate: {
899
+ actions: [
900
+ R((e) => e.sessionManagementActor)
901
+ ]
902
+ },
903
+ SessionManagementStateChanged: {
904
+ actions: [
905
+ // Assign the received data
906
+ p((e, n) => ({
907
+ session: n.session,
908
+ sessionInitialization: n.sessionInitialization,
909
+ sessionUpdating: n.sessionUpdating
910
+ })),
911
+ // Forward the session to the configuration subscription
912
+ be((e) => ({
913
+ type: "ChangeSession",
914
+ session: e.session
915
+ }), { to: (e) => e.configurationSubscriptionManagementActor }),
916
+ "calculateReadyState"
917
+ ]
918
+ },
919
+ ConfigurationChanged: {
920
+ actions: [
921
+ p((e, n) => ({
922
+ configuration: {
923
+ session: n.session,
924
+ configuration: n.configuration
925
+ }
926
+ })),
927
+ "calculateReadyState"
928
+ ]
929
+ }
930
+ },
931
+ initial: "Idle",
932
+ states: {
933
+ Idle: {}
934
+ }
935
+ }, {
936
+ actions: {
937
+ calculateReadyState: p((e, n) => {
938
+ var a;
939
+ const t = !((a = e.sessionInitialization) != null && a.isInitializing) && e.session != null && e.configuration != null && e.configuration.session === e.session;
940
+ return e.isReadyPromise && t && (e.isReadyPromise.resolve(), e.isReadyPromise.capsule.promise = null), {
941
+ isReadyPromise: (() => t ? null : e.isReadyPromise != null ? e.isReadyPromise : Z())()
942
+ };
943
+ })
944
+ }
945
+ });
946
+ function mn(e) {
947
+ var c, h;
948
+ const [n, t] = Pe(pn, {
949
+ logger: (...u) => console.log("ConfigurationManagement:", ...u)
950
+ });
951
+ L(() => {
952
+ t({
953
+ type: "ChangeConfigurationClient",
954
+ client: e.configuratorClient
955
+ }), e.configuratorClient || console.warn("The configurator client is null or undefined. This will dispose the session that may exist. If this was not intended, make sure you pass a valid client.");
956
+ }, [e.configuratorClient]), L(() => {
957
+ const u = r(
958
+ s.fromNullable(e.sessionContext),
959
+ s.chainFirst((S) => s.fromNullable(S.configurationModelSource)),
960
+ s.toNullable
961
+ );
962
+ t({
963
+ type: "ChangeSessionContext",
964
+ sessionContext: u
965
+ }), u || console.warn("The session context is null or undefined. This will dispose the session that may exist. If this was not intended, make sure you pass valid session context data.");
966
+ }, [e.sessionContext]);
967
+ const i = m(
968
+ () => {
969
+ var u, S, y, E;
970
+ return {
971
+ isInitializing: ((S = (u = n.context.isReadyPromise) == null ? void 0 : u.capsule) == null ? void 0 : S.promise) != null,
972
+ isInitializingPromise: (y = n.context.isReadyPromise) == null ? void 0 : y.capsule,
973
+ error: ((E = n.context.sessionInitialization) == null ? void 0 : E.errorType) && {
974
+ type: n.context.sessionInitialization.errorType,
975
+ retry: () => t({ type: "RetrySessionCreation" })
976
+ }
977
+ };
978
+ },
979
+ [n.context.sessionInitialization, n.context.isReadyPromise]
980
+ ), a = m(
981
+ () => {
982
+ var u, S;
983
+ return {
984
+ isUpdating: (u = n.context.sessionUpdating) == null ? void 0 : u.isUpdating,
985
+ error: ((S = n.context.sessionUpdating) == null ? void 0 : S.errorType) && {
986
+ type: n.context.sessionUpdating.errorType,
987
+ retry: () => t({ type: "RetrySessionUpdate" })
988
+ }
989
+ };
990
+ },
991
+ [n.context.sessionUpdating]
992
+ ), l = ((c = n.context.configuration) == null ? void 0 : c.session) === n.context.session ? (h = n.context.configuration) == null ? void 0 : h.configuration : null;
993
+ return {
994
+ configurationInitialization: i,
995
+ configurationUpdating: a,
996
+ session: n.context.session,
997
+ configuration: l
998
+ };
999
+ }
1000
+ function Dn(e) {
1001
+ const { configurationInitialization: n, configurationUpdating: t, session: i, configuration: a } = mn({
1002
+ configuratorClient: e.configuratorClient,
1003
+ sessionContext: e
1004
+ });
1005
+ return /* @__PURE__ */ x(fe.Provider, { value: n, children: /* @__PURE__ */ x(ge.Provider, { value: t, children: /* @__PURE__ */ x(de.Provider, { value: i, children: /* @__PURE__ */ x(pe.Provider, { value: a, children: e.children }) }) }) });
1006
+ }
1007
+ function Cn() {
1008
+ return N(fe);
1009
+ }
1010
+ function Nn() {
1011
+ return N(ge);
1012
+ }
1013
+ function wn(e) {
1014
+ const { children: n } = e, { isInitializingPromise: t } = Cn();
1015
+ if (t != null && t.promise)
1016
+ throw t.promise;
1017
+ return /* @__PURE__ */ x(Ee, { children: n });
1018
+ }
1019
+ function kn() {
1020
+ const e = K(), n = v();
1021
+ return G(e), A(n), m(() => ({
1022
+ configuration: n,
1023
+ restoreConfiguration: (t) => e.restoreConfiguration(t)
1024
+ }), [n, e]);
1025
+ }
1026
+ export {
1027
+ Dn as Configuration,
1028
+ wn as ConfigurationSuspender,
1029
+ xn as useAttributes,
1030
+ Un as useBooleanAttribute,
1031
+ Mn as useChoiceAttribute,
1032
+ In as useComponentAttribute,
1033
+ kn as useConfiguration,
1034
+ Cn as useConfigurationInitialization,
1035
+ Nn as useConfigurationUpdating,
1036
+ O as useDecision,
1037
+ Ze as useExplain,
1038
+ Rn as useNumericAttribute
1039
+ };
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@viamedici-spc/configurator-react",
3
+ "version": "0.1.0",
4
+ "description": "",
5
+ "sideEffects": false,
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "main": "dist/index.cjs",
10
+ "module": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "build": "vite build",
21
+ "test": "tsc -p ./tsconfig.test.json --noEmit && vitest --run",
22
+ "test:watch": "vitest watch --reporter default",
23
+ "typecheck": "tsc --noEmit",
24
+ "postinstall": "npm-sort"
25
+ },
26
+ "keywords": [
27
+ "viamedici",
28
+ "product",
29
+ "configuration",
30
+ "spc",
31
+ "hca",
32
+ "csp",
33
+ "constraint",
34
+ "satisfaction",
35
+ "problem",
36
+ "solver",
37
+ "react"
38
+ ],
39
+ "author": "Viamedici Software GmbH",
40
+ "license": "MIT",
41
+ "devDependencies": {
42
+ "@testing-library/react": "^12.1.5",
43
+ "@testing-library/react-hooks": "^8.0.1",
44
+ "@types/react": "^17.0.2",
45
+ "@vitest/coverage-istanbul": "^0.34.1",
46
+ "jsdom": "^22.1.0",
47
+ "npm-sort": "^0.0.4",
48
+ "react": "^16.14.0",
49
+ "react-dom": "^16.14.0",
50
+ "typescript": "^5.1.6",
51
+ "vite": "^4.4.8",
52
+ "vite-plugin-checker": "^0.6.1",
53
+ "vite-plugin-dts": "^3.5.0",
54
+ "vitest": "^0.34.1"
55
+ },
56
+ "dependencies": {
57
+ "@viamedici-spc/configurator": "^0.1.0",
58
+ "@viamedici/fp-ts-extensions": "1.2.0",
59
+ "@xstate/react": "^3.2.2",
60
+ "fast-equals": "^4.0.3",
61
+ "ts-pattern": "^4.2.0",
62
+ "url-join": "^5.0.0",
63
+ "xstate": "^4.38.2"
64
+ },
65
+ "peerDependencies": {
66
+ "react": ">=16.8"
67
+ }
68
+ }