@viamedici-spc/configurator-react 0.1.0-alpha0000

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Viamedici Software GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # configurator-react
2
+ React TypeScript library to build configurator web applications based on the Viamedici Headless Configuration API (HCA).
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@viamedici-spc/configurator-ts"),s=require("@viamedici-spc/fp-ts-extensions"),u=require("react"),A=require("ts-pattern"),m=require("react/jsx-runtime"),l=require("xstate"),d=require("xstate/lib/actions"),Q=require("fast-equals"),H=require("@xstate/react"),O=u.createContext(null),T=u.createContext(null),N=u.createContext(null),k=u.createContext(null),M=()=>u.useContext(O),S=()=>u.useContext(k),z="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 w(e){if(!e)throw new Error(z)}function E(e){if(!e)throw new Error(z)}function h(){const e=M();return w(e),u.useMemo(()=>({makeDecision:n=>e.makeDecision(n),setManyDecision:(n,t)=>e.setMany(n,t)}),[e])}globalThis&&globalThis.__spreadArray;var V=function(e){return e._tag==="Some"},R=function(e){return function(n){return V(e(n))}};const K=R(e=>e.type===o.AttributeType.Choice?s.some(e):s.none),$=R(e=>e.type===o.AttributeType.Numeric?s.some(e):s.none),G=R(e=>e.type===o.AttributeType.Boolean?s.some(e):s.none),J=R(e=>e.type===o.AttributeType.Component?s.some(e):s.none);function x(e){return e.decision!=null&&e.decision.kind===o.DecisionKind.Explicit}function j(e){return s.pipe(e.values,s.RA.filter(x),s.RA.map(n=>({type:o.AttributeType.Choice,attributeId:e.id,choiceValueId:n.id,state:null})))}function L(e){return s.pipe(e,s.O.fromPredicate(x),s.O.map(()=>({type:o.AttributeType.Numeric,attributeId:e.id,state:null})))}function W(e){return s.pipe(e,s.O.fromPredicate(x),s.O.map(()=>({type:o.AttributeType.Boolean,attributeId:e.id,state:null})))}function X(e){return s.pipe(e,s.O.fromPredicate(x),s.O.map(()=>({type:o.AttributeType.Component,attributeId:e.id,state:null})))}function Y(e,n){return s.pipe(o.ConfigurationInterpreter.filterAttributesOfComponent(n,e,!0),t=>[s.pipe(t,s.RA.filter(K),s.RA.chain(j)),s.pipe(t,s.RA.filter($),s.RA.map(L),s.RA.compact),s.pipe(t,s.RA.filter(G),s.RA.map(W),s.RA.compact),s.pipe(t,s.RA.filter(J),s.RA.map(X),s.RA.compact)],s.RA.flatten)}function _(){const e=M();return w(e),u.useMemo(()=>({explain:(n,t)=>A.match(t).with("decisions",i=>e.explain(n,i)).with("constraints",i=>e.explain(n,i)).with("full",i=>e.explain(n,i)).exhaustive(),applySolution:n=>e.applySolution(n)}),[e])}function Z(e,n=!1){const t=S();return E(t),u.useMemo(()=>s.pipe(s.O.fromNullable(e),s.O.map(s.flow(s.RA.map(i=>o.ConfigurationInterpreter.getAttribute(t,i)),n?s.RA.filterMap(s.O.fromNullable):s.identity)),s.O.getOrElse(()=>t.attributes)),[e,t,n])}function ee(e){const n=S(),{makeDecision:t,setManyDecision:i}=h(),r=b(e,o.ExplainQuestionSubject.choiceValue);E(n);const a=o.ConfigurationInterpreter.getChoiceAttribute(n,e),g=u.useMemo(()=>({makeDecision:(c,f)=>t({type:o.AttributeType.Choice,attributeId:e,choiceValueId:c,state:f}),clearDecisions:s.pipe(a,s.O.fromNullable,s.O.map(j),s.O.filter(s.RA.isNonEmpty),s.O.map(c=>()=>i(c,{type:"Default"})),s.O.getOrElse(()=>()=>Promise.resolve())),...r}),[e,a,t,i,r]),p=u.useMemo(()=>({...g,attribute:a}),[a,g]);if(a)return p}function ne(e){const n=S(),{makeDecision:t}=h(),i=b(e,o.ExplainQuestionSubject.numeric);E(n);const r=o.ConfigurationInterpreter.getNumericAttribute(n,e),a=u.useMemo(()=>({makeDecision:p=>t({type:o.AttributeType.Numeric,attributeId:e,state:p}),...i}),[e,t,i]),g=u.useMemo(()=>({...a,attribute:r}),[r,a]);if(r)return g}function se(e){const n=S(),{makeDecision:t}=h(),i=b(e,o.ExplainQuestionSubject.boolean);E(n);const r=o.ConfigurationInterpreter.getBooleanAttribute(n,e),a=u.useMemo(()=>({makeDecision:p=>t({type:o.AttributeType.Boolean,attributeId:e,state:p}),...i}),[e,t,i]),g=u.useMemo(()=>({...a,attribute:r}),[r,a]);if(r)return g}function te(e){const n=S(),{makeDecision:t,setManyDecision:i}=h(),r=b(e,o.ExplainQuestionSubject.component);E(n);const a=n.attributes,g=o.ConfigurationInterpreter.getComponentAttribute(n,e),p=u.useMemo(()=>({makeDecision:f=>t({type:o.AttributeType.Component,attributeId:e,state:f}),clearSubtree:s.pipe(Y(e,a),s.O.fromPredicate(s.RA.isNonEmpty),s.O.map(f=>()=>i(f,{type:"Default"})),s.O.getOrElse(()=>()=>Promise.resolve())),...r}),[e,t,a,i,r]),c=u.useMemo(()=>({...p,attribute:g}),[g,p]);if(g)return c}function b(e,n){const{explain:t,applySolution:i}=_();return u.useMemo(()=>({explain:(r,a)=>{const g=A.match(r.question).with(o.ExplainQuestionType.whyIsNotSatisfied,()=>o.ExplainQuestionSubject.attribute).otherwise(()=>n),p={...r,subject:g,attributeId:e};return A.match(a).with("decisions",c=>t(p,c)).with("constraints",c=>t(p,c)).with("full",c=>t(p,c)).exhaustive()},applySolution:i}),[e,n,t,i])}const I=s.Eq.fromEquals(o.globalAttributeIdEquals),ie=s.Eq.fromEquals(o.globalConstraintIdEquals),oe=s.Eq.fromEquals((e,n)=>s.RR.getEq(s.Str.Eq).equals(e??{},n??{})),re=s.Eq.struct({attributeId:I,decisions:s.RA.getEq(I)}),ae=s.Eq.fromEquals((e,n)=>s.RA.getEq(re).equals(e??[],n??[])),le=s.Eq.struct({type:s.Str.Eq}),ue=s.Eq.struct({type:s.Str.Eq}),ce=s.Eq.struct({type:s.Str.Eq,rules:s.RA.getEq(ie)}),ge=s.Eq.fromEquals((e,n)=>A.match({x:e,y:n}).returnType().with({x:{type:o.AllowedRulesInExplainType.all},y:{type:o.AllowedRulesInExplainType.all}},({x:t,y:i})=>le.equals(t,i)).with({x:{type:o.AllowedRulesInExplainType.none},y:{type:o.AllowedRulesInExplainType.none}},({x:t,y:i})=>ue.equals(t,i)).with({x:{type:o.AllowedRulesInExplainType.specific},y:{type:o.AllowedRulesInExplainType.specific}},({x:t,y:i})=>ce.equals(t,i)).otherwise(()=>!1)),de=s.Eq.struct({rules:s.Eq.eqNullable(ge)}),F=s.Eq.struct({configurationModelSource:s.Eq.fromEquals((e,n)=>Q.deepEqual(e,n)),attributeRelations:ae,usageRuleParameters:oe,allowedInExplain:s.Eq.eqNullable(de)}),q=s.Eq.eqNullable(F),pe=s.Eq.eqStrict,y=s.Eq.eqNullable(pe),fe=()=>l.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:"),C(2)],always:[{target:"DisposeSession",cond:"shallDisposeSession"},{target:"CreateSession",cond:"shallCreateSession"},{target:"UpdateSession",cond:"shallUpdateSession"}]},DisposeSession:{entry:[d.log("Entering DisposeSession","SessionManagement:"),C(2)],always:{actions:["disposeOldSession"],target:"ProcessChanges"}},CreateSession:{entry:[d.log("Entering CreateSession","SessionManagement:"),C(0)],invoke:{id:"getNewSession",src:"createSession",onDone:{actions:["setSessionCreationResult","setHasEverSuccessfullyCreatedSession"],target:"ProcessChanges"},onError:{actions:"setSessionCreationError",target:"SessionCreationFailed"}}},SessionCreationFailed:{entry:[d.log("Entering SessionCreationFailed","SessionManagement:"),C(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:"),C(1)],invoke:{id:"updateExistingSession",src:"updateSession",onDone:{target:"ProcessChanges"},onError:{actions:"setSessionUpdateError",target:"SessionUpdateFailed"}}},SessionUpdateFailed:{entry:[d.log("Entering SessionUpdateFailed","SessionManagement:"),C(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:l.assign({desiredClient:(e,n)=>n.client}),saveDesiredSessionContext:l.assign({desiredSessionContext:(e,n)=>n.sessionContext}),disposeOldSession:l.assign((e,n)=>(e.session&&e.session.close().then(s.constVoid).catch(t=>{}),{session:null,actualClient:null})),setSessionCreationResult:l.assign((e,n)=>({session:n.data.session,actualClient:n.data.client})),setSessionCreationError:l.assign((e,n)=>({sessionCreationError:n.data})),clearSessionCreationError:l.assign({sessionCreationError:()=>null}),setSessionUpdateError:l.assign((e,n)=>({sessionUpdateError:n.data})),clearSessionUpdateError:l.assign({sessionUpdateError:()=>null}),setHasEverSuccessfullyCreatedSession:l.assign({hasEverSuccessfullyCreatedSession:()=>!0})},services:{createSession:e=>e.desiredClient.createSession(e.desiredSessionContext).then(n=>({session:n,client:e.desiredClient})).catch(n=>Promise.reject({failureResult:n,client:e.desiredClient,sessionContext:e.desiredSessionContext})),updateSession:e=>e.session.setSessionContext(e.desiredSessionContext).catch(n=>Promise.reject({failureResult:n,sessionContext:e.desiredSessionContext}))},guards:{shallDisposeSession:e=>e.session!=null&&(e.desiredSessionContext==null||e.desiredClient==null||!y.equals(e.actualClient,e.desiredClient)),shallCreateSession:e=>e.session==null&&e.desiredClient!=null&&e.desiredSessionContext!=null,shallUpdateSession:e=>e.session!=null&&!F.equals(e.session.getSessionContext(),e.desiredSessionContext),shallImmediatelyProcessChangesAfterSessionCreationError:e=>!y.equals(e.desiredClient,e.sessionCreationError.client)||!q.equals(e.desiredSessionContext,e.sessionCreationError.sessionContext),shallImmediatelyProcessChangesAfterSessionUpdateError:e=>!y.equals(e.desiredClient,e.actualClient)||!q.equals(e.desiredSessionContext,e.sessionUpdateError.sessionContext)}});function C(e){const n=e===0,t=e===1;return d.pure((i,r)=>{const a={isInitializing:(!i.hasEverSuccessfullyCreatedSession||n)&&i.sessionCreationError==null,failureResult:i.sessionCreationError&&i.sessionCreationError.failureResult},g={isUpdating:t&&i.sessionUpdateError==null,failureResult:i.sessionUpdateError&&i.sessionUpdateError.failureResult};return l.sendParent({type:"SessionManagementStateChanged",sessionInitialization:a,sessionUpdating:g,session:i.session})})}const Ce=e=>n=>(n({type:"ConfigurationChanged",session:e,configuration:e.getConfiguration()}),e.setOnConfigurationChangedHandler(t=>{n({type:"ConfigurationChanged",session:e,configuration:t})}),()=>{e.setOnConfigurationChangedHandler(null)}),me=()=>l.createMachine({predictableActionArguments:!0,preserveActionOrder:!0,schema:{context:{},events:{}},context:{session:null},on:{ConfigurationChanged:{actions:[l.sendParent((e,n)=>n)]}},initial:"ProcessChanges",states:{ProcessChanges:{entry:[d.log("Entering ProcessChanges","ConfigurationSubscriptionManagement:")],on:{ChangeSession:{actions:["saveSession"]}},always:[{target:"Subscribe",cond:(e,n)=>e.session!=null}]},Subscribe:{entry:[d.log("Entering Subscribe","ConfigurationSubscriptionManagement:")],on:{ChangeSession:{target:"ProcessChanges",cond:(e,n)=>n.session==null||e.session!==n.session,actions:["saveSession"]}},invoke:{id:"configurationSubscriptionActor",src:(e,n)=>Ce(e.session)}}}},{actions:{saveSession:l.assign((e,n)=>({session:n.session}))}}),Se=()=>{let e,n;return{promise:new Promise((i,r)=>{e=i,n=r}),resolve:e,reject:n}},U=()=>{const e=Se();return{capsule:{promise:e.promise},resolve:e.resolve,reject:e.reject}};var Ee=function(e,n,t){var i=u.useRef(),r=u.useRef(0);return i.current==null&&(i.current=e),n.equals(e,i.current)||(t&&t.debug&&process.env.NODE_ENV!=="production"&&console.info("Stable hook update triggered:",{prev:i.current,value:e}),i.current=e,r.current+=1),[r.current]},D=function(e,n,t,i){return u.useEffect(e,Ee(n,t,i))};const he=()=>l.createMachine({predictableActionArguments:!0,preserveActionOrder:!0,schema:{context:{},events:{}},context:{sessionManagementActor:null,configurationSubscriptionManagementActor:null,sessionInitialization:null,sessionUpdating:null,session:null,configuration:null,isReadyPromise:U()},entry:[l.assign({sessionManagementActor:()=>l.spawn(fe()),configurationSubscriptionManagementActor:()=>l.spawn(me())})],exit:[d.stop(e=>e.sessionManagementActor),d.stop(e=>e.configurationSubscriptionManagementActor)],on:{ChangeConfigurationClient:{actions:[l.forwardTo(e=>e.sessionManagementActor)]},ChangeSessionContext:{actions:[l.forwardTo(e=>e.sessionManagementActor)]},RetrySessionCreation:{actions:[l.forwardTo(e=>e.sessionManagementActor)]},RetrySessionUpdate:{actions:[l.forwardTo(e=>e.sessionManagementActor)]},SessionManagementStateChanged:{actions:[l.assign((e,n)=>({session:n.session,sessionInitialization:n.sessionInitialization,sessionUpdating:n.sessionUpdating})),l.send(e=>({type:"ChangeSession",session:e.session}),{to:e=>e.configurationSubscriptionManagementActor}),"calculateReadyState"]},ConfigurationChanged:{actions:[l.assign((e,n)=>({configuration:{session:n.session,configuration:n.configuration}})),"calculateReadyState"]}},initial:"Idle",states:{Idle:{}}},{actions:{calculateReadyState:l.assign((e,n)=>{var r;const t=!((r=e.sessionInitialization)!=null&&r.isInitializing)&&e.session!=null&&e.configuration!=null&&e.configuration.session===e.session;return e.isReadyPromise&&t&&(e.isReadyPromise.resolve(),e.isReadyPromise.capsule.promise=null),{isReadyPromise:(()=>t?null:e.isReadyPromise!=null?e.isReadyPromise:U())()}})}});function ye(e){var g,p;const[n,t]=H.useMachine(he,{logger:(...c)=>console.log("ConfigurationManagement:",...c)});D(()=>{t({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],s.Eq.tuple(y)),D(()=>{const c=s.pipe(s.O.fromNullable(e.sessionContext),s.O.chainFirst(f=>s.O.fromNullable(f.configurationModelSource)),s.O.toNullable);t({type:"ChangeSessionContext",sessionContext:c}),c||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],s.Eq.tuple(q));const i=u.useMemo(()=>{var c,f,P,v;return{isInitializing:((f=(c=n.context.isReadyPromise)==null?void 0:c.capsule)==null?void 0:f.promise)!=null,isInitializingPromise:(P=n.context.isReadyPromise)==null?void 0:P.capsule,error:((v=n.context.sessionInitialization)==null?void 0:v.failureResult)&&{...n.context.sessionInitialization.failureResult,retry:()=>t({type:"RetrySessionCreation"})}}},[n.context.sessionInitialization,n.context.isReadyPromise]),r=u.useMemo(()=>{var c,f;return{isUpdating:(c=n.context.sessionUpdating)==null?void 0:c.isUpdating,error:((f=n.context.sessionUpdating)==null?void 0:f.failureResult)&&{...n.context.sessionUpdating.failureResult,retry:()=>t({type:"RetrySessionUpdate"})}}},[n.context.sessionUpdating]),a=((g=n.context.configuration)==null?void 0:g.session)===n.context.session?(p=n.context.configuration)==null?void 0:p.configuration:null;return{configurationInitialization:i,configurationUpdating:r,session:n.context.session,configuration:a}}function Ae(e){const{configuratorClient:n,...t}=e,{configurationInitialization:i,configurationUpdating:r,session:a,configuration:g}=ye({configuratorClient:n,sessionContext:t});return m.jsx(T.Provider,{value:i,children:m.jsx(N.Provider,{value:r,children:m.jsx(O.Provider,{value:a,children:m.jsx(k.Provider,{value:g,children:e.children})})})})}function B(){return u.useContext(T)}function Re(){return u.useContext(N)}function xe(e){const{children:n}=e,{isInitializingPromise:t}=B();if(t!=null&&t.promise)throw t.promise;return m.jsx(m.Fragment,{children:n})}function be(){const e=M(),n=S();return w(e),E(n),u.useMemo(()=>({configuration:n,restoreConfiguration:t=>e.restoreConfiguration(t)}),[n,e])}exports.Configuration=Ae;exports.ConfigurationSuspender=xe;exports.useAttributes=Z;exports.useBooleanAttribute=se;exports.useChoiceAttribute=ee;exports.useComponentAttribute=te;exports.useConfiguration=be;exports.useConfigurationInitialization=B;exports.useConfigurationUpdating=Re;exports.useDecision=h;exports.useExplain=_;exports.useNumericAttribute=ne;
@@ -0,0 +1,202 @@
1
+ import { AllowedInExplain } from '@viamedici-spc/configurator-ts';
2
+ import { Attribute } from '@viamedici-spc/configurator-ts';
3
+ import { AttributeRelations } from '@viamedici-spc/configurator-ts';
4
+ import { BooleanAttribute } from '@viamedici-spc/configurator-ts';
5
+ import { ChoiceAttribute } from '@viamedici-spc/configurator-ts';
6
+ import { ChoiceValueDecisionState } from '@viamedici-spc/configurator-ts';
7
+ import { ChoiceValueId } from '@viamedici-spc/configurator-ts';
8
+ import { ComponentAttribute } from '@viamedici-spc/configurator-ts';
9
+ import { ComponentDecisionState } from '@viamedici-spc/configurator-ts';
10
+ import { Configuration as Configuration_2 } from '@viamedici-spc/configurator-ts';
11
+ import { ConfigurationModelSource } from '@viamedici-spc/configurator-ts';
12
+ import { ConstraintsExplainAnswer } from '@viamedici-spc/configurator-ts';
13
+ import { DecisionsExplainAnswer } from '@viamedici-spc/configurator-ts';
14
+ import { ExplainQuestion } from '@viamedici-spc/configurator-ts';
15
+ import { ExplainQuestionParam as ExplainQuestionParam_2 } from '@viamedici-spc/configurator-ts';
16
+ import { ExplainSolution } from '@viamedici-spc/configurator-ts';
17
+ import { ExplicitDecision } from '@viamedici-spc/configurator-ts';
18
+ import { FailureResult } from '@viamedici-spc/configurator-ts';
19
+ import { FullExplainAnswer } from '@viamedici-spc/configurator-ts';
20
+ import { GlobalAttributeId } from '@viamedici-spc/configurator-ts';
21
+ import { IConfiguratorClient } from '@viamedici-spc/configurator-ts';
22
+ import { NumericAttribute } from '@viamedici-spc/configurator-ts';
23
+ import { PropsWithChildren } from 'react';
24
+ import { SetManyMode } from '@viamedici-spc/configurator-ts';
25
+ import { WhyIsAttributeNotSatisfied } from '@viamedici-spc/configurator-ts';
26
+ import { WhyIsBooleanStateNotPossible } from '@viamedici-spc/configurator-ts';
27
+ import { WhyIsChoiceValueStateNotPossible } from '@viamedici-spc/configurator-ts';
28
+ import { WhyIsComponentStateNotPossible } from '@viamedici-spc/configurator-ts';
29
+ import { WhyIsNumericStateNotPossible } from '@viamedici-spc/configurator-ts';
30
+ import { WhyIsStateNotPossible } from '@viamedici-spc/configurator-ts';
31
+
32
+ export declare function Configuration(props: PropsWithChildren<ConfigurationProps>): JSX.Element;
33
+
34
+ export declare type ConfigurationError = FailureResult & {
35
+ retry?: () => void;
36
+ };
37
+
38
+ export declare type ConfigurationInitialization = {
39
+ /**
40
+ * Gets whether the configuration is currently initializing.
41
+ * This information is required for some hooks to be safely used.
42
+ */
43
+ isInitializing: boolean;
44
+ /**
45
+ * Houses a promise when the configuration is in the initializing state.
46
+ * The promise resolves upon completion of the configuration initialization, subsequently becoming null.
47
+ * A new promise is generated each time the configuration re-enters the initializing state.
48
+ *
49
+ * @remarks
50
+ * 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.
51
+ * 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.
52
+ * Upon fulfillment of the promise, the encapsulation is imperatively updated to remove the promise for all listeners inside React Suspense barriers.
53
+ */
54
+ isInitializingPromise: EncapsulatedPromise | null;
55
+ error?: ConfigurationError;
56
+ };
57
+
58
+ export declare type ConfigurationProps = {
59
+ /**
60
+ * The client that is used to create a configuration session.
61
+ * When the instance changes, the old session is disposed and a new session is created. All decisions are discarded in this case.
62
+ */
63
+ configuratorClient: IConfiguratorClient;
64
+ configurationModelSource: ConfigurationModelSource;
65
+ attributeRelations?: AttributeRelations | null;
66
+ usageRuleParameters?: Record<string, string> | null;
67
+ allowedInExplain?: AllowedInExplain | null;
68
+ };
69
+
70
+ /**
71
+ * The ConfigurationSuspender avoids to manually handle the initialization state.
72
+ * Combined with the React Suspense component, it stops the component subtree from rendering while the configuration is initializing.
73
+ * So unsafe hooks like "useAttributes" can safely be used.
74
+ * See the hook documentation whether a hook is safe to use while initialization.
75
+ */
76
+ export declare function ConfigurationSuspender(props: PropsWithChildren<{}>): JSX.Element;
77
+
78
+ export declare type ConfigurationUpdating = {
79
+ isUpdating: boolean;
80
+ error?: ConfigurationError;
81
+ };
82
+
83
+ declare type EncapsulatedPromise = {
84
+ promise: Promise<void> | null;
85
+ };
86
+
87
+ declare type ExplainQuestionParam<T extends WhyIsStateNotPossible> = SimplifiedExplainQuestion<WhyIsAttributeNotSatisfied> | SimplifiedExplainQuestion<T>;
88
+
89
+ declare type SimplifiedExplainQuestion<T extends ExplainQuestion> = Omit<T, "attributeId" | "subject">;
90
+
91
+ declare type UseAttributeExplainResult<T extends WhyIsStateNotPossible> = {
92
+ explain(question: ExplainQuestionParam<T>, answerType: "decisions"): Promise<DecisionsExplainAnswer>;
93
+ explain(question: ExplainQuestionParam<T>, answerType: "constraints"): Promise<ConstraintsExplainAnswer>;
94
+ explain(question: ExplainQuestionParam<T>, answerType: "full"): Promise<FullExplainAnswer>;
95
+ applySolution(solution: ExplainSolution): Promise<void>;
96
+ };
97
+
98
+ /**
99
+ * Retrieves the requested attributes. Will return all existing attributes if requested attributes is null or undefined.
100
+ * @param attributes The attributes to return or null/undefined if all attributes shall be returned.
101
+ * @param ignoreMissingAttributes Whether to ignore that requested attributes are missing. If true, missing attributes will be filtered out of the result.
102
+ * Otherwise, they will appear as undefined. Only applicable if @param attributes has items. Defaults to false.
103
+ * @throws If configuration is initializing.
104
+ */
105
+ export declare function useAttributes(attributes?: GlobalAttributeId[], ignoreMissingAttributes?: boolean): readonly Attribute[];
106
+
107
+ /**
108
+ * Gets the requested boolean attribute with the command to make decisions.
109
+ * @param attributeId The id of the boolean attribute.
110
+ * @throws If configuration is initializing.
111
+ * @returns Undefined if attribute doesn't exist, or it is not a boolean attribute.
112
+ */
113
+ export declare function useBooleanAttribute(attributeId: GlobalAttributeId): UseBooleanAttributeResult | undefined;
114
+
115
+ export declare type UseBooleanAttributeResult = UseAttributeExplainResult<WhyIsBooleanStateNotPossible> & {
116
+ attribute: BooleanAttribute;
117
+ makeDecision: (state: boolean | null | undefined) => Promise<void>;
118
+ };
119
+
120
+ /**
121
+ * Gets the requested choice attribute with commands for making decisions or explaining consequences.
122
+ * @param attributeId The id of the choice attribute.
123
+ * @throws If configuration is initializing.
124
+ * @returns Undefined if attribute doesn't exist, or it is not a choice attribute.
125
+ */
126
+ export declare function useChoiceAttribute(attributeId: GlobalAttributeId): UseChoiceAttributeResult | undefined;
127
+
128
+ export declare type UseChoiceAttributeResult = UseAttributeExplainResult<WhyIsChoiceValueStateNotPossible> & {
129
+ attribute: ChoiceAttribute;
130
+ makeDecision: (choiceValueId: ChoiceValueId, state: ChoiceValueDecisionState | null | undefined) => Promise<void>;
131
+ clearDecisions: () => Promise<void>;
132
+ };
133
+
134
+ export declare function useComponentAttribute(attributeId: GlobalAttributeId): UseComponentAttributeResult | undefined;
135
+
136
+ export declare type UseComponentAttributeResult = UseAttributeExplainResult<WhyIsComponentStateNotPossible> & {
137
+ attribute: ComponentAttribute;
138
+ makeDecision: (state: ComponentDecisionState | null | undefined) => Promise<void>;
139
+ clearSubtree: () => Promise<void>;
140
+ };
141
+
142
+ /**
143
+ * Gets the current configuration data and allows to restore a configuration.
144
+ * @throws If configuration is initializing.
145
+ */
146
+ export declare function useConfiguration(): UseConfigurationResult;
147
+
148
+ /**
149
+ * Gets the initialization information for the configuration.
150
+ * This is safe to use if the configuration is initializing.
151
+ */
152
+ export declare function useConfigurationInitialization(): ConfigurationInitialization;
153
+
154
+ export declare type UseConfigurationResult = {
155
+ configuration: Configuration_2;
156
+ restoreConfiguration: (configuration: Configuration_2) => Promise<void>;
157
+ };
158
+
159
+ /**
160
+ * Gets the updating information for the configuration.
161
+ * This is safe to use if the configuration is initializing.
162
+ */
163
+ export declare function useConfigurationUpdating(): ConfigurationUpdating;
164
+
165
+ /**
166
+ * Gets commands for making one or many decisions.
167
+ * @throws If configuration is initializing.
168
+ */
169
+ export declare function useDecision(): UseDecisionResult;
170
+
171
+ export declare type UseDecisionResult = {
172
+ makeDecision: (decision: ExplicitDecision) => Promise<void>;
173
+ setManyDecision: (decisions: ReadonlyArray<ExplicitDecision>, mode: SetManyMode) => Promise<void>;
174
+ };
175
+
176
+ /**
177
+ * Gets commands for explaining consequences.
178
+ * @throws If configuration is initializing.
179
+ */
180
+ export declare function useExplain(): UseExplainResult;
181
+
182
+ export declare type UseExplainResult = {
183
+ explain(question: ExplainQuestionParam_2, answerType: "decisions"): Promise<DecisionsExplainAnswer>;
184
+ explain(question: ExplainQuestionParam_2, answerType: "constraints"): Promise<ConstraintsExplainAnswer>;
185
+ explain(question: ExplainQuestionParam_2, answerType: "full"): Promise<FullExplainAnswer>;
186
+ applySolution(solution: ExplainSolution): Promise<void>;
187
+ };
188
+
189
+ /**
190
+ * Gets the requested numeric attribute with the command to make decisions.
191
+ * @param attributeId The id of the numeric attribute.
192
+ * @throws If configuration is initializing.
193
+ * @returns Undefined if attribute doesn't exist, or it is not a numeric attribute.
194
+ */
195
+ export declare function useNumericAttribute(attributeId: GlobalAttributeId): UseNumericAttributeResult | undefined;
196
+
197
+ export declare type UseNumericAttributeResult = UseAttributeExplainResult<WhyIsNumericStateNotPossible> & {
198
+ attribute: NumericAttribute;
199
+ makeDecision: (state: number | null | undefined) => Promise<void>;
200
+ };
201
+
202
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,757 @@
1
+ import { AttributeType as S, ConfigurationInterpreter as E, DecisionKind as ie, ExplainQuestionSubject as A, ExplainQuestionType as te, globalAttributeIdEquals as oe, globalConstraintIdEquals as re, AllowedRulesInExplainType as h } from "@viamedici-spc/configurator-ts";
2
+ import { pipe as m, RA as l, O as a, some as w, none as M, flow as ae, identity as le, Eq as c, RR as ue, Str as U, constVoid as ce } from "@viamedici-spc/fp-ts-extensions";
3
+ import { createContext as D, useContext as I, useMemo as g, useRef as V, useEffect as de } from "react";
4
+ import { match as v } from "ts-pattern";
5
+ import { jsx as b, Fragment as ge } from "react/jsx-runtime";
6
+ import { createMachine as T, assign as f, sendParent as W, spawn as Q, forwardTo as P, send as fe } from "xstate";
7
+ import { log as C, pure as pe, stop as K } from "xstate/lib/actions";
8
+ import { deepEqual as Ce } from "fast-equals";
9
+ import { useMachine as me } from "@xstate/react";
10
+ const X = D(null), Y = D(null), Z = D(null), $ = D(null), F = () => I(X), x = () => I($), ee = "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.";
11
+ function j(e) {
12
+ if (!e)
13
+ throw new Error(ee);
14
+ }
15
+ function R(e) {
16
+ if (!e)
17
+ throw new Error(ee);
18
+ }
19
+ function N() {
20
+ const e = F();
21
+ return j(e), g(() => ({
22
+ makeDecision: (n) => e.makeDecision(n),
23
+ setManyDecision: (n, s) => e.setMany(n, s)
24
+ }), [e]);
25
+ }
26
+ globalThis && globalThis.__spreadArray;
27
+ var Se = function(e) {
28
+ return e._tag === "Some";
29
+ }, k = function(e) {
30
+ return function(n) {
31
+ return Se(e(n));
32
+ };
33
+ };
34
+ const he = k((e) => e.type === S.Choice ? w(e) : M), ye = k((e) => e.type === S.Numeric ? w(e) : M), Ee = k((e) => e.type === S.Boolean ? w(e) : M), xe = k((e) => e.type === S.Component ? w(e) : M);
35
+ function z(e) {
36
+ return e.decision != null && e.decision.kind === ie.Explicit;
37
+ }
38
+ function ne(e) {
39
+ return m(
40
+ e.values,
41
+ l.filter(z),
42
+ l.map((n) => ({
43
+ type: S.Choice,
44
+ attributeId: e.id,
45
+ choiceValueId: n.id,
46
+ state: null
47
+ }))
48
+ );
49
+ }
50
+ function Re(e) {
51
+ return m(
52
+ e,
53
+ a.fromPredicate(z),
54
+ a.map(() => ({
55
+ type: S.Numeric,
56
+ attributeId: e.id,
57
+ state: null
58
+ }))
59
+ );
60
+ }
61
+ function be(e) {
62
+ return m(
63
+ e,
64
+ a.fromPredicate(z),
65
+ a.map(() => ({
66
+ type: S.Boolean,
67
+ attributeId: e.id,
68
+ state: null
69
+ }))
70
+ );
71
+ }
72
+ function Ae(e) {
73
+ return m(
74
+ e,
75
+ a.fromPredicate(z),
76
+ a.map(() => ({
77
+ type: S.Component,
78
+ attributeId: e.id,
79
+ state: null
80
+ }))
81
+ );
82
+ }
83
+ function Pe(e, n) {
84
+ return m(
85
+ E.filterAttributesOfComponent(n, e, !0),
86
+ (s) => [
87
+ m(
88
+ s,
89
+ l.filter(he),
90
+ l.chain(ne)
91
+ ),
92
+ m(
93
+ s,
94
+ l.filter(ye),
95
+ l.map(Re),
96
+ l.compact
97
+ ),
98
+ m(
99
+ s,
100
+ l.filter(Ee),
101
+ l.map(be),
102
+ l.compact
103
+ ),
104
+ m(
105
+ s,
106
+ l.filter(xe),
107
+ l.map(Ae),
108
+ l.compact
109
+ )
110
+ ],
111
+ l.flatten
112
+ );
113
+ }
114
+ function qe() {
115
+ const e = F();
116
+ return j(e), g(() => ({
117
+ explain: (n, s) => v(s).with("decisions", (i) => e.explain(n, i)).with("constraints", (i) => e.explain(n, i)).with("full", (i) => e.explain(n, i)).exhaustive(),
118
+ applySolution: (n) => e.applySolution(n)
119
+ }), [e]);
120
+ }
121
+ function en(e, n = !1) {
122
+ const s = x();
123
+ return R(s), g(
124
+ () => m(
125
+ a.fromNullable(e),
126
+ a.map(ae(
127
+ l.map((i) => E.getAttribute(s, i)),
128
+ n ? l.filterMap(a.fromNullable) : le
129
+ )),
130
+ a.getOrElse(() => s.attributes)
131
+ ),
132
+ [e, s, n]
133
+ );
134
+ }
135
+ function nn(e) {
136
+ const n = x(), { makeDecision: s, setManyDecision: i } = N(), t = _(e, A.choiceValue);
137
+ R(n);
138
+ const o = E.getChoiceAttribute(n, e), u = g(() => ({
139
+ makeDecision: (r, p) => s({
140
+ type: S.Choice,
141
+ attributeId: e,
142
+ choiceValueId: r,
143
+ state: p
144
+ }),
145
+ clearDecisions: m(
146
+ o,
147
+ a.fromNullable,
148
+ a.map(ne),
149
+ // Only setMany if there are decisions to clear.
150
+ a.filter(l.isNonEmpty),
151
+ a.map((r) => () => i(r, { type: "Default" })),
152
+ a.getOrElse(() => () => Promise.resolve())
153
+ ),
154
+ ...t
155
+ }), [e, o, s, i, t]), d = g(() => ({
156
+ ...u,
157
+ attribute: o
158
+ }), [o, u]);
159
+ if (o)
160
+ return d;
161
+ }
162
+ function sn(e) {
163
+ const n = x(), { makeDecision: s } = N(), i = _(e, A.numeric);
164
+ R(n);
165
+ const t = E.getNumericAttribute(n, e), o = g(() => ({
166
+ makeDecision: (d) => s({
167
+ type: S.Numeric,
168
+ attributeId: e,
169
+ state: d
170
+ }),
171
+ ...i
172
+ }), [e, s, i]), u = g(() => ({
173
+ ...o,
174
+ attribute: t
175
+ }), [t, o]);
176
+ if (t)
177
+ return u;
178
+ }
179
+ function tn(e) {
180
+ const n = x(), { makeDecision: s } = N(), i = _(e, A.boolean);
181
+ R(n);
182
+ const t = E.getBooleanAttribute(n, e), o = g(() => ({
183
+ makeDecision: (d) => s({
184
+ type: S.Boolean,
185
+ attributeId: e,
186
+ state: d
187
+ }),
188
+ ...i
189
+ }), [e, s, i]), u = g(() => ({
190
+ ...o,
191
+ attribute: t
192
+ }), [t, o]);
193
+ if (t)
194
+ return u;
195
+ }
196
+ function on(e) {
197
+ const n = x(), { makeDecision: s, setManyDecision: i } = N(), t = _(e, A.component);
198
+ R(n);
199
+ const o = n.attributes, u = E.getComponentAttribute(n, e), d = g(() => ({
200
+ makeDecision: (p) => s({
201
+ type: S.Component,
202
+ attributeId: e,
203
+ state: p
204
+ }),
205
+ clearSubtree: m(
206
+ Pe(e, o),
207
+ // Only setMany if there are decisions to clear.
208
+ a.fromPredicate(l.isNonEmpty),
209
+ a.map((p) => () => i(p, { type: "Default" })),
210
+ a.getOrElse(() => () => Promise.resolve())
211
+ ),
212
+ ...t
213
+ }), [e, s, o, i, t]), r = g(() => ({
214
+ ...d,
215
+ attribute: u
216
+ }), [u, d]);
217
+ if (u)
218
+ return r;
219
+ }
220
+ function _(e, n) {
221
+ const { explain: s, applySolution: i } = qe();
222
+ return g(() => ({
223
+ explain: (t, o) => {
224
+ const u = v(t.question).with(te.whyIsNotSatisfied, () => A.attribute).otherwise(() => n), d = {
225
+ ...t,
226
+ subject: u,
227
+ attributeId: e
228
+ };
229
+ return v(o).with("decisions", (r) => s(d, r)).with("constraints", (r) => s(d, r)).with("full", (r) => s(d, r)).exhaustive();
230
+ },
231
+ applySolution: i
232
+ }), [e, n, s, i]);
233
+ }
234
+ const G = c.fromEquals(oe), ve = c.fromEquals(re), we = c.fromEquals((e, n) => ue.getEq(U.Eq).equals(e ?? {}, n ?? {})), Me = c.struct({
235
+ attributeId: G,
236
+ decisions: l.getEq(G)
237
+ }), Ue = c.fromEquals((e, n) => l.getEq(Me).equals(e ?? [], n ?? [])), De = c.struct({
238
+ type: U.Eq
239
+ }), Ie = c.struct({
240
+ type: U.Eq
241
+ }), Ne = c.struct({
242
+ type: U.Eq,
243
+ rules: l.getEq(ve)
244
+ }), ke = c.fromEquals((e, n) => v({ x: e, y: n }).returnType().with({ x: { type: h.all }, y: { type: h.all } }, ({ x: s, y: i }) => De.equals(s, i)).with({ x: { type: h.none }, y: { type: h.none } }, ({ x: s, y: i }) => Ie.equals(s, i)).with({ x: { type: h.specific }, y: { type: h.specific } }, ({ x: s, y: i }) => Ne.equals(s, i)).otherwise(() => !1)), ze = c.struct({
245
+ rules: c.eqNullable(ke)
246
+ }), se = c.struct({
247
+ configurationModelSource: c.fromEquals((e, n) => Ce(e, n)),
248
+ attributeRelations: Ue,
249
+ usageRuleParameters: we,
250
+ allowedInExplain: c.eqNullable(ze)
251
+ }), O = c.eqNullable(se), _e = c.eqStrict, q = c.eqNullable(_e), Oe = () => T({
252
+ predictableActionArguments: !0,
253
+ preserveActionOrder: !0,
254
+ schema: {
255
+ context: {},
256
+ events: {}
257
+ },
258
+ context: {
259
+ desiredClient: null,
260
+ desiredSessionContext: null,
261
+ actualClient: null,
262
+ session: null,
263
+ sessionCreationError: null,
264
+ sessionUpdateError: null,
265
+ hasEverSuccessfullyCreatedSession: !1
266
+ },
267
+ initial: "ProcessChanges",
268
+ on: {
269
+ ChangeConfigurationClient: {
270
+ actions: ["saveDesiredClient"]
271
+ },
272
+ ChangeSessionContext: {
273
+ actions: ["saveDesiredSessionContext"]
274
+ }
275
+ },
276
+ exit: [
277
+ C("Shutting down", "SessionManagement:"),
278
+ "disposeOldSession"
279
+ ],
280
+ states: {
281
+ ProcessChanges: {
282
+ entry: [
283
+ C("Entering ProcessChanges", "SessionManagement:"),
284
+ y(
285
+ 2
286
+ /* Other */
287
+ )
288
+ ],
289
+ always: [
290
+ { target: "DisposeSession", cond: "shallDisposeSession" },
291
+ { target: "CreateSession", cond: "shallCreateSession" },
292
+ { target: "UpdateSession", cond: "shallUpdateSession" }
293
+ ]
294
+ },
295
+ DisposeSession: {
296
+ entry: [
297
+ C("Entering DisposeSession", "SessionManagement:"),
298
+ y(
299
+ 2
300
+ /* Other */
301
+ )
302
+ ],
303
+ always: {
304
+ actions: ["disposeOldSession"],
305
+ target: "ProcessChanges"
306
+ }
307
+ },
308
+ CreateSession: {
309
+ entry: [
310
+ C("Entering CreateSession", "SessionManagement:"),
311
+ y(
312
+ 0
313
+ /* CreateSession */
314
+ )
315
+ ],
316
+ invoke: {
317
+ id: "getNewSession",
318
+ src: "createSession",
319
+ onDone: {
320
+ actions: ["setSessionCreationResult", "setHasEverSuccessfullyCreatedSession"],
321
+ target: "ProcessChanges"
322
+ },
323
+ onError: {
324
+ actions: "setSessionCreationError",
325
+ target: "SessionCreationFailed"
326
+ }
327
+ }
328
+ },
329
+ SessionCreationFailed: {
330
+ entry: [
331
+ C("Entering SessionCreationFailed", "SessionManagement:"),
332
+ y(
333
+ 2
334
+ /* Other */
335
+ )
336
+ ],
337
+ always: {
338
+ // Immediately process changes if there were changes during session creation attempt
339
+ // This will also be triggered if session context or client changes
340
+ target: "ProcessChanges",
341
+ cond: "shallImmediatelyProcessChangesAfterSessionCreationError"
342
+ },
343
+ exit: [
344
+ C("Exiting SessionCreationFailed", "SessionManagement:"),
345
+ "clearSessionCreationError"
346
+ ],
347
+ on: {
348
+ RetrySessionCreation: {
349
+ target: "ProcessChanges",
350
+ actions: C("Retrying session creation", "SessionManagement:")
351
+ }
352
+ }
353
+ },
354
+ UpdateSession: {
355
+ entry: [
356
+ C("Entering UpdateSession", "SessionManagement:"),
357
+ y(
358
+ 1
359
+ /* UpdateSession */
360
+ )
361
+ ],
362
+ invoke: {
363
+ id: "updateExistingSession",
364
+ src: "updateSession",
365
+ onDone: {
366
+ target: "ProcessChanges"
367
+ },
368
+ onError: {
369
+ actions: "setSessionUpdateError",
370
+ target: "SessionUpdateFailed"
371
+ }
372
+ }
373
+ },
374
+ SessionUpdateFailed: {
375
+ entry: [
376
+ C("Entering SessionUpdateFailed", "SessionManagement:"),
377
+ y(
378
+ 2
379
+ /* Other */
380
+ )
381
+ ],
382
+ always: {
383
+ // Immediately process changes if there were changes during session update attempt
384
+ // This will also be triggered if session context or client changes
385
+ target: "ProcessChanges",
386
+ cond: "shallImmediatelyProcessChangesAfterSessionUpdateError"
387
+ },
388
+ exit: [
389
+ C("Exiting SessionUpdateFailed", "SessionManagement:"),
390
+ "clearSessionUpdateError"
391
+ ],
392
+ on: {
393
+ RetrySessionUpdate: {
394
+ target: "ProcessChanges",
395
+ actions: C("Retrying session update", "SessionManagement:")
396
+ }
397
+ }
398
+ }
399
+ }
400
+ }, {
401
+ actions: {
402
+ saveDesiredClient: f({
403
+ desiredClient: (e, n) => n.client
404
+ }),
405
+ saveDesiredSessionContext: f({
406
+ desiredSessionContext: (e, n) => n.sessionContext
407
+ }),
408
+ disposeOldSession: f((e, n) => (e.session && e.session.close().then(ce).catch((s) => {
409
+ }), {
410
+ session: null,
411
+ actualClient: null
412
+ })),
413
+ setSessionCreationResult: f((e, n) => ({
414
+ session: n.data.session,
415
+ actualClient: n.data.client
416
+ })),
417
+ setSessionCreationError: f((e, n) => ({
418
+ sessionCreationError: n.data
419
+ })),
420
+ clearSessionCreationError: f({ sessionCreationError: () => null }),
421
+ setSessionUpdateError: f((e, n) => ({
422
+ sessionUpdateError: n.data
423
+ })),
424
+ clearSessionUpdateError: f({ sessionUpdateError: () => null }),
425
+ setHasEverSuccessfullyCreatedSession: f({
426
+ hasEverSuccessfullyCreatedSession: () => !0
427
+ })
428
+ },
429
+ services: {
430
+ createSession: (e) => e.desiredClient.createSession(e.desiredSessionContext).then((n) => ({
431
+ session: n,
432
+ client: e.desiredClient
433
+ })).catch((n) => Promise.reject({
434
+ failureResult: n,
435
+ client: e.desiredClient,
436
+ sessionContext: e.desiredSessionContext
437
+ })),
438
+ updateSession: (e) => e.session.setSessionContext(e.desiredSessionContext).catch((n) => Promise.reject({
439
+ failureResult: n,
440
+ sessionContext: e.desiredSessionContext
441
+ }))
442
+ },
443
+ guards: {
444
+ shallDisposeSession: (e) => e.session != null && (e.desiredSessionContext == null || e.desiredClient == null || !q.equals(e.actualClient, e.desiredClient)),
445
+ shallCreateSession: (e) => e.session == null && e.desiredClient != null && e.desiredSessionContext != null,
446
+ shallUpdateSession: (e) => e.session != null && !se.equals(e.session.getSessionContext(), e.desiredSessionContext),
447
+ shallImmediatelyProcessChangesAfterSessionCreationError: (e) => (
448
+ // The desired client and the desired session context is not the same that resulted in the error.
449
+ !q.equals(e.desiredClient, e.sessionCreationError.client) || !O.equals(e.desiredSessionContext, e.sessionCreationError.sessionContext)
450
+ ),
451
+ shallImmediatelyProcessChangesAfterSessionUpdateError: (e) => (
452
+ // The desired client was changed
453
+ !q.equals(e.desiredClient, e.actualClient) || !O.equals(e.desiredSessionContext, e.sessionUpdateError.sessionContext)
454
+ )
455
+ }
456
+ });
457
+ function y(e) {
458
+ const n = e === 0, s = e === 1;
459
+ return pe((i, t) => {
460
+ const o = {
461
+ isInitializing: (!i.hasEverSuccessfullyCreatedSession || n) && i.sessionCreationError == null,
462
+ failureResult: i.sessionCreationError && i.sessionCreationError.failureResult
463
+ }, u = {
464
+ isUpdating: s && i.sessionUpdateError == null,
465
+ failureResult: i.sessionUpdateError && i.sessionUpdateError.failureResult
466
+ };
467
+ return W({
468
+ type: "SessionManagementStateChanged",
469
+ sessionInitialization: o,
470
+ sessionUpdating: u,
471
+ session: i.session
472
+ });
473
+ });
474
+ }
475
+ const Te = (e) => (n) => (n({
476
+ type: "ConfigurationChanged",
477
+ session: e,
478
+ configuration: e.getConfiguration()
479
+ }), e.setOnConfigurationChangedHandler((s) => {
480
+ n({
481
+ type: "ConfigurationChanged",
482
+ session: e,
483
+ configuration: s
484
+ });
485
+ }), () => {
486
+ e.setOnConfigurationChangedHandler(null);
487
+ }), Fe = () => T({
488
+ predictableActionArguments: !0,
489
+ preserveActionOrder: !0,
490
+ schema: {
491
+ context: {},
492
+ events: {}
493
+ },
494
+ context: {
495
+ session: null
496
+ },
497
+ on: {
498
+ // Forward the configuration data to the parent.
499
+ ConfigurationChanged: {
500
+ actions: [
501
+ W((e, n) => n)
502
+ ]
503
+ }
504
+ },
505
+ initial: "ProcessChanges",
506
+ states: {
507
+ ProcessChanges: {
508
+ entry: [
509
+ C("Entering ProcessChanges", "ConfigurationSubscriptionManagement:")
510
+ ],
511
+ on: {
512
+ ChangeSession: {
513
+ actions: [
514
+ "saveSession"
515
+ ]
516
+ }
517
+ },
518
+ always: [
519
+ {
520
+ target: "Subscribe",
521
+ cond: (e, n) => e.session != null
522
+ }
523
+ ]
524
+ },
525
+ Subscribe: {
526
+ entry: [
527
+ C("Entering Subscribe", "ConfigurationSubscriptionManagement:")
528
+ ],
529
+ on: {
530
+ ChangeSession: {
531
+ target: "ProcessChanges",
532
+ cond: (e, n) => n.session == null || e.session !== n.session,
533
+ actions: [
534
+ "saveSession"
535
+ ]
536
+ }
537
+ },
538
+ invoke: {
539
+ id: "configurationSubscriptionActor",
540
+ src: (e, n) => Te(e.session)
541
+ }
542
+ }
543
+ }
544
+ }, {
545
+ actions: {
546
+ saveSession: f((e, n) => ({
547
+ session: n.session
548
+ }))
549
+ }
550
+ }), je = () => {
551
+ let e, n;
552
+ return {
553
+ promise: new Promise((i, t) => {
554
+ e = i, n = t;
555
+ }),
556
+ resolve: e,
557
+ reject: n
558
+ };
559
+ }, J = () => {
560
+ const e = je();
561
+ return {
562
+ capsule: { promise: e.promise },
563
+ resolve: e.resolve,
564
+ reject: e.reject
565
+ };
566
+ };
567
+ var Be = function(e, n, s) {
568
+ var i = V(), t = V(0);
569
+ return i.current == null && (i.current = e), n.equals(e, i.current) || (s && s.debug && process.env.NODE_ENV !== "production" && console.info("Stable hook update triggered:", { prev: i.current, value: e }), i.current = e, t.current += 1), [t.current];
570
+ }, L = function(e, n, s, i) {
571
+ return de(e, Be(n, s, i));
572
+ };
573
+ const He = () => T({
574
+ predictableActionArguments: !0,
575
+ preserveActionOrder: !0,
576
+ schema: {
577
+ context: {},
578
+ events: {}
579
+ },
580
+ context: {
581
+ sessionManagementActor: null,
582
+ configurationSubscriptionManagementActor: null,
583
+ sessionInitialization: null,
584
+ sessionUpdating: null,
585
+ session: null,
586
+ configuration: null,
587
+ isReadyPromise: J()
588
+ },
589
+ entry: [
590
+ f({
591
+ sessionManagementActor: () => Q(Oe()),
592
+ configurationSubscriptionManagementActor: () => Q(Fe())
593
+ })
594
+ ],
595
+ exit: [
596
+ K((e) => e.sessionManagementActor),
597
+ K((e) => e.configurationSubscriptionManagementActor)
598
+ ],
599
+ on: {
600
+ // Forward events for sessionManagement
601
+ ChangeConfigurationClient: {
602
+ actions: [
603
+ P((e) => e.sessionManagementActor)
604
+ ]
605
+ },
606
+ ChangeSessionContext: {
607
+ actions: [
608
+ P((e) => e.sessionManagementActor)
609
+ ]
610
+ },
611
+ RetrySessionCreation: {
612
+ actions: [
613
+ P((e) => e.sessionManagementActor)
614
+ ]
615
+ },
616
+ RetrySessionUpdate: {
617
+ actions: [
618
+ P((e) => e.sessionManagementActor)
619
+ ]
620
+ },
621
+ SessionManagementStateChanged: {
622
+ actions: [
623
+ // Assign the received data
624
+ f((e, n) => ({
625
+ session: n.session,
626
+ sessionInitialization: n.sessionInitialization,
627
+ sessionUpdating: n.sessionUpdating
628
+ })),
629
+ // Forward the session to the configuration subscription
630
+ fe((e) => ({
631
+ type: "ChangeSession",
632
+ session: e.session
633
+ }), { to: (e) => e.configurationSubscriptionManagementActor }),
634
+ "calculateReadyState"
635
+ ]
636
+ },
637
+ ConfigurationChanged: {
638
+ actions: [
639
+ f((e, n) => ({
640
+ configuration: {
641
+ session: n.session,
642
+ configuration: n.configuration
643
+ }
644
+ })),
645
+ "calculateReadyState"
646
+ ]
647
+ }
648
+ },
649
+ initial: "Idle",
650
+ states: {
651
+ Idle: {}
652
+ }
653
+ }, {
654
+ actions: {
655
+ calculateReadyState: f((e, n) => {
656
+ var t;
657
+ const s = !((t = e.sessionInitialization) != null && t.isInitializing) && e.session != null && e.configuration != null && e.configuration.session === e.session;
658
+ return e.isReadyPromise && s && (e.isReadyPromise.resolve(), e.isReadyPromise.capsule.promise = null), {
659
+ isReadyPromise: (() => s ? null : e.isReadyPromise != null ? e.isReadyPromise : J())()
660
+ };
661
+ })
662
+ }
663
+ });
664
+ function Ve(e) {
665
+ var u, d;
666
+ const [n, s] = me(He, {
667
+ logger: (...r) => console.log("ConfigurationManagement:", ...r)
668
+ });
669
+ L(() => {
670
+ s({
671
+ type: "ChangeConfigurationClient",
672
+ client: e.configuratorClient
673
+ }), 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.");
674
+ }, [e.configuratorClient], c.tuple(q)), L(() => {
675
+ const r = m(
676
+ a.fromNullable(e.sessionContext),
677
+ a.chainFirst((p) => a.fromNullable(p.configurationModelSource)),
678
+ a.toNullable
679
+ );
680
+ s({
681
+ type: "ChangeSessionContext",
682
+ sessionContext: r
683
+ }), r || 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.");
684
+ }, [e.sessionContext], c.tuple(O));
685
+ const i = g(
686
+ () => {
687
+ var r, p, B, H;
688
+ return {
689
+ isInitializing: ((p = (r = n.context.isReadyPromise) == null ? void 0 : r.capsule) == null ? void 0 : p.promise) != null,
690
+ isInitializingPromise: (B = n.context.isReadyPromise) == null ? void 0 : B.capsule,
691
+ error: ((H = n.context.sessionInitialization) == null ? void 0 : H.failureResult) && {
692
+ ...n.context.sessionInitialization.failureResult,
693
+ retry: () => s({ type: "RetrySessionCreation" })
694
+ }
695
+ };
696
+ },
697
+ [n.context.sessionInitialization, n.context.isReadyPromise]
698
+ ), t = g(
699
+ () => {
700
+ var r, p;
701
+ return {
702
+ isUpdating: (r = n.context.sessionUpdating) == null ? void 0 : r.isUpdating,
703
+ error: ((p = n.context.sessionUpdating) == null ? void 0 : p.failureResult) && {
704
+ ...n.context.sessionUpdating.failureResult,
705
+ retry: () => s({ type: "RetrySessionUpdate" })
706
+ }
707
+ };
708
+ },
709
+ [n.context.sessionUpdating]
710
+ ), o = ((u = n.context.configuration) == null ? void 0 : u.session) === n.context.session ? (d = n.context.configuration) == null ? void 0 : d.configuration : null;
711
+ return {
712
+ configurationInitialization: i,
713
+ configurationUpdating: t,
714
+ session: n.context.session,
715
+ configuration: o
716
+ };
717
+ }
718
+ function rn(e) {
719
+ const { configuratorClient: n, ...s } = e, { configurationInitialization: i, configurationUpdating: t, session: o, configuration: u } = Ve({
720
+ configuratorClient: n,
721
+ sessionContext: s
722
+ });
723
+ return /* @__PURE__ */ b(Y.Provider, { value: i, children: /* @__PURE__ */ b(Z.Provider, { value: t, children: /* @__PURE__ */ b(X.Provider, { value: o, children: /* @__PURE__ */ b($.Provider, { value: u, children: e.children }) }) }) });
724
+ }
725
+ function Qe() {
726
+ return I(Y);
727
+ }
728
+ function an() {
729
+ return I(Z);
730
+ }
731
+ function ln(e) {
732
+ const { children: n } = e, { isInitializingPromise: s } = Qe();
733
+ if (s != null && s.promise)
734
+ throw s.promise;
735
+ return /* @__PURE__ */ b(ge, { children: n });
736
+ }
737
+ function un() {
738
+ const e = F(), n = x();
739
+ return j(e), R(n), g(() => ({
740
+ configuration: n,
741
+ restoreConfiguration: (s) => e.restoreConfiguration(s)
742
+ }), [n, e]);
743
+ }
744
+ export {
745
+ rn as Configuration,
746
+ ln as ConfigurationSuspender,
747
+ en as useAttributes,
748
+ tn as useBooleanAttribute,
749
+ nn as useChoiceAttribute,
750
+ on as useComponentAttribute,
751
+ un as useConfiguration,
752
+ Qe as useConfigurationInitialization,
753
+ an as useConfigurationUpdating,
754
+ N as useDecision,
755
+ qe as useExplain,
756
+ sn as useNumericAttribute
757
+ };
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@viamedici-spc/configurator-react",
3
+ "version": "0.1.0-alpha0000",
4
+ "description": "React TypeScript library to build configurator web applications based on the Viamedici Headless Configuration API (HCA).",
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
+ "@viamedici-spc/configurator-ts": "1.1.0-alpha0009",
46
+ "@vitest/coverage-istanbul": "^0.34.1",
47
+ "jsdom": "^22.1.0",
48
+ "npm-sort": "^0.0.4",
49
+ "react": "^16.14.0",
50
+ "react-dom": "^16.14.0",
51
+ "typescript": "^5.1.6",
52
+ "vite": "^4.4.8",
53
+ "vite-plugin-checker": "^0.6.1",
54
+ "vite-plugin-dts": "^3.5.0",
55
+ "vitest": "^0.34.1"
56
+ },
57
+ "dependencies": {
58
+ "@viamedici-spc/fp-ts-extensions": "1.0.0",
59
+ "@xstate/react": "^3.2.2",
60
+ "fast-equals": "^4.0.3",
61
+ "fp-ts-react-stable-hooks": "^1.5.0",
62
+ "ts-pattern": "^5.0.6",
63
+ "url-join": "^5.0.0",
64
+ "xstate": "^4.38.2"
65
+ },
66
+ "peerDependencies": {
67
+ "react": ">=16.8",
68
+ "@viamedici-spc/configurator-ts": "1.x"
69
+ }
70
+ }